diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml index 49e0e11ef4..061ddeed50 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml @@ -21,8 +21,8 @@ en: 985e0eb63f3d1fd6 zh: 337cc44fadc6227e /agent-note-single-file-executable-sdk-runtime-distribution-single-exe/decision/build-pipeline-and-artifacts: - en: 9d885e8d58bc8bbb - zh: 41a9779fbdea8a1a + en: 9a4ba22142a7be24 + zh: 8553b02a923641a3 /agent-note-single-file-executable-sdk-runtime-distribution-single-exe/decision/python-sdk-distribution-two-carriers-exe-for-production-node-for-development: en: b2a740a1ab7a5002 zh: a48be6ca6fc65912 diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md index 8349e7cf31..34d346c96a 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md @@ -48,7 +48,7 @@ The [Office kit](2026-09-14-independent-libreoffice-kit.md) and its installed de ### Build pipeline and artifacts -[`scripts/build-exe-for-python-sdk.ts`](../../../../scripts/build-exe-for-python-sdk.ts): runtime closure verification → `pnpm run build` → (after clearing) `pnpm --filter dsh-python-runtime-closure deploy --legacy --prod --config.allow-unused-patches=true --config.node-linker=hoisted --config.auto-install-peers=false --config.link-workspace-packages=true --config.hoist-workspace-packages=false` **directly into** `python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/`, including [`python/sdk-runtime/runtime-bootstrap.mjs`](../../../../python/sdk-runtime/runtime-bootstrap.mjs) as the carrier-root `runtime-bootstrap.mjs` → restore direct workspace packages omitted by legacy deploy and reject any remaining manifest gap → replace staged dependency symlinks with their target bytes, remove package-manager `.bin` links, and fail if any symlink remains → verify the deployed bootstrap and inject pkg configuration with that bin plus assets covering dynamic profile, bundle, frontend, preset, native-library, and configuration reads → stage the target `node-pty` addon → invoke `pkg --sea --compress Brotli` once per target → write `deepseek-harness-sdk-runtime--` under `dist-exe/` and copy it with its lightweight resource manifest and Office skill assets into the runtime directory. The Python runtime owns that bootstrap. It calls the public CLI export for ordinary launches and dispatches a provider-private selection to the same `@deepseek-ai/dsh-subprocess-local/runner` core without changing CLI grammar or adding another executable; the [native-containment reference](../../../../packages/subprocess/subprocess-local/README.md) owns that private path. Linux CI rebuilds `pty.node` inside the matching manylinux 2.28 container because legacy deploy omits that install side effect. Every target copies its native `@vscode/ripgrep` binary beside the executable as the required `-rg` sidecar; pkg runtimes select that sidecar through `process.pkg`, while ordinary Node execution uses `@vscode/ripgrep` directly. macOS uses its target prebuild and also emits the required `-spawn-helper`. The deploy flags preserve the measured runtime layout: `--legacy` is the mandatory path with inject-workspace-packages off; hoisted supplies package directories that staging makes symlink-free; staging removes nested workspace copies only when pnpm records the same dependency identity at the payload root, preserving singleton services; disabling workspace hoisting excludes unrelated workspace source packages; disabling automatic peer installation prevents undeclared peers from expanding the closure; link-workspace-packages selects direct workspace dependencies. [`pnpm-workspace.yaml`](../../../../pnpm-workspace.yaml) overrides the transitive `@deepseek-ai/cosmokit` and `@deepseek-ai/schemastery` semver requests to the pinned vendor sources so legacy deploy never resolves those unpublished names from a registry. Production deployment permits unused workspace patches because development-only tools can be absent from its closure; included-package patch failures still fail deployment. Workspace installs retain strict unused-patch validation. +[`scripts/build-exe-for-python-sdk.ts`](../../../../scripts/build-exe-for-python-sdk.ts): runtime closure verification → `pnpm run build` → (after clearing) `pnpm --filter dsh-python-runtime-closure deploy --legacy --prod --config.allow-unused-patches=true --config.node-linker=hoisted --config.auto-install-peers=false --config.link-workspace-packages=true --config.hoist-workspace-packages=false` **directly into** `python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/`, including [`python/sdk-runtime/runtime-bootstrap.mjs`](../../../../python/sdk-runtime/runtime-bootstrap.mjs) as the carrier-root `runtime-bootstrap.mjs` → restore direct workspace packages omitted by legacy deploy and reject any remaining manifest gap → replace staged dependency symlinks with their target bytes, remove package-manager `.bin` links, and fail if any symlink remains → verify the deployed bootstrap and inject pkg configuration with that bin plus assets covering dynamic profile, bundle, frontend, preset, native-library, and configuration reads → stage the target `node-pty` addon → invoke `pkg --sea --compress Brotli` once per target, where the vendored pkg patch pins Brotli's quality to 6: pkg passes no options, so its default quality 11 measured 132.8 s against 3.2 s at quality 6 for an archive 12% larger → write `deepseek-harness-sdk-runtime--` under `dist-exe/` and copy it with its lightweight resource manifest and Office skill assets into the runtime directory. The Python runtime owns that bootstrap. It calls the public CLI export for ordinary launches and dispatches a provider-private selection to the same `@deepseek-ai/dsh-subprocess-local/runner` core without changing CLI grammar or adding another executable; the [native-containment reference](../../../../packages/subprocess/subprocess-local/README.md) owns that private path. Linux CI rebuilds `pty.node` inside the matching manylinux 2.28 container because legacy deploy omits that install side effect. Every target copies its native `@vscode/ripgrep` binary beside the executable as the required `-rg` sidecar; pkg runtimes select that sidecar through `process.pkg`, while ordinary Node execution uses `@vscode/ripgrep` directly. macOS uses its target prebuild and also emits the required `-spawn-helper`. The deploy flags preserve the measured runtime layout: `--legacy` is the mandatory path with inject-workspace-packages off; hoisted supplies package directories that staging makes symlink-free; staging removes nested workspace copies only when pnpm records the same dependency identity at the payload root, preserving singleton services; disabling workspace hoisting excludes unrelated workspace source packages; disabling automatic peer installation prevents undeclared peers from expanding the closure; link-workspace-packages selects direct workspace dependencies. [`pnpm-workspace.yaml`](../../../../pnpm-workspace.yaml) overrides the transitive `@deepseek-ai/cosmokit` and `@deepseek-ai/schemastery` semver requests to the pinned vendor sources so legacy deploy never resolves those unpublished names from a registry. Production deployment permits unused workspace patches because development-only tools can be absent from its closure; included-package patch failures still fail deployment. Workspace installs retain strict unused-patch validation. CI: [`.github/workflows/build-exe-for-python-sdk.yml`](../../../../.github/workflows/build-exe-for-python-sdk.yml) runs [installed-wheel validation](../testing/2026-08-23-installed-python-wheel-black-box-ci.md) on Linux/Windows x64 for pull requests and Linux ARM64 plus both macOS architectures for master pushes. The [public publication workflow](../../archived/process/2026-08-11-python-publication-workflow.md) calls it for all five targets; `workflow_dispatch` can still select a subset. Native builds run on linux-x64 / linux-arm64 (`ubuntu-24.04-arm`) / macos-arm64 / macos-x64 (`macos-15-intel`) / win-x64 (`windows-2025`), with `~/.pkg-cache` cached where applicable, and pkg handles macOS ad-hoc signing. Each leg installs the release-shaped SDK and runtime wheels into a clean venv outside the checkout, verifies their package and executable origin, then drives the complete keyless scenario set through the public SDK and direct NDJSON JSON-RPC. Trusted pull requests and master pushes additionally run a real DeepSeek two-turn tool smoke on their selected targets; fork and Dependabot heads receive no key. Linux inspects the executable and native addon's GLIBC requirements and runs an additional manylinux 2.28 smoke, while macOS checks the runtime, ripgrep, and PTY helper architectures and verifies that all three deployment targets fit the wheel tag. A full five-target run retains six artifacts, each containing one release file: the platform-independent SDK wheel and five native runtime wheels; a subset dispatch retains the SDK wheel and selected runtime wheels. Bare executables and source bundles remain intermediate test inputs. [`.gitlab-ci.yml`](../../../../.gitlab-ci.yml) accepts `python-v` tag pipelines whose version matches the root `package.json`, builds one SDK wheel and five native runtime wheels, then a single serialized job checks and publishes all six to the project PyPI registry. The [`python/sdk-runtime` README](../../../../python/sdk-runtime/README.md) owns the Windows target and the explicit exclusion of Windows arm64. diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md index f28f3da059..6e1e2c51b6 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md @@ -48,7 +48,7 @@ exe 的 VFS 内是**构建产物形态的真实包树**(各包的 `lib/` + 真 ### 构建流水线与产物 -[`scripts/build-exe-for-python-sdk.ts`](../../../../scripts/build-exe-for-python-sdk.ts):运行时闭包校验 → `pnpm run build` →(清空后)`pnpm --filter dsh-python-runtime-closure deploy --legacy --prod --config.allow-unused-patches=true --config.node-linker=hoisted --config.auto-install-peers=false --config.link-workspace-packages=true --config.hoist-workspace-packages=false` **直接写入** `python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/`,其中包含作为载体根目录 `runtime-bootstrap.mjs` 的 [`python/sdk-runtime/runtime-bootstrap.mjs`](../../../../python/sdk-runtime/runtime-bootstrap.mjs) → 恢复 legacy deploy 遗漏的直接工作区包,并拒绝剩余的 manifest 缺口 → 将暂存依赖中的符号链接替换为目标文件内容,删除包管理器的 `.bin` 链接,并在仍有任何符号链接时失败 → 验证已部署的 bootstrap,并注入以该文件为 bin 的 pkg 配置及覆盖动态读取 profile、bundle、前端、preset、原生库与配置文件的 assets → 暂存目标平台的 `node-pty` addon → 每个构建目标调用一次 `pkg --sea --compress Brotli` → 将 `deepseek-harness-sdk-runtime--` 写入 `dist-exe/`,并将它与轻量资源清单及 Office skill 资源一同拷回运行时目录。该 bootstrap 由 Python runtime 拥有;普通启动时它调用公开 CLI export,而提供方私有选择会分派到同一个 `@deepseek-ai/dsh-subprocess-local/runner` 核心,不改变 CLI 语法,也不增加另一个可执行文件;[原生 containment 参考](../../../../packages/subprocess/subprocess-local/README.zh.md)负责这条私有路径。Linux CI 会在匹配的 manylinux 2.28 容器中重新构建 `pty.node`,因为 legacy deploy 会遗漏这一安装副作用。每个目标都会把对应的原生 `@vscode/ripgrep` 二进制复制到可执行文件旁,作为必需的 `-rg` 伴随文件;pkg 运行时通过 `process.pkg` 选择该伴随文件,普通 Node 执行则直接使用 `@vscode/ripgrep`。macOS 使用对应目标的预构建产物,并额外生成所需的 `-spawn-helper`。部署标志都有实测依据:未启用 `inject-workspace-packages` 时必须使用 `--legacy`;`hoisted` 提供包目录,再由暂存步骤消除符号链接;只有 pnpm 在载荷根目录记录了相同依赖标识时,暂存步骤才删除对应的嵌套工作区副本,以保留服务单例;关闭工作区提升可排除无关的工作区源码包;关闭对等依赖自动安装可防止未声明的对等依赖扩大闭包;`link-workspace-packages` 选择直接工作区依赖。[`pnpm-workspace.yaml`](../../../../pnpm-workspace.yaml) 将传递的 `@deepseek-ai/cosmokit` 与 `@deepseek-ai/schemastery` semver 请求覆盖到固定的 vendor 源码,使 legacy deploy 不会从注册表解析这些未发布名称。 生产部署允许未使用的工作区补丁,因为开发工具可能不属于运行时闭包;闭包内包的补丁应用失败仍会中止部署。工作区安装继续严格校验未使用的补丁。 +[`scripts/build-exe-for-python-sdk.ts`](../../../../scripts/build-exe-for-python-sdk.ts):运行时闭包校验 → `pnpm run build` →(清空后)`pnpm --filter dsh-python-runtime-closure deploy --legacy --prod --config.allow-unused-patches=true --config.node-linker=hoisted --config.auto-install-peers=false --config.link-workspace-packages=true --config.hoist-workspace-packages=false` **直接写入** `python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/`,其中包含作为载体根目录 `runtime-bootstrap.mjs` 的 [`python/sdk-runtime/runtime-bootstrap.mjs`](../../../../python/sdk-runtime/runtime-bootstrap.mjs) → 恢复 legacy deploy 遗漏的直接工作区包,并拒绝剩余的 manifest 缺口 → 将暂存依赖中的符号链接替换为目标文件内容,删除包管理器的 `.bin` 链接,并在仍有任何符号链接时失败 → 验证已部署的 bootstrap,并注入以该文件为 bin 的 pkg 配置及覆盖动态读取 profile、bundle、前端、preset、原生库与配置文件的 assets → 暂存目标平台的 `node-pty` addon → 每个构建目标调用一次 `pkg --sea --compress Brotli`,其中 vendor 的 pkg 补丁把 Brotli 质量固定为 6:pkg 不传参数时默认质量 11,同一载荷实测 132.8 s,质量 6 为 3.2 s,产物大 12% → 将 `deepseek-harness-sdk-runtime--` 写入 `dist-exe/`,并将它与轻量资源清单及 Office skill 资源一同拷回运行时目录。该 bootstrap 由 Python runtime 拥有;普通启动时它调用公开 CLI export,而提供方私有选择会分派到同一个 `@deepseek-ai/dsh-subprocess-local/runner` 核心,不改变 CLI 语法,也不增加另一个可执行文件;[原生 containment 参考](../../../../packages/subprocess/subprocess-local/README.zh.md)负责这条私有路径。Linux CI 会在匹配的 manylinux 2.28 容器中重新构建 `pty.node`,因为 legacy deploy 会遗漏这一安装副作用。每个目标都会把对应的原生 `@vscode/ripgrep` 二进制复制到可执行文件旁,作为必需的 `-rg` 伴随文件;pkg 运行时通过 `process.pkg` 选择该伴随文件,普通 Node 执行则直接使用 `@vscode/ripgrep`。macOS 使用对应目标的预构建产物,并额外生成所需的 `-spawn-helper`。部署标志都有实测依据:未启用 `inject-workspace-packages` 时必须使用 `--legacy`;`hoisted` 提供包目录,再由暂存步骤消除符号链接;只有 pnpm 在载荷根目录记录了相同依赖标识时,暂存步骤才删除对应的嵌套工作区副本,以保留服务单例;关闭工作区提升可排除无关的工作区源码包;关闭对等依赖自动安装可防止未声明的对等依赖扩大闭包;`link-workspace-packages` 选择直接工作区依赖。[`pnpm-workspace.yaml`](../../../../pnpm-workspace.yaml) 将传递的 `@deepseek-ai/cosmokit` 与 `@deepseek-ai/schemastery` semver 请求覆盖到固定的 vendor 源码,使 legacy deploy 不会从注册表解析这些未发布名称。 生产部署允许未使用的工作区补丁,因为开发工具可能不属于运行时闭包;闭包内包的补丁应用失败仍会中止部署。工作区安装继续严格校验未使用的补丁。 CI 使用 [`.github/workflows/build-exe-for-python-sdk.yml`](../../../../.github/workflows/build-exe-for-python-sdk.yml):[安装后 wheel 包验证](../testing/2026-08-23-installed-python-wheel-black-box-ci.zh.md)在拉取请求上运行 Linux/Windows x64,在 master 推送上运行 Linux ARM64 与两种 macOS 架构。[公开发布工作流](../../archived/process/2026-08-11-python-publication-workflow.md)调用它构建全部五个目标;`workflow_dispatch` 仍可选择部分目标。linux-x64、linux-arm64(`ubuntu-24.04-arm`)、macos-arm64、macos-x64(`macos-15-intel`)与 win-x64(`windows-2025`)分别进行原生构建,并在适用平台缓存 `~/.pkg-cache`;macOS 的 ad-hoc 签名由 pkg 处理。每个平台都把发布形态的 SDK wheel 包与运行时 wheel 包安装到 checkout 外的干净 venv,证明包与可执行文件来源,再通过公开 SDK 与直接 NDJSON JSON-RPC 运行完整 keyless 场景。可信拉取请求与 master 推送还会在各自选定的目标上运行真实 DeepSeek 双轮工具冒烟测试;fork 与 Dependabot head 不会获得密钥。Linux 会检查可执行文件和原生 addon 各自的 GLIBC 依赖,并额外运行 manylinux 2.28 冒烟测试;macOS 则检查 runtime、ripgrep 与 PTY helper 的架构,并验证三个载荷的部署目标都符合 wheel 包标签。完整构建五个目标时保留 6 个产物,每个产物只含一个发布文件:平台无关的 SDK wheel 包与 5 个原生运行时 wheel 包;手动选择部分目标时保留 SDK wheel 与所选运行时 wheel。裸 exe 与源码包只作为测试中间输入。[`.gitlab-ci.yml`](../../../../.gitlab-ci.yml) 只接受版本与根目录 `package.json` 匹配的 `python-v` 标签流水线,构建一个 SDK wheel 包和 5 个原生运行时 wheel 包,再由单个串行任务校验并将这 6 个文件发布到项目的 PyPI 注册表。[`python/sdk-runtime` README](../../../../python/sdk-runtime/README.zh.md)负责 Windows 目标及对 Windows arm64 的明确排除。 diff --git a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.i18n.yaml index 23935ef2ad..93feec2b95 100644 --- a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.i18n.yaml @@ -27,14 +27,14 @@ en: d5d0d6a57a4fa581 zh: 265973b157f957d9 /agent-note-session-history-control-state-and-remote-event-transport/decision/session-controller: - en: e338ac27490a380f - zh: 12600011ec742e5b + en: f432480a52414d56 + zh: 15a3f175b69cdb53 /agent-note-session-history-control-state-and-remote-event-transport/decision/session-controller/activation-policy: - en: 534dcc62a26d305e - zh: 03d64abc0a46bbec + en: 03e24cdee8519a92 + zh: 82dc02eb26d7d7f4 /agent-note-session-history-control-state-and-remote-event-transport/decision/session-controller/session-journal: - en: bb710f8cf35f2028 - zh: aae2cfb8cd848069 + en: 4de2965717900b96 + zh: 1d129003824fa6bd /agent-note-session-history-control-state-and-remote-event-transport/decision/session-controller/session-live-control: en: a11d627cd68650c3 zh: 9aff565b9f712853 diff --git a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.md b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.md index de05a0e62b..ee43b551eb 100644 --- a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.md +++ b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.md @@ -139,11 +139,11 @@ If a page request is canceled with its physical carrier generation, the journal `packages/api/session-controller` provides Host `ctx.sessionController` and the generated `ctx.remote.session` namespace. -It owns Session list, search, create, selectModel, rename, fork, prompt, attachment, updateQueue, cancel, page, follow, and control. The Host-generation model catalog is exposed separately through `session/modelCatalog` because it is not Session-specific. +It owns Session list, search, create, selectModel, rename, fork, prompt, attachment, updateQueue, cancel, `events`, the deprecated `page`, `follow`, `control`, plus `observeEvent`, `projections`, `observeProjections`, `state`, `observeState`, and `wait`. The Host-generation model catalog is exposed separately through `session/modelCatalog` because it is not Session-specific. The package separates agent, commands, control, history, and list controllers internally, but Session identity resolution, activation policy, subagent ownership, and Remote error projection have one public owner. -Other Host Remote namespaces reuse the same identity rules through `ctx.sessionController.inspect()` or `resolveAgent()`; they do not retain a second Session resolver. +Other Host Remote namespaces reuse the same resume-capable identity rules through `ctx.sessionController.resolveAgent()`; they do not retain a second Session resolver. #### Activation policy @@ -157,7 +157,8 @@ Each method explicitly selects a cold inspection, live-only lookup, or resume-ca | `session.page(address)` | attached Session or persistence log | Never resumes an Agent | | `session.follow(address)` | one live or prepared observation carrying the opening page and projections | Publishes the snapshot first, then promotes an ordinary cold Session once in the background | | `session.control()` | current attached Agents, pending registry, and process-local registries | Baseline and reconnect do not resume an Agent | -| `session.attachment`, fork source read | authorized durable Session data | A read does not resume an Agent | +| Fork source read | authorized durable Session data | A read does not resume an Agent | +| `session.attachment` | attachment store under the [image access rule](2026-10-23-store-scoped-image-reads.md) | A read does not resume an Agent | | `session.updateQueue` | live Agent or ordinary persisted Session | Resumes an ordinary cold Session before mutating its Inbox | | `session.cancel` | only the current live Agent | Does not resume vanished state | | `models`, `selectModel`, `rename`, `prompt` | command resolves the target Session | Resumes only when the method explicitly permits it | @@ -173,9 +174,9 @@ Reading titles, lists, and projections does not require an Agent. An observation #### Session journal -`session.page` returns a history window clipped on message boundaries with contiguous internal sequence numbers. Every request must carry an explicit `throughSeq`; this value comes from the corresponding `session.follow` generation's opening cursor and fixes the read at the same log cut. A tail page without `beforeSeq` must end exactly at `throughSeq`, where `-1` denotes an empty log. `beforeSeq` only selects an older page before that cut and cannot replace the synchronization cursor. `maxMessages` limits user/assistant message count without dropping chunks, tools, or state events between those messages. +`session.events` returns a history window clipped on message boundaries with contiguous internal sequence numbers. `throughSeq` is optional: when omitted, the read selects the observed log end and returns it as the page's inclusive `cursor`; a supplied value fixes the read at that cut. A page without `beforeSeq` ends exactly at the selected cut, where `-1` denotes an empty log. `beforeSeq` only selects an older page before that cut and cannot replace the synchronization cursor. `maxMessages` limits user/assistant message count without dropping chunks, tools, or state events between those messages. The deprecated `session.page` entry returns the same type. -The tail page also carries a projection baseline no later than `throughSeq`; older pages carry only historical entries. The Client merges pages and subsequent live control updates by projection watermark. +A page carries only its records, `hasMore`, and inclusive `cursor`; a projection baseline comes from a follow opening snapshot or the control stream, never from a page. The Client merges pages and subsequent live control updates by projection watermark. Ordinary Sessions and direct subagents use one `SessionAddress` protocol. A direct-subagent address carries parent Session, child Session, and mode; a cold Host read verifies durable ownership and descriptor rather than authorizing access from the child id alone. diff --git a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.zh.md b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.zh.md index 004da80fee..9df5c55701 100644 --- a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.zh.md @@ -139,11 +139,11 @@ repair 期间旧 window 保持可读;page 与期间积累的 live entries 拼 `packages/api/session-controller` 提供 Host `ctx.sessionController` 与生成的 `ctx.remote.session` namespace。 -它拥有 Session list、search、create、selectModel、rename、fork、prompt、attachment、updateQueue、cancel、page、follow 与 control。Host generation 的 model catalog 通过独立的 `session/modelCatalog` 公开,因为它不属于特定 Session。 +它拥有 Session list、search、create、selectModel、rename、fork、prompt、attachment、updateQueue、cancel、`events`、已弃用的 `page`、`follow`、`control`,以及 `observeEvent`、`projections`、`observeProjections`、`state`、`observeState` 与 `wait`。Host generation 的 model catalog 通过独立的 `session/modelCatalog` 公开,因为它不属于特定 Session。 包内的 agent、commands、control、history 与 list controller 分开实现,但 Session 身份解析、激活策略、subagent ownership 和 Remote 错误投影只有一个公开 owner。 -其他 Host Remote namespace 通过 `ctx.sessionController.inspect()` 或 `resolveAgent()` 复用同一身份规则,不保留第二份 Session resolver。 +其他 Host Remote namespace 通过 `ctx.sessionController.resolveAgent()` 复用同一套允许恢复 Session 的身份规则,不保留第二份 Session resolver。 #### 激活策略 @@ -157,7 +157,8 @@ Session Remote 方法传递 `SessionId` 或 `SessionAddress`,不靠参数类 | `session.page(address)` | attached Session 或 persistence 日志 | 永不恢复 Agent | | `session.follow(address)` | 一份携带 opening page 与 projection 的 live 或 prepared observation | 先发布 snapshot,再在后台把普通冷 Session 提升一次 | | `session.control()` | 当前 attached Agent、pending registry 与进程内 registry | baseline 与重连不恢复 Agent | -| `session.attachment`、fork 源读取 | 已授权的持久 Session 数据 | 读取不恢复 Agent | +| Fork 源读取 | 已授权的持久 Session 数据 | 读取不恢复 Agent | +| `session.attachment` | 按[图片访问规则](2026-10-23-store-scoped-image-reads.zh.md)读取附件存储 | 读取不恢复 Agent | | `session.updateQueue` | live Agent 或普通持久 Session | 修改 Inbox 前恢复普通冷 Session | | `session.cancel` | 仅命中当前 live Agent | 不为已消失状态恢复 Agent | | `models`、`selectModel`、`rename`、`prompt` | 命令解析目标 Session | 仅按方法约定显式恢复 | @@ -173,9 +174,9 @@ Session Remote 方法传递 `SessionId` 或 `SessionAddress`,不靠参数类 #### Session 日志 -`session.page` 返回一段按消息边界裁剪、内部 seq 连续的历史窗口。每个请求必须显式携带 `throughSeq`;该值来自对应 `session.follow` generation 的 opening cursor,并把本次读取固定在同一个日志切点。无 `beforeSeq` 的 tail page 必须精确结束于 `throughSeq`,其中 `-1` 表示空日志;`beforeSeq` 只选择该切点之前的更早页面,不能替代同步 cursor。`maxMessages` 限制 user/assistant 消息数,不丢弃这些消息之间的 chunk、tool 或状态事件。 +`session.events` 返回一段按消息边界裁剪、内部 seq 连续的历史窗口。`throughSeq` 可省略:省略时选取观察到的日志末尾,并把该切点作为页面的 inclusive `cursor` 返回;显式提供时把本次读取固定在该切点。无 `beforeSeq` 的 page 精确结束于所选切点,其中 `-1` 表示空日志;`beforeSeq` 只选择该切点之前的更早页面,不能替代同步 cursor。`maxMessages` 限制 user/assistant 消息数,不丢弃这些消息之间的 chunk、tool 或状态事件。已弃用的 `session.page` 入口返回同一类型。 -tail page 同时携带不晚于 `throughSeq` 的 projection baseline;旧页只携带历史 entries。Client 以 projection watermark 合并 page 与后续 live control 更新。 +page 只携带记录、`hasMore` 和 inclusive `cursor`;projection baseline 来自 follow 的开场快照或 control 流,不来自 page。Client 以 projection watermark 合并 page 与后续 live control 更新。 普通 Session 与 direct subagent 使用同一个 `SessionAddress` 协议。direct subagent 地址同时携带父 Session、子 Session 与 mode,Host 冷读时验证持久 ownership 和 descriptor,不能只凭 child id 越权读取。 diff --git a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.i18n.yaml index e70e858963..86b5f42ac4 100644 --- a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.i18n.yaml @@ -51,8 +51,8 @@ en: 51f99cfca9c4c808 zh: ce95bab241d306f7 /agent-note-client-derived-presentation-from-raw-session-tool-events/host-design: - en: 16fd2b3e545ede21 - zh: 4d28f52132495441 + en: d5e5d1376dc42558 + zh: c2f302b2a5d1de39 /agent-note-client-derived-presentation-from-raw-session-tool-events/host-design/performance-constraints: en: 102b14e3eb9367ff zh: d391099dbc41db24 diff --git a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.md b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.md index 8a0c4ea6fc..8c32436c6a 100644 --- a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.md +++ b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.md @@ -195,9 +195,9 @@ The Client narrows `meta` locally at runtime. Renaming `presentationMeta` to mor ## Host Design -After obtaining source events, `SessionHistoryController.page()` performs only pagination and the existing projection-baseline calculation. Attached Sessions use the projection registry snapshot; detached Sessions use its restore path over the inspected log. History does not mount a preset to change the registered projection set. +After obtaining source events, `HistoryController.history()` performs only pagination and requests projections only for a subagent address that needs descriptor validation. Attached Sessions use the projection registry snapshot; detached Sessions use its restore path over the inspected log. History does not mount a preset to change the registered projection set. -`SessionHistoryController.follow()` retains listener-first setup, opening cursors, gap-free replay, live buffering, cancellation, and teardown. It maintains no additional state for tool events. +`WebController.follow()` retains listener-first setup, opening cursors, gap-free replay, live buffering, cancellation, and teardown. It maintains no additional state for tool events. The controller has no `presenterScopeFor()`, `viewFor()`, `backscanArgs()`, `parseToolCall()`, or `jsonView()` path. Page state contains no presenter scope or argument resolver; follow state contains no `openCalls`, `fallbackEvents`, or presentation argument resolver. Each page/follow event is wrapped only as `{event}` while addressing, ownership, cursor, sequence, and projection logic remains intact. diff --git a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.zh.md b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.zh.md index 2dd4ad8bc9..6ba3e040bd 100644 --- a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.zh.md @@ -195,9 +195,9 @@ Client 对 `meta` 做局部运行时收窄。是否把 `presentationMeta` 改名 ## Host 端设计 -`SessionHistoryController.page()` 在取得 source events 后只执行分页与现有 projection baseline 计算。attached Session 使用 projection registry snapshot;detached Session 使用该 registry 对 inspected log 的 restore 路径。history 不通过挂载 preset 改变已注册的 projection 集合。 +`HistoryController.history()` 在取得 source events 后只执行分页,并且只有需要校验 descriptor 的 subagent 地址才请求投影。attached Session 使用 projection registry snapshot;detached Session 使用该 registry 对 inspected log 的 restore 路径。history 不通过挂载 preset 改变已注册的 projection 集合。 -`SessionHistoryController.follow()` 保留 listener-first、opening cursor、gap-free replay、live buffering、取消和 teardown;它不为工具事件维护额外状态。 +`WebController.follow()` 保留 listener-first、opening cursor、gap-free replay、live buffering、取消和 teardown;它不为工具事件维护额外状态。 Controller 不存在 `presenterScopeFor()`、`viewFor()`、`backscanArgs()`、`parseToolCall()` 或 `jsonView()` 路径。page state 不含 presenter scope 或参数 resolver;follow state 不含 `openCalls`、`fallbackEvents` 或 presentation 参数 resolver。每个 page/follow event 只包装成 `{event}`,地址、ownership、cursor、seq 与 projection 逻辑保持完整。 diff --git a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.i18n.yaml index bd2626e850..c67dff0722 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.i18n.yaml @@ -15,17 +15,17 @@ en: 480284ae1a6ce210 zh: d42c72ada9f019f8 /agent-note-session-observations-and-projection-owned-client-state/decision/observation-is-the-point-read-unit: - en: fac92f8547482a49 - zh: 60240c47fbe4611f + en: 283136ae36512767 + zh: e342b446c77ae300 /agent-note-session-observations-and-projection-owned-client-state/decision/source-resolution-and-lifetime: - en: e550ae9892474276 - zh: fb6a2d9e91ebd4d9 + en: bced4b90cb03525d + zh: b0c1ca4bf1064f89 /agent-note-session-observations-and-projection-owned-client-state/decision/projection-execution-boundary: - en: 148de86941b90f41 - zh: c065a8e96e28b9d7 + en: b3b235fa0250868a + zh: 0bb5eedf14cdafee /agent-note-session-observations-and-projection-owned-client-state/decision/read-audiences: - en: 888f62659f4d868d - zh: e74491e8c85046ee + en: e394e9480340f69c + zh: 7eea994ee9fa380d /agent-note-session-observations-and-projection-owned-client-state/decision/replayable-client-facts-are-projection-owned: en: efded09f0cd30a8e zh: 5e16580a39ff3359 @@ -48,11 +48,11 @@ en: 8d699dfc22ab5c5f zh: 8dcd9fc6bd1594db /agent-note-session-observations-and-projection-owned-client-state/verification: - en: df17217023668428 - zh: 88f7da4deffc6bf9 + en: 29f364d1031b7d85 + zh: 2b193ceb52fb0406 /agent-note-session-observations-and-projection-owned-client-state/alternatives-considered: - en: a25138b4298cda16 - zh: 92799a9bd8867d47 + en: 90574351058d5d8c + zh: 6aa514cf47495ed2 /agent-note-session-observations-and-projection-owned-client-state/consequences: en: e1f8bd8fa68de603 zh: 5afcd06f2611bc1e diff --git a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.md b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.md index 523122c9ae..530aeb36e1 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.md +++ b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.md @@ -24,7 +24,7 @@ The two ownership rules meet at the observation's projection snapshot. Lightweig flowchart LR List["list / search"] --> Corpus["SessionQuery corpus"] Follow["follow"] --> Observe["observeSession"] - Page["page / attachment / fork"] --> Observe + Page["page / fork"] --> Observe Subagent["subagent list / continuation"] --> Observe Corpus --> Cache["projection cache hints"] Cache --> ClientList["Client Session list"] @@ -46,7 +46,7 @@ flowchart LR `SessionQueryEngine.observeSession(sessionId, options)` returns a disposable `SessionObservation` containing one source kind, header, contiguous event prefix, cursor, optional projection snapshot, and the durable revision for a prepared source. An attached Session wins. Otherwise the reader's own prepared cache — keyed by `stat().revision` and pinned by observation leases — serves the cold Session, sharing one persistence read (`open(id, 'read')` + `read`) across concurrent observations, including an in-flight cold load. -Every owner disposes its observation. `retain()` creates another lease over the same cut, which lets `session.follow` publish a snapshot and then transfer that exact prepared source to background Agent promotion without rereading the log. A live Session that appears during cold resolution wins before publication; a disappeared live source is retried as cold. +Every owner disposes its observation. `retain()` creates another lease over the same cut, which lets `session.follow` transfer that exact prepared source to background Agent promotion before delivering the snapshot, without rereading the log. A live Session that appears during cold resolution wins before publication; a disappeared live source is retried as cold. ### Source resolution and lifetime @@ -56,7 +56,7 @@ Live preference is checked both before and after a cold borrow. The second check Persistence absence maps to Session-not-found only after no attached Session exists. Durable corruption, source-identity conflict, cancellation, and operational persistence failure remain distinct `SessionQueryError` outcomes so API owners can preserve their own public error vocabulary without duplicating source detection. -The observation owns no mutation authority. Its event array is an immutable prefix, and its prepared Session remains unpublished. Promotion is an explicit ownership transfer performed by the Session Controller after it has emitted the opening snapshot; other readers cannot turn an observation into a live Agent. +The observation owns no mutation authority. Its event array is an immutable prefix, and its prepared Session remains unpublished. Promotion is an explicit ownership transfer the Session Controller starts once the opening is computed, before delivering it; other readers cannot turn an observation into a live Agent. Projection work is deliberately `all | none`. `all` computes every registered projection at the observation's event cursor; `none` leaves projection state untouched. There is no per-key preparation state, `projectionKeys` mode, or cached `viewedState`/`viewedValue` layer. A publisher may filter the completed values for an audience, but the underlying observation is never partly projected. @@ -72,7 +72,7 @@ The registry owns fold state; each domain owns its `init`, `apply`, `view`, sche Corpus listing remains a separate lightweight operation. `listSessions()` returns live-preferred headers without materializing every log. Session list first uses live projection state or durable projection-cache rows. Subagent discovery reads parent-catalog projections through exact observations. Session list may take one complete observation for an individually stored artifact within its configured small-log limit when cached metadata cannot establish whether it is blank; a large or unreadable cache miss remains visible with unknown hints. -`session.follow` publishes a required opening snapshot containing header, cursor, the initial event window, and a complete projection baseline. Reconnect replaces the previous generation from another complete snapshot. `session.page` is reserved for older-history reads and gap repair. Observation-only reads never activate an Agent; only an ordinary follow may retain its prepared observation and request promotion after the opening snapshot has been delivered. +`session.follow` publishes a required opening snapshot containing header, cursor, the initial event window, and a complete projection baseline. Reconnect replaces the previous generation from another complete snapshot. `session.page` supports current or fixed-cut history reads, older-history reads, and gap repair. Observation-only reads never activate an Agent; only an activation-enabled ordinary Follow may retain its prepared observation and request promotion once the opening snapshot is computed, before it is delivered. The [snapshot and subscription decision](2026-10-21-session-history-stream-and-snapshot.md) defines the Controller composition and passive subscription semantics. ### Read audiences @@ -82,9 +82,10 @@ Each public operation chooses one query and projection policy. The choice is par |---|---|---|---| | `session.list` | Corpus headers, live state, and cached rows; bounded small-log fallback | Partial hints, or one full small-log observation | Never | | `session.search` | Corpus authorization plus the configured search provider | None for result listing | Never | -| `session.follow` | One exact observation | All, carried in the opening snapshot | Ordinary cold Session only, after snapshot delivery | +| `session.follow` | One exact observation | All, carried in the opening snapshot | Only with `activate: true`, for an ordinary cold Session once the opening is computed, before delivery | | `session.page` | One exact observation | None, except projection-backed subagent authorization | Never | -| Attachment and fork source | One exact observation | None unless authorization requires it | Never for the source | +| Fork source | One exact observation | None unless authorization requires it | Never for the source | +| Attachment | Direct store read under the [image access rule](2026-10-23-store-scoped-image-reads.md) | None | Never | | Subagent list and continuation | Parent-catalog observations for listing; target observations for continuation | All; listing consumes catalog values, continuation consumes identity and inherited values | Never for listing; continuation follows its explicit command semantics | ### Replayable Client facts are projection-owned @@ -171,7 +172,7 @@ These rules apply to new Session-derived Client state even when a direct event s ## Verification -Persistence and SessionQuery tests pin shared cold loading, cancellation, live-source races, retained observations, disposal, and all-or-none projection calculation. Session Controller and Gateway tests pin snapshot-first opening, replacement reconnect, older-page reads, gap repair, list-cache hints, bounded small-log fallback, and promotion after snapshot delivery. +Persistence and SessionQuery tests pin shared cold loading, cancellation, live-source races, retained observations, disposal, and all-or-none projection calculation. Session Controller and Gateway tests pin snapshot-first opening, replacement reconnect, older-page reads, gap repair, list-cache hints, bounded small-log fallback, and promotion once the opening is computed. Client tests pin higher-sequence-wins projection storage, title updates, model catalog and selection readiness, preset roster refresh and Session-specific selection, and subagent loading without transient offline presentation. Subagent tests pin parent-catalog order, recursive traversal, branch diagnostics, cancellation, fork isolation, and no Agent activation during listing. @@ -179,7 +180,7 @@ Client tests pin higher-sequence-wins projection storage, title updates, model c **Keep source resolution in each consumer.** Rejected because every caller would continue to implement its own live race, persistence error mapping, preparation lifetime, cancellation, and projection cut, allowing both duplicate work and inconsistent results. -**Activate an Agent for every exact read.** Rejected because list, history, attachment, search, and subagent inspection are read operations. Activation loads plugins and changes process state, and it has no natural retirement point for pagination or catalog reads. +**Activate an Agent for every exact read.** Rejected because list, history, search, and subagent inspection are read operations. Activation loads plugins and changes process state, and it has no natural retirement point for pagination or catalog reads. **Prepare only requested projection keys.** Rejected because a partially projected Session creates another lifecycle state that every cache, restore, plugin-registration, and caller path must track. Projection units are pure and few; computing all registered units for an exact observation is simpler than maintaining `O(E*k)` partial state instead of `O(E*P)` complete state. diff --git a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.zh.md b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.zh.md index 6639047731..62ac9db852 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.zh.md @@ -24,7 +24,7 @@ Session 精确读取使用可保留的 `SessionObservation`,向 Client 暴露 flowchart LR List["list / search"] --> Corpus["SessionQuery corpus"] Follow["follow"] --> Observe["observeSession"] - Page["page / attachment / fork"] --> Observe + Page["page / fork"] --> Observe Subagent["subagent list / continuation"] --> Observe Corpus --> Cache["projection cache hints"] Cache --> ClientList["Client Session list"] @@ -46,7 +46,7 @@ flowchart LR `SessionQueryEngine.observeSession(sessionId, options)` 返回可 dispose(资源释放)的 `SessionObservation`,其中包含同一份 source kind、header、连续事件前缀、cursor、可选 projection snapshot,以及 prepared source 的持久化 revision。已挂载 Session 优先;否则由读取方自己的 prepared cache——以 `stat().revision` 为键、由 observation lease 固定——提供冷 Session,让并发 observation 共享同一次持久化读取(`open(id, 'read')` + `read`),包括尚未完成的冷加载。 -每个 owner 都会 dispose 自己的 observation。`retain()` 为同一切面创建另一份 lease,使 `session.follow` 能够先发布 snapshot,再把完全相同的 prepared source 转交给后台 Agent promotion,而无需重读日志。冷解析期间出现的 live Session 会在发布前胜出;已经消失的 live source 会按 cold source 重试。 +每个 owner 都会 dispose 自己的 observation。`retain()` 为同一切面创建另一份 lease,使 `session.follow` 能把完全相同的 prepared source 转交给后台 Agent promotion,并在交付 snapshot 前启动它,而无需重读日志。冷解析期间出现的 live Session 会在发布前胜出;已经消失的 live source 会按 cold source 重试。 ### 数据源解析与生命周期 @@ -56,7 +56,7 @@ flowchart LR 只有在不存在已挂载 Session 后,persistence absence 才映射为 Session-not-found。持久数据损坏、source identity 冲突、取消和 persistence 操作失败分别保留不同的 `SessionQueryError`,API owner 因而可以维持自身公开错误词汇,而不用重复数据源判定。 -Observation 不拥有任何 mutation 权限。其事件数组是不可变前缀,prepared Session 保持未发布。Promotion 是 Session Controller 在 opening snapshot 发出后执行的显式 ownership transfer;其他读方不能把 observation 变成 live Agent。 +Observation 不拥有任何 mutation 权限。其事件数组是不可变前缀,prepared Session 保持未发布。Promotion 是 Session Controller 在 opening 计算完成后、交付前启动的显式 ownership transfer;其他读方不能把 observation 变成 live Agent。 Projection 工作明确只有 `all | none` 两种模式。`all` 在 observation 的事件 cursor 上计算所有已注册 projection;`none` 完全不触碰 projection 状态。系统不存在按 key preparation 的状态、`projectionKeys` 模式或额外的 `viewedState`/`viewedValue` cache。发布方可以按 audience 筛选已完成的值,但底层 observation 不会处于只算完部分 projection 的状态。 @@ -72,7 +72,7 @@ Registry 拥有 fold state;各领域拥有自己的 `init`、`apply`、`view` 语料库 list 仍是独立的轻量操作。`listSessions()` 返回 live-preferred header,而不物化每份日志。Session list 先读取 live projection 状态或持久 projection-cache row。Subagent 发现通过精确 observation 读取父目录 projection。当 cache 无法判断 Session 是否为空,且该 Session 拥有的独立产物未超过配置的小日志限制时,Session list 可以执行一次完整 observation;大型或不可读的 cache miss 仍以 hints 未知但 row 可见的方式返回。 -`session.follow` 发布必需的 opening snapshot,其中包含 header、cursor、首个事件窗口和完整 projection baseline。重连使用另一份完整 snapshot 替换上一 generation。`session.page` 仅用于旧历史读取与 gap repair。只读 observation 不激活 Agent;只有普通 follow 可以保留 prepared observation,并在 opening snapshot 已交付后请求 promotion。 +`session.follow` 发布必需的 opening snapshot,包含 header、cursor、初始事件窗口与完整 projection baseline。重连通过另一份完整快照替换之前的 generation。`session.page` 支持当前或固定切点的历史读取、旧历史分页及缺口修复。只读 Observation 不激活 Agent;只有显式启用激活的普通 Follow 可以在开场计算完成后、交付之前 retain prepared observation 并请求提升。[快照与订阅决策](2026-10-21-session-history-stream-and-snapshot.zh.md)定义 Controller 组合和纯订阅语义。 ### 读取 audience @@ -82,9 +82,10 @@ Registry 拥有 fold state;各领域拥有自己的 `init`、`apply`、`view` |---|---|---|---| | `session.list` | Corpus header、live state 和 cached row;有界小日志 fallback | 部分 hints,或一次完整小日志 observation | 从不 | | `session.search` | Corpus 鉴权加已配置 search provider | 结果列表不计算 | 从不 | -| `session.follow` | 一份精确 observation | 全算,并由 opening snapshot 携带 | 仅普通 cold Session,且在 snapshot 交付后 | +| `session.follow` | 一份精确 observation | 全算,并由 opening snapshot 携带 | 仅 `activate: true` 的普通 cold Session,且在开场计算完成后、交付前 | | `session.page` | 一份精确 observation | 不计算,但 projection-backed subagent 鉴权除外 | 从不 | -| Attachment 与 fork source | 一份精确 observation | 鉴权不要求时不计算 | source 从不激活 | +| Fork source | 一份精确 observation | 鉴权不要求时不计算 | source 从不激活 | +| Attachment | 按[图片访问规则](2026-10-23-store-scoped-image-reads.zh.md)直接读取存储 | 不计算 | 从不 | | Subagent list 与 continuation | Listing 观察父目录;continuation 观察目标 | 全算;listing 消费目录值,continuation 消费身份与继承值 | Listing 从不;continuation 遵循显式命令语义 | ### 可回放的 Client 事实归 projection 所有 @@ -171,7 +172,7 @@ Client 本地交互状态也继续留在本地:loading 和 error 状态、打 ## 验证 -Persistence 与 SessionQuery 测试固定共享冷加载、取消、live-source race、retained observation、dispose 和 all-or-none projection 计算。Session Controller 与 Gateway 测试固定 snapshot-first opening、replacement reconnect、旧分页读取、gap repair、list-cache hints、小日志有界 fallback,以及 snapshot 交付后的 promotion。 +Persistence 与 SessionQuery 测试固定共享冷加载、取消、live-source race、retained observation、dispose 和 all-or-none projection 计算。Session Controller 与 Gateway 测试固定 snapshot-first opening、replacement reconnect、旧分页读取、gap repair、list-cache hints、小日志有界 fallback,以及开场计算完成后的 promotion。 Client 测试固定 higher-sequence-wins projection store、title 更新、model catalog 与 selection readiness、preset roster refresh 与 Session 专属选择,以及不会短暂展示离线状态的 subagent loading。Subagent 测试固定父目录顺序、递归遍历、分支诊断、取消、fork 隔离,以及 listing 期间不激活 Agent。 @@ -179,7 +180,7 @@ Client 测试固定 higher-sequence-wins projection store、title 更新、model **由各消费方继续解析数据源。** 否决,因为每个调用方都需要重复实现 live race、persistence error mapping、preparation lifetime、cancellation 和 projection cut,既会重复工作,也会产生不一致结果。 -**每次精确读取都激活 Agent。** 否决,因为 list、history、attachment、search 与 subagent inspection 都是读取操作。Activation 会加载插件并改变进程状态,也没有适合分页或 catalog 读取的自然退出点。 +**每次精确读取都激活 Agent。** 否决,因为 list、history、search 与 subagent inspection 都是读取操作。Activation 会加载插件并改变进程状态,也没有适合分页或 catalog 读取的自然退出点。 **只 prepare 被请求的 projection key。** 否决,因为只完成部分 projection 的 Session 会增加一种生命周期状态,所有 cache、restore、plugin registration 和调用路径都必须追踪它。Projection unit 数量少且为纯函数;精确 observation 计算全部已注册 unit,比为了 `O(E*k)` 而维护部分状态、取代 `O(E*P)` 完整状态更简单。 diff --git a/.agents/notes/implemented/architecture/2026-09-05-read-only-session-migration-preparation.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-05-read-only-session-migration-preparation.i18n.yaml index 93080791e0..ed47cbd168 100644 --- a/.agents/notes/implemented/architecture/2026-09-05-read-only-session-migration-preparation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-05-read-only-session-migration-preparation.i18n.yaml @@ -30,8 +30,8 @@ en: 9d2d50cb76754b74 zh: 9ceed3652475f18d /agent-note-historical-session-reads-prepare-before-write-publication/decision/follow-and-agent-promotion: - en: 692c29db3e7ab07e - zh: 7da0cfdbc80f407d + en: 46da45b9b63e7298 + zh: 3d55099479a80bd9 /agent-note-historical-session-reads-prepare-before-write-publication/problem-to-solution-mapping: en: e067e187cd4d0a8c zh: b0c79b635a637296 diff --git a/.agents/notes/implemented/architecture/2026-09-05-read-only-session-migration-preparation.md b/.agents/notes/implemented/architecture/2026-09-05-read-only-session-migration-preparation.md index 081044e34d..4948e31a32 100644 --- a/.agents/notes/implemented/architecture/2026-09-05-read-only-session-migration-preparation.md +++ b/.agents/notes/implemented/architecture/2026-09-05-read-only-session-migration-preparation.md @@ -102,7 +102,7 @@ No external caller can append before the handle exists. `append`, `flush`, and ` ### Follow and Agent promotion -`session.follow` opens history through the read path, restores the Session and projections, emits the opening snapshot, and then starts Agent promotion. Agent resume uses write open, so it waits for publication before the Agent accepts a new turn. History visibility and write readiness are separate timing points without introducing an unpublished append state. +`session.follow` opens history through the read path, restores the Session and projections, starts Agent promotion from the separately retained Observation when the caller requests activation, and then delivers the opening snapshot. Agent resume uses write open, so it waits for publication before the Agent accepts a new turn. History visibility and write readiness are separate timing points without introducing an unpublished append state. ## Problem-to-solution mapping diff --git a/.agents/notes/implemented/architecture/2026-09-05-read-only-session-migration-preparation.zh.md b/.agents/notes/implemented/architecture/2026-09-05-read-only-session-migration-preparation.zh.md index 7406e7cf31..41a87efa86 100644 --- a/.agents/notes/implemented/architecture/2026-09-05-read-only-session-migration-preparation.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-05-read-only-session-migration-preparation.zh.md @@ -102,7 +102,7 @@ Handle 返回前,外部 caller 无法 append。因此 `append`、`flush` 与 ` ### Follow 与 Agent promotion -`session.follow` 通过 read path 打开历史、恢复 Session 与 projections、发出 opening snapshot,然后启动 Agent promotion。Agent resume 使用 write open,因此会在 Agent 接收新一轮对话前等待 publication。历史可见与写入就绪成为两个明确时间点,同时不引入 unpublished append state。 +`session.follow` 通过 read path 打开历史、恢复 Session 与 projections,在调用方请求激活时先用单独 retain 的 Observation 启动 Agent promotion,再交付 opening snapshot。Agent resume 使用 write open,因此会在 Agent 接收新一轮对话前等待 publication。历史可见与写入就绪成为两个明确时间点,同时不引入 unpublished append state。 ## 问题与方案对照 diff --git a/.agents/notes/implemented/architecture/2026-09-05-workspace-files-service.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-05-workspace-files-service.i18n.yaml index 38d42e7d93..59746973b8 100644 --- a/.agents/notes/implemented/architecture/2026-09-05-workspace-files-service.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-05-workspace-files-service.i18n.yaml @@ -39,8 +39,8 @@ en: ef015f605f7b00ab zh: eee9c79faebf3dff /agent-note-workspace-file-service/alternatives-considered: - en: 8eee658526db4465 - zh: 4a655accf6a5c08a + en: c750d88e0e746a99 + zh: 9e904ad4172fda49 /agent-note-workspace-file-service/consequences: en: 246bb7aed62f6c9b zh: debf6d4129ee477b diff --git a/.agents/notes/implemented/architecture/2026-09-05-workspace-files-service.md b/.agents/notes/implemented/architecture/2026-09-05-workspace-files-service.md index 02937e54e2..e475fb24b2 100644 --- a/.agents/notes/implemented/architecture/2026-09-05-workspace-files-service.md +++ b/.agents/notes/implemented/architecture/2026-09-05-workspace-files-service.md @@ -117,7 +117,7 @@ The [resource model](2026-09-05-client-resource-model.md) owns `ctx.resources`, **Serving navigable workspace documents.** Rejected on origin grounds; the [binary transfer](2026-09-17-workspace-file-binary-transfer.md) returns multipart data while HTML remains isolated in a Blob iframe. -**Log-reachable or workspace-contained authorization for file reads.** The one precedent that sends file content over the wire, command attachments, authorizes only files that appear in the session log. That excludes typed paths, while workspace containment excludes readable files elsewhere on the Session backend. The [workspace file read authority](2026-09-09-workspace-file-read-authority.md) instead makes the backend's read decision authoritative and keeps containment only for workspace-shaped operations. +**Log-reachable or workspace-contained authorization for file reads.** Requiring a Session-log reference excludes typed paths, while workspace containment excludes readable files elsewhere on the Session backend. The [workspace file read authority](2026-09-09-workspace-file-read-authority.md) makes the backend's read decision authoritative and keeps containment only for workspace-shaped operations. Image attachment reads separately follow the [store-level access rule](2026-10-23-store-scoped-image-reads.md). **Whole-file read and slice for the byte window.** The interim form of `readBytes` read the file from its start to the window's end through `readBytes(target, signal, offset + length)` and sliced. It cannot read a window of a file longer than that end — the seam refuses such a file as too large — so no window could ever report `eof: false`, which contradicts the reason the method exists. Rejected in favour of the `readByteRange` seam, whose bound is the window. diff --git a/.agents/notes/implemented/architecture/2026-09-05-workspace-files-service.zh.md b/.agents/notes/implemented/architecture/2026-09-05-workspace-files-service.zh.md index 60b9597225..b11f7d5388 100644 --- a/.agents/notes/implemented/architecture/2026-09-05-workspace-files-service.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-05-workspace-files-service.zh.md @@ -117,7 +117,7 @@ Client 导出向 `ctx.resources` 注册一个 `ResourceProvider<'file'>`,存 **提供可导航的工作区文档。** 因源隔离问题不采用;[二进制传输](2026-09-17-workspace-file-binary-transfer.zh.md)返回 multipart 数据,HTML 仍隔离在 Blob iframe 中。 -**文件读取采用“日志可达”或工作区包含授权。** 唯一把文件内容送过线路的先例——命令附件——只授权出现在会话日志里的文件,这会排除手输路径;工作区包含则会排除 Session 后端其他位置的可读文件。[工作区文件读取权限](2026-09-09-workspace-file-read-authority.zh.md)改为以后端读取决策为准,只对工作区形态的操作保留包含限制。 +**文件读取采用“日志可达”或工作区包含授权。** 要求 Session 日志引用会排除手输路径;工作区包含则会排除 Session 后端其他位置的可读文件。[工作区文件读取权限](2026-09-09-workspace-file-read-authority.zh.md)以后端读取决策为准,只对工作区形态的操作保留包含限制。图片附件读取另行遵循[存储范围的访问规则](2026-10-23-store-scoped-image-reads.zh.md)。 **为字节窗口整文件读取再切片。** `readBytes` 的临时形态经 `readBytes(target, signal, offset + length)` 从文件开头读到窗口末端再切片。它读不了比该末端更长的文件的窗口——seam 会以过大拒绝这样的文件——因此没有任何窗口能报告 `eof: false`,与该方法存在的理由相悖。被否,改为以窗口为界的 `readByteRange` seam。 diff --git a/.agents/notes/implemented/architecture/2026-09-09-awaited-agent-creation.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-09-awaited-agent-creation.i18n.yaml index 47d3a65a12..057703698a 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-awaited-agent-creation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-09-awaited-agent-creation.i18n.yaml @@ -6,8 +6,8 @@ en: 982ac05aa02da2f0 zh: 225f89c994efb1c4 /agent-note-awaited-per-agent-initialization/problem: - en: 03e6b75365b29406 - zh: cc880a33cf2303d0 + en: 6e9393e78ff71286 + zh: b931a7e606cad37e /agent-note-awaited-per-agent-initialization/decision: en: 48cdb570d3feb222 zh: 904a1169540e3111 @@ -15,5 +15,5 @@ en: 466a9ebbb13f68c6 zh: ab88fb34786d2c2b /agent-note-awaited-per-agent-initialization/consequences: - en: d8cfe8d88ccacfc8 - zh: 8d2aa21408e6e40e + en: 3fc2b36a94ace3ba + zh: 65bb386b89ff89ce diff --git a/.agents/notes/implemented/architecture/2026-09-09-awaited-agent-creation.md b/.agents/notes/implemented/architecture/2026-09-09-awaited-agent-creation.md index 40dcec53a8..1c49baf206 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-awaited-agent-creation.md +++ b/.agents/notes/implemented/architecture/2026-09-09-awaited-agent-creation.md @@ -6,7 +6,7 @@ English | [中文](2026-09-09-awaited-agent-creation.zh.md) ## Problem -Shared presets install tools and prompt sections separately for each Agent. That installation can await plugin activation, and external SessionStart hooks can produce context asynchronously. A creator must know that these contributions have finished before the Agent's first model request. +Agent-specific plugins can install tools asynchronously, and external SessionStart hooks can produce context asynchronously. A creator must know that these contributions have finished before the Agent's first model request. ## Decision @@ -28,4 +28,6 @@ This decision owns asynchronous creation timing. The [scope runtime reference](. Creation latency includes asynchronous plugin and SessionStart work. Initializer failures become caller-visible creation failures, and cancellation relies on listeners settling cooperatively. Notifications already delivered cannot be undone; rollback pairs them with disposal notifications. -Scoped installer tests verify rollback, lifecycle tests verify ordered completion and cancellation, and the SDK serial-created scenario verifies that asynchronous prompt context reaches the first request. Hook tests cover awaited context injection and subprocess disposal. +Lifecycle tests verify initialization rollback, ordered completion and cancellation, and the SDK serial-created scenario verifies that asynchronous prompt context reaches the first request. Hook tests cover awaited context injection and subprocess disposal. + +Delegation tools use [shared preset registrations](../bug-fix/2026-10-25-shared-preset-delegation-tools.md); they do not require per-Agent installation. This event still owns asynchronous Agent initialization. diff --git a/.agents/notes/implemented/architecture/2026-09-09-awaited-agent-creation.zh.md b/.agents/notes/implemented/architecture/2026-09-09-awaited-agent-creation.zh.md index 43b0bfa7d1..29b50eefb1 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-awaited-agent-creation.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-09-awaited-agent-creation.zh.md @@ -6,7 +6,7 @@ Status: implemented ## 问题 -共享 preset 为每个 Agent(智能体)分别安装工具与提示词段。安装可能要等待插件激活,外部 SessionStart 钩子也可能异步产生上下文。创建方必须知道这些贡献已完成,才能允许 Agent 发起首次模型请求。 +针对单个 Agent(智能体)的插件可能异步安装工具,外部 SessionStart 钩子也可能异步产生上下文。创建方必须知道这些贡献已完成,才能允许 Agent 发起首次模型请求。 ## 决策 @@ -28,4 +28,6 @@ AgentLoop 在 setup 与创建分发期间保留现有的维护活动。初始化 创建延迟包括异步插件与 SessionStart 工作。初始化器失败成为调用方可见的创建失败,取消依赖监听器协作结算。已经送达的通知无法撤回;回滚会为其配对销毁通知。 -作用域安装器测试验证回滚,生命周期测试验证有序完成与取消,SDK serial-created 场景验证异步提示词上下文进入首次请求。钩子测试覆盖需等待的上下文注入与子进程 dispose。 +生命周期测试验证初始化回滚、有序完成与取消,SDK serial-created 场景验证异步提示词上下文进入首次请求。钩子测试覆盖需等待的上下文注入与子进程 dispose。 + +委派工具使用[预设共享注册](../bug-fix/2026-10-25-shared-preset-delegation-tools.zh.md),无须按 Agent 安装。此事件仍负责异步 Agent 初始化。 diff --git a/.agents/notes/implemented/architecture/2026-09-20-dynamic-tool-updates.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-20-dynamic-tool-updates.i18n.yaml index 2663220c51..c0587791fd 100644 --- a/.agents/notes/implemented/architecture/2026-09-20-dynamic-tool-updates.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-20-dynamic-tool-updates.i18n.yaml @@ -15,5 +15,5 @@ en: b78785f2a603eba8 zh: b8c268228da7e2e7 /agent-note-active-tool-headers-and-stateful-request-projection/consequences: - en: 93c32b795b71a1cc - zh: d42b5c563341c898 + en: 60d7bf28fa5a8fd1 + zh: a17b222e7aca01e2 diff --git a/.agents/notes/implemented/architecture/2026-09-20-dynamic-tool-updates.md b/.agents/notes/implemented/architecture/2026-09-20-dynamic-tool-updates.md index 1b505eec4b..a40b85601c 100644 --- a/.agents/notes/implemented/architecture/2026-09-20-dynamic-tool-updates.md +++ b/.agents/notes/implemented/architecture/2026-09-20-dynamic-tool-updates.md @@ -30,7 +30,7 @@ DeepSeek translates projected updates into system-role `tool_addition` and `tool ## Consequences -Tool lists and logical update events are capability-independent; only outgoing declarations and messages vary. Calls to removed retained tools fail through the existing `UNKNOWN_TOOL` path. Changed definitions and incomplete auxiliary prefixes sacrifice prefix reuse for coherent declarations; unchanged restoration keeps the cached prefix on `in-history` routes only while the request series continues. Routes supporting tool updates and in-history system prompts preserve earlier messages when tools are added alongside a changed prompt or after an earlier prompt update. Routes without tool-update support still consolidate on tool changes; explicit series starts and surface replacements still consolidate on every route. No persisted fields or Session format revision are added. +Tool lists and logical update events are capability-independent; only outgoing declarations and messages vary. Calls to removed retained tools fail through the existing `UNKNOWN_TOOL` path. Changed definitions and incomplete auxiliary prefixes sacrifice prefix reuse for coherent declarations; unchanged restoration keeps the cached prefix on `in-history` routes only while the request series continues. Routes supporting tool updates and in-history system prompts preserve earlier messages when tools are added alongside a changed prompt or after an earlier prompt update. Routes without tool-update support still start a new series on tool changes; explicit series starts and surface replacements consolidate the prompt only when the effective text differs, and otherwise leave the surviving prompt node in place. No persisted fields or Session format revision are added. The authored [headless prompt/tool scenario](../../../../snapshots/session/dynamic-tool-prompt-updates/snapshot.yml) pins an appended prompt beside a deferred tool addition and verifies that the first request's messages stay unchanged. It shares the stable-prompt scenario's tool lifecycle and schema expectations. diff --git a/.agents/notes/implemented/architecture/2026-09-20-dynamic-tool-updates.zh.md b/.agents/notes/implemented/architecture/2026-09-20-dynamic-tool-updates.zh.md index 6a8fb256c5..372dcb27af 100644 --- a/.agents/notes/implemented/architecture/2026-09-20-dynamic-tool-updates.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-20-dynamic-tool-updates.zh.md @@ -30,7 +30,7 @@ DeepSeek 把投影后的更新转换为 system 角色的 `tool_addition` 和 `to ## Consequences -工具列表和逻辑更新事件不依赖能力;只有发出的声明和消息不同。调用已移除但保留声明的工具时,通过现有 `UNKNOWN_TOOL` 路径失败。定义变化和不完整辅助前缀为保证声明一致而放弃前缀复用;仅当请求序列继续时,未变化的恢复才在 `in-history` 路由上保留缓存前缀。同时支持工具更新和历史内系统提示词的路由,在工具添加与提示词变化同时发生或晚于此前提示词更新时,保留此前消息。不支持工具更新的路由仍在工具变化时归并提示词;所有路由仍在显式新序列和 surface 替换时归并。不增加持久字段或 Session 格式版本。 +工具列表和逻辑更新事件不依赖能力;只有发出的声明和消息不同。调用已移除但保留声明的工具时,通过现有 `UNKNOWN_TOOL` 路径失败。定义变化和不完整辅助前缀为保证声明一致而放弃前缀复用;仅当请求序列继续时,未变化的恢复才在 `in-history` 路由上保留缓存前缀。同时支持工具更新和历史内系统提示词的路由,在工具添加与提示词变化同时发生或晚于此前提示词更新时,保留此前消息。不支持工具更新的路由仍在工具变化时开启新序列;显式新序列和 surface 替换只在有效文本不同时归并提示词,否则保留存活的提示词节点。不增加持久字段或 Session 格式版本。 手写的[无界面提示词/工具场景](../../../../snapshots/session/dynamic-tool-prompt-updates/snapshot.yml)钉住追加提示词与延迟工具添加同时发生的行为,并验证首次请求的消息保持不变。它复用稳定提示词场景的工具生命周期和 schema 期望值。 diff --git a/.agents/notes/implemented/architecture/2026-09-22-fatal-diagnostics-and-crash-reports.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-22-fatal-diagnostics-and-crash-reports.i18n.yaml index fae09a79ee..8d1fed4a2e 100644 --- a/.agents/notes/implemented/architecture/2026-09-22-fatal-diagnostics-and-crash-reports.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-22-fatal-diagnostics-and-crash-reports.i18n.yaml @@ -15,8 +15,8 @@ en: eced414858f08ef9 zh: 40639593b0d5bb6f /agent-note-fatal-diagnostics-and-desktop-crash-reports/relationship-to-the-desktop-logging-design: - en: 7dc438912d10574a - zh: 07d05f9f17043d67 + en: ca4a912437c7b02e + zh: 2c7953ce5e8c196f /agent-note-fatal-diagnostics-and-desktop-crash-reports/testing: en: 864a8e71e3b3378b zh: a71807db24d9409c diff --git a/.agents/notes/implemented/architecture/2026-09-22-fatal-diagnostics-and-crash-reports.md b/.agents/notes/implemented/architecture/2026-09-22-fatal-diagnostics-and-crash-reports.md index 0cf5f64b89..541d22b228 100644 --- a/.agents/notes/implemented/architecture/2026-09-22-fatal-diagnostics-and-crash-reports.md +++ b/.agents/notes/implemented/architecture/2026-09-22-fatal-diagnostics-and-crash-reports.md @@ -32,7 +32,7 @@ This partially supersedes the [native Desktop fatal recovery](2026-09-15-desktop ## Relationship to the Desktop logging design -The Desktop local logging design (a Worker-owned rolling JSONL log with a closed event vocabulary, redaction, and rate limits) is a continuous-log design and remains future work. It stated that Host stderr and renderer console output are never persisted and that errors reach the log only as fixed categories. This decision carves out one exception: the one-time crash report of a fatal failure keeps the raw error and the retained stderr and console tails, because that raw content is what both field diagnoses needed and the report is bounded (the error section is cut at 256 KiB, the Host diagnostic at 64 KiB, the renderer console tail at 64 KiB), local, owner-only, and written only when the application is already showing its fatal dialog. The dialog names the file so a user knows what they would be sharing. The continuous-log privacy posture is unchanged for anything that is not a crash report. +Desktop continuously persists a bounded plugin-management journal with whitelisted facts, two rotating segments and a bounded write queue; its budgets and failure guarantees belong to the [Desktop README](../../../../apps/desktop/README.md). It excludes raw installation specs, error text and package-manager output. The broader Worker-owned continuous log remains deferred. Fatal crash reports independently retain raw errors and bounded stderr and renderer-console tails because these contain the field-diagnosis evidence; files are local and owner-only where supported. An isolated Worker appends bounded management history after the basic report is saved, preserving access to the basic report when collection fails or is still running. Recent operations provide context, not causal attribution. ## Testing diff --git a/.agents/notes/implemented/architecture/2026-09-22-fatal-diagnostics-and-crash-reports.zh.md b/.agents/notes/implemented/architecture/2026-09-22-fatal-diagnostics-and-crash-reports.zh.md index c3513bbddd..045134bb2e 100644 --- a/.agents/notes/implemented/architecture/2026-09-22-fatal-diagnostics-and-crash-reports.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-22-fatal-diagnostics-and-crash-reports.zh.md @@ -32,7 +32,7 @@ macOS 上,启动审计把一组 Web 客户端行列为 `import failed (see con ## 与 Desktop 日志体系设计的关系 -Desktop 本地日志设计(Worker 独占写入的滚动 JSONL 日志、封闭事件词汇、脱敏与限流)是持续日志设计,仍是未来工作。它规定 Host stderr 与渲染进程 console 输出永不持久化、错误只以固定分类进入日志。本决定划出一个例外:致命失败的一次性崩溃报告保留原始错误以及保留的 stderr 与 console 尾部,因为两次现场定位需要的正是这些原始内容,而报告有界(error 段截至 256 KiB、Host 诊断 64 KiB、渲染进程 console 尾部 64 KiB)、本地、仅所有者可读,且只在应用已经弹出致命对话框时写入。对话框标明文件名,用户知道自己会分享什么。任何非崩溃报告的内容仍遵循持续日志的隐私姿态。 +Desktop 持续保存有界的插件管理日志,使用事实白名单、两个轮换文件段和有界写入队列;预算及失败保障由 [Desktop README](../../../../apps/desktop/README.zh.md) 定义。日志不包含原始安装 spec、错误文本或包管理器输出。更广泛的 Worker 独占持续日志仍属延期工作。致命崩溃报告独立保留原始错误以及有界的 stderr 和渲染进程 console 尾部,因为这些内容包含现场定位证据;文件保存在本地,并在平台支持时仅所有者可读。独立 Worker 在基本报告保存后追加有界管理历史,收集失败或尚未结束时仍可获取基本报告。近期操作提供上下文,不构成因果归因。 ## Testing diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml index 615a8d43cf..9ed59785ea 100644 --- a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml @@ -9,11 +9,11 @@ en: e42db40b879fdbf4 zh: 6017da9c4da17835 /agent-note-node-ptc-execution-modes-and-in-memory-state/decision: - en: d2d08c54c6520f02 - zh: 520a9b3421ff5c65 + en: 7b5808a31493ac1e + zh: 8d9c698c41dbf18e /agent-note-node-ptc-execution-modes-and-in-memory-state/alternatives-considered: en: 396157a9fc293198 zh: a061f05b4423e26f /agent-note-node-ptc-execution-modes-and-in-memory-state/consequences: - en: 9b9172f4aafe907f - zh: 022a6bd52d7caf05 + en: 56fa39e2958afdff + zh: d04f539437d0c00d diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md index 153a63b87e..fac34c9f7f 100644 --- a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md @@ -12,7 +12,7 @@ Interactive automation retains application objects, imported modules and helper The existing `@deepseek-ai/dsh-ptc-runtime-node` plugin selects its execution mode through `executionMode`. The default `per-call` mode starts a fresh process under the configured file policy. Opt-in `persistent-in-memory` mode keeps a Node REPL process per explicit, object-identity state owner. Both modes provide the same `ctx.ptcRuntime` service. PTC uses the live Agent as owner and awaits release during its context disposal. Changing the configuration reloads the provider and releases its processes. The [sandboxed Node decision](2026-09-11-sandboxed-node-ptc-runtime.md) owns per-call confinement; the [PTC foundation](../feature/2026-06-15-ptc.md) owns tool dispatch and logged model requests. -Mode names describe state retention rather than a process implementation or source syntax. `per-call` retains state for one invocation; `persistent-in-memory` retains it across invocations until the process or owner ends. `durable` names the deferred ability to save and restore execution state across restarts. It is not an accepted configuration value: a future implementation must define its recovery point, recoverable values and external-resource handling before exposing that mode. The [retained-process permission decision](2026-10-08-persistent-ptc-sandbox.md) owns confinement, policy changes and temporary escalation. +The `per-call` and `persistent-in-memory` names describe their fixed state-retention policies: one invocation or across invocations until the process or owner ends. The [Script evaluation decision](2026-10-20-ptc-script-evaluation-and-retention.md) extends these modes with independently configured syntax and retention. `durable` names the deferred ability to save and restore execution state across restarts. It is not an accepted configuration value: a future implementation must define its recovery point, recoverable values and external-resource handling before exposing that mode. The [retained-process permission decision](2026-10-08-persistent-ptc-sandbox.md) owns confinement, policy changes and temporary escalation. One npm package and one plugin entry keep existing installation and loading paths stable. Communication, binding proxies, JSON encoding and output limits remain package-local modules. The Node provider delegates retained process ownership to an internal execution object, which registers no additional Cordis service. Per-call and in-memory execution keep their distinct lifecycle rules. `programFormat` describes source evaluation independently of retention: a REPL need not retain state. The runtime owns syntax, completion and retention instructions through `executionInstructions`; tools own call arguments, SDK declarations and image attachment. Workflow uses `programFormat` to wrap its program and refuses restricted file policies when the selected runtime cannot enforce them. @@ -34,4 +34,4 @@ A realm inside the Harness process shares process lifetime with model code and c Selecting `persistent-in-memory` retains execution state; the [permission decision](2026-10-08-persistent-ptc-sandbox.md) defines its file restrictions. Nested tools keep their normal authorization and logging. Memory and native handles may disappear without a Harness restart. The model must recover from reference or resource errors; the runtime never retries a program automatically. -An idle owner retains a process with no expiration timer. Callers release owners explicitly; ownerless service calls use temporary processes. Programs use REPL statements and a final expression rather than top-level return, and calls for one retained owner cannot overlap. Tool schemas and program guidance follow the selected mode. +An idle owner retains a process with no expiration timer. Callers release owners explicitly; ownerless service calls use temporary processes. The `persistent-in-memory` mode uses REPL statements and a final expression rather than top-level return, and calls for one retained owner cannot overlap. Tool schemas and program guidance follow the selected mode. diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md index a4c4a52828..93959fe07a 100644 --- a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md @@ -12,7 +12,7 @@ Status: implemented 现有 `@deepseek-ai/dsh-ptc-runtime-node` 插件通过 `executionMode` 选择执行模式。默认的 `per-call` 模式按配置的文件策略启动新进程。显式启用的 `persistent-in-memory` 模式为每个以对象身份标识的状态所有者保留一个 Node REPL 进程。两种模式都提供同一个 `ctx.ptcRuntime` 服务。PTC 使用存活的 Agent 作为所有者,在其上下文销毁时等待释放。修改配置会重载提供方并释放其进程。[Node 沙箱决策](2026-09-11-sandboxed-node-ptc-runtime.zh.md)负责逐次执行的文件约束,[PTC 基础决策](../feature/2026-06-15-ptc.zh.md)负责工具分派与模型请求日志。 -模式名称描述状态保留方式,不绑定进程实现或代码语法。`per-call` 只为一次调用保留状态;`persistent-in-memory` 跨调用保留状态,直到进程或所有者结束。`durable` 用于命名未来跨重启保存与恢复执行状态的能力。它不是可接受的配置值:实现必须先明确恢复点、可恢复的值以及外部资源的处理方式,才能公开这个模式。[常驻进程权限决策](2026-10-08-persistent-ptc-sandbox.zh.md)负责文件约束、权限切换与临时提权。 +`per-call` 和 `persistent-in-memory` 名称描述各自固定的状态保留策略:只保留一次调用,或跨调用保留至进程或所有者结束。[Script 求值决策](2026-10-20-ptc-script-evaluation-and-retention.zh.md)在这两种模式之外增加独立配置的语法与保留方式。`durable` 用于命名未来跨重启保存与恢复执行状态的能力。它不是可接受的配置值:实现必须先明确恢复点、可恢复的值以及外部资源的处理方式,才能公开这个模式。[常驻进程权限决策](2026-10-08-persistent-ptc-sandbox.zh.md)负责文件约束、权限切换与临时提权。 一个 npm 包和一个插件入口保持现有安装与加载路径稳定。通信、绑定代理、JSON 编码和输出限制继续作为包内模块复用。Node 提供方将保留进程的所有权交给内部执行对象,该对象不注册额外的 Cordis 服务。逐次执行和内存保留各自管理不同的生命周期。`programFormat` 描述代码求值形式,与状态保留独立:REPL 不必跨调用保留状态。运行时通过 `executionInstructions` 负责语法、完成值和状态保留指引;工具层负责调用参数、SDK 声明和图片附加。工作流根据 `programFormat` 包装程序;所选运行时无法执行受限文件策略时,工作流拒绝执行。 @@ -34,4 +34,4 @@ Harness 进程内的独立执行上下文与模型代码共享进程生命周期 选择 `persistent-in-memory` 会保留执行状态;[权限决策](2026-10-08-persistent-ptc-sandbox.zh.md)定义其文件限制。嵌套工具仍遵循原有授权和日志规则。即使 Harness 没有重启,内存和原生句柄也可能丢失。模型需要从引用或资源错误中恢复,运行时不会自动重试程序。 -空闲所有者保留一个没有过期计时器的进程。调用方显式释放所有者,没有所有者的服务调用使用临时进程。程序使用 REPL 语句和末尾表达式,不支持顶层 return;同一保留所有者的调用不能重叠。工具 schema 和程序指引跟随所选模式。 +空闲所有者保留一个没有过期计时器的进程。调用方显式释放所有者,没有所有者的服务调用使用临时进程。`persistent-in-memory` 模式使用 REPL 语句和末尾表达式,不支持顶层 return;同一保留所有者的调用不能重叠。工具 schema 和程序指引跟随所选模式。 diff --git a/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.i18n.yaml index 71c61113a6..d8e3f3fcaf 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.i18n.yaml @@ -9,8 +9,8 @@ en: 2eeb916eb65c66e7 zh: 7bf5c0abb8bb61e4 /agent-note-deepseek-account-models-come-from-the-account-listing-and-gate-by-client-version/decision: - en: 42e800c4cd3b6ebe - zh: 06fabe5a9681fa27 + en: 0125e33ba966c8ac + zh: bf6af389336999af /agent-note-deepseek-account-models-come-from-the-account-listing-and-gate-by-client-version/alternatives-considered: en: 7c7880fdb0cc95f6 zh: 2b8a539192626789 diff --git a/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.md b/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.md index 75265db1ce..867198fba2 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.md +++ b/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.md @@ -12,8 +12,8 @@ The account route's catalog was deployment configuration: a build advertised the - [`llm-deepseek-account`](../../../../packages/llm/llm-deepseek-account/README.md) loads the listing lazily for each credential, waits for it once up to `modelsTimeoutMs`, refreshes it in the background after `modelsMaxAgeMs`, keeps the last good listing when a load fails or returns no model, and serves the bundled catalog before any listing loads. The cache lives in memory and is keyed by endpoint and token fingerprint, so per-account rollouts stay separate. - A listed model is available when its `client_requirements["deepseek-harness"].min_version` is at most the current DeepSeek Harness version in semantic-version order. Without that declaration, only ids the built-in catalog knows are available; the others stay hidden, because a client cannot tell which future version supports them. A request for a refused listed model fails before network I/O with `CLIENT_UPGRADE_REQUIRED` or `MODEL_UNSUPPORTED`. -- Listed capabilities replace bundled ones field by field; the bundled entry keeps client-side knowledge such as tool-update mode and image budgets; `modelOverrides` applies last and reuses the `models` entry fields and validation. `max_output_tokens` bounds the request default instead of becoming it. -- The shared transport gains only two provider hooks, `connect` and `admit`; listing, gating, and merging stay in the account package. +- Listed capabilities replace bundled ones field by field; the bundled entry keeps client-side knowledge the listing does not declare, such as image budgets and a protocol mode the listing omits or sets to `null`; `modelOverrides` applies last and reuses the `models` entry fields and validation. `max_output_tokens` bounds the request default instead of becoming it. +- The shared transport gains only two provider hooks, `connect` and `admit`. Listing, gating, and merging live in the shared transport, which the [official route](2026-10-22-deepseek-official-model-listing.md) also uses. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.zh.md b/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.zh.md index 7199091c73..37487fbc88 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.zh.md @@ -12,8 +12,8 @@ Status: implemented - [`llm-deepseek-account`](../../../../packages/llm/llm-deepseek-account/README.zh.md) 按凭据懒加载列表,首次访问最多等待 `modelsTimeoutMs`,超过 `modelsMaxAgeMs` 后在后台刷新;获取失败或返回的列表中没有模型时保留上一份,还没有加载到任何列表时使用内置目录。缓存只在内存中,以端点和 token 指纹为键,因此按账号灰度互不干扰。 - 列出的模型在其 `client_requirements["deepseek-harness"].min_version` 按 semver 顺序不高于当前 DeepSeek Harness 版本时可用。没有这个声明时,只有内置目录认识的 id 可用,其余保持隐藏,因为客户端无法判断将来哪个版本会支持它们。请求被拒绝的已列出模型时,在网络请求之前以 `CLIENT_UPGRADE_REQUIRED` 或 `MODEL_UNSUPPORTED` 失败。 -- 列表中的能力逐字段覆盖内置能力;内置条目保留工具更新模式、图片预算等客户端知识;`modelOverrides` 最后叠加,复用 `models` 条目的字段与校验。`max_output_tokens` 只限制请求默认值,不直接成为默认值。 -- 共享传输层只新增 `connect` 与 `admit` 两个提供方钩子;列表、门控与合并都留在账号包中。 +- 列表中的能力逐字段覆盖内置能力;内置条目保留列表没有声明的客户端知识,例如图片预算,以及列表没有给出或设为 `null` 的协议模式;`modelOverrides` 最后叠加,复用 `models` 条目的字段与校验。`max_output_tokens` 只限制请求默认值,不直接成为默认值。 +- 共享传输层只新增 `connect` 与 `admit` 两个提供方钩子。列表、门控与合并位于共享传输包中,[官方路由](2026-10-22-deepseek-official-model-listing.zh.md)也使用它们。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.i18n.yaml index 46925831d8..8b028995ae 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.i18n.yaml @@ -9,11 +9,11 @@ en: abd0263d14861926 zh: e1736cd08e87f795 /agent-note-shared-time-vocabulary-for-wall-clock-selectors/decision: - en: 52b45f1ac62e65ab - zh: 7f83cd4fb8dd09a6 + en: fdd39b7e8fa89d70 + zh: 4a0dfc81509e5485 /agent-note-shared-time-vocabulary-for-wall-clock-selectors/alternatives-considered: en: 1737484c099fab52 zh: 303b144c52d167bd /agent-note-shared-time-vocabulary-for-wall-clock-selectors/consequences: - en: 6ec74e7ac065bd5e - zh: 04d029059dea732b + en: 79d8d66071453d1f + zh: f940f0b6d74148d6 diff --git a/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.md b/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.md index 607dc68b7a..2cc2c8be43 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.md +++ b/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.md @@ -20,6 +20,8 @@ Schedule consumes it and keeps every domain decision. `canonicalizeTimeZone`, `d `Duration` holds one span as a single millisecond count, and it is a class rather than a branded number because TypeScript's arithmetic erases a brand: adding two differently branded numbers answers an unbranded `number`, so a brand cannot stop seconds and milliseconds from being mixed, while an instance can. The unit is milliseconds because every producer and consumer in this repository already uses it (`Date.now()`, `SessionEvent.time`, the session log, the client), and because a double holds every millisecond of the whole `Date` range exactly, so no precision is spent on the unit. Instances are frozen, no coercion hook is overridden, and a span is bounded by the exactly representable millisecond range, which is what makes the split exact. The published surface is `fromMilliseconds` and a whole-part `decompose()`, the two entries the migrated consumer calls. +The last copy of the canonical instant profile moves too. `packages/session/session-format-v0-to-v1/src/payload-validation.ts` validated a stored schedule instant with its own regular expression and round trip; the shared `fourDigitYearEpoch` owns that same profile, so the migration now asks it and keeps its own error type and message. Because that migration reads released logs, its accepted set is a compatibility promise: `packages/session/session-format-v0-to-v1/tests/validation.spec.ts` accepts the four-digit-year bounds and refuses each spelling a regular expression alone would admit (`0000`, `2026-02-30`, a four-digit fraction, a numeric offset, surrounding whitespace). + The maintained `@js-temporal/polyfill` 0.5.1 becomes a runtime dependency of `dsh-util-time` as well as of `dsh-schedule`. Local resolution continues to use it, so the Host's IANA data still decides gaps and overlaps and no caller owns offset sampling. `util/time`'s own description and README drop the `zero-dependency` phrase as ambiguous: the group's charter forbids harness dependencies so any group may depend on util, and does not ban external packages, which is why `packages/README.md` and the `util/` line in `AGENTS.md` keep the phrase while `packages/util/README.md` and this package's own description name what it loads. Observable behavior does not change. Every accepted input resolves to the same epoch, every refused input raises the same `ScheduleInputError` or `ScheduleLogError` code and the same message, and the stored `scheduledAt` profile is unchanged, so no durable record and no recorded snapshot is re-recorded. Schedule's suites assert error codes and a few unrelated message substrings, so the assertion this change adds to `packages/schedule/schedule/tests/domain.spec.ts` is the only place that pins the three local-calendar message strings. `packages/util/time/tests/instant.spec.ts` covers the new entries directly, per-file 100% included. @@ -48,4 +50,4 @@ A value type publishes what its consumers call, so the span exposes the construc The elapsed reading keeps its split in the library and its wording in the consumer: `dsh-time-context` still decides that a backward clock reading clamps to zero and how the compact line reads, while `Duration.decompose()` answers the whole parts. That swap is byte-identical for every finite sample, measured over more than eight thousand inputs including negatives, fractions, and values past a year. That measurement is not a committed test: the consumer's own suite pins the readings it renders (`1d 1h 1m 1s`, `1m 1s`, `4m 2s`, and the clamped zero). Two samples do change: `NaN` rendered `NaNs` and `+Infinity` rendered `Infinityd NaNs`, and both now throw from the span constructor, so a reading that is not a finite number fails where it is produced instead of rendering text. A `-Infinity` sample is unchanged, because the consumer clamps it to zero before the span is built. -Time-context keeps the two policies this change did not touch: its ISO-shaped timestamp rendering in `packages/context/time-context/src/timestamp.ts`, which is that package's durable reading format, and the elapsed-duration wording in its own plugin. The browser client keeps its own localized date rendering and its own UTC-offset reading, which serve a different purpose (a reader's locale) from a boundary value; unifying those means deciding whether the shared library should also own display formatting, and which package then owns the durable reading format. `packages/session/session-format-v0-to-v1/src/payload-validation.ts` also validates the canonical four-digit-year UTC instant with its own regular expression and round trip, which is a remaining copy of the instant profile this change did not touch. +Time-context keeps the two policies this change did not touch: its ISO-shaped timestamp rendering in `packages/context/time-context/src/timestamp.ts`, which is that package's durable reading format, and the elapsed-duration wording in its own plugin. The browser client keeps its own localized date rendering and its own offset reading for display, which serve a different purpose (a reader's locale) from a boundary value; unifying those means deciding whether the shared library should also own display formatting, and which package then owns the durable reading format. Five time sites keep their own code, each for a different reason. `packages/experimental/tool-session-query/src/input.ts` parses a wider profile than the shared entry — seconds optional, any number of fractional digits, and the digits below the millisecond kept so two instants can be compared exactly — so substituting the shared parser would narrow what it accepts, and moving that profile into the library is a design step of its own. The `Date.parse(record.scheduledAt)` reads in `dsh-schedule` parse a value the write path already validated, so a discriminated decode would add a rejection branch that cannot occur in practice and change what a corrupt record reports. The `everySeconds`, `afterSeconds`, and `refreshMarginSeconds` multiplications each sit beside a validation that raises the package's own error, so routing them through a constructor that throws its own type would change the failure a caller sees. The UTC offset a client reports is computed in `packages/client/ui-settings-account/src/client/client-metadata.ts` instead of shared: the client bundle admits a cross-plugin value import only for the packages it lists as inline-safe, `dsh-util-time` is not one of them, and it imports the `Temporal` polyfill at module scope, so inlining it would ship that polyfill to the browser. The Desktop host computes the same offset from the shared library, where no such rule applies. `dsh-workspace` writes its record timestamps with the platform's `toISOString`, which is the canonical rendering for every representable epoch: the extended-year and fractional-truncation cases a shared writer would refuse are unreachable from `Date.now()` and from a `SessionHeader` epoch, so adopting the shared formatter there would add a module and a dependency without changing a byte. diff --git a/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.zh.md b/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.zh.md index 838f6b9d4b..72d4e6b12b 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.zh.md @@ -20,6 +20,8 @@ Schedule 消费它,并保留全部域内决策。`canonicalizeTimeZone`、`dec `Duration` 以单一毫秒计数保存一段时间;它做成类而不是 branded number,是因为 TypeScript 的算术会抹掉 brand:两个不同品牌的数字相加得到的是无品牌的 `number`,所以 brand 挡不住秒与毫秒的混用,而实例可以。单位选毫秒,是因为本仓库的每个生产者与消费者本来就用它(`Date.now()`、`SessionEvent.time`、Session 日志、客户端),也因为 double 能精确表示 `Date` 全范围内的每一个毫秒,这个单位不消耗任何精度。实例被冻结,不覆盖任何强制转换钩子,且时间段受可精确表示的毫秒范围约束——这正是拆分精确的前提。公开面就是 `fromMilliseconds` 与整数量拆解 `decompose()`,即已迁移消费方所调用的两个入口。 +最后一份规范时刻剖面副本也一并迁移。`packages/session/session-format-v0-to-v1/src/payload-validation.ts` 原本用自己的一段正则与往返比对校验持久记录里的调度时刻;共享的 `fourDigitYearEpoch` 拥有同一剖面,因此该迁移改为询问它,并保留自己的错误类型与文案。由于这个迁移要读取已发布的日志,其接受集是兼容性承诺:`packages/session/session-format-v0-to-v1/tests/validation.spec.ts` 接受四位年份两端,并拒绝只靠正则会放进来的每种拼写(`0000`、`2026-02-30`、四位小数、数字偏移、首尾空白)。 + 受维护的 `@js-temporal/polyfill` 0.5.1 在成为 `dsh-schedule` 运行时依赖之外,也成为 `dsh-util-time` 的运行时依赖。本地解析继续使用它,因此缺口与重叠仍由宿主 IANA 数据决定,也没有调用方需要自己实现偏移采样。`util/time` 自身的描述与 README 去掉了 `zero-dependency` 这一说法,因为它容易被误读:该组的约定禁止的是 harness 依赖(以便任何组都能依赖 util),并不禁止外部包;因此 `packages/README.md` 与 `AGENTS.md` 里的 `util/` 一行保留该说法,而 `packages/util/README.md` 与本包自己的描述写明它加载了什么。 可观察行为不变。每个被接受的输入解析出相同的纪元值,每个被拒绝的输入抛出相同的 `ScheduleInputError` 或 `ScheduleLogError` 错误码与相同的消息,存储的 `scheduledAt` 剖面不变,因此没有持久记录或录制快照需要重录。Schedule 的测试断言错误码以及少量无关的消息子串,因此本次在 `packages/schedule/schedule/tests/domain.spec.ts` 新增的断言是唯一固定这三条本地日历消息的地方。`packages/util/time/tests/instant.spec.ts` 直接覆盖新增入口,包含逐文件 100% 覆盖。 @@ -48,4 +50,4 @@ Schedule 消费它,并保留全部域内决策。`canonicalizeTimeZone`、`dec 耗时读数的拆分上收到库、措辞留在一侧:`dsh-time-context` 仍然决定回退的时钟读数钳到零、以及那行紧凑文本怎么写,而 `Duration.decompose()` 回答整数量。这次替换对每个有限样本都逐字不变,用一份覆盖八千多个输入(含负数、小数与一年以上的值)的差分测得。该测量不是提交进仓库的测试:消费方自己那套测试固定了它渲染出的读数(`1d 1h 1m 1s`、`1m 1s`、`4m 2s`,以及被钳到零的那次)。有两个样本会变:`NaN` 原本渲染出 `NaNs`、`+Infinity` 原本渲染出 `Infinityd NaNs`,现在两者都由时间段构造函数抛出,于是非有限的读数在产生它的地方失败,而不是渲染出一段文本。`-Infinity` 样本不变,因为消费方在构造时间段之前已把它钳到零。 -本次未触及、仍归 time-context 的两项:`packages/context/time-context/src/timestamp.ts` 中的 ISO 形状时间戳渲染(那是该包的持久读数字格式),以及其插件内的耗时措辞。浏览器客户端也保留自己的本地化日期渲染与自己的 UTC 偏移读取——它们服务的目的(读者的区域设置)与边界值不同;统一它们意味着先决定共享库是否也要拥有展示格式化,以及届时由谁拥有持久读数字格式。`packages/session/session-format-v0-to-v1/src/payload-validation.ts` 也用自己的一段正则与往返比对校验规范的四位年份 UTC 时刻,这是本次未触及、仍然存在的时刻剖面副本。 +本次未触及、仍归 time-context 的两项:`packages/context/time-context/src/timestamp.ts` 中的 ISO 形状时间戳渲染(那是该包的持久读数字格式),以及其插件内的耗时措辞。浏览器客户端也保留自己的本地化日期渲染与用于展示的偏移读取——它们服务的目的(读者的区域设置)与边界值不同;统一它们意味着先决定共享库是否也要拥有展示格式化,以及届时由谁拥有持久读数字格式。有五处时间代码各自保留实现,原因各不相同。`packages/experimental/tool-session-query/src/input.ts` 解析的剖面比共享入口更宽——秒可省略、小数位不限、并保留下毫秒数字以便精确比较两个时刻——因此换成共享解析器会收窄它接受的输入,而把那条剖面搬进本库是另一项独立的设计。`dsh-schedule` 里的 `Date.parse(record.scheduledAt)` 读的是写入路径已经校验过的值,换成带判别值的解码会在每个读取点新增一个实际不可能发生的拒绝分支,并改变损坏记录的报告方式。`everySeconds`、`afterSeconds` 与 `refreshMarginSeconds` 三处乘法旁边都紧跟一条抛本包自有错误的校验,因此把它们改走会抛自身错误类型的构造函数,会改变调用方看到的失败。客户端上报的 UTC 偏移由 `packages/client/ui-settings-account/src/client/client-metadata.ts` 自行计算而不共享:客户端 bundle 只允许对列入 inline-safe 的包做跨插件值导入,`dsh-util-time` 不在其中,而且它在模块顶层静态导入 `Temporal` polyfill,内联它等于把该 polyfill 打进浏览器;Desktop 的宿主侧则用共享库计算同一个偏移,那里没有这条限制。`dsh-workspace` 用平台的 `toISOString` 写记录时间戳,对每个可表示的纪元那已是规范渲染:共享写入器会拒绝的扩展年份与小数截断两种情形,从 `Date.now()` 与 `SessionHeader` 的纪元出发都不可达,因此在那边采用共享格式化器只会增加一个模块与一条依赖,却不会改变任何字节。 diff --git a/.agents/notes/implemented/architecture/2026-09-26-cua-application-consent.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-26-cua-application-consent.i18n.yaml index 2f89f011b6..03e2dc829a 100644 --- a/.agents/notes/implemented/architecture/2026-09-26-cua-application-consent.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-26-cua-application-consent.i18n.yaml @@ -9,11 +9,11 @@ en: b32a7ce6483b9b48 zh: ec0938ad032b99d8 /agent-note-application-consent-for-native-computer-use/decision: - en: 36c560c24c376f12 - zh: 5e4ff72f66574e38 + en: b34d24e39879277e + zh: 03363665d4682ddb /agent-note-application-consent-for-native-computer-use/alternatives-considered: - en: 80cd5fd93a42d937 - zh: 2a0e241b1b8c2e1d + en: 18b2c124f1d4e601 + zh: 621a6c9512d5612b /agent-note-application-consent-for-native-computer-use/consequences: en: 4bda3366af65250a zh: 7c83561b4db07284 diff --git a/.agents/notes/implemented/architecture/2026-09-26-cua-application-consent.md b/.agents/notes/implemented/architecture/2026-09-26-cua-application-consent.md index 389a994714..84cfd7fe65 100644 --- a/.agents/notes/implemented/architecture/2026-09-26-cua-application-consent.md +++ b/.agents/notes/implemented/architecture/2026-09-26-cua-application-consent.md @@ -10,17 +10,15 @@ macOS privileges authorize an execution host, not a user's choice of target appl ## Decision -The CUA executor owns application consent for every object-API and native-tool dispatch. It uses the existing User Questions service for human decisions and the provider's existing profile configuration for saved grants. The existing question UI presents the offered labels; the executor rejects custom text or answers that do not select exactly one offered label. Permission-page icons and names are presentation metadata, excluded from saved identities and model results. General tool approval and operating-system privileges remain separate requirements. Arbitrary persistent PTC code and separately authorized shell tools retain their own execution authority. +The CUA executor owns application consent for every object-API and native-tool dispatch. It uses the existing User Questions service for human decisions and profile-scoped domain storage for saved grants. Its fixed approval presentation reuses the tool-approval card without adopting the session's tool-approval policy. Native icons and names are presentation metadata, excluded from saved identities and model results. General tool approval and operating-system privileges remain separate requirements. Arbitrary persistent PTC code and separately authorized shell tools retain their own execution authority. System-permission buttons call the native helper on the DSH host and remain available to remote browsers. The [usage documentation](../../../../packages/experimental/cua/README.md#use-this-package) explains where to complete authorization; the page has no persistent remote-access notice. -A saved identity combines the canonical executable path with a verified designated signing requirement, represented by a SHA-256 digest. The path prevents authorization from following a copied application, and the signing requirement distinguishes replacements while allowing matching signed updates. Unverifiable and ad-hoc applications receive session access only, tied to a process instance. Labels do not establish identity. +Application identity is owned by [bundle-ID consent](2026-10-25-cua-bundle-id-consent.md), which supersedes this note's original path/signature choice. That original choice prevented copied or replaced applications from inheriting access, at the cost of separate grants per installation and no saved grants for unsigned applications. Enforcement and human decision ownership remain as described here. -Cold application selection prepares an executable identity and handle without launching. The same consent decision guards the private launch continuation, and the helper checks the executable again before launch and binds the resulting process afterward. Signed selections retain the normal designated-requirement identity; an unverifiable executable uses a content identity for this pending selection and cannot create a saved grant. Preparing metadata before asking avoids starting an application the user refuses. +Cold application selection prepares an executable identity and handle without launching. The same consent decision guards the private launch continuation, and the helper checks the executable again before launch and binds the resulting process afterward. Selections with a bundle identifier retain that identity after launch; an application without one uses its canonical executable path before and after launch and can save that grant. Preparing metadata before asking avoids starting an application the user refuses. -Session decisions are kept in memory by Session ID and application identity. Agent disposal and helper replacement release native handles without discarding these decisions; provider disposal or DSH restart clears them. This scope covers follow-up turns without relying on the model to decide when a user intent has ended. - -Selections of the same application within one session are serialized, so a pending question does not produce competing decisions. Saved-grant additions and revocations share one mutation queue and read the current grant list inside it. Provider shutdown cancels writes still waiting for HMR admission; admitted writes settle before disposal completes. Refusals prevent another prompt until the user permits asking again; a restored saved grant takes precedence in both dispatch and the permission-page projection. +Conversation decisions survive provider disposal and DSH restart according to [profile consent storage](2026-10-19-cua-profile-consent-storage.md). That decision owns persistence, migration and cross-process revocation. The executor continues to serialize application selections within a conversation, refuse repeated prompts after denial, and give an explicit long-term grant precedence over conversation refusals. Revocation invalidates the Agent connections that retain the application's handles, then awaits native cleanup. Reauthorization uses a fresh connection, so old app and window snapshots cannot become valid again. The [native object decision](2026-09-17-experimental-cua-object-api.md) continues to own process identity, coordinate semantics, and separation from the evaluator. @@ -28,9 +26,9 @@ Revocation invalidates the Agent connections that retain the application's handl **Trust model instructions or hide controls.** Retained objects and direct tool calls can still reach native operations. The executor must enforce the decision at dispatch. -**Persist application names or unsigned paths.** A replacement can reuse both. Durable grants require a verifiable signing identity; session access supports unsigned development applications without that promise. +**Persist application names or unsigned paths.** A replacement can reuse both. [Bundle-ID consent](2026-10-25-cua-bundle-id-consent.md) owns the identity choices and the decision to share permission between installations. -**Add an approval database or Session control stream.** Profile settings already own user configuration, and User Questions already owns interactive answers. The permission UI observes the provider and its owning settings namespace without another authorization store or event channel. +**Add an approval database or Session control stream.** User Questions already owns interactive answers. The existing domain service provides durable state without introducing a dedicated database or Session control stream; storage tradeoffs are owned by the profile consent decision. **Disable permission buttons based on the browser address.** A user may operate the DSH host through screen sharing and complete authorization there. Port forwarding and proxies make the address an unreliable indication of whether the browser and DSH run on the same computer. diff --git a/.agents/notes/implemented/architecture/2026-09-26-cua-application-consent.zh.md b/.agents/notes/implemented/architecture/2026-09-26-cua-application-consent.zh.md index e7311dfc6d..17590a47c0 100644 --- a/.agents/notes/implemented/architecture/2026-09-26-cua-application-consent.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-26-cua-application-consent.zh.md @@ -10,17 +10,15 @@ macOS 权限授权执行宿主,不能表达用户允许操作哪些目标应 ## 决策 -CUA 执行器在每次对象 API 和原生工具调用时检查应用授权。人工决定复用 User Questions 服务,长期许可保存在 provider 的现有 profile 配置中。通用工具审批和操作系统权限仍是独立要求。任意 persistent PTC 代码和另行授权的 shell 工具保留各自的执行权限。现有问答界面展示授权选项;执行器拒绝自由文本或未准确选中一个所给选项的回答。权限页图标和名称仅用于展示,不进入保存的身份信息或模型结果。 +CUA 执行器在每次对象 API 和原生工具调用时检查应用授权。人工决定复用 User Questions 服务,长期许可保存在按 profile 隔离的存储域中。通用工具审批和操作系统权限仍是独立要求。任意 persistent PTC 代码和另行授权的 shell 工具保留各自的执行权限。 固定审批呈现复用工具审批卡片,同时保留独立于会话工具审批策略的授权规则。本机图标和名称仅用于展示,不进入保存的身份信息或模型结果。 系统权限按钮调用运行 DSH 的电脑上的原生 helper,远程访问时仍可使用。授权地点写在[使用说明](../../../../packages/experimental/cua/README.zh.md#use-this-package)中,页面不常驻远程访问提示。 -长期身份由规范化可执行文件路径和经过验证的签名指定要求组成,以 SHA-256 摘要表示。路径阻止许可跟随应用副本,签名要求区分替换程序,并允许符合相同签名要求的更新。签名不可验证或使用 ad-hoc 签名的应用只能获得会话授权,许可绑定进程实例。显示名称不用于确定身份。 +应用身份由[Bundle ID 授权](2026-10-25-cua-bundle-id-consent.zh.md)负责,取代本记录原先的路径和签名选择。原选择防止应用副本或替换程序继承许可,代价是各安装副本必须分别授权,未签名应用无法保存长期许可。执行检查和用户决定的所有权仍由本记录规定。 -选择尚未运行的应用时,先准备可执行文件身份和句柄,不立即启动。同一授权决定保护内部启动续接,helper 在启动前再次核对可执行文件,并在启动后绑定实际进程。已签名应用沿用签名指定要求身份;签名不可验证的程序使用本次待启动选择的内容身份,不能生成长期许可。先准备元数据再询问,可以避免启动用户拒绝的应用。 +选择尚未运行的应用时,先准备可执行文件身份和句柄,不立即启动。同一授权决定保护内部启动续接,helper 在启动前再次核对可执行文件,并在启动后绑定实际进程。有 Bundle ID 的应用在启动后沿用该身份;没有 Bundle ID 的程序在启动前后使用规范化可执行路径,并可保存该许可。先准备元数据再询问,可以避免启动用户拒绝的应用。 -会话决定按 Session ID 和应用身份保存在内存中。Agent 销毁或 helper 重建会释放原生句柄,但保留授权决定;提供方卸载或 DSH 重启后清除。会话范围可以覆盖用户的后续指令,无须由模型判断一次用户意图何时结束。 - -同一会话对同一应用的选择串行执行,避免未完成的问题产生相互冲突的决定。长期许可的新增和撤销共用写入队列,并在队列内读取当前许可列表。提供方关闭时取消尚在等待 HMR 调度的写入,已开始的写入会在销毁完成前结束。拒绝会阻止再次询问,直到用户允许重询;重新添加的长期许可在执行检查和权限页中均优先于旧拒绝记录。 +会话决定按[profile 授权存储](2026-10-19-cua-profile-consent-storage.zh.md)的规则,在提供方卸载和 DSH 重启后保留。该记录负责持久化、迁移和跨进程撤销。执行器继续将同一对话对同一应用的选择串行化,拒绝后不再次询问,显式长期许可优先于会话拒绝。 撤销使保留目标应用句柄的 Agent 连接失效,并等待原生清理完成。重新授权使用新连接,因此旧应用对象和窗口快照不能重新生效。[原生对象决策](2026-09-17-experimental-cua-object-api.zh.md)继续负责进程身份、坐标语义和与执行器分离的设计。 @@ -28,9 +26,9 @@ CUA 执行器在每次对象 API 和原生工具调用时检查应用授权。 **依赖模型指引或隐藏控件。** 保留的对象和直接工具调用仍能到达原生操作。执行器必须在派发时检查用户决定。 -**保存应用名称或未签名路径。** 替换程序可以复用二者。长期许可需要可验证的签名身份;会话授权支持未签名的开发应用,但不承诺跨进程复用。 +**保存应用名称或未签名路径。** 替换程序可以复用二者。身份选择和在安装副本之间共用许可的决定由[Bundle ID 授权](2026-10-25-cua-bundle-id-consent.zh.md)负责。 -**新增审批数据库或 Session 控制流。** Profile settings 已负责用户配置,User Questions 已负责交互回答。权限界面查询 provider,并监听其配置 namespace,无须另一份授权存储或事件通道。 +**增加审批数据库或 Session 控制流。** User Questions 已经负责交互式回答。现有域服务提供持久状态,无须增加专用数据库或 Session 控制流;存储取舍由 profile 授权存储决策负责。 **根据浏览器访问地址禁用权限按钮。** 用户可能通过屏幕共享操作运行 DSH 的电脑,并在该电脑上完成授权。端口转发和代理使访问地址无法可靠判断浏览器与 DSH 是否运行在同一台电脑上。 diff --git a/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.i18n.yaml index 9378bc4f0b..4cf8989458 100644 --- a/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.i18n.yaml @@ -27,17 +27,17 @@ en: a01ac57fc71a84f0 zh: 3e488ef3da5e4b8c /agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control: - en: a55516339b0d49dd - zh: 3281df9ea7878fc0 + en: 725a2d4145c0a75e + zh: b98a64532cadeaba /agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/correspondence-with-rbac: en: a78a2410eb52f777 zh: a868bf1b0e690c9f /agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/resources-and-resource-readers-deepseek-ai-dsh-typert-protocol-deepseek-ai-dsh-typert-registry: - en: 625b20552962e268 - zh: 1136c0fd7cdc6901 + en: d50ae22978165c57 + zh: 8c1fcfb7dc2d3367 /agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/endpoint-resources: - en: ec1677d8e338e115 - zh: 6bedd163f208eaa9 + en: 582f5f527ecc58c8 + zh: 4a4b68361de2dcf0 /agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/roles-bindings-and-policies-deepseek-ai-dsh-api-remote-access: en: e57f396239ea9f56 zh: ddb26278b1521ceb @@ -45,8 +45,8 @@ en: 3c911f57f0f6ca4b zh: 1509781eeda4c922 /agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/host-access-check-order: - en: 6c58dc8777e107ef - zh: bc14605c96e4d8f3 + en: 2d97a251cc4c9db0 + zh: df072d5a96a9e82f /agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/forwarded-events: en: 5fe34ee5ec31942a zh: ef39b020b0539b8f @@ -75,14 +75,14 @@ en: 305ec45a7cd85ed7 zh: d2cd4209a56b1d0c /agent-note-peer-principals-and-method-level-remote-access-control/alternatives-considered: - en: 130df2981ba550df - zh: e9a0a89af6fb50a3 + en: 60da38bca6e9c3d6 + zh: 61ea578fe8185b61 /agent-note-peer-principals-and-method-level-remote-access-control/consequences: en: 89452c3c3f042e75 zh: 9bcad00a60c65303 /agent-note-peer-principals-and-method-level-remote-access-control/consequences/verification: - en: 2279a8c153cc5b89 - zh: 63c0b6462722f0a3 + en: d7d0909974609247 + zh: 6ebf20714f8d545b /agent-note-peer-principals-and-method-level-remote-access-control/consequences/costs-and-limits: en: 1e254cec680b1a37 zh: 06a31e057ba965aa diff --git a/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md b/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md index c9894ae409..7c13d393f3 100644 --- a/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md +++ b/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md @@ -131,7 +131,7 @@ The single read point is `this.ctx.invocation.peer.principal`; an owner test is ### Method-level access control -Resource types and the `resources` readers of `@Remote` live in `@deepseek-ai/dsh-typert-protocol`; resource kinds live in typert beside lookups and Contexts: `TypertResourceMap` declares the kinds, `typert.resources` holds each kind's default wire field, and lookups and Host Context adapters declare the resource kind their wire identity names. The Gateway resolves one call or forwarded event to the resources it touches. Decisions, list filtering, and the access snapshot live in the new package `@deepseek-ai/dsh-api-remote-access` (`packages/api/remote-access`), which reads no argument field. The Gateway and domain packages depend on remote-access only for types and inject `remoteAccess`; their only value dependency is `dsh-typert-protocol`, so `package-dependency-policy` gains no remote-access entry. Business packages define and register roles, bindings, and policies; liveshare is the first user. Apart from the built-in `global`, no resource-kind name appears in remote-access or the Gateway, which follows the [`packages/api` carries generic orchestration only](../../../../docs/defensive-patterns/remote-and-api.md) review rule. +Resource types and the `resources` readers of `@Remote` live in `@deepseek-ai/dsh-typert-protocol`; resource kinds live in typert beside lookups and Contexts: `TypertResourceMap` declares the kinds, `typert.resources` holds each kind's default wire field or resolver, and lookups and Host Context adapters declare the resource kind their wire identity names. The Gateway resolves one call or forwarded event to the resources it touches. Decisions, list filtering, and the access snapshot live in the new package `@deepseek-ai/dsh-api-remote-access` (`packages/api/remote-access`), which reads no argument field. The Gateway and domain packages depend on remote-access only for types and inject `remoteAccess`; their only value dependency is `dsh-typert-protocol`, so `package-dependency-policy` gains no remote-access entry. Business packages define and register roles, bindings, and policies; liveshare is the first user. Apart from the built-in `global`, no resource-kind name appears in remote-access or the Gateway, which follows the [`packages/api` carries generic orchestration only](../../../../docs/defensive-patterns/remote-and-api.md) review rule. #### Correspondence with RBAC @@ -165,7 +165,7 @@ export interface TypertResourceMap {} // @deepseek-ai/dsh-workspace/types: workspace: TypertResource // Runtime registries in typert -ctx.typert.resources.register(kind, { field }): TypertDisposer +ctx.typert.resources.register(kind, { field } | { resolve }): TypertDisposer ctx.typert.lookups.register(key, { parameter, wire, resource?, … }) // resource: the kind its wire id names ctx.typert.contexts.registerHost(key, { wire, resource?, … }) // a TypertHostContextAdapter @@ -213,11 +213,11 @@ export function RemoteScope | Rule | Content | |---|---| -| Syntax | `@Remote({ name: 'page', resources: { session: (request) => request.address.kind === 'session' ? request.address.sessionId : request.address.childSessionId } })`; a Context method writes `@RemoteScope('agent')` and gets its Session resource from the Agent Context's `resource: 'session'`, and writes `@RemoteScope('agent', { resources: { workspace: (request) => request.workspaceId } })` when it needs another resource. Most methods write no `resources` and get their resources from automatic resolution | +| Syntax | `@Remote({ name: 'prompt', resources: { session: (request) => request.sessionId } })` when a method must name its resource by hand; `session/page` and `session/follow` instead rely on the registered `session` default resolver; a Context method writes `@RemoteScope('agent')` and gets its Session resource from the Agent Context's `resource: 'session'`, and writes `@RemoteScope('agent', { resources: { workspace: (request) => request.workspaceId } })` when it needs another resource. Most methods write no `resources` and get their resources from automatic resolution | | Resource kinds | The lower-level packages that declare the identity types merge the resource kinds: `session: TypertResource` in `@deepseek-ai/dsh-session/types` and `workspace: TypertResource` in `@deepseek-ai/dsh-workspace/types`. session-controller references the commands package, so a merge in session-controller would make commands reference session-controller and form a project-reference cycle. remote-access builds in `global`, which has no id and stays out of `TypertResourceMap`; typert reserves the name, and `typert.resources.register('global', …)` throws | -| Default fields and declarations | The domain that owns a kind registers its default wire field when its controller is constructed: the `SessionController` constructor calls `typert.resources.register('session', { field: 'sessionId' })` and the `WorkspaceController` constructor registers `workspace` → `workspaceId`; registering a kind twice throws. The Agent, Session, and `workspaceFileScope` lookups declare `resource: 'session'`, and the agent package's Agent Context declares `resource: 'session'` | -| Resolution precedence | Each resource kind takes, in order: ① that kind's reader in the method's `resources`; ② every lookup parameter that declares that kind as its `resource` contributes its wire identity, and an omitted optional lookup parameter contributes none; when the Context of a Context method declares that kind as its `resource`, the Context's wire identity contributes too; ③ that kind's default field: a top-level named argument of that name when one exists, otherwise that field of the first object argument. A default field names one identity, so an array there is an invalid value | -| Argument values | Resource resolution and the `args` of `decide()` read the named arguments validated against their Typert-compiled types: each JSON argument is decoded once by its codec, which drops object fields its type does not declare, and dispatch reuses that value, so a caller cannot change the resources with an undeclared field; lookup parameters and the Context identity keep their wire identities, and no lookup or Agent is resolved at that point | +| Default extraction declarations | The owning domain registers either `{ field }` or `{ resolve }`, never both. SessionController registers `resolveSessionResource`; WorkspaceController registers `workspaceId`. Duplicate kinds are rejected. Lookup and Host Context resource declarations remain independent of these defaults | +| Resolution precedence | Per kind: explicit method reader, then lookup and Host Context identities, then the registered default field or resolver. A field reads the named top-level parameter or the first object argument. A resolver receives validated named `args` and ordered parameter descriptions once before lookup resolution. Defaults return one non-empty string or undefined; arrays are invalid | +| Argument values | Compiled codecs strip undeclared object fields; SRC fallback checks JSON safety without stripping them. Resolution and dispatch use the same validated values. The Session resolver rejects a request object containing both sessionId and address, even when equal. Lookup and Context identities remain wire values until after authorization | | Resolution result | The resources of every kind together are the resources the call touches; with none, the call touches `[global]`; when resources resolve, only those are used and `global` is not added | | Readers | Called with the method's positional arguments: the named arguments mapped by the descriptor back to the method's parameter order (the validated value in a JSON position, the wire identity in a lookup position, and the call's signal in the cancellation position); return one id, an id array (every one must be allowed), or `undefined` (no resource of that kind) | | Invalid values | A reader that throws or returns an empty array, or a read value (including a Context's wire identity) that is not a non-empty string, makes the resources invalid: the Gateway refuses the call with `remote-access/denied` (reason `resource-invalid`) without asking `decide()` | @@ -228,7 +228,7 @@ export function RemoteScope #### Endpoint resources -The table lists the endpoints #3854 viewers use and where their resources come from. Only `session/page` and `session/follow` need explicit `resources`; the rest rely on a lookup's `resource` or the default field: +The table lists the endpoints #3854 viewers use and where their resources come from. Session history endpoints use the registered Session resolver; special method readers can override defaults: | Endpoint | Resource | Resolution source | Filtering inside the method | |---|---|---|---| @@ -241,16 +241,18 @@ The table lists the endpoints #3854 viewers use and where their resources come f | `llm/listProviders` | `global` | no resource | no | | `commands/list` | session: `args.agentId` (the Agent lookup's wire field) | Agent lookup `resource: 'session'` | no | | `goals/get` | session: `args.agentId` | Agent lookup `resource: 'session'` | no | -| `session/attachment` | session: `args.request.sessionId` | default field | no | -| `skills/list` | session: `args.request.sessionId` | default field | no | -| `session/fork` | session: `args.request.sessionId` | default field | no | -| `session/prompt` | session: `args.request.sessionId` | default field | no | -| `session/cancel` | session: `args.request.sessionId` | default field | no | -| `session/projections` | session: `args.request.sessionId` | default field | no | -| `session/page` | session: `args.request.address.sessionId` for a Session address; `args.request.address.childSessionId` for a subagent address | `resources` | no | -| `session/follow` | same as above | `resources` | no | +| `session/attachment` | session: `args.request.sessionId` | default resolver | no: a grant on one Session permits reads from the whole attachment store | +| `skills/list` | session: `args.request.sessionId` | default resolver | no | +| `session/fork` | session: `args.request.sessionId` | default resolver | no | +| `session/prompt` | session: `args.request.sessionId` | default resolver | no | +| `session/cancel` | session: `args.request.sessionId` | default resolver | no | +| `session/projections` | session: `args.request.sessionId` | default resolver | no | +| `session/page` | session: `args.request.address.sessionId` for a Session address; `args.request.address.childSessionId` for a subagent address | default resolver | no | +| `session/follow` | same as above | default resolver | no | | `remoteAccess/follow` | `global` | no resource; remote-access allows it for every principal | no | +For `session/attachment`, `sessionId` identifies the resource for the Gateway check; it does not constrain which image may be read. Once that check permits the call, an image may belong to another Session or no Session, and the handler does not check whether the supplied Session exists. Policy authors must treat this action as access to the whole attachment store, as defined by the [image access rule](2026-10-23-store-scoped-image-reads.md). + A subagent address reads the child transcript, so its resource is the child Session. A Client rereads the projections of known Sessions after a reconnect, including the parent of a subagent Session; a reader without a grant on that parent has its projection read refused. Whether a grant on a parent Session covers its subagent children is the policy's decision, that is, whether it gives a binding for the child Session; the generic layer derives no parent resource. Methods that need no non-owner access declare nothing, and a method no role lists is refused. The request fields of subagent `prompt` are `parentSessionId` / `childSessionId`, so automatic resolution finds no Session and resolves it to `global`; it must therefore stay out of every `global` role. `session/search` filters its hits per Session inside the method. `subagents/list` is not a Remote endpoint (`SubagentRuntime.list()` carries no `@Remote`). @@ -392,7 +394,7 @@ Every call path (HTTP `/api`, WebSocket streams, in-process `fetch(request, peer | 1 | Admission yields the Peer: network paths from Connection `admit()` (`browserPeer`), in-process paths from the caller. The Gateway checks `peer.signal` before it reads the wire payload | Failed network admission answers HTTP 401 / 403 without entering the Gateway; a disposed Peer: `gateway/peer-disposed` | | 2 | Resolve the endpoint and validate the argument field set (`resolveDescriptor`, `assertExactArguments`), then validate the JSON arguments against their Typert-compiled types, decoding each once | `gateway/invocation-unavailable`, `gateway/ambiguous-endpoint`, `gateway/definition-unavailable`; extra or missing fields: `gateway/arguments-invalid`; a JSON argument failing validation: `gateway/input-invalid` (for owners and non-owners alike, before the access check) | | 3 | Owner pass-through: for `principal.kind === 'owner'` go straight to step 5 | — | -| 4 | Non-owner: the Gateway resolves resources from the arguments validated in step 2 (`resources` readers, then lookup parameters and the `resource` a Context declares, then default fields; lookup and Context identities are wire identities, and neither a lookup nor the Context is resolved), then asks `remoteAccess.decide({ principal, action: endpoint, resources, args })` with the validated arguments as `args`; invalid resources are refused with `resource-invalid` without asking `decide()`; a `deny` decision becomes the thrown error | `remote-access/denied` with details `{ action, reason }` | +| 4 | Non-owner: the Gateway resolves resources from the arguments validated in step 2 (`resources` readers, then lookup parameters and the `resource` a Context declares, then the registered default field or resolver; lookup and Context identities are wire identities, and neither a lookup nor the Context is resolved), then asks `remoteAccess.decide({ principal, action: endpoint, resources, args })` with the validated arguments as `args`; invalid resources are refused with `resource-invalid` without asking `decide()`; a `deny` decision becomes the thrown error | `remote-access/denied` with details `{ action, reason }` | | 5 | Dispatch: `resolveReceiverContext` (which can activate an Agent), lookup resolution (JSON arguments reuse the step 2 values), and the method call | Existing codes unchanged, such as `gateway/lookup-not-found`, `gateway/context-not-found`, `gateway/input-invalid`, `gateway/service-unavailable`, `gateway/method-unavailable`, and business errors | The access check (steps 3–4) precedes lookup and Context resolution, so a refused call activates no Session and causes no other side effect. The only new Gateway error code is `gateway/peer-disposed`; remote-access declares the refusal code `remote-access/denied`. @@ -600,7 +602,7 @@ The review rule's home is the "`@Remote` marks capability methods" section of [R **Refusal reasons from conditions only.** Without a binding there is no condition to give a reason, so a viewer page could not tell "share expired" from "share not writable"; `explain` gives a reason only after the decision is already a refusal and never changes it. -**A global resource-resolver registry (domain packages register recognizers by field name).** Field recognition separates from the method, nothing flags a method signature change, and same-named fields in other packages are misread; resource resolution uses a default convention on the method plus per-method `resources`, and a domain package registers only its own kind's default field. +**A global resource-resolver registry (domain packages register recognizers by field name).** Field recognition separates from the method, nothing flags a method signature change, and same-named fields in other packages are misread; resource resolution uses a default convention on the method plus per-method `resources`, and a domain package registers only its own kind's default field or resolver. **Dot-path resource declarations (`'request.address.sessionId'`).** Types cannot constrain a path; the parameter types of `resources` readers are inferred from the decorated method, so a typo fails compilation. @@ -635,8 +637,8 @@ The review rule's home is the "`@Remote` marks capability methods" section of [R | Check order | The owner calls any method normally without reading a policy; a method no role lists refuses non-owners with `remote-access/denied` (`no-allow`); the access check precedes lookups, so a refused call activates no Session | Gateway host spec | | Policy registration | One policy per non-owner principal kind, and a second registration throws; once the disposer withdraws it, that kind is refused with `no-allow`; it is withdrawn with its fiber | remote-access host spec | | Decisions | Every resource needs a matching binding (AND); a role without the action, an unequal resource, or a refusing condition does not allow; the refusal reason follows condition > `explain` > `no-allow`; `explain` never changes the decision; conditions receive args for calls but not for snapshots and list filtering; a throwing `bindings()`, condition, or `explain()` refuses with `policy-failed`, each policy is logged once between `invalidate()` calls, and on the event path the owner stream and the shared event source continue; `remoteAccess/follow` is allowed for every principal | remote-access host spec, Gateway host spec | -| Resource resolution | A default field (top-level or first object argument) yields its resource; a lookup parameter that declares that kind as its `resource` yields its wire identity; a Context method gets its Session resource from the Agent Context identity in args without activating the Agent, and may declare other resources through `resources`; a `resources` reader overrides its kind, an array yields several resources, and `undefined` none; with nothing the call is `[global]`; a throw, an empty array, or a value that is not a non-empty string (including a Context identity) is invalid, refused by the Gateway with `resource-invalid` without asking `decide()`; a Context that declares no `resource` resolves by the ordinary rules; resources and `args` read the validated arguments, so an undeclared nested field changes no resource and no condition sees it, and a JSON argument failing validation returns `gateway/input-invalid` before the access check | Gateway host spec (gateway-access) | -| Resource registry | `typert.resources` registers one default field per kind, rejects a second registration and `global`, and withdraws the registration with its fiber; a configured lookup resolver keeps the provider's `resource`; a Host Context adapter keeps its `resource` | typert-registry spec | +| Resource resolution | A default field or resolver yields one resource; a default resolver returning an array is invalid; a lookup parameter that declares that kind as its `resource` yields its wire identity; a Context method gets its Session resource from the Agent Context identity in args without activating the Agent, and may declare other resources through `resources`; a `resources` reader overrides its kind, an array yields several resources, and `undefined` none; with nothing the call is `[global]`; a throw, an empty array, or a value that is not a non-empty string (including a Context identity) is invalid, refused by the Gateway with `resource-invalid` without asking `decide()`; a Context that declares no `resource` resolves by the ordinary rules; resources and `args` read the validated arguments, with undeclared fields stripped only by compiled codecs, and a JSON argument failing validation returns `gateway/input-invalid` before the access check | Gateway host spec (gateway-access) | +| Resource registry | `typert.resources` registers one default field or resolver per kind, rejects a second registration and `global`, and withdraws the registration with its fiber; a configured lookup resolver keeps the provider's `resource`; a Host Context adapter keeps its `resource` | typert-registry spec | | Forwarded events | A non-owner `$events` stream receives an event, whole, only when `event:` is granted on its resources; an event that declares no resources is decided on `global`; an event whose reader returns `undefined` does not reach non-owners, and `decide()` is not asked; the owner receives all | Gateway host spec (gateway-access) | | First snapshot | `snapshotFor()` returns the owner baseline or the principal's grants; remote-access injects the snapshot of the Peer each index speaks for; the Client starts from the injected baseline and rejects a malformed one | remote-access host and client specs | | Type inference | The parameter types of `resources` readers are inferred from the method; lookup positions have wire types; a missing property, more parameters than the method has, and a `global` key fail compilation; a binding whose resource kind differs from its role's fails compilation | typert-protocol spec, remote-access spec (type tests) | diff --git a/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md b/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md index ed124e8159..9503b430aa 100644 --- a/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md @@ -131,7 +131,7 @@ export function principalOf(invocation: RemoteInvocation | undefined): Principal ### 方法级访问控制 -资源类型与 `@Remote` 的 `resources` 读取函数在 `@deepseek-ai/dsh-typert-protocol`;资源种类在 typert 中与 lookups、Contexts 并列:`TypertResourceMap` 声明种类,`typert.resources` 保存每个种类的默认 wire 字段,lookup 与 Host Context adapter 声明其 wire 身份所属的资源种类。Gateway 把一次调用或一个转发事件解析为它访问的资源。判定、列表过滤与访问快照在新包 `@deepseek-ai/dsh-api-remote-access`(`packages/api/remote-access`),该包不读取任何参数字段。Gateway 与领域包对 remote-access 只做 type-only 依赖并 inject `remoteAccess`,值依赖只有 `dsh-typert-protocol`,不为 remote-access 新增 `package-dependency-policy` 条目。role、binding 与 policy 由业务包定义和注册,liveshare 为首个使用方。除内置的 `global` 外,remote-access 与 Gateway 中不出现任何资源种类名,符合 [`packages/api` 只承载通用编排](../../../../docs/defensive-patterns/remote-and-api.zh.md) 的评审规则。 +资源类型与 `@Remote` 的 `resources` 读取函数在 `@deepseek-ai/dsh-typert-protocol`;资源种类在 typert 中与 lookups、Contexts 并列:`TypertResourceMap` 声明种类,`typert.resources` 保存每个种类的默认 wire 字段或 resolver,lookup 与 Host Context adapter 声明其 wire 身份所属的资源种类。Gateway 把一次调用或一个转发事件解析为它访问的资源。判定、列表过滤与访问快照在新包 `@deepseek-ai/dsh-api-remote-access`(`packages/api/remote-access`),该包不读取任何参数字段。Gateway 与领域包对 remote-access 只做 type-only 依赖并 inject `remoteAccess`,值依赖只有 `dsh-typert-protocol`,不为 remote-access 新增 `package-dependency-policy` 条目。role、binding 与 policy 由业务包定义和注册,liveshare 为首个使用方。除内置的 `global` 外,remote-access 与 Gateway 中不出现任何资源种类名,符合 [`packages/api` 只承载通用编排](../../../../docs/defensive-patterns/remote-and-api.zh.md) 的评审规则。 #### 与 RBAC 的对应 @@ -165,7 +165,7 @@ export interface TypertResourceMap {} // @deepseek-ai/dsh-workspace/types: workspace: TypertResource // Runtime registries in typert -ctx.typert.resources.register(kind, { field }): TypertDisposer +ctx.typert.resources.register(kind, { field } | { resolve }): TypertDisposer ctx.typert.lookups.register(key, { parameter, wire, resource?, … }) // resource: the kind its wire id names ctx.typert.contexts.registerHost(key, { wire, resource?, … }) // a TypertHostContextAdapter @@ -213,11 +213,11 @@ export function RemoteScope | 规则 | 内容 | |---|---| -| 写法 | `@Remote({ name: 'page', resources: { session: (request) => request.address.kind === 'session' ? request.address.sessionId : request.address.childSessionId } })`;Context 方法写 `@RemoteScope('agent')`,由 Agent Context 的 `resource: 'session'` 得到会话资源,需要其他资源时写 `@RemoteScope('agent', { resources: { workspace: (request) => request.workspaceId } })`。多数方法不写 `resources`,由自动解析得到资源 | +| 写法 | 方法必须手工点名资源时写 `@Remote({ name: 'prompt', resources: { session: (request) => request.sessionId } })`;`session/page` 与 `session/follow` 则依赖已注册的 `session` 默认 resolver;Context 方法写 `@RemoteScope('agent')`,由 Agent Context 的 `resource: 'session'` 得到会话资源,需要其他资源时写 `@RemoteScope('agent', { resources: { workspace: (request) => request.workspaceId } })`。多数方法不写 `resources`,由自动解析得到资源 | | 资源种类 | 资源种类由声明 id 类型的底层包合并:`session: TypertResource` 在 `@deepseek-ai/dsh-session/types`,`workspace: TypertResource` 在 `@deepseek-ai/dsh-workspace/types`。session-controller 引用 commands 包,若在 session-controller 合并,commands 要引用 session-controller,形成 project reference 环。`global` 由 remote-access 内置,没有 id,不进 `TypertResourceMap`;typert 保留该名,`typert.resources.register('global', …)` 抛错 | -| 默认字段与声明 | 拥有该种类的领域在控制器构造时登记默认 wire 字段:`SessionController` 构造函数调用 `typert.resources.register('session', { field: 'sessionId' })`,`WorkspaceController` 构造函数登记 `workspace` → `workspaceId`;同一种类重复登记即抛错。Agent、Session 与 `workspaceFileScope` lookup 声明 `resource: 'session'`,agent 包的 Agent Context 声明 `resource: 'session'` | -| 解析优先级 | 对每个资源种类依次取:① 该方法 `resources` 中该种类的读取函数;② 声明了该种类 `resource` 的每个 lookup 参数贡献其 wire 身份,省略的可选 lookup 参数不贡献;Context 方法的 Context 声明了该种类 `resource` 时,其 wire 身份同样贡献;③ 该种类的默认字段:命名参数中有同名顶层参数就读它,否则读第一个对象参数的同名字段。默认字段只表示一个身份,读到数组即为非法值 | -| 参数来源 | 资源解析与 `decide()` 的 `args` 读取经 Typert 编译类型校验后的命名参数:每个 JSON 参数由其 codec 解码一次,类型未声明的对象字段被移除,分派复用该值,因此调用方无法用未声明字段改变资源;lookup 参数与 Context 身份取 wire 身份,此时不解析 lookup、不激活 Agent | +| 默认提取声明 | 资源所属领域登记 `{ field }` 或 `{ resolve }`,两者互斥。SessionController 登记 `resolveSessionResource`;WorkspaceController 登记 `workspaceId`。重复种类被拒绝;lookup 和 Host Context 的资源声明独立于默认规则 | +| 解析优先级 | 每个种类依次采用方法显式 reader、lookup 与 Host Context 身份、注册的默认字段或 resolver。字段读取同名顶层参数或首个对象参数。resolver 在 lookup 解析前调用一次,接收已校验的命名 `args` 及有序参数描述。默认规则返回一个非空字符串或 undefined,数组非法 | +| 参数来源 | 编译 codec 移除未声明的对象字段;SRC fallback 只检查 JSON 安全性,不移除字段。解析和分派使用相同的已校验值。Session resolver 拒绝同时包含 sessionId 与 address 的请求对象,即使两者相同。lookup 和 Context 身份在授权完成前保持 wire 值 | | 解析结果 | 各种类的资源合在一起即本次调用访问的资源;一个都没有即 `[global]`;解析出资源时只用这些资源,不附加 `global` | | 读取函数 | 以方法的位置参数调用:按描述符把命名参数映射回方法参数顺序(JSON 位为校验后的值,lookup 位为 wire 身份,取消参数位为调用的 signal);返回一个 id、id 数组(每个都须被允许)或 `undefined`(该种类无资源) | | 非法值 | 读取函数抛错或返回空数组,或读到的值(含 Context 的 wire 身份)不是非空字符串即资源非法:Gateway 不询问 `decide()`,直接以 `remote-access/denied`(reason `resource-invalid`)拒绝调用 | @@ -228,7 +228,7 @@ export function RemoteScope #### 端点的资源 -下表列出 #3854 读者用到的端点及其资源来源。只有 `session/page` 与 `session/follow` 需要显式 `resources`,其余靠 lookup 的 `resource` 或默认字段: +下表列出 #3854 读者用到的端点及其资源来源。Session 历史端点使用注册的 Session resolver;特殊方法可用显式 reader 覆盖默认规则: | 端点 | 资源 | 解析来源 | 方法内过滤 | |---|---|---|---| @@ -241,16 +241,18 @@ export function RemoteScope | `llm/listProviders` | `global` | 无资源 | 否 | | `commands/list` | session:`args.agentId`(Agent lookup 的 wire 字段) | Agent lookup `resource: 'session'` | 否 | | `goals/get` | session:`args.agentId` | Agent lookup `resource: 'session'` | 否 | -| `session/attachment` | session:`args.request.sessionId` | 默认字段 | 否 | -| `skills/list` | session:`args.request.sessionId` | 默认字段 | 否 | -| `session/fork` | session:`args.request.sessionId` | 默认字段 | 否 | -| `session/prompt` | session:`args.request.sessionId` | 默认字段 | 否 | -| `session/cancel` | session:`args.request.sessionId` | 默认字段 | 否 | -| `session/projections` | session:`args.request.sessionId` | 默认字段 | 否 | -| `session/page` | session:Session 地址读 `args.request.address.sessionId`;subagent 地址读 `args.request.address.childSessionId` | `resources` | 否 | -| `session/follow` | 同上 | `resources` | 否 | +| `session/attachment` | session:`args.request.sessionId` | 默认 resolver | 否:一条 Session 上的授权允许读取整个附件存储 | +| `skills/list` | session:`args.request.sessionId` | 默认 resolver | 否 | +| `session/fork` | session:`args.request.sessionId` | 默认 resolver | 否 | +| `session/prompt` | session:`args.request.sessionId` | 默认 resolver | 否 | +| `session/cancel` | session:`args.request.sessionId` | 默认 resolver | 否 | +| `session/projections` | session:`args.request.sessionId` | 默认 resolver | 否 | +| `session/page` | session:Session 地址读 `args.request.address.sessionId`;subagent 地址读 `args.request.address.childSessionId` | 默认 resolver | 否 | +| `session/follow` | 同上 | 默认 resolver | 否 | | `remoteAccess/follow` | `global` | 无资源;remote-access 对任何 principal 放行 | 否 | +对于 `session/attachment`,`sessionId` 指定 Gateway 检查的资源,不限制可读取哪张图片。该检查放行后,图片可以属于其他 Session 或不属于任何 Session,处理函数也不检查请求中的 Session 是否存在。policy 作者必须把此 action 视为整个附件存储的读取权限,具体规则见[图片访问规则](2026-10-23-store-scoped-image-reads.zh.md)。 + subagent 地址读取的是子会话转录,因此其资源是子会话。Client 在重连后会重新读取已知会话的 projections,其中包括 subagent 会话的父会话;没有该父会话授权的读者,其 projection 读取被拒。父会话的授权是否覆盖其 subagent 子会话由 policy 决定,即是否为子会话给出 binding;通用层不推导父资源。 不需要非 owner 访问的方法不做任何声明,没有 role 列出它即被拒。subagent `prompt` 的请求字段为 `parentSessionId` / `childSessionId`,自动解析不到会话,解析为 `global`,因此不得放进任何 `global` 级 role;`session/search` 在方法内按会话逐项过滤命中。`subagents/list` 不是 Remote 端点(`SubagentRuntime.list()` 未标 `@Remote`)。 @@ -392,7 +394,7 @@ const childPrompt = child => ({ action, args }) => | 1 | 准入得到 Peer:网络路径由 Connection `admit()` 给出(`browserPeer`);进程内路径由调用方传入。Gateway 在读取 wire payload 之前检查 `peer.signal` | 网络准入失败返回 HTTP 401 / 403(不进入 Gateway);Peer 已 dispose:`gateway/peer-disposed` | | 2 | 解析端点并做参数字段集校验(`resolveDescriptor`、`assertExactArguments`),再按 Typert 编译类型校验 JSON 参数,每个参数解码一次 | `gateway/invocation-unavailable`、`gateway/ambiguous-endpoint`、`gateway/definition-unavailable`;字段多余或缺失:`gateway/arguments-invalid`;JSON 参数校验失败:`gateway/input-invalid`(owner 与非 owner 相同,先于访问检查) | | 3 | owner 直通:`principal.kind === 'owner'` 时直接进入第 5 步 | — | -| 4 | 非 owner:Gateway 从第 2 步校验后的参数解析资源(`resources` 读取函数、其次 lookup 参数与 Context 声明的 `resource`、再次默认字段;lookup 与 Context 身份取 wire 身份,不解析 lookup 与 Context),再以校验后的参数为 `args` 询问 `remoteAccess.decide({ principal, action: endpoint, resources, args })`;资源非法时不询问 `decide()`,直接以 `resource-invalid` 拒绝;`deny` 结论变为抛出的错误 | `remote-access/denied`,details `{ action, reason }` | +| 4 | 非 owner:Gateway 从第 2 步校验后的参数解析资源(`resources` 读取函数、其次 lookup 参数与 Context 声明的 `resource`、再次注册的默认字段或 resolver;lookup 与 Context 身份取 wire 身份,不解析 lookup 与 Context),再以校验后的参数为 `args` 询问 `remoteAccess.decide({ principal, action: endpoint, resources, args })`;资源非法时不询问 `decide()`,直接以 `resource-invalid` 拒绝;`deny` 结论变为抛出的错误 | `remote-access/denied`,details `{ action, reason }` | | 5 | 分派:`resolveReceiverContext`(可能激活 Agent)、lookup 解析(JSON 参数复用第 2 步的值)、调用方法 | 既有错误码不变,如 `gateway/lookup-not-found`、`gateway/context-not-found`、`gateway/input-invalid`、`gateway/service-unavailable`、`gateway/method-unavailable` 与业务错误 | 鉴权(第 3–4 步)位于 lookup 与 Context 解析之前,未授权调用不会激活会话或产生其他副作用。Gateway 新增的错误码只有 `gateway/peer-disposed`;拒绝码 `remote-access/denied` 由 remote-access 声明。 @@ -600,7 +602,7 @@ GlobalStandardProps.useWorkspaceAccess: (workspaceId: WorkspaceId, action: Remot **拒绝原因只由 condition 给出。** 没有 binding 时没有 condition 可以给出原因,读者页面无法区分「分享已过期」「分享不允许写入」等情况;`explain` 只在结论已为拒绝后给出原因,不改变结论。 -**全局资源 resolver 注册表(领域包按字段名注册识别函数)。** 字段识别与方法分离,方法改签名时无人提醒,跨包同名字段也会被误认;资源解析采用方法上的默认约定加 per-method `resources`,领域包只登记自己种类的默认字段。 +**全局资源 resolver 注册表(领域包按字段名注册识别函数)。** 字段识别与方法分离,方法改签名时无人提醒,跨包同名字段也会被误认;资源解析采用方法上的默认约定加 per-method `resources`,领域包只登记自己种类的默认字段或 resolver。 **按点路径声明资源(`'request.address.sessionId'`)。** 路径无法由类型推导约束;`resources` 读取函数的参数类型从被装饰方法推断,拼错即编译失败。 @@ -635,8 +637,8 @@ GlobalStandardProps.useWorkspaceAccess: (workspaceId: WorkspaceId, action: Remot | 鉴权顺序 | owner 调用任何方法照常分派且不读取 policy;没有 role 列出的方法对非 owner 以 `remote-access/denied`(`no-allow`)拒绝;访问检查早于 lookup,被拒调用不激活会话 | Gateway host spec | | policy 注册 | 每个非 owner principal kind 一个 policy,重复注册抛错;disposer 撤回后该 kind 以 `no-allow` 拒绝;随 fiber 撤回 | remote-access host spec | | 判定 | 每个资源都需要匹配的 binding(AND);role 不含该 action、资源不相等或 condition 拒绝都不放行;拒绝原因按 condition > `explain` > `no-allow` 取;`explain` 不改变结论;condition 在调用时收到 args,在快照与列表过滤时不收;`bindings()`、condition 或 `explain()` 抛错以 `policy-failed` 拒绝,每个 policy 在两次 `invalidate()` 之间只记录一次日志,事件路径上 owner 流与共享事件源照常;`remoteAccess/follow` 对任何 principal 放行 | remote-access host spec、Gateway host spec | -| 资源解析 | 默认字段(顶层或首个对象参数)得到对应资源;声明了该种类 `resource` 的 lookup 参数得到其 wire 身份;Context 方法从 args 中的 Agent Context 身份得到其 session 资源且不激活 Agent,另可经 `resources` 声明其他资源;`resources` 读取函数覆盖该种类,数组为多个资源,`undefined` 为无;都没有为 `[global]`;抛错、空数组或非非空字符串(含 Context 身份)为非法,Gateway 以 `resource-invalid` 拒绝且不询问 `decide()`;未声明 `resource` 的 Context 按普通规则解析;资源与 `args` 读取校验后的参数,未声明的嵌套字段不改变资源、condition 也读不到它,JSON 参数校验失败在访问检查前返回 `gateway/input-invalid` | Gateway host spec(gateway-access) | -| 资源注册表 | `typert.resources` 每个种类登记一个默认字段,拒绝重复登记与 `global`,并随 fiber 撤回;配置的 lookup resolver 保留 provider 的 `resource`;Host Context adapter 保留其 `resource` | typert-registry spec | +| 资源解析 | 默认字段或 resolver 得到一个资源,默认 resolver 返回数组为非法;声明了该种类 `resource` 的 lookup 参数得到其 wire 身份;Context 方法从 args 中的 Agent Context 身份得到其 session 资源且不激活 Agent,另可经 `resources` 声明其他资源;`resources` 读取函数覆盖该种类,数组为多个资源,`undefined` 为无;都没有为 `[global]`;抛错、空数组或非非空字符串(含 Context 身份)为非法,Gateway 以 `resource-invalid` 拒绝且不询问 `decide()`;未声明 `resource` 的 Context 按普通规则解析;资源与 `args` 读取校验后的参数,只有编译 codec 才移除未声明字段,JSON 参数校验失败在访问检查前返回 `gateway/input-invalid` | Gateway host spec(gateway-access) | +| 资源注册表 | `typert.resources` 每个种类登记一个默认字段或 resolver,拒绝重复登记与 `global`,并随 fiber 撤回;配置的 lookup resolver 保留 provider 的 `resource`;Host Context adapter 保留其 `resource` | typert-registry spec | | 转发事件 | 非 owner 的 `$events` 流只在 `event:` 于其资源上被授权时整条收到事件;未声明资源的事件按 `global` 判定;读取函数返回 `undefined` 的事件不送达非 owner,且不询问 `decide()`;owner 全部收到 | Gateway host spec(gateway-access) | | 首份快照 | `snapshotFor()` 返回 owner baseline 或该 principal 的 grant;remote-access 为每个 index 注入其所代表 Peer 的快照;Client 从注入的 baseline 起步并拒绝格式错误的快照 | remote-access host 与 client spec | | 类型推断 | `resources` 读取函数的参数类型从方法推断;lookup 位为 wire 类型;访问不存在的属性、参数多于方法参数与 `global` 键编译失败;binding 的资源种类与 role 不符编译失败 | typert-protocol spec、remote-access spec(类型测试) | diff --git a/.agents/notes/implemented/architecture/2026-10-19-cua-profile-consent-storage.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-19-cua-profile-consent-storage.i18n.yaml new file mode 100644 index 0000000000..d95e587c31 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-19-cua-profile-consent-storage.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-19-cua-profile-consent-storage.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-19-cua-profile-consent-storage.md +/agent-note-durable-computer-use-consent-within-one-profile: + en: b2aa270d586efd93 + zh: 99606fa28dc4a752 +/agent-note-durable-computer-use-consent-within-one-profile/problem: + en: f2c70036a57ddb41 + zh: 9bbbf3dd09d486f5 +/agent-note-durable-computer-use-consent-within-one-profile/decision: + en: 11622523090f5d88 + zh: 1d0f8ad94645f069 +/agent-note-durable-computer-use-consent-within-one-profile/alternatives-considered: + en: 2af74afa3ecaf3b9 + zh: 96f7f43c5d1150df +/agent-note-durable-computer-use-consent-within-one-profile/consequences: + en: 66fe232589e46d64 + zh: fc69831be76248d9 diff --git a/.agents/notes/implemented/architecture/2026-10-19-cua-profile-consent-storage.md b/.agents/notes/implemented/architecture/2026-10-19-cua-profile-consent-storage.md new file mode 100644 index 0000000000..c70651899c --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-19-cua-profile-consent-storage.md @@ -0,0 +1,31 @@ +# Agent Note: Durable Computer Use consent within one profile + +Status: implemented + +English | [中文](2026-10-19-cua-profile-consent-storage.zh.md) + +## Problem + +Application grants stored as plugin configuration make each authorization change depend on configuration reconciliation. Process-local conversation decisions also disappear when the same conversation resumes after a restart. A shared in-memory storage handle cannot observe another process revoking permission. + +## Decision + +The CUA owner uses the existing domain storage service, with one domain per canonical profile directory. It stores long-term grants and conversation decisions by native application identity. Conversation IDs scope permission without turning it into permission for every conversation. The native identity policy remains owned by [bundle-ID consent](2026-10-25-cua-bundle-id-consent.md); this note replaces only that note's storage and restart-lifetime choices. + +Every operation opens fresh domain state while holding the profile's existing file-lock primitive and closes the domain before releasing the lock. Native dispatch and revocation use a separate lock for the selected application. Storage reads and unrelated applications remain available during a native call. Revocation cancels this process's affected work first, then commits after other processes' already-admitted operations have finished. A completed revocation therefore leaves no operation using the old authority. App-wide revocation generations and per-conversation decision revisions prevent an old handle or delayed answer from restoring revoked access. + +The JSON backend remains the shipped default. The domain name contains the SHA-256 digest of the canonical profile directory, isolating profiles that share one storage root. Legacy `allowedApps` is imported once; a persisted migration marker prevents an old configuration from restoring a revoked grant. Users can remove that configuration after checking the migrated list. Corrupt or unavailable profile storage fails closed. A composition without a profile has only temporary conversation state. + +## Alternatives considered + +**Keep authorization in configuration.** It preserves existing storage but retains configuration-write and HMR coupling for runtime application decisions. + +**Keep one domain open and rely on change events.** Domain notifications are process-local. Another host could continue to use stale grants after revocation. + +**Add a new watcher, revision file or authorization broker.** The existing domain and file-lock primitives provide fresh reads and serialized operation admission without a new shared storage or IPC framework. Operations on the same application are serialized across processes; other applications and their conversation decisions remain independent. + +## Consequences + +File locks coordinate processes on one machine and PID namespace. A network-mounted profile shared across hosts is unsupported. Revocation may wait for another process's native call to settle. No timer establishes authorization validity. + +The permission page still omits conversation-only grants and reads current state on entry, focus, actions and reconnection. Storage changes do not emit configuration events. System permissions remain owned by macOS. Tests cover restart retention, profile isolation, another process's write, cancellation, corrupted data, legacy import and non-resurrection after revocation. Stored conversation records currently require explicit retention management rather than automatic eviction. diff --git a/.agents/notes/implemented/architecture/2026-10-19-cua-profile-consent-storage.zh.md b/.agents/notes/implemented/architecture/2026-10-19-cua-profile-consent-storage.zh.md new file mode 100644 index 0000000000..ef6be5c57b --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-19-cua-profile-consent-storage.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 同一 profile 内的持久 Computer Use 授权 + +Status: implemented + +[English](2026-10-19-cua-profile-consent-storage.md) | 中文 + +## 问题 + +把应用许可保存为插件配置,会让每次授权变更依赖配置重组。只保存在进程内的会话决定,也会在重启后恢复同一对话时丢失。长期持有的内存存储句柄无法观察另一个进程的撤销操作。 + +## 决策 + +CUA 使用现有域存储服务,每个 profile 的真实目录对应独立存储域,按本机应用身份保存长期许可和会话决定。对话 ID 限定权限范围,不把本会话许可扩展为所有对话的许可。本机身份规则仍由[Bundle ID 授权](2026-10-25-cua-bundle-id-consent.zh.md)负责,本记录仅替代其中的存储和重启后有效期选择。 + +每个操作使用现有文件锁,在 profile 锁内打开并读取最新存储状态,关闭域后才释放锁。原生操作和撤销使用单独的目标应用锁;原生调用期间仍可读取存储或访问其他应用。撤销先取消本进程中受影响的工作,再等待其他进程已获准执行的操作结束后提交。因此,撤销完成后不会留下仍使用旧授权的操作。应用级撤销代次和各对话的决定版本,阻止旧句柄或迟到回答恢复被撤销的访问权限。 + +随附配置继续使用 JSON 后端。域名包含 profile 真实目录的 SHA-256 摘要,隔离共用存储根目录的不同 profile。旧 `allowedApps` 只导入一次,持久化迁移标记阻止旧配置恢复已撤销的许可。用户确认列表迁移完成后可删除旧配置。profile 存储损坏或不可用时拒绝访问。没有 profile 的组合只保留临时会话状态。 + +## 考虑过的替代方案 + +**继续将授权保存在配置中。** 可以复用旧存储,但运行时应用决定仍依赖配置写入和 HMR。 + +**长期打开域并依赖变更事件。** 域事件只在进程内传播,另一个宿主可能在撤销后继续使用旧许可。 + +**增加新的监听器、版本文件或授权代理。** 现有域存储和文件锁已经能提供最新状态与串行准入,无须增加通用存储或 IPC 框架。不同进程对同一应用的操作串行执行,其他应用及其会话决定保持独立。 + +## 后果 + +文件锁协调同一电脑及 PID 命名空间中的进程,不支持跨主机共用网络目录。撤销可能等待其他进程的原生调用结束。授权是否有效不由计时器决定。 + +权限页仍不显示仅对单个会话生效的许可,在进入页面、返回窗口、完成操作和重连后读取最新状态。存储变更不发送配置事件,系统权限仍归 macOS 管理。测试覆盖重启恢复、profile 隔离、其他进程写入、取消、数据损坏、旧配置导入和撤销后不恢复。已保存的会话记录目前需要显式管理保留期限,不自动淘汰。 diff --git a/.agents/notes/implemented/architecture/2026-10-20-ptc-script-evaluation-and-retention.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-20-ptc-script-evaluation-and-retention.i18n.yaml new file mode 100644 index 0000000000..89f47b3ea8 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-20-ptc-script-evaluation-and-retention.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-20-ptc-script-evaluation-and-retention.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-20-ptc-script-evaluation-and-retention.md +/agent-note-ptc-script-evaluation-and-state-retention: + en: e222c8cda4cee561 + zh: 9e624e5643ad2984 +/agent-note-ptc-script-evaluation-and-state-retention/problem: + en: 2da844a2a4e1903b + zh: 3b74ba7c1bcdae89 +/agent-note-ptc-script-evaluation-and-state-retention/decision: + en: 4beff8714f1d1555 + zh: a22019a90989eb66 +/agent-note-ptc-script-evaluation-and-state-retention/alternatives-considered: + en: 8ee3f3c7e04b4f25 + zh: ac604fa8debcfebf +/agent-note-ptc-script-evaluation-and-state-retention/consequences: + en: 64b7d3a5d247d82b + zh: 6f94d6b37f1ea4c1 diff --git a/.agents/notes/implemented/architecture/2026-10-20-ptc-script-evaluation-and-retention.md b/.agents/notes/implemented/architecture/2026-10-20-ptc-script-evaluation-and-retention.md new file mode 100644 index 0000000000..ef8a85dbfb --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-20-ptc-script-evaluation-and-retention.md @@ -0,0 +1,33 @@ +# Agent Note: PTC Script evaluation and state retention + +Status: implemented + +English | [中文](2026-10-20-ptc-script-evaluation-and-retention.zh.md) + +## Problem + +Program syntax and memory lifetime answer different questions. A consumer may need Script declarations and completion values while requiring either a fresh environment or retained references. Inferring memory lifetime from REPL syntax prevents that choice. + +## Decision + +The Node provider adds `executionMode: vm-script` and a separate `scriptPersistence` option, defaulting to false. `PtcRuntime.programFormat` describes accepted syntax; `retainsState` describes owner-scoped memory. Consumers use the latter for persistence controls and guidance. Existing `per-call` and `persistent-in-memory` configurations retain their meanings and defaults. + +This extends the mode-naming decision in [best-effort persistent PTC](2026-09-23-best-effort-persistent-ptc.md), whose ownership, non-durability and recovery decisions remain active. The Node provider selects its evaluator once and shares managed process mechanisms across temporary and retained lifetimes. AsyncFunction, REPL and Script remain separate evaluator implementations, so process reuse does not define syntax. + +VM Script uses a separate realm inside the managed child process. Top-level await uses the Node.js v26.6.0 REPL transform, with Acorn and acorn-walk supplying parsing and traversal. Detection precedes native compilation because non-strict Script can compile `await` as an identifier. The adapted visitors traverse computed method keys without entering method bodies. The source retains upstream attribution and license; the [package reference](../../../../packages/ptc-runtime/ptc-runtime-node/README.md#known-limitations-and-deferred-work) owns declaration and realm limitations. + +## Alternatives considered + +**Replace existing modes with Script.** This would change async-function return syntax and REPL declaration behavior for existing consumers. An additional mode preserves those choices while exposing Script semantics. + +**Encode syntax and retention in every mode name.** Separate names for fresh and retained Script would repeat syntax choices and encourage consumers to infer persistence from the format. One Script mode and an explicit retention option keep each fact separately observable. + +**Use native Script without await conversion.** Native Script cannot evaluate top-level await. Parsing only after native compilation fails also misses valid programs where `await` compiles as an identifier. The Node transform supplies retained declarations and completion handling while keeping its known semantic tradeoffs explicit. + +**Own a generic AST walker.** A local walker duplicates traversal provided by acorn-walk and must independently track new Acorn nodes. The maintained walker removes that implementation; only the evaluation-specific visitors remain local. + +## Consequences + +Script state is best-effort process memory, with the same explicit owner release and sandbox invalidation rules as retained REPL execution. It is neither serialized nor reconstructed by rerunning earlier programs. An uncaught callback exception or unhandled rejection terminates the Script process; programs must await asynchronous work. + +The published format union now includes `script`, and custom retained providers must report `retainsState`. The [upgrade guide](../../../../docs/upgrade-guide/v0.2.1-rc.2/ptc-script-format/guide.md) describes consumer migration. Source deployments need the evaluator modules and Acorn packages; private process bundles include those dependencies. diff --git a/.agents/notes/implemented/architecture/2026-10-20-ptc-script-evaluation-and-retention.zh.md b/.agents/notes/implemented/architecture/2026-10-20-ptc-script-evaluation-and-retention.zh.md new file mode 100644 index 0000000000..1dcdf4f1bc --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-20-ptc-script-evaluation-and-retention.zh.md @@ -0,0 +1,33 @@ +# Agent Note: PTC Script 求值与状态保留 + +Status: implemented + +[English](2026-10-20-ptc-script-evaluation-and-retention.md) | 中文 + +## 问题 + +程序语法和内存生命周期回答不同的问题。消费者可能需要 Script 声明和完成值,同时要求全新环境或保留引用。根据 REPL 语法推断内存生命周期会阻碍这种选择。 + +## 决策 + +Node 提供方增加 `executionMode: vm-script` 和独立的 `scriptPersistence` 选项,后者默认为 false。`PtcRuntime.programFormat` 描述接受的语法,`retainsState` 描述按所有者保留的内存。消费者通过后者提供持久化控制和指引。已有 `per-call` 和 `persistent-in-memory` 配置保留原有含义与默认值。 + +本决策扩展[尽力保留 PTC 状态](2026-09-23-best-effort-persistent-ptc.zh.md)中的模式命名决策;其中的所有权、非持久存储及恢复决策仍然有效。Node 提供方一次性选择求值器,并在临时和保留生命周期之间共用受管进程机制。AsyncFunction、REPL 和 Script 仍是独立的求值器实现,进程复用不决定语法。 + +VM Script 在受管子进程内使用独立 realm。顶层 await 使用 Node.js v26.6.0 REPL 转换,由 Acorn 和 acorn-walk 提供解析与遍历。在原生编译之前检测 await,因为非严格 Script 可以将 `await` 编译为标识符。适配后的 visitor 遍历方法的计算属性名,但不进入方法体。源码保留上游署名和许可;[包参考](../../../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#known-limitations-and-deferred-work)负责声明与 realm 限制。 + +## 考虑过的替代方案 + +**用 Script 替换已有模式。** 这会改变现有消费者的异步函数返回语法和 REPL 声明行为。增加模式可在提供 Script 语义的同时保留已有选择。 + +**在每个模式名称中同时编码语法与保留方式。** 为全新和保留状态的 Script 分别命名,会重复语法选项,并鼓励消费者根据格式推断持久化。一个 Script 模式加显式保留选项,让两项事实可以分别观测。 + +**仅使用原生 Script,不转换 await。** 原生 Script 无法求值顶层 await。只在原生编译失败后解析,也会漏掉将 `await` 编译为标识符的有效程序。Node 转换提供声明保留和完成值处理,同时明确其已知语义取舍。 + +**自行维护通用 AST 遍历器。** 局部遍历器重复 acorn-walk 已提供的遍历功能,还必须独立跟踪新增 Acorn 节点。使用维护中的遍历器可以删除这部分实现,只保留与求值相关的局部 visitor。 + +## 影响 + +Script 状态是尽力保留的进程内存,遵循与保留 REPL 相同的显式所有者释放和沙箱失效规则。状态不会序列化,也不会通过重新执行旧程序重建。未捕获的回调异常或未处理的 Promise 拒绝会终止 Script 进程;程序必须等待异步工作。 + +公开格式联合类型现包含 `script`,自定义保留状态的提供方必须报告 `retainsState`。[升级指南](../../../../docs/upgrade-guide/v0.2.1-rc.2/ptc-script-format/guide.zh.md)说明消费者迁移。源码部署需要求值器模块和 Acorn 包,私有进程 bundle 包含这些依赖。 diff --git a/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.i18n.yaml new file mode 100644 index 0000000000..9ae0452069 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for 2026-10-21-session-history-stream-and-snapshot.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.md +/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation: + en: 0c9a7bc6591feb16 + zh: 3606a2c1caffd36f +/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/problem: + en: ac1583e7ae1377f8 + zh: c60bdbda9ee89144 +/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/decision: + en: 45c63df5dac389eb + zh: d72a5bcb94de22f1 +/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/decision/reads-and-subscriptions: + en: 38df4f3c4fba2cc9 + zh: a34f3376faf26f0c +/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/decision/follow-ordering-and-ownership: + en: 352ff87a3e9cd110 + zh: 4ac6366cecfc08a3 +/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/decision/state-and-wait: + en: a87c7427582e6b03 + zh: b28d2a73b36eb27f +/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/alternatives-considered: + en: c5fb06ab9df9e7ad + zh: b20adf151018111c +/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/consequences: + en: dc1da262b4911a31 + zh: 2a4e503696fc477b diff --git a/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.md b/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.md new file mode 100644 index 0000000000..b5e1112a18 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.md @@ -0,0 +1,59 @@ +# Agent Note: Session snapshots, passive subscriptions, and Web aggregation + +Status: implemented + +English | [中文](2026-10-21-session-history-stream-and-snapshot.zh.md) + +## Problem + +A point read, an event subscription, and a Web conversation opening have different lifetimes. Combining them inside one history controller makes passive observation perform unnecessary reads and gives each aggregate its own acquisition logic. Reading before subscribing also creates a gap that requires another read to repair. The APIs need independent operations that can compose without losing events or duplicating ownership. + +## Decision + +`SessionController` is the single Session Remote Service. It owns ordinary `HistoryController`, `StateController`, and `WebController` instances, not three additional Cordis Services or Remote namespaces. The implementation separates six operations: history snapshot and observation, projection snapshot and observation, and state snapshot and observation. Follow and Wait compose those capabilities for their callers; the existing `page` entry forwards to the history reader. + +### Reads and subscriptions + +History reads return chronological records, `hasMore`, and an inclusive cursor. An omitted `throughSeq` selects the observed log end; `beforeSeq` selects older records without changing that read cut. Projection reads return exact sequenced values, sequence-free cache hints when migration is required, or null when the Session is absent. Live projection reads avoid persistence metadata access. + +`usingObservation({ sessionId, projection }, signal, callback?)` acquires the existing disposable SessionObservation. A callback borrows it until the callback settles; without a callback the caller owns disposal. Ordinary history, state, and Wait output reads do not request projections. Follow, exact projection reads, and subagent history descriptor validation request them. No read activates an Agent implicitly. + +`observeEvent` and `observeProjections` install listeners without acquiring an Observation. Their initial `ready` confirms subscription, not a snapshot cursor, existence, parent-child validity, or Agent readiness. History establishes continuity from its first received event; projection updates replace individual keys and may share a sequence number. `observeState` instead begins with a complete state read and coalesces later Session and Agent invalidations. + +History, history observation, and Follow accept Address requests; projection and state operations accept Session IDs. All internal readers and listeners use Session IDs. History and Follow validate Address against their opening Observation at the Controller layer, including the existing subagent descriptor rules. Pure history observation does not acquire a read for entity validation. Gateway resource authorization remains independent: the registered Session resolver extracts the target ID from the request before access is decided. + +### Follow ordering and ownership + +Follow installs history and optional assistant listeners first, then acquires one projected Observation. It captures the assistant baseline and binding-local arrival ordinal synchronously, sets both cuts, publishes the opening snapshot, and consumes the shared output queue. History notifications at or before the snapshot cursor and assistant notifications at or before the ordinal are discarded at consumption. Later notifications remain ordered without a second history read, background merge pumps, or a tail repair introduced by the opening itself. + +`session/created` contributes constructor seed events through the same history buffer. The adapter retains the supplied Session and its captured end position, then reads that in-memory prefix when consumed; it does not acquire another Observation. Each binding owns its subscriptions; a shared output queue belongs to Follow rather than to either listener. + +Follow activates only when the caller passes `activate: true`; the Web Client does so explicitly. Background promotion starts once the opening is computed and before it is delivered, and does not promise Agent readiness. Ordinary promotion reuses the existing Agent controller and receives a separately retained Observation. Either Follow releases its opening Observation once the opening is computed, before yielding it; activation continues on the separately retained lease, so the cold entry's reference count drops to that lease alone. Subagent Sessions do not use ordinary promotion. + +### State and Wait + +State contains the event cursor, active and running flags, the complete readable queue or null, and pending-input kinds. It exposes neither a header nor an internal revision. Gateway owns unsettled Remote events; State samples their detached metadata and classifies approval, question, or other input without copying a request registry. + +Wait evaluates complete states, confirms active-Agent quiescence with `whenIdle`, and rejects stale observations using listener-local revisions and Agent/Session identity checks. Session and Agent events wake reads immediately; while waiting, a one-second recheck detects pending input that produces no such event. This avoids adding a Gateway change event, at the cost of polling and bounded sampling delay rather than instantaneous notification. `observeState` does not poll, so pending-only changes need another state invalidation to become visible there. + +Wait returns idle, input-required, or timeout with the last state it accepted and bounded assistant output. Output contains only `assistant/message` records in `(afterSeq, state.cursor]`, newest first, and reports truncation only when another eligible record exists. The caller's cancellation signal controls that output read independently of the expired wait deadline. A wait that accepts no state before its deadline fails instead of inventing a state. + +## Alternatives considered + +**Read history, then subscribe and repair the gap.** Subscription-before-read already captures opening-time increments. A second read adds acquisition and replay obligations without improving that ordering. + +**Give pure subscriptions an Observation or ready cursor.** These values conflate subscription readiness with an independently selected read cut. Callers that need both subscribe and buffer first, then read and discard covered increments. + +**Keep separate Remote Services for the implementation controllers.** The classes divide behavior, not external service identity. One Session Service owns their composition, resource policy, and Remote entry points. + +**Have Gateway interpret pending input or emit Session status.** Gateway only owns Remote event transport and unsettled-event metadata. State owns classification; Wait's periodic sampling avoids adding a transport notification solely for Session waiting. + +**Merge assistant and history with independent asynchronous pumps.** One caller-owned buffer retains cross-source arrival order without extra pump cancellation or queue ownership. Snapshot construction and per-binding buffering retain distinct lifetimes. + +## Consequences + +The standard reads and Web aggregate share one Observation acquisition path, while pure subscriptions remain read-free. The old combined History controller is removed; still-used pagination, validation, and wire helpers remain at their original path. Cancellation, consumer termination, failed opening reads, and Context disposal release subscriptions and owned leases without cancelling Agent execution. + +The [Observation decision](2026-08-25-session-observations-and-projection-owned-client-state.md) remains the authority for exact read cuts and projection derivation. The [history and Remote transport decision](2026-08-18-session-history-and-event-transport.md) retains ownership of Client reconnection and transport lifetimes. This decision refines Session API composition rather than replacing either broader decision. + +The migrated history, cold-read, and transport tests exercise the new classes, including cursor overlap, assistant ordinal cuts, sequence gaps, subagent validation, and teardown. Slow consumers can still retain queued notifications; silent dropping is not a supported recovery strategy. Independent completion-acknowledged activation is not implemented by these reads or by Follow's background activation option. diff --git a/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.zh.md b/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.zh.md new file mode 100644 index 0000000000..773ab039b3 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.zh.md @@ -0,0 +1,59 @@ +# Agent Note: Session 快照、纯订阅与 Web 聚合 + +Status: implemented + +[English](2026-10-21-session-history-stream-and-snapshot.md) | 中文 + +## Problem + +定点读取、事件订阅和 Web 会话开场具有不同的生命周期。把它们合并在同一个历史控制器中,会使被动观察执行不必要的读取,并让每个聚合各自维护获取数据的逻辑。先读后订阅还会产生需要再次读取来修复的缺口。接口需要相互独立的操作,使组合既不丢事件,也不重复资源所有权。 + +## Decision + +`SessionController` 是唯一的 Session Remote Service。它持有普通的 `HistoryController`、`StateController` 和 `WebController` 实例,而不是额外的三个 Cordis Service 或 Remote namespace。实现分离六个操作:历史快照与观察、投影快照与观察、状态快照与观察。Follow 和 Wait 为调用方组合这些能力;已有的 `page` 入口转发到历史读取器。 + +### 读取与订阅 + +历史读取返回时间正序的记录、`hasMore` 和包含末项的游标。省略 `throughSeq` 时选择观察到的日志末尾;`beforeSeq` 只选择更早的记录,不改变读取点位。投影读取返回精确的有序值、需要迁移时无序号的缓存提示,或在 Session 不存在时返回 null。live 投影读取不访问持久化元信息。 + +`usingObservation({ sessionId, projection }, signal, callback?)` 获取已有的可释放 SessionObservation。有回调时租约借给回调直到其结束;无回调时由调用方释放。普通历史、状态及 Wait 输出读取不请求投影。Follow、精确投影读取和子会话历史 descriptor 校验请求投影。读取不会隐式激活 Agent。 + +`observeEvent` 和 `observeProjections` 安装监听而不获取 Observation。首个 `ready` 确认订阅生效,不代表快照游标、实体存在、父子关系有效或 Agent 就绪。历史从首个收到的事件建立连续性;投影更新替换单个键,多个更新可以共享序号。`observeState` 则从完整状态读取开始,并合并后续 Session 和 Agent 失效通知。 + +历史、历史观察和 Follow 接收 Address 请求;投影和状态操作接收 Session ID。所有内部读取器和监听器都使用 Session ID。History 和 Follow 在 Controller 层以开场 Observation 校验 Address,包括已有的子会话 descriptor 规则。纯历史观察不为实体校验获取读取。Gateway 资源授权与之独立:注册的 Session 解析器在访问判定前从请求提取目标 ID。 + +### Follow 顺序与所有权 + +Follow 先安装历史和可选 assistant 监听,再获取一份带投影的 Observation。它同步捕获 assistant 基线和绑定局部的到达序号,设置两种截断点,发布开场快照,然后消费共享输出队列。消费时丢弃序号不超过快照游标的历史通知,以及到达序号不超过截断点的 assistant 通知。后续通知保持顺序,无需第二次历史读取、后台合并任务,或由开场自身引入的尾部修复。 + +`session/created` 经同一历史缓冲提供构造期种子事件。适配器保留收到的 Session 及捕获的末尾位置,在消费时读取对应内存前缀,不获取另一份 Observation。每个绑定拥有自己的订阅;共享输出队列属于 Follow,而不是任一监听器。 + +只有调用方传入 `activate: true` 时 Follow 才激活;Web Client 显式传入该参数。后台提升在开场计算完成后、交付之前启动,不承诺 Agent 已就绪。普通提升复用已有 Agent controller,并接收单独 retain 的 Observation。两种 Follow 都在开场计算完成后、交付前释放开场 Observation;激活则继续使用单独 retain 的租约,因此冷 entry 的引用计数只剩那一份。子会话不走普通提升。 + +### 状态与 Wait + +State 包含事件游标、active 与 running 标志、完整可读队列或 null,以及待输入种类。它不暴露 header 或内部 revision。Gateway 拥有未结算的 Remote 事件;State 采样独立元数据,将输入分类为 approval、question 或 other,不复制请求注册表。 + +Wait 判断完整状态,通过 `whenIdle` 确认活跃 Agent 已静止,并通过监听器局部 revision 和 Agent/Session 身份检查拒绝过时观察。Session 和 Agent 事件立即唤醒读取;等待期间每秒重查一次,检测没有产生上述事件的待输入请求。这避免新增 Gateway change 事件,代价是轮询和采样延迟,而非即时通知。`observeState` 不轮询,因此仅有 pending 变化时,需要另一项状态失效通知才会显示更新。 + +Wait 返回 idle、input-required 或 timeout,以及最后一次被接受的状态和有界 assistant 输出。输出仅包含 `(afterSeq, state.cursor]` 内从新到旧的 `assistant/message` 记录,只有存在另一条符合条件的记录时才报告截断。输出读取使用调用方的取消信号,不受已过期的等待截止信号控制。截止前没有任何状态通过校验的 wait 会失败,不构造虚假的状态。 + +## Alternatives considered + +**先读历史,再订阅并修复缺口。** 先订阅后读取已经捕获开场期间的增量。第二次读取增加资源获取和重放责任,却不改善这个顺序。 + +**给纯订阅提供 Observation 或 ready 游标。** 这会混淆订阅就绪和独立选取的读取点位。需要两者的调用方先订阅并缓冲,再读取并丢弃已覆盖增量。 + +**为各实现 Controller 保留独立 Remote Service。** 这些类划分行为,而不是外部服务身份。一个 Session Service 拥有其组合、资源策略和 Remote 入口。 + +**让 Gateway 解释待输入状态或发送 Session status。** Gateway 只拥有 Remote 事件传输和未结算事件元数据。State 拥有分类;Wait 定期采样,避免仅为 Session 等待增加传输通知。 + +**用独立异步任务合并 assistant 与历史。** 调用方拥有的单个缓冲保留跨来源到达顺序,不引入额外任务取消或队列所有权。快照构造和各绑定缓冲仍保留不同生命周期。 + +## Consequences + +标准读取和 Web 聚合共享同一 Observation 获取路径,纯订阅不读取数据。旧的合并 History controller 已删除;仍使用的分页、校验和 wire 辅助函数留在原路径。取消、消费者结束、开场读取失败和 Context 释放都会释放订阅及拥有的租约,而不取消 Agent 执行。 + +[Observation 决策](2026-08-25-session-observations-and-projection-owned-client-state.zh.md)仍拥有精确读取点位和投影派生规则。[历史与 Remote 传输决策](2026-08-18-session-history-and-event-transport.zh.md)继续拥有 Client 重连和传输生命周期。本决策细化 Session API 组合,而不取代上述更广泛的决策。 + +迁移后的历史、冷读取和传输测试覆盖新类,包括游标重叠、assistant 到达序号截断、序号缺口、子会话校验和释放。慢消费者仍可能积累队列通知;静默丢弃不是支持的恢复策略。这些读取以及 Follow 的后台激活选项均未实现独立的、确认完成后返回的激活接口。 diff --git a/.agents/notes/implemented/architecture/2026-10-22-deepseek-official-model-listing.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-22-deepseek-official-model-listing.i18n.yaml new file mode 100644 index 0000000000..cc59fcf7ad --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-22-deepseek-official-model-listing.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-22-deepseek-official-model-listing.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-22-deepseek-official-model-listing.md +/agent-note-the-official-deepseek-route-follows-the-official-model-listing-until-its-catalog-is-customized: + en: 20de6c2a1bc643b4 + zh: 2fe21450cebf7f32 +/agent-note-the-official-deepseek-route-follows-the-official-model-listing-until-its-catalog-is-customized/problem: + en: 51a513e6134e6ad9 + zh: e0b19412c9b88e24 +/agent-note-the-official-deepseek-route-follows-the-official-model-listing-until-its-catalog-is-customized/decision: + en: ceb2f960085577c3 + zh: 1bbc833b7cf24070 +/agent-note-the-official-deepseek-route-follows-the-official-model-listing-until-its-catalog-is-customized/alternatives-considered: + en: fa126e4f4e0790b4 + zh: c4f6d266d1ba6753 +/agent-note-the-official-deepseek-route-follows-the-official-model-listing-until-its-catalog-is-customized/consequences: + en: 047e30a0f55acb24 + zh: 804e15532d172157 diff --git a/.agents/notes/implemented/architecture/2026-10-22-deepseek-official-model-listing.md b/.agents/notes/implemented/architecture/2026-10-22-deepseek-official-model-listing.md new file mode 100644 index 0000000000..341cc43776 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-22-deepseek-official-model-listing.md @@ -0,0 +1,36 @@ +# Agent Note: The official DeepSeek route follows the official model listing until its catalog is customized + +Status: implemented + +English | [中文](2026-10-22-deepseek-official-model-listing.zh.md) + +## Problem + +The `deepseek-official` route offered whatever its `models` setting held, and that setting defaults to the catalog bundled with each build. A model the DeepSeek API added reached API-key users only through a release, while the account route already followed the service's `GET /models` listing at the same origin. Unlike the account route's catalog, the official route's catalog is user-editable: the Models page stores an edited catalog in `models`, and a gateway behind `baseURL` declares its models there. + +## Decision + +- [`llm-deepseek-api-key`](../../../../packages/llm/llm-deepseek-api-key/README.md) follows `GET https://api.deepseek.com/models`, authenticated with the API key in `x-api-key`, only while the Messages origin is `https://api.deepseek.com` and `models` equals the built-in catalog. Any other endpoint or catalog sends no listing request. +- Loading, refresh, fallback, merging, and the client-version gate are the [account route's](2026-09-24-deepseek-account-remote-model-catalog.md): a first access waits up to `modelsTimeoutMs`, a listing older than `modelsMaxAgeMs` refreshes in the background on the next access, a failure keeps the last good listing or the built-in catalog, and the cache lives in memory, keyed by endpoint and key fingerprint. +- A customized `models` list wins whole: it replaces the catalog and stops listing requests. A list is customized when it resolves differently from the built-in catalog, because the schema default materializes an absent `models` as the built-in list and the Models page shows that default as its inherited rows. +- Switching between a customized catalog and the listing invalidates the cache from a `loader/volatile-update` listener, so Restore defaults reloads the listing on the next access even when the cached listing is fresh. +- The listing request, its cache, catalog resolution, and the gate live in the shared [Messages transport](../../../../packages/llm/llm-deepseek/README.md) because two routes consume them; the transport's provider hooks remain `connect` and `admit`. + +## Alternatives considered + +**Follow the listing on every endpoint.** A gateway that publishes an OpenAI-style `/models` returns entries without `api_capabilities.anthropic_messages`, which the decoder hides, so the route would offer no models. Every such gateway would also receive an extra request carrying the key. + +**Merge the customized catalog with the listing by model id.** Customized users would keep receiving new listed models, but a model the user deleted would return, and the Models page cannot hide one listed model. + +**Mark an unset `models` by removing its schema default.** An absent value would select the listing without comparing catalogs, but the Models page would lose the inherited rows it shows and copies, with their hidden `systemPromptUpdate` and `toolUpdate` fields, into a customized catalog. Rows copied from the generic model-discovery API would drop those fields. + +**Fetch once per process, or refresh on a timer.** A single fetch leaves a long-running Web or desktop host on its startup catalog, and one transient failure pins it to the built-in catalog. A timer sends requests while the route is idle. Access-triggered background refresh matches the account route. + +**Reuse the cached listing after Restore defaults.** The cache could serve a listing loaded before the customization for up to `modelsMaxAgeMs`; the request is cheap, so restoring always reloads it. The reload starts on the next access rather than inside the listener, which keeps credential lookup and its failures on the request path; the Web page's settings refresh makes that access right after the save. + +## Consequences + +- API-key users on the official endpoint receive listed models without a release, and an older build hides or refuses a model that needs a newer client, as account users' builds do. +- A customized catalog receives no later listed models until Restore defaults, and a `models` list identical to the built-in catalog counts as uncustomized. The comparison uses the running version's built-in catalog, so a saved list equal to an earlier version's built-in catalog counts as customized once the built-in catalog changes. +- The Models page shows the built-in rows while the listing is followed, so a model only the listing offers appears only in model selectors, and editing the page's catalog drops it. +- The first catalog access on the official endpoint can wait up to `modelsTimeoutMs`, and a suite that boots the route there must answer the listing itself to stay off the network. diff --git a/.agents/notes/implemented/architecture/2026-10-22-deepseek-official-model-listing.zh.md b/.agents/notes/implemented/architecture/2026-10-22-deepseek-official-model-listing.zh.md new file mode 100644 index 0000000000..ea6073171a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-22-deepseek-official-model-listing.zh.md @@ -0,0 +1,36 @@ +# Agent Note: DeepSeek 官方路由在目录未自定义时跟随官方模型列表 + +Status: implemented + +[English](2026-10-22-deepseek-official-model-listing.md) | 中文 + +## 问题 + +`deepseek-official` 路由提供的是 `models` 设置里的内容,而这个设置默认是每个构建自带的目录。DeepSeek API 新增的模型只能随发版到达 API key 用户,而账号路由已经在同一个 origin 上跟随服务端的 `GET /models` 列表。与账号路由不同,官方路由的目录可以由用户编辑:模型页把编辑后的目录存进 `models`,`baseURL` 后面的网关也在这里声明自己的模型。 + +## 决策 + +- [`llm-deepseek-api-key`](../../../../packages/llm/llm-deepseek-api-key/README.zh.md) 只在 Messages 的 origin 是 `https://api.deepseek.com`、且 `models` 等于内置目录时,跟随 `GET https://api.deepseek.com/models`,并用 `x-api-key` 携带 API key 鉴权。其他端点或目录不发列表请求。 +- 加载、刷新、兜底、合并与客户端版本门控沿用[账号路由](2026-09-24-deepseek-account-remote-model-catalog.zh.md)的规则:首次访问最多等待 `modelsTimeoutMs`,列表超过 `modelsMaxAgeMs` 后在下一次访问时后台刷新,失败时保留上一份成功的列表或使用内置目录,缓存只在内存中,以端点和 key 指纹为键。 +- 自定义的 `models` 列表整份优先:它替换目录,并停止列表请求。解析结果与内置目录不同的列表才算自定义,因为 schema 默认值会把缺省的 `models` 物化为内置列表,模型页也把这个默认值显示为继承的行。 +- 在自定义目录与列表之间切换时,一个 `loader/volatile-update` 监听器会让缓存失效,因此点恢复默认后,即使缓存的列表尚未过期,下一次访问也会重新加载。 +- 列表请求、缓存、目录解析和门控放在共享的 [Messages 传输包](../../../../packages/llm/llm-deepseek/README.zh.md)中,因为现在有两条路由使用它们;传输层的提供方钩子仍然只有 `connect` 和 `admit`。 + +## 考虑过的替代方案 + +**在所有端点上跟随列表。** 发布 OpenAI 风格 `/models` 的网关返回的条目没有 `api_capabilities.anthropic_messages`,解码器会隐藏它们,路由就不提供任何模型。每个这样的网关还会多收到一个携带 key 的请求。 + +**按模型 id 合并自定义目录与列表。** 自定义用户会继续收到新列出的模型,但用户删掉的模型会重新出现,而模型页无法隐藏某一个列出的模型。 + +**去掉 `models` 的 schema 默认值来标记未设置。** 缺省值不用比较目录就能选中列表,但模型页会失去它显示的继承行;这些行连同隐藏的 `systemPromptUpdate`、`toolUpdate` 字段会被复制进自定义目录。从通用模型发现 API 复制的行会丢掉这些字段。 + +**每个进程只获取一次,或按定时器刷新。** 只获取一次会让常驻的 Web 或桌面宿主停留在启动时的目录,一次偶发失败就会让它固定在内置目录。定时器会在路由空闲时发请求。由访问触发的后台刷新与账号路由一致。 + +**恢复默认后沿用缓存的列表。** 缓存可能在 `modelsMaxAgeMs` 内一直提供自定义之前加载的列表;列表请求代价很小,所以恢复默认总是重新加载。重新加载从下一次访问开始,而不是在监听器里进行,这样凭据查询及其失败都留在请求路径上;Web 页面保存后的设置刷新会立即发起这次访问。 + +## 影响 + +- 使用官方端点的 API key 用户无需发版就能看到列出的模型,旧构建会像账号用户的构建一样隐藏或拒绝需要新版客户端的模型。 +- 自定义目录在恢复默认之前收不到之后列出的模型;与内置目录完全相同的 `models` 列表视为未自定义。比较的是当前版本的内置目录,所以保存的列表若等于旧版本的内置目录,内置目录变化后就算作自定义。 +- 跟随列表期间,模型页仍显示内置的行,因此只有列表提供的模型只出现在模型选择器里,在模型页编辑目录会丢掉它。 +- 官方端点上的第一次目录访问可能等待最多 `modelsTimeoutMs`,在该端点上启动路由的测试套件必须自己应答列表请求,才能不访问网络。 diff --git a/.agents/notes/implemented/architecture/2026-10-23-independent-session-forks.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-23-independent-session-forks.i18n.yaml new file mode 100644 index 0000000000..5f7f17ddbb --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-23-independent-session-forks.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-10-23-independent-session-forks.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-23-independent-session-forks.md +/agent-note-ordinary-forks-have-no-durable-creator-relationship: + en: 543a84d51e8aea24 + zh: 24aeec7c3cdf5900 +/agent-note-ordinary-forks-have-no-durable-creator-relationship/problem: + en: d2edaafdd83e5974 + zh: 57ce9ad368c404c2 +/agent-note-ordinary-forks-have-no-durable-creator-relationship/decision: + en: aae0053e9dc3be9f + zh: bd37095fd5c43c3d +/agent-note-ordinary-forks-have-no-durable-creator-relationship/compatibility: + en: 8393e8526f927134 + zh: c957cbde9dc6712d +/agent-note-ordinary-forks-have-no-durable-creator-relationship/alternatives-considered: + en: 748aa21283186e02 + zh: 51d3b0207b250784 +/agent-note-ordinary-forks-have-no-durable-creator-relationship/consequences: + en: adcb06ccf7503e55 + zh: 30e02c6104eefe01 diff --git a/.agents/notes/implemented/architecture/2026-10-23-independent-session-forks.md b/.agents/notes/implemented/architecture/2026-10-23-independent-session-forks.md new file mode 100644 index 0000000000..1518ee8ac3 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-23-independent-session-forks.md @@ -0,0 +1,35 @@ +# Agent Note: Ordinary forks have no durable creator relationship + +Status: implemented + +English | [中文](2026-10-23-independent-session-forks.zh.md) + +## Problem + +Using `parentSession` for both copied history and delegation makes an ordinary fork appear to be a subagent. Consumers can emit false child-start notifications, hide resumable sessions, or impose source-relative ordering. Removing the writer alone leaves historical ordinary forks misclassified and exposes a V4 reader assumption: inherited delivery acknowledgements require a parent id even though the validated seed range already identifies copied events. + +## Decision + +Ordinary forks preserve their complete selected prefix, `isSeeded`, `inheritedEventCount`, and inherited end-seed marker, but record no source id. Subagents retain their direct creator, including when their backend copies history. `origin: subagent` supplies coarse classification; a valid own-range descriptor separately supplies continuation identity. Historical parent metadata remains readable and unchanged. Runtime Agent ownership remains governed by the [explicit identity decision](2026-08-31-explicit-agent-runtime-identity.md). + +The V4 reader permits another Session's delivery id only inside the validated inherited range. Own-range markers still require the current id, and every active-generation `throughSeq` must precede its marker. These checks do not require a persistent source relationship. + +## Compatibility + +This is a same-version behavior change with no declared persistence-type change. The generated inventory reports no schema transitions, so no new type acknowledgement or finalization checkpoint is needed. Existing ordinary forks and subagent logs retain their meanings, and the new reader accepts both parent-bearing and parentless seeds without rewriting either. Frozen schemas and historical generations remain untouched. + +The released `dsh-v0.2.0-rc.2` validator and the reviewed master baseline share the parent-dependent delivery check. Before changing that check, real plain and compressed JSONL probes verified rejection through both read and write opens for parentless ordinary and nested forks, with byte-identical files afterward. Rejection occurs during completed-log relationship validation, before a handle is granted or tail repair runs. Older readers report corruption rather than an upgrade diagnostic; that diagnostic limitation is explicit in the [upgrade guide](../../../../docs/upgrade-guide/v0.2.1-rc.3/independent-session-forks/guide.md). Parentless seeds without active inherited delivery markers remain readable. This observed admission behavior meets the [safe-refusal rule](../process/2026-10-08-session-reader-compatibility-review.md); optionality alone is not the justification. + +## Alternatives considered + +**Keep the source under another field.** A replacement such as `forkSourceId` preserves the durable relationship the user chose to remove, along with its downstream maintenance cost. + +**Erase parent metadata from existing logs.** Historical mutation loses recorded information and violates immutable-generation guarantees. Consumers distinguish old ordinary forks without cleanup. + +**Bump the format solely because older readers reject some new logs.** The existing inherited range and complete-log check prevent unsafe execution and truncation. A global bump and adjacent copy add no protection to this transition; same-version refusal has a documented diagnostic limitation. + +## Consequences + +Ordinary-fork source tracing is intentionally unavailable in new data. Manual ordering preserves saved positions and treats new forks like other ordinary sessions. Operation-local source access preserves title increments and workspace selection. The [side-session proposal](../../proposed/feature/2026-07-08-interactive-side-sessions.md) retains its separate handback idea but cannot use a stored ordinary-fork parent. Runtime ownership, projection-cache identity, and Team membership decisions remain independently useful and are not superseded. + +Verification covers real fork/persist/reopen paths for ordinary, nested, historical, and subagent seeds, rejection without writes for foreign own-range delivery and invalid coordinates, SDK notification classification, ACP resume, client ordering, and title generation. TypeScript and Python recorded SDK scenarios create ordinary and nested forks plus historical parent-bearing metadata while retaining the expected real-subagent lifecycle. diff --git a/.agents/notes/implemented/architecture/2026-10-23-independent-session-forks.zh.md b/.agents/notes/implemented/architecture/2026-10-23-independent-session-forks.zh.md new file mode 100644 index 0000000000..a11be9b69d --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-23-independent-session-forks.zh.md @@ -0,0 +1,35 @@ +# Agent Note: 普通 fork 不保留持久创建者关系 + +Status: implemented + +[English](2026-10-23-independent-session-forks.md) | 中文 + +## 问题 + +同时用 `parentSession` 表示复制历史和委派,会让普通 fork 看起来像子代理。消费方可能发送错误的子代理启动通知、隐藏可恢复会话,或施加相对来源的排序。仅删除写入仍会误分类历史普通 fork,并暴露 V4 reader 的一项假设:继承投递确认要求父 ID,尽管已验证的 seed 区间已经标识复制事件。 + +## 决策 + +普通 fork 保留完整的选定前缀、`isSeeded`、`inheritedEventCount` 及继承结束标记,但不记录来源 ID。子代理保留直接创建者,包括 backend 复制历史的情况。`origin: subagent` 提供粗粒度分类;有效的自身区间 descriptor 单独提供继续运行身份。历史父元数据保持可读且不变。运行时 Agent 归属仍遵循[显式身份决策](2026-08-31-explicit-agent-runtime-identity.zh.md)。 + +V4 reader 仅在已验证的继承区间中允许其他 Session 的投递 ID。自身区间标记仍要求当前 ID,每个活动代际的 `throughSeq` 必须早于其标记。这些检查不需要持久来源关系。 + +## 兼容性 + +这是没有声明持久化类型变化的同版本行为变更。生成清单报告没有 schema 转换,因此不需要新增类型确认或定稿检查点。已有普通 fork 和子代理日志保留其含义,新 reader 接受有父关系及无父关系的 seed,且不改写任一种。冻结 schema 与历史代际保持不变。 + +已发布的 `dsh-v0.2.0-rc.2` 校验器与所审查 master 基线具有相同的依赖父关系的投递检查。修改此检查之前,真实的普通及压缩 JSONL 探针验证:无父关系的普通和嵌套 fork 在 read、write 打开时都被拒绝,之后文件字节完全一致。拒绝发生在完整日志的关系校验期间,早于授予句柄或尾部修复。旧 reader 报告损坏而非升级诊断;[升级指南](../../../../docs/upgrade-guide/v0.2.1-rc.3/independent-session-forks/guide.zh.md)明确说明这一诊断限制。没有活动继承投递标记的无父关系 seed 仍然可读。这一已观察到的接纳行为满足[安全拒绝规则](../process/2026-10-08-session-reader-compatibility-review.zh.md);可选字段本身不是依据。 + +## 考虑过的替代方案 + +**用其他字段保留来源。** `forkSourceId` 等替代字段保留了用户决定移除的持久关系及其下游维护成本。 + +**清除已有日志的父元数据。** 修改历史会丢失已记录信息,并违反代际不可变保证。消费方可以在不清理的情况下区分旧普通 fork。 + +**仅因旧 reader 拒绝部分新日志就升级格式。** 现有继承区间和完整日志检查阻止不安全执行与截断。全局升级和相邻复制不会为这次转换增加保护;同版本拒绝的诊断限制已有明确记录。 + +## 影响 + +新数据有意不支持普通 fork 的来源追踪。手动排序保留已保存位置,将新 fork 当作其他普通会话处理。操作期间访问来源保留标题递增和工作区选择。[侧会话提案](../../proposed/feature/2026-07-08-interactive-side-sessions.zh.md)保留独立的交回设想,但不能使用普通 fork 的持久父字段。运行时归属、投影缓存身份和 Team 成员关系决策仍分别有用,未被取代。 + +验证覆盖普通、嵌套、历史及子代理 seed 的真实 fork/持久化/重新打开路径,自身区间外来投递及非法坐标的无写入拒绝,SDK 通知分类、ACP 恢复、客户端排序与标题生成。TypeScript 和 Python 录制 SDK 场景创建普通及嵌套 fork 和携带历史父元数据的会话,同时保留真正子代理的预期生命周期。 diff --git a/.agents/notes/implemented/architecture/2026-10-23-store-scoped-image-reads.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-23-store-scoped-image-reads.i18n.yaml new file mode 100644 index 0000000000..0acdacdd56 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-23-store-scoped-image-reads.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-10-23-store-scoped-image-reads.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-23-store-scoped-image-reads.md +/agent-note-image-reads-use-attachment-store-access: + en: 31c8a0d9016d99af + zh: 05db308dec85db67 +/agent-note-image-reads-use-attachment-store-access/problem: + en: ff8886cfa4634163 + zh: 46dfdd50638b64c2 +/agent-note-image-reads-use-attachment-store-access/decision: + en: 439a3277ee3b169d + zh: c9f1e10254850844 +/agent-note-image-reads-use-attachment-store-access/alternatives-considered: + en: 0c7a8319c0c91dc2 + zh: 6b7b58b142839571 +/agent-note-image-reads-use-attachment-store-access/consequences: + en: a46c3d951077ec7d + zh: 30a0cc5bcb681a21 +/agent-note-image-reads-use-attachment-store-access/verification: + en: 89603b3a4c3e12df + zh: f1b01d166f399f87 diff --git a/.agents/notes/implemented/architecture/2026-10-23-store-scoped-image-reads.md b/.agents/notes/implemented/architecture/2026-10-23-store-scoped-image-reads.md new file mode 100644 index 0000000000..8805102882 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-23-store-scoped-image-reads.md @@ -0,0 +1,52 @@ +# Agent Note: Image reads use attachment-store access + +Status: implemented + +English | [中文](2026-10-23-store-scoped-image-reads.zh.md) + +## Problem + +Historical image loading read the requesting Session and searched its event content for every uncached attachment. The search established that the Session referenced the image; it did not locate the bytes, whose storage path already follows from the content-addressed ID. This added work proportional to history length to each image read. The reported loading delay also involved uploads; this finding alone does not identify all of that delay. + +## Decision + +Session membership is not an image-access restriction. After connection authentication and Gateway permission checks authorize `session/attachment`, every caller may read any image in the same attachment store using a complete `ImageAttachmentRef`, including objects referenced only by other Sessions or not referenced at all. The request retains `sessionId` for the existing Session resource permission check. After that check passes, the handler does not require that Session to exist and does not return `session/not-found` solely because it is absent. No identity receives a separate history-scanning path. + +The Client already holds the message's complete image reference and sends it as `attachment` beside `sessionId`. Session Controller delegates directly to the existing `AttachmentStore.readImage(ref)`. Its local provider validates the canonical ID, derives the path within its object directory, verifies SHA-256, and compares the actual format, byte length, width, and height with the supplied reference. A missing, unreadable, corrupt, or mismatched object rejects the operation. No Session history is needed to recover the reference. + +The response preserves the supplied reference. Its optional `name` and `originalDimensions` are caller-supplied display information and are not verified against the stored object. The Client's existing historical-image cache continues to own per-Session results and object URLs; the Host adds no image-byte cache. + +This rule narrows the readers covered by [Session observations](2026-08-25-session-observations-and-projection-owned-client-state.md) and the [history transport activation policy](2026-08-18-session-history-and-event-transport.md). [Workspace file reads](2026-09-05-workspace-files-service.md) keep their own filesystem authorization. + +## Alternatives considered + +**Keep a Session-to-image map or projection.** An index removes repeated scans but preserves an access restriction the product does not require, adding derivation, lifetime, and invalidation work. + +**Issue signed image tickets.** Tickets add issuance and validation state for the same unnecessary Session-membership restriction. + +**Optimize only owner reads.** That gives identities different image-access semantics and leaves the scan cost for permitted non-owner callers without a product requirement. + +## Consequences + +Knowing a valid image reference and having permission to invoke the endpoint for the supplied Session resource permits reading that object across Sessions. The local ID is the SHA-256 of normalized bytes. For known PNG, JPEG, or WebP bytes that admission preserves unchanged, a caller can calculate the ID, derive the format, byte length, and dimensions, and use an authorized read to test whether the object exists. The required reference fields need not come from a Session log. + +Image isolation requires separate Host instances with separate `DSH_HOME` directories. The shipped composition uses one attachment store per Host and does not select a store by Session. Authentication, Gateway action/resource checks, fixed storage paths, digest verification, and explicit failures remain required. + +Image reads no longer depend on history length or Session materialization. File reading, integrity verification, encoding, and transport still cost time; this change makes no claim about upload or model inference latency. Existing Session data and fork references need no migration. + +## Verification + +The read-path invariant is zero Session-history queries or traversal for attachment reads. Coverage must distinguish a permitted cross-Session image read from a denied Gateway call and exercise valid references, invalid IDs, mismatched intrinsic metadata, preserved optional display fields, missing and corrupt objects, old history pages, and inherited fork images. Performance evidence must separate historical scanning, storage work, and transport rather than attribute the entire reported delay to the scan. + +The diagnostic is [`image-read.perf.ts`](../../../../packages/api/session-controller/tests/image-read.perf.ts), compiled by its [tsdown configuration](../../../../packages/api/session-controller/tests/image-read.perf.config.ts). The baseline worker pairs the pre-change controller with `{ sessionId, attachmentId: ref.attachmentId }`; the candidate worker pairs the current controller with `{ sessionId, attachment: ref }`. Both use the same image fixtures, workload, and output checks, and run against the same built Local store with `readImage(ref)` verification. From the candidate checkout root, compile and run: + +```sh +pnpm exec tsdown --config-loader native --config packages/api/session-controller/tests/image-read.perf.config.ts +(cd packages/api/session-controller && node --expose-gc .dsh-build/image-read/image-read.perf.js --expect-no-history) +``` + +Run the separately compiled baseline worker without `--expect-no-history`; its diagnostic request must match the baseline controller's ID-only request fields. The baseline negative control adds `--sample typical --expect-no-history` and must fail because that implementation queries and traverses history. The parent process runs each workload in five fresh child processes, each with a loaded Session and a first uncached read of every image. Images are deterministic synthetic 1024 × 768 PNGs; the two workloads contain 120 turns, 960 events, and 8 images, or 2,000 turns, 16,000 events, and 32 images. Fixture writes can leave the operating system's file cache warm. + +`controllerMs` covers the direct controller call through base64 return. `storeMs` includes file I/O, SHA-256, and header verification; `snapshotMs` measures history snapshot acquisition separately. `scanAndDispatchMs` is the time before store entry minus `snapshotMs`, so it includes dispatch overhead and is not an isolated scan timer. JSON serialization and loopback HTTP transfer are separate measurements over retained responses. `requestJsonBytes` and `idOnlyRequestJsonBytes` compare serialized request lengths; they do not measure request transmission time. Cold Session restoration, Gateway processing, browser rendering, remote-network latency, upload, and model inference are excluded. PR #7021 records the worker revisions and before/after results under these limits. + +The memory endpoints run GC after fixture setup and after all image responses. The Session, admitted image references, and every base64 response remain reachable at the second endpoint. These retained endpoints include setup-owned objects, and peak RSS is cumulative from process start, including fixture generation. They do not measure image-request memory in isolation or impose a retained-memory budget. diff --git a/.agents/notes/implemented/architecture/2026-10-23-store-scoped-image-reads.zh.md b/.agents/notes/implemented/architecture/2026-10-23-store-scoped-image-reads.zh.md new file mode 100644 index 0000000000..0fe69e71a0 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-23-store-scoped-image-reads.zh.md @@ -0,0 +1,52 @@ +# Agent Note: 图片读取使用附件存储访问权限 + +Status: implemented + +[English](2026-10-23-store-scoped-image-reads.md) | 中文 + +## Problem + +历史图片加载会为每个未缓存的附件读取请求中的 Session,并搜索其事件内容。搜索用于确认 Session 引用了图片;它不负责定位字节,存储路径已经能由内容寻址 ID 推导。每次读图因此增加了与历史长度成正比的工作。用户反馈的加载延迟还涉及上传;这项发现本身不能确定全部延迟的来源。 + +## Decision + +Session 关联不构成图片访问限制。连接身份认证和 Gateway 权限检查允许调用 `session/attachment` 后,任何调用者都可以通过完整的 `ImageAttachmentRef` 读取同一附件存储中的任意图片,包括仅被其他 Session 引用或未被任何 Session 引用的对象。请求保留 `sessionId`,供现有 Session 资源权限检查使用。该检查通过后,处理函数不要求该 Session 存在,也不会仅因其不存在而返回 `session/not-found`。所有身份使用相同的读图路径。 + +Client 已经持有消息中的完整图片引用,将其作为 `attachment` 与 `sessionId` 一起发送。Session Controller 直接调用已有的 `AttachmentStore.readImage(ref)`。本地提供方校验规范 ID,在自己的对象目录内推导路径,校验 SHA-256,并把实际格式、字节数、宽度和高度与传入引用比对。对象缺失、不可读、损坏或与引用不符时,操作失败。取得引用无需查询 Session 历史。 + +响应保留传入引用。可选的 `name` 和 `originalDimensions` 是调用方提交的显示信息,不根据存储对象校验。Client 现有的历史图片缓存继续按 Session 管理结果和对象 URL;Host 不增加图片字节缓存。 + +该规则缩小了 [Session observation](2026-08-25-session-observations-and-projection-owned-client-state.zh.md) 与[历史传输激活策略](2026-08-18-session-history-and-event-transport.zh.md)涵盖的读取范围。[工作区文件读取](2026-09-05-workspace-files-service.zh.md)保留自己的文件系统授权。 + +## Alternatives considered + +**保留 Session 到图片的 Map 或 projection。** 索引可以消除重复扫描,但保留了产品不需要的访问限制,并增加派生、生命周期和失效处理。 + +**签发图片签名票据。** 票据为同一项不需要的 Session 关联限制增加签发和验证状态。 + +**只优化 owner 的读取。** 这会让不同身份使用不同的图片访问规则,并让获准调用的非 owner 继续承担扫描成本,没有相应产品需求。 + +## Consequences + +调用方知道有效图片引用,且有权为请求中的 Session 资源调用该接口,就可以跨 Session 读取对象。本地 ID 是规范化字节的 SHA-256。对于准入时原样保留的已知 PNG、JPEG 或 WebP 字节,调用方可以计算 ID,取得格式、字节数和尺寸,并通过获准的读取请求探测对象是否存在。这些必需的引用字段不一定来自 Session 日志。 + +图片隔离需要独立 Host 实例及各自的 `DSH_HOME` 目录。随附组合在每个 Host 中使用一个附件存储,不会按 Session 选择存储。身份认证、Gateway 操作与资源检查、固定存储路径、摘要校验和明确失败仍是必需的。 + +图片读取不再依赖历史长度或 Session 物化。文件读取、完整性校验、编码和传输仍有耗时;本次改动不说明上传或模型推理延迟已得到改善。已有 Session 数据和 fork 引用无需迁移。 + +## Verification + +附件读取不得查询或遍历 Session 历史。验证必须区分获准的跨 Session 图片读取与被 Gateway 拒绝的调用,并覆盖正常引用、无效 ID、固有元数据不符、可选显示字段原样保留、缺失和损坏的对象、旧历史页以及 fork 继承图片。性能证据必须区分历史扫描、存储操作和传输,不能把用户反馈的全部延迟归因于扫描。 + +诊断脚本是 [`image-read.perf.ts`](../../../../packages/api/session-controller/tests/image-read.perf.ts),通过配套的 [tsdown 配置](../../../../packages/api/session-controller/tests/image-read.perf.config.ts)编译。基线 worker 使用改动前的控制器与 `{ sessionId, attachmentId: ref.attachmentId }`;候选 worker 使用当前控制器与 `{ sessionId, attachment: ref }`。两者使用相同图片 fixture、工作量和输出校验,并通过同一套已构建的 Local store 执行 `readImage(ref)` 校验。在候选检出目录的根目录编译并运行: + +```sh +pnpm exec tsdown --config-loader native --config packages/api/session-controller/tests/image-read.perf.config.ts +(cd packages/api/session-controller && node --expose-gc .dsh-build/image-read/image-read.perf.js --expect-no-history) +``` + +运行单独编译的基线 worker 时不带 `--expect-no-history`;诊断请求必须匹配基线控制器仅接收 ID 的请求字段。基线负对照加上 `--sample typical --expect-no-history`,该实现会查询和遍历历史,因此负对照必须失败。父进程为每种工作量运行五个新子进程,每个子进程使用已加载的 Session,并对每张图片执行第一次未缓存读取。图片是确定性合成的 1024 × 768 PNG;两种工作量分别为 120 轮、960 个事件、8 张图片,以及 2,000 轮、16,000 个事件、32 张图片。fixture 写入可能已经预热操作系统的文件缓存。 + +`controllerMs` 覆盖从直接调用控制器到返回 base64 的时间。`storeMs` 包含文件 I/O、SHA-256 和文件头校验;`snapshotMs` 单独测量取得历史快照的时间。`scanAndDispatchMs` 是进入存储前的时间减去 `snapshotMs`,因此也包含分派开销,不是独立的扫描计时。JSON 序列化和本机回环 HTTP 传输使用保留的响应单独测量。`requestJsonBytes` 与 `idOnlyRequestJsonBytes` 比较序列化后的请求长度,不测量请求传输时间。冷 Session 恢复、Gateway 处理、浏览器渲染、远端网络延迟、上传和模型推理均不在测量范围内。PR #7021 记录 worker 修订,以及在这些限制下测得的修改前后结果。 + +内存端点在 fixture 准备完成后,以及所有图片响应完成后执行 GC。第二个端点仍保留 Session、已准入的图片引用和每个 base64 响应。这两个保留内存端点包含准备阶段拥有的对象,峰值 RSS 则从进程启动累计,包含 fixture 生成。它们不单独测量图片请求内存,也不规定保留内存预算。 diff --git a/.agents/notes/implemented/architecture/2026-10-25-cua-bundle-id-consent.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-25-cua-bundle-id-consent.i18n.yaml new file mode 100644 index 0000000000..7a21fc65bd --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-25-cua-bundle-id-consent.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-25-cua-bundle-id-consent.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-25-cua-bundle-id-consent.md +/agent-note-macos-consent-shared-by-bundle-identifier: + en: 41cd1b8e2629e049 + zh: f1bcef434b6d247f +/agent-note-macos-consent-shared-by-bundle-identifier/problem: + en: bb387fc89c1c578c + zh: 947456baea45cc95 +/agent-note-macos-consent-shared-by-bundle-identifier/decision: + en: 7b1bbab1f95b7610 + zh: 434e7a3fba81174b +/agent-note-macos-consent-shared-by-bundle-identifier/alternatives-considered: + en: 637b1fd2bafb1b28 + zh: 06d882818ffaf800 +/agent-note-macos-consent-shared-by-bundle-identifier/consequences: + en: 1af6d29a57ff86e2 + zh: 32517607b2fc935f diff --git a/.agents/notes/implemented/architecture/2026-10-25-cua-bundle-id-consent.md b/.agents/notes/implemented/architecture/2026-10-25-cua-bundle-id-consent.md new file mode 100644 index 0000000000..b5cfc122cd --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-25-cua-bundle-id-consent.md @@ -0,0 +1,33 @@ +# Agent Note: macOS consent shared by bundle identifier + +Status: implemented + +English | [中文](2026-10-25-cua-bundle-id-consent.zh.md) + +## Problem + +Users who install multiple versions of one application want one permission decision for that software. Executable paths split those decisions, and signing checks exclude unsigned development applications from saved access. + +## Decision + +macOS application consent uses the exact, case-sensitive native bundle identifier. The helper hashes `macos:bundle-id:` followed by that identifier into `CuaApplicationId`. When a bundle identifier exists, installation paths, versions and signatures do not distinguish grants. Otherwise, the helper hashes `macos:executable-path:` followed by the canonical executable path. Both identities support saved access; path identities survive restart and in-place updates, while a different path requires a new decision. Conversation decisions and saved grants retain the scopes and revocation behavior of [profile consent storage](2026-10-19-cua-profile-consent-storage.md). + +This supersedes the executable/signature identity choice in [application consent](2026-09-26-cua-application-consent.md); that note still owns enforcement and human decisions. The running process path comes from the operating system. A valid runtime bundle identifier does not depend on path-query success. Missing paths omit optional grant metadata; they never substitute a cached catalog path. When both bundle identity and process path are unavailable, consent fails with the path query cause. Process identity must still be verified, and any available process path must match the selected target. Missing catalog path metadata does not block consent when the process path is available. If the runtime bundle identifier is unavailable, a reported application bundle can supply it only when its main executable matches the process path; otherwise the executable path identifies the grant. Native process, executable-location and window checks continue to bind each handle to its selected target. Launch checks reread the bundle identifier and executable path from disk; they do not fingerprint executable content. Replacing bytes at the same path while retaining the identifier or path identity therefore retains consent, including during an approval wait. + +The identity prefixes separate new grants from old path/signature, process-instance and executable-content digests. Old grants remain removable but do not grant access to new bundle identities; users decide again before permission covers other installations. + +Apple’s [PPPC configuration](https://support.apple.com/guide/deployment/privacy-preferences-policy-control-payload-dep38df53c2a/web) supports bundle-ID or path selectors and separately requires a code-signing requirement. [TN3127](https://developer.apple.com/documentation/technotes/tn3127-inside-code-signing-requirements) explains that designated requirements track code identity across versions, while unsigned and ad-hoc code cannot provide the same stability. DSH adopts the selector alternatives for application management without requiring publisher authentication. + +## Alternatives considered + +**Bundle identifier and path.** This distinguishes installed copies but requires separate decisions for the multiple versions the user wants to authorize together. + +**Bundle identifiers only.** Missing identifiers would exclude otherwise usable applications from saved access. Canonical executable paths supply a stable fallback without using a PID or content hash. + +**Verified signing identity.** This distinguishes publishers but denies saved access when signing is absent or cannot be verified. Publisher authentication is outside this application-management policy. + +## Consequences + +Another program declaring the same bundle identifier or replacing an executable at its approved fallback path inherits consent, including a program created or changed through separately authorized model tools. The worst consequence is observing or controlling an application that the user did not approve separately, within its available data and capabilities. The model cannot supply the authorization identity through the CUA request; the native helper reads it from the selected application. Different bundle identifiers require different decisions, even when users consider them versions of one product. + +Revocation applies to every installation sharing the identifier. Tests exercise unsigned copies, different identifiers, missing identifiers with persistent path consent, process restarts, symlink aliases, pending and running identity agreement, shared handle revocation and refusal to widen old grants. diff --git a/.agents/notes/implemented/architecture/2026-10-25-cua-bundle-id-consent.zh.md b/.agents/notes/implemented/architecture/2026-10-25-cua-bundle-id-consent.zh.md new file mode 100644 index 0000000000..bfc0bc5020 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-25-cua-bundle-id-consent.zh.md @@ -0,0 +1,33 @@ +# Agent Note: 按 Bundle ID 共用 macOS 应用授权 + +Status: implemented + +[English](2026-10-25-cua-bundle-id-consent.md) | 中文 + +## 问题 + +用户安装同一应用的多个版本时,希望对这个软件只做一次权限决定。可执行文件路径会拆分这些决定,签名检查也会让未签名的开发版应用无法保存长期授权。 + +## 决策 + +macOS 应用授权使用原生应用提供的、区分大小写的完整 Bundle ID。helper 将 `macos:bundle-id:` 和该标识连接后计算摘要,生成 `CuaApplicationId`。有 Bundle ID 时,安装路径、版本和签名不区分授权。否则,helper 对 `macos:executable-path:` 与规范化可执行路径计算摘要。两种身份都支持长期许可;路径身份在重启和原地更新后保持不变,另一个路径需要新的决定。会话决定和长期许可保留[profile 授权存储](2026-10-19-cua-profile-consent-storage.zh.md)规定的范围和撤销行为。 + +本决策取代[应用授权](2026-09-26-cua-application-consent.zh.md)中的可执行文件和签名身份选择,原记录仍负责执行检查与用户决定。运行进程的可执行路径由操作系统提供。有效的运行时 Bundle ID 不依赖路径查询成功。无法取得路径时省略授权记录中的可选路径信息,不用缓存的应用目录路径代替。Bundle ID 和实际路径均不可用时,授权失败并报告路径查询原因。进程身份仍须验证,可取得的实际路径仍须与所选目标一致。只要能取得实际进程路径,应用目录信息中缺少路径不会阻止授权。运行时无法取得 Bundle ID 时,仅在其报告的应用 bundle 主可执行文件与进程路径一致时读取该标识,否则按可执行路径识别授权。原生进程、可执行文件位置和窗口检查继续把每个句柄绑定到所选目标。启动检查从磁盘重新读取 Bundle ID 和可执行路径,但不计算可执行内容指纹。因此,在相同路径下替换内容且保留相同标识或路径身份时,许可仍会沿用,包括等待用户批准期间的替换。 + +身份前缀将新授权与旧的路径和签名、进程实例、可执行内容摘要分开。旧授权仍可撤销,但不能授予新 Bundle ID 身份访问权限;许可覆盖其他安装副本前,需要用户重新决定。 + +Apple 的 [PPPC 配置](https://support.apple.com/guide/deployment/privacy-preferences-policy-control-payload-dep38df53c2a/web)支持 Bundle ID 或路径选择条件,同时另行要求代码签名条件。[TN3127](https://developer.apple.com/documentation/technotes/tn3127-inside-code-signing-requirements)说明了指定要求如何跨版本识别代码,以及未签名和临时签名代码无法提供同等稳定性。DSH 采用这两种选择条件管理应用,不要求验证发布者身份。 + +## 考虑过的替代方案 + +**Bundle ID 加路径。** 可以区分安装副本,但用户希望共同授权的多个版本仍需分别确认。 + +**仅使用 Bundle ID。** 缺少标识会让本可操作的应用无法获得长期许可。规范化可执行路径提供稳定的后备标识,无须使用进程号或内容摘要。 + +**验证签名身份。** 可以区分发布者,但没有签名或验签失败时无法保存长期授权。发布者身份验证不属于本项应用管理规则。 + +## 后果 + +其他程序声明相同 Bundle ID,或替换路径授权对应的可执行文件时,会继承许可,包括通过其他已授权模型工具创建或修改的程序。最坏后果是在应用已有数据和能力范围内,读取或控制用户未单独批准的程序。模型不能在 CUA 请求中提交授权身份,该身份由原生 helper 从实际选中的应用读取。不同 Bundle ID 仍需分别授权,即使用户将它们视为同一产品的不同版本。 + +撤销作用于同一标识的所有安装副本。测试覆盖未签名副本、不同标识、缺少标识时的持久路径许可、进程重启、符号链接、启动前后身份一致、多个句柄共同撤销,以及不扩大旧授权。 diff --git a/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.i18n.yaml new file mode 100644 index 0000000000..e910137117 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-09-20-unambiguous-tool-arguments.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.md +/agent-note-unambiguous-tool-argument-compatibility: + en: dcb2b9835f9ee758 + zh: 68be9713f74571c4 +/agent-note-unambiguous-tool-argument-compatibility/problem: + en: c389c332bdadbbe4 + zh: 217520278ccf0932 +/agent-note-unambiguous-tool-argument-compatibility/decision: + en: 71c04efcfd972b02 + zh: d1f842920b1b0e3f +/agent-note-unambiguous-tool-argument-compatibility/alternatives-considered: + en: b2a96695819a978f + zh: c6f84b244be0dddf +/agent-note-unambiguous-tool-argument-compatibility/consequences: + en: bd24ad737c617c90 + zh: dbb7fa67c41af828 diff --git a/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.md b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.md new file mode 100644 index 0000000000..7e2a5111c3 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.md @@ -0,0 +1,25 @@ +# Agent Note: Unambiguous tool argument compatibility + +Status: implemented + +English | [中文](2026-09-20-unambiguous-tool-arguments.zh.md) + +## Problem + +Models can populate optional fields that do not affect the requested operation. Rejecting these calls adds retries without protecting any state. + +## Decision + +`grep` treats an exact empty `include` as omitted. Whitespace-only, negated, and comma-separated filters remain invalid. `update_goal` uses replacement fields only for `edit` and a blocker reason only for `blocked`; other actions ignore those known fields. Declared types, consumed values, authority, and exact revisions remain validated. Ignored fields never reach another goal operation or change unrelated state, and call summaries select only values used by the action. `write` and `edit` allow absent or blank justification when no sandbox mode is requested or the effective mode is repeated; actual widening retains its reason and approval requirements, and filesystem observation and denial checks remain active. + +This partially supersedes the unused-field rejection in the [goal-tool decision](../feature/2026-07-19-model-facing-goal-tools.md). Its authority, lifecycle, scheduling, and persistence decisions remain active. The rules apply to every provider and stay inside the owning tool rather than weakening its underlying service. + +## Alternatives considered + +- **Complete strict-schema adaptation first** — deferred because it is a separate provider-wide change; these cases have deterministic meanings and direct regression evidence. +- **Normalize all empty, null, or zero values** — rejected because such values can be meaningful input, including empty file contents and numeric limits. +- **Reject every populated inactive field** — rejected because the explicit action determines the goal operation, and unused fields cannot alter it. + +## Consequences + +The tools accept these calls without extra mutations. Unit tests cover ignored fields for every goal action, consumed-field and authority failures, stale revisions, filter validation, and real search results. A headless recorded-session scenario verifies both file extensions are searched and completion preserves the original objective and round cap. These rules give up detecting conflicting intent expressed only in inactive goal fields; they do not weaken authorization or establish a generic coercion policy. diff --git a/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.zh.md b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.zh.md new file mode 100644 index 0000000000..6887d9feb8 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-20-unambiguous-tool-arguments.zh.md @@ -0,0 +1,25 @@ +# Agent Note: 无歧义的工具参数兼容 + +Status: implemented + +[English](2026-09-20-unambiguous-tool-arguments.md) | 中文 + +## 问题 + +模型可能填写不影响所请求操作的可选字段。拒绝这些调用只会增加重试,并不保护任何状态。 + +## 决策 + +`grep` 将值恰好为空字符串的 `include` 视为省略。仅含空白、否定形式和逗号分隔的过滤器仍然无效。`update_goal` 仅在 `edit` 时使用替换字段,仅在 `blocked` 时使用阻塞原因;其他 action 忽略这些已知字段。声明的类型、实际使用的值、权限和精确修订号仍会校验。被忽略的字段不会传入另一种目标操作,也不会改变无关状态;调用摘要仅选择当前 action 使用的值。未请求沙箱模式或重复当前生效模式时,`write` 和 `edit` 允许省略理由或提供空白理由;真正升权仍需理由和审批,文件系统观察与拒绝检查继续生效。 + +本决策部分取代[目标工具决策](../feature/2026-07-19-model-facing-goal-tools.zh.md)中对无关字段的拒绝规则。其权限、生命周期、调度和持久化决策继续生效。这些规则适用于所有提供方,并保留在所属工具内,不削弱底层服务的校验。 + +## 考虑过的替代方案 + +- **先完成严格 schema 适配**——暂缓,因为这是单独的提供方级改造;这些情况具有确定含义和直接的回归证据。 +- **统一规范化所有空值、null 或零值**——不予采纳,因为这些值可能是有意义的输入,包括空文件内容和数值限制。 +- **拒绝所有已填写的非当前 action 字段**——不予采纳,因为显式 action 决定目标操作,而未使用的字段无法改变该操作。 + +## 后果 + +工具接受这些调用,且不会产生额外变更。单元测试覆盖每种目标 action 对无关字段的忽略、有效字段与权限失败、陈旧修订号、过滤器校验以及真实搜索结果。headless 会话回放验证两种扩展名的文件都参与搜索,并且完成操作保留原始目标和轮数上限。这些规则放弃检测仅由非当前 action 的目标字段表达的冲突意图;它们不削弱授权,也不建立通用类型转换策略。 diff --git a/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.i18n.yaml new file mode 100644 index 0000000000..8b8bba1309 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-10-21-subagent-end-turn-guidance.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.md +/agent-note-subagent-end-turn-guidance-stays-in-the-delegation-paragraph: + en: bfafb6d348cf2d21 + zh: 191bedbfa12b6329 +/agent-note-subagent-end-turn-guidance-stays-in-the-delegation-paragraph/problem: + en: 36ff1fff46915956 + zh: 198c8ca7efaeb5b6 +/agent-note-subagent-end-turn-guidance-stays-in-the-delegation-paragraph/decision: + en: 47b44ed9313c2ccf + zh: 7ad254f8ef88351d +/agent-note-subagent-end-turn-guidance-stays-in-the-delegation-paragraph/alternatives-considered: + en: d52fa1af379dea5b + zh: 4e404994f7a607dc +/agent-note-subagent-end-turn-guidance-stays-in-the-delegation-paragraph/verification: + en: be076216381ea64d + zh: 2da8d9819c20e2fe +/agent-note-subagent-end-turn-guidance-stays-in-the-delegation-paragraph/consequences: + en: d7c144cbe750a873 + zh: 602c06d08572481c diff --git a/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.md b/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.md new file mode 100644 index 0000000000..cd800e94fe --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.md @@ -0,0 +1,44 @@ +# Agent Note: Subagent end-turn guidance stays in the delegation paragraph + +Status: implemented + +English | [中文](2026-10-21-subagent-end-turn-guidance.zh.md) + +## Problem + +The delegation guidance paragraph ended with `When only waiting for their results remains, end your turn instead of sleeping or polling; the next result starts a new turn.` A later prompt revert removed that sentence together with unrelated prompt changes. + +Before the sentence existed, one long Session slept seven times for 150–240 seconds each (about 25 minutes) waiting for review subagents that finished in 2–9 minutes (#6057). A controlled probe on 2026-10-21 measured the sentence's effect on the model's next message after a child starts: `deepseek-v4-flash` and `deepseek-v4-pro`, 150 requests per arm per model, minimal system prompt, real `subagent` and `bash` schemas, history ending with `started subagent reviewer-1`. + +| Arm | Sleep call | Any bash call | Ended turn | +|---|---|---|---| +| With the sentence | 0/300 | 7/300 | 291/300 | +| Without the sentence | 29/300 | 120/300 | 179/300 | + +The per-model difference is `0/150` vs `6/150` for flash (p=0.030) and `0/150` vs `23/150` for pro (p=9.6e-8), two-sided Fisher exact. The two remaining samples in the with-sentence arm called `subagent` again instead of ending the turn. + +## Decision + +The delegation paragraph keeps the end-turn sentence, byte-identical to the text introduced for #6057. Ending the turn does not lose the result: a settled child delivers a user-role notice to its parent, and a notice that reaches an idle parent starts one independent model request ([`dsh-subagent`](../../../../packages/subagent/subagent/README.md)). Hosts that keep children progressing alternate `agent.whenIdle()` and `waitForChildren(agent)` ([ACP `session.ts`](../../../../packages/acp/acp/src/session.ts)), and `dsh-goal-round-driver` waits for running descendants before starting the next goal round. + +The sentence stays one literal line. Rewording `the next result starts a new turn` to `each result starts a new turn` would re-render 83 prompt sidecars without a measured behavior change. + +## Alternatives considered + +**Rely on the tool description.** The `subagent` tool description states that the runtime notifies the model when the child finishes. The probe measured 29/300 sleep calls without the paragraph sentence, so the tool description does not replace it. + +**Move the guidance into the tool description.** The paragraph is assembled from the set of visible delegation tools and lists their names; the tool description describes one tool. Moving the sentence changes ownership without changing the behavior it prevents. + +**Restore every prompt phrase reverted together with this sentence.** The read guidance and the `run_code` argument order are separate decisions with their own evidence; this note records only the delegation paragraph. + +## Verification + +- `packages/subagent/tool-subagent/tests/tool-subagent.spec.ts` asserts the rendered paragraph for each visible-tool combination, including the restored sentence (9 expectations). +- 83 `snapshots/**/system-prompt*.expected.md` sidecars carry the restored text and replay through the shipped headless profile in `test:snapshot`. +- The probe is a one-off controlled measurement and is not committed; its two arms differ only in the guidance sentence. + +## Consequences + +- Every request with a visible delegation tool carries one more sentence, about 30 tokens. +- The model ends its turn while only waiting for a delegated result instead of calling `bash sleep` or polling. +- A future prompt-slimming pass must treat this sentence as load-bearing; the probe table above is the evidence for keeping it. diff --git a/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.zh.md b/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.zh.md new file mode 100644 index 0000000000..b11656473a --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.zh.md @@ -0,0 +1,44 @@ +# Agent Note: 委派指导段保留结束本轮说明 + +Status: implemented + +[English](2026-10-21-subagent-end-turn-guidance.md) | 中文 + +## 问题 + +委派指导段以 `When only waiting for their results remains, end your turn instead of sleeping or polling; the next result starts a new turn.` 结尾。后来的一次提示词回退把这句和不相关的提示词改动一起删掉了。 + +这句出现之前,一个长 Session 为了等待 2–9 分钟就结束的 review 子代理,七次 `sleep` 150–240 秒,累计约 25 分钟(#6057)。2026-10-21 的受控探针测量了这句对「子代理启动后模型下一条消息」的影响:`deepseek-v4-flash` 与 `deepseek-v4-pro`,每臂每模型 150 次请求,最小 system prompt,真实 `subagent` 与 `bash` schema,历史以 `started subagent reviewer-1` 结束。 + +| 组 | sleep 调用 | 任何 bash 调用 | 结束本轮 | +|---|---|---|---| +| 有这句 | 0/300 | 7/300 | 291/300 | +| 无这句 | 29/300 | 120/300 | 179/300 | + +分模型差异:flash `0/150` vs `6/150`(p=0.030),pro `0/150` vs `23/150`(p=9.6e-8),双侧 Fisher 精确检验。有这句的一组里剩余 2 次是重新调用 `subagent`,而不是结束本轮。 + +## 决策 + +委派段保留结束本轮这句,文本与 #6057 引入的版本逐字一致。结束本轮不会丢失结果:子代理结束后会向父级投递 user-role 通知,通知到达空闲父级会起一次独立的模型请求([`dsh-subagent`](../../../../packages/subagent/subagent/README.zh.md))。在子代理继续推进期间,宿主交替等待 `agent.whenIdle()` 与 `waitForChildren(agent)`([ACP `session.ts`](../../../../packages/acp/acp/src/session.ts)),`dsh-goal-round-driver` 也会等运行中的后代结束再开下一轮 goal。 + +这句保持为一行字面文本。把 `the next result starts a new turn` 改成 `each result starts a new turn` 会重录 83 个提示词 sidecar,而测不到行为变化。 + +## 考虑过的替代方案 + +**只依赖工具描述。** `subagent` 工具描述写明运行时会在子代理结束时通知模型。探针测得没有这句时 sleep 为 29/300,说明工具描述替代不了它。 + +**把说明移进工具描述。** 这段指导按可见委派工具集合组装并列出工具名,工具描述只描述单个工具。移动这句会改变归属,但不改变它阻止的行为。 + +**把与这句一起被回退的所有提示词都恢复。** read 指导与 `run_code` 参数顺序是各自有证据的独立决定;本记录只覆盖委派段。 + +## 验证 + +- `packages/subagent/tool-subagent/tests/tool-subagent.spec.ts` 对每种可见工具组合断言渲染出的指导段,包含恢复后的这句(9 条断言)。 +- 83 个 `snapshots/**/system-prompt*.expected.md` sidecar 带有恢复后的文本,由 `test:snapshot` 通过随附 headless profile 回放。 +- 探针是一次性受控测量,未入库;两组只差这一句指导。 + +## 影响 + +- 只要存在可见委派工具,每个请求多一句,约 30 token。 +- 模型在只剩等待委派结果时结束本轮,不再调用 `bash sleep` 或轮询。 +- 后续的提示词精简必须把这句当作承重文本;上面的探针表是保留它的证据。 diff --git a/.agents/notes/implemented/bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.i18n.yaml new file mode 100644 index 0000000000..272a511792 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-10-22-series-start-unchanged-prompt-prefix.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.md +/agent-note-a-series-start-with-an-unchanged-prompt-keeps-the-surviving-system-node: + en: f62e2980951e0cb3 + zh: 3cd4fd49a89fae40 +/agent-note-a-series-start-with-an-unchanged-prompt-keeps-the-surviving-system-node/problem: + en: b2b7d5e9a4850ece + zh: cbd91b67969bca02 +/agent-note-a-series-start-with-an-unchanged-prompt-keeps-the-surviving-system-node/decision: + en: 8a3404207a36ecfb + zh: d8bc1decefa60a20 +/agent-note-a-series-start-with-an-unchanged-prompt-keeps-the-surviving-system-node/verification: + en: 1970ea84337ce9b5 + zh: da5b9928606c07c6 +/agent-note-a-series-start-with-an-unchanged-prompt-keeps-the-surviving-system-node/alternatives-considered: + en: 2e87f55619f04607 + zh: 7ca5a8e9a42a799a +/agent-note-a-series-start-with-an-unchanged-prompt-keeps-the-surviving-system-node/consequences: + en: bf8a9d6c56722efd + zh: 18dfdf8a7b9bcb5c diff --git a/.agents/notes/implemented/bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.md b/.agents/notes/implemented/bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.md new file mode 100644 index 0000000000..34352ed8b0 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.md @@ -0,0 +1,39 @@ +# Agent Note: A series start with an unchanged prompt keeps the surviving system node + +Status: implemented + +English | [中文](2026-10-22-series-start-unchanged-prompt-prefix.zh.md) + +## Problem + +On an in-history route, a prompt change is appended as a later `system/message`, so node 0 stays stale while the latest surviving node carries the rendering. A surface replacement (compaction, tool-result prune, image offload) starts a new request series. Re-baselining node 0 at a series start while the rendering already matched that latest node emptied the later node and wrote the identical text into node 0. The wire request then differed at its first message, so the provider prefix cache missed from the first token although no prompt text changed. + +Real session `session-da55bbc9-…`, turn 710 step 2: `compaction/prune` replaced one tool result (seq 34669, 34670); the next request wrote 7,618 characters identical to the node it emptied (seq 34672, 34673), `request/header` logged reason `series` (seq 34674), and the step billed 722,332 uncached input tokens with 1,152 cache-read tokens (0.16% hit) against about 99.9% on the neighboring steps. A build update at turn 707 had appended the prompt node; nothing changed the rendering at turn 710. + +## Decision + +`SystemPromptProjection.project` re-baselines node 0 only when the effective text must move: an incapable route, an empty rendering, or a series start whose latest surviving non-empty node text differs from the rendering. When the route is in-history, the rendering is non-empty, and the latest surviving node already holds it, the projection returns no updates and the node stays where the cached history carried it. The loop still records the request series through `request/header` (`series`, or `change` with `startsSeries: true`) and rebuilds declarations as before; when the unchanged-rendering skip coincides with a tool-schema series start, the header records the declaration change without `startsSeries`. + +Retry recovery keeps its guarantee: when a retry compaction shadows the latest node, the effective text falls back to an older node, differs from the rendering, and the head is rewritten before users are admitted again. The projection never appends an update after already-admitted users. + +## Verification + +- [`system-prompt-projection.spec.ts`](../../../../packages/core/agent-loop/tests/system-prompt-projection.spec.ts) pins the no-operation decision for a capable series start whose surviving node already matches. +- [`system-prompt-admission.spec.ts`](../../../../packages/core/agent-loop/tests/system-prompt-admission.spec.ts) pins the wire request: a compaction replacement with an unchanged rendering keeps both system messages, the previous request messages remain a prefix, and the neighboring steps regain the provider prefix. +- The [`in-history-series-start`](../../../../snapshots/session/in-history-series-start/) recorded session replays the shipped headless profile through a prompt change and a later surface replacement, pinning the unchanged-rendering series start to two retained prompt versions and no `system/message` event. + +## Alternatives considered + +**Always keep the appended node and never re-baseline.** Simpler, but a route that cannot append prompts, or a prompt that must clear, still needs a single current head, and a changed rendering at a series start must not append after users already admitted by a failed attempt. Rejected. + +**Skip consolidation whenever the head differs.** A stale head is authoritative again on an incapable destination route, because that route ignores later system nodes; the route capability, not the head text, decides whether the later node is effective. Rejected. + +**Stop treating local surface replacements as series starts.** A prune changes one tool result, so the cache loss is local, but image-offload and compaction decisions still legitimately start a series; the projection must not depend on which replacement produced the boundary. Rejected: the projection owns the prompt decision. + +**Compare reconstructed requests instead of surface text.** The loop derives requests from surface events, so comparing past wire messages would duplicate request reconstruction and still need the same effective-text comparison. Rejected. + +## Consequences + +- A capable route can retain earlier prompt versions in model history after a series start; they cost input tokens until a later consolidation or compaction shadows them. +- A tool-schema series start on a route without tool updates no longer writes a `system/message` event, so its header records the declaration change without `startsSeries`. The request still carries the complete active declaration set through the unsupported-route projection (`projectToolUpdates`), while `Session.toolHistory()` keeps its incremental baseline instead of resetting. +- Consolidation still applies when the rendering actually differs: route switches, prompt updates concurrent with compaction, and retries that shadow the latest node. diff --git a/.agents/notes/implemented/bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.zh.md b/.agents/notes/implemented/bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.zh.md new file mode 100644 index 0000000000..3d8b2cb0ac --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.zh.md @@ -0,0 +1,39 @@ +# Agent Note: 渲染未变的新序列保留存活的系统节点 + +Status: implemented + +[English](2026-10-22-series-start-unchanged-prompt-prefix.md) | 中文 + +## Problem + +在 in-history 路由上,提示词变化会追加为后续的 `system/message`,因此 node 0 保持陈旧,由最新存活节点承载渲染文本。surface 替换(压缩、工具结果剪枝、图片省略)会开启新的请求序列。在渲染文本已经与该最新节点一致时重写 node 0,会清空该节点并把完全相同的文本写进 node 0。于是 wire 请求的第一条消息发生变化,提供方前缀缓存从第一个 token 起未命中,尽管提示词文本没有任何变化。 + +真实会话 `session-da55bbc9-…` 第 710 轮第 2 步:`compaction/prune` 替换了一条工具结果(seq 34669、34670);下一次请求写入的 7,618 个字符与它清空的节点完全相同(seq 34672、34673),`request/header` 记录 reason `series`(seq 34674),该步计费 722,332 个未命中输入 token、1,152 个缓存读取 token(命中率 0.16%),而相邻步骤约为 99.9%。第 707 轮的构建更新追加了提示词节点;第 710 轮没有任何东西改变渲染文本。 + +## Decision + +`SystemPromptProjection.project` 只在有效文本必须移动时重写 node 0:不具备能力的路由、空渲染文本,或最新存活非空节点文本与渲染文本不同的新序列开始。当路由为 in-history、渲染文本非空、且最新存活节点已经持有它时,投影不产生任何更新,节点保持在已缓存历史携带它的位置。loop 仍通过 `request/header` 记录请求序列(`series`,或带 `startsSeries: true` 的 `change`),并照旧重建声明;当「渲染未变则跳过」与工具 schema 起因的新序列重合时,header 记录声明变化但不带 `startsSeries`。 + +重试恢复保持原有保证:重试压缩遮蔽最新节点后,有效文本回退到更旧的节点,与渲染文本不同,于是头节点在用户消息再次被接纳之前重写。投影从不会在已接纳的用户消息之后追加更新。 + +## Verification + +- [`system-prompt-projection.spec.ts`](../../../../packages/core/agent-loop/tests/system-prompt-projection.spec.ts) 固定「能力路由的新序列开始时存活节点文本已一致则不产生操作」的决策。 +- [`system-prompt-admission.spec.ts`](../../../../packages/core/agent-loop/tests/system-prompt-admission.spec.ts) 固定 wire 请求:渲染文本未变的压缩替换保留两条系统消息,上一次请求的消息仍构成前缀,相邻步骤重新获得提供方前缀。 +- [`in-history-series-start`](../../../../snapshots/session/in-history-series-start/) 录制会话通过 shipped headless profile 回放「提示词变化 + 后续 surface 替换」,固定渲染未变的新序列保留两份提示词版本且不写 `system/message` 事件。 + +## Alternatives considered + +**永远保留追加节点、从不重写。** 更简单,但无法追加提示词的路由、或必须清空的提示词仍需要单一当前头节点;新序列开始时若渲染文本确实变化,也不能在失败尝试已接纳的用户消息之后追加。拒绝。 + +**只要 head 不同就跳过归并。** 在目标路由变为不具备能力时,陈旧 head 会重新成为权威,因为该路由忽略后续系统节点;决定后续节点是否生效的是路由能力,而不是 head 文本。拒绝。 + +**让局部 surface 替换不再算新序列。** 剪枝只改一条工具结果的文本,缓存损失是局部的,但图片省略与压缩决定仍合理地开启新序列;投影不应依赖是哪种替换制造了边界。拒绝:提示词决策属于投影。 + +**比较重建后的请求而不是 surface 文本。** loop 从 surface 事件派生请求,比较历史 wire 消息会重复请求重建,而且仍然需要同样的有效文本比较。拒绝。 + +## Consequences + +- 具备能力的路由在新序列开始后可能在模型历史中保留更早的提示词版本;在被后续归并或压缩遮蔽之前,它们会计入输入 token。 +- 不支持工具更新的路由上,工具 schema 变化开启的新序列不再写出 `system/message` 事件,因此其 header 记录声明变化但不带 `startsSeries`。请求仍通过不支持更新的路由投影(`projectToolUpdates`)携带完整的生效声明集合,而 `Session.toolHistory()` 保留其增量基线、不再重置。 +- 渲染文本确实不同时归并仍然生效:路由切换、与压缩同时发生的提示词更新,以及遮蔽最新节点的重试。 diff --git a/.agents/notes/implemented/bug-fix/2026-10-25-shared-preset-delegation-tools.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-10-25-shared-preset-delegation-tools.i18n.yaml new file mode 100644 index 0000000000..5b65ef830c --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-25-shared-preset-delegation-tools.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-25-shared-preset-delegation-tools.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-10-25-shared-preset-delegation-tools.md +/agent-note-shared-preset-delegation-tools: + en: 2f33b8a19d8291b8 + zh: 4f49de632ac53d01 +/agent-note-shared-preset-delegation-tools/problem: + en: 3150532ae6efd14c + zh: 3c3d662c5bcb323b +/agent-note-shared-preset-delegation-tools/decision: + en: ccaa0792d54fe79d + zh: b2993214c35c1db0 +/agent-note-shared-preset-delegation-tools/alternatives-considered: + en: 2f53caf2af750178 + zh: cd4d9b823a9348dc +/agent-note-shared-preset-delegation-tools/consequences: + en: 4aaaaec2038b3f1d + zh: b52bdd02118ffb6f diff --git a/.agents/notes/implemented/bug-fix/2026-10-25-shared-preset-delegation-tools.md b/.agents/notes/implemented/bug-fix/2026-10-25-shared-preset-delegation-tools.md new file mode 100644 index 0000000000..5fc077b02c --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-25-shared-preset-delegation-tools.md @@ -0,0 +1,31 @@ +# Agent Note: Shared preset delegation tools + +Status: implemented + +English | [中文](2026-10-25-shared-preset-delegation-tools.zh.md) + +## Problem + +Agents sharing a preset need the same delegation definitions immediately after a preset switch. Installing identical tools separately for each Agent introduces an asynchronous visibility gap and places those definitions in the Agent's own registration layer, which is exempt from inherited-tool restrictions. + +## Decision + +Each tool-subagent instance registers its definition in its owning composition. Agents sharing a preset revision inherit that registration. Switching presets changes ancestry; it requires no per-Agent installation or tool-change reconciliation. Provider availability and the owning composition's disposal control registration lifetime. + +Tool configuration validates its own fields, allowlist consistency, required services and provider capabilities. Candidate preset documents are not read during registration, for either Host-mounted or preset-mounted tools. The delegation executor validates the model's selection against the allowlist; child startup resolves the selected id against the current registry. A later declaration can therefore satisfy a previously unavailable target without reinstalling the tool. Independent selection and restoration retain the [spawn preset semantics](../feature/2026-09-20-spawn-agent-preset-selection.md). + +The schema contains preset ids and default or inheritance guidance without candidate descriptions. This keeps shared definitions independent of other presets' declaration order and avoids retaining document text that can become stale. [Awaited Agent initialization](../architecture/2026-09-09-awaited-agent-creation.md) remains necessary for other asynchronous contributions. + +## Alternatives considered + +**Reinstall tools for each Agent.** Identical definitions gain extra installation, disposal and reconciliation work, and Agent-local ownership prevents inherited-tool restrictions from applying. + +**Validate every target at tool registration.** A target declared later is rejected even though it can be available when used. An early successful lookup also cannot guarantee availability after registry changes. + +**Retain candidate descriptions in shared schemas.** Reading descriptions during registration makes the result depend on declaration order. Keeping those descriptions current requires additional update coordination; the tool exposes ids instead. + +## Consequences + +Unknown or unloadable targets fail the selected delegation without leaving a child Agent or Session. An unused invalid reference remains undetected. Agent restrictions and restored historical filters apply to inherited delegation schemas, execution and guidance; sibling Agents retain their tools. + +Focused preset-selection tests cover immediate switch visibility, shared ownership and disposal, restrictions, missing targets and retry after declaration. The Web Loader cases cover shipped composition compatibility, and the headless preset snapshot pins model-visible choices. The historical-filter tests exercise child composition directly; they do not establish cold-resume coverage. diff --git a/.agents/notes/implemented/bug-fix/2026-10-25-shared-preset-delegation-tools.zh.md b/.agents/notes/implemented/bug-fix/2026-10-25-shared-preset-delegation-tools.zh.md new file mode 100644 index 0000000000..3c3cadfd1a --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-25-shared-preset-delegation-tools.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 预设共享委派工具 + +Status: implemented + +[English](2026-10-25-shared-preset-delegation-tools.md) | 中文 + +## 问题 + +共享预设的 Agent(智能体)需要在预设切换完成后立即取得相同的委派定义。为每个 Agent 分别安装相同工具会产生异步可见性缺口,并将定义放在 Agent 自身的注册层,而该层不受继承工具限制约束。 + +## 决策 + +每个 tool-subagent 实例在所属组装中注册定义。共享同一预设代际的 Agent 继承该注册。切换预设只改变祖先关系,无须按 Agent 安装或协调工具变更。提供方可用性及所属组装的 dispose(资源释放)决定注册的生命周期。 + +工具配置校验自身字段、白名单一致性、必需服务及提供方能力。Host 挂载和预设内挂载的工具都不在注册时读取候选预设文档。委派执行器按白名单校验模型选择,子级启动时再从当前注册表解析所选 id。因此,后续声明能够使原先不可用的目标变得可用,无须重新安装工具。独立选择与恢复保留 [spawn 预设语义](../feature/2026-09-20-spawn-agent-preset-selection.zh.md)。 + +schema 包含预设 id 及默认或继承提示,不包含候选描述。这使共享定义不依赖其他预设的声明顺序,也避免保留可能陈旧的文档文本。其他异步贡献仍需要[等待 Agent 初始化](../architecture/2026-09-09-awaited-agent-creation.zh.md)。 + +## 考虑过的替代方案 + +**为每个 Agent 重新安装工具。** 相同定义需要额外的安装、释放与协调工作,Agent 本地所有权还会阻止继承工具限制生效。 + +**在工具注册时校验所有目标。** 后声明的目标即使在使用时可用,也会被拒绝。提前查找成功同样无法保证注册表变更后的可用性。 + +**在共享 schema 中保留候选描述。** 注册时读取描述会使结果依赖声明顺序。保持描述同步需要额外的更新协调;工具选择公开 id。 + +## 后果 + +未知或无法加载的目标会使选中它的委派失败,不残留子 Agent 或 Session。未使用的无效引用仍不会被发现。Agent 限制及恢复的历史过滤器约束继承的委派 schema、执行与指导文本;同级 Agent 保留各自的工具。 + +针对性预设选择测试覆盖切换完成时的即时可见性、共享所有权与释放、限制、缺失目标及补声明后重试。Web Loader 用例覆盖 shipped 组装兼容性,headless 预设快照固定模型可见选项。历史过滤器测试直接执行子级组装,不证明冷恢复覆盖。 diff --git a/.agents/notes/implemented/bug-fix/2026-10-26-malformed-charset-declaration.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-10-26-malformed-charset-declaration.i18n.yaml new file mode 100644 index 0000000000..22e56fbdd0 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-26-malformed-charset-declaration.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-26-malformed-charset-declaration.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-10-26-malformed-charset-declaration.md +/agent-note-malformed-charset-recovery-prefers-utf-8: + en: d8a759b84c36b308 + zh: 3b6ff2eb5519afb1 +/agent-note-malformed-charset-recovery-prefers-utf-8/problem: + en: dce96445b3801a7f + zh: e026d26fa680556a +/agent-note-malformed-charset-recovery-prefers-utf-8/decision: + en: ba74ad57757231ca + zh: 46999cd0100814ae +/agent-note-malformed-charset-recovery-prefers-utf-8/alternatives-considered: + en: 9fafffb6a7a78a29 + zh: ee1dcc27d0315e68 +/agent-note-malformed-charset-recovery-prefers-utf-8/consequences: + en: c8aad3cc3f02e81e + zh: 29d9313afd1c7b5b diff --git a/.agents/notes/implemented/bug-fix/2026-10-26-malformed-charset-declaration.md b/.agents/notes/implemented/bug-fix/2026-10-26-malformed-charset-declaration.md new file mode 100644 index 0000000000..9e36964e09 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-26-malformed-charset-declaration.md @@ -0,0 +1,33 @@ +# Agent Note: Malformed charset recovery prefers UTF-8 + +Status: implemented + +English | [中文](2026-10-26-malformed-charset-declaration.zh.md) + +## Problem + +A response can declare `charset=utf-8,gbk` over readable UTF-8 HTML. Passing that entire parameter to `TextDecoder` rejects the page before reading it. Compatibility needs an explicit encoding preference because successful decoding alone cannot identify the server's intended encoding. + +## Decision + +`decoderForCharset` preserves valid single-label declarations and the absent-header UTF-8 default. If a declaration is unsupported as a whole, it checks its comma- and whitespace-separated labels for UTF-8, including standard aliases. A match selects a fatal UTF-8 decoder; otherwise the declaration fails before the response body is read and the provider cancels the stream. + +The provider decodes once. Recovery rejects invalid UTF-8 with `WEB_UNSUPPORTED_CONTENT_TYPE` and preserves the decoding error as its cause. Only an actual byte-cap truncation enables streaming decode, which omits an incomplete suffix and keeps `truncated: true`. Complete responses, including those exactly at the cap, validate the final sequence at EOF. + +UTF-8 recovery is an explicit heuristic, not proof of the original encoding. The bytes `C2 A9` represent `©` in UTF-8 and `漏` in GBK; repeating them preserves that ambiguity at any length. The provider accepts that ambiguity for UTF-8 recovery but does not extend it to arbitrary legacy-encoding guesses. + +## Alternatives considered + +**Choose the first declared encoding that decodes.** A GBK body can also decode as `windows-1252` with different text. Declaration order does not resolve the conflict, and single-byte encodings can turn a decoding failure into silent corruption. Rejected. + +**Use strict probes followed by ordinary decoding.** This decodes successful bodies twice. An unflushed streaming probe also accepts an incomplete EOF sequence that the ordinary decoder replaces. One fatal decode with explicit truncation state is sufficient. + +**Read BOM and HTML meta declarations.** This would add HTML encoding identification and a dependency or parser, with a separate policy for missing metadata and non-HTML content. It remains deferred; the bounded UTF-8 preference resolves the reported response without claiming browser-equivalent detection. + +## Consequences + +- Malformed declarations containing UTF-8 can return readable text; a failed UTF-8 recovery never falls back to another encoding or inserts replacement characters. +- Malformed declarations without a UTF-8 label remain unsupported, including repeated legacy aliases. Valid single-label legacy decoding is unchanged. +- [`fetch-http.spec.ts`](../../../../packages/web/web-fetch-http/tests/fetch-http.spec.ts) covers recovery, conflicting labels, invalid bytes, EOF, truncation, and response-stream cancellation. +- The recorded [`web-fetch`](../../../../snapshots/session/web-fetch/snapshot.yml) scenario serves literal UTF-8 characters with `charset=gbk,utf-8` through the real HTTP provider and verifies the same model-visible text. +- HTML `` remains ignored. The package README documents the remaining ambiguity. diff --git a/.agents/notes/implemented/bug-fix/2026-10-26-malformed-charset-declaration.zh.md b/.agents/notes/implemented/bug-fix/2026-10-26-malformed-charset-declaration.zh.md new file mode 100644 index 0000000000..8e9d1f31ed --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-26-malformed-charset-declaration.zh.md @@ -0,0 +1,33 @@ +# Agent Note: 畸形 charset 声明的恢复优先使用 UTF-8 + +Status: implemented + +[English](2026-10-26-malformed-charset-declaration.md) | 中文 + +## Problem + +响应可能在可读的 UTF-8 HTML 上声明 `charset=utf-8,gbk`。把整个参数交给 `TextDecoder` 会在读取前拒绝页面。兼容处理需要明确的编码优先规则,因为解码成功本身无法识别服务器原本使用的编码。 + +## Decision + +`decoderForCharset` 保留合法的单标签声明,以及未声明时默认使用 UTF-8 的行为。如果整个声明不受支持,它检查按逗号和空白分隔的标签是否包含 UTF-8(含标准别名)。匹配时选择 fatal UTF-8 解码器;否则在读取正文前拒绝声明,由提供方取消响应流。 + +提供方只解码一次。恢复路径以 `WEB_UNSUPPORTED_CONTENT_TYPE` 拒绝非法 UTF-8,并保留解码错误作为 cause。只有真正触发字节上限截断时才启用流式解码,省略不完整的末尾序列并保持 `truncated: true`。完整响应(包括恰好达到上限的响应)在 EOF 校验末尾序列。 + +UTF-8 恢复是明确的启发式规则,不是原始编码的证明。字节 `C2 A9` 在 UTF-8 下表示 `©`,在 GBK 下表示 `漏`;重复这些字节后,任意长度都保留该歧义。提供方为 UTF-8 恢复接受这种歧义,但不将其扩展为任意传统编码的猜测。 + +## Alternatives considered + +**选择声明中第一个能解码的编码。** GBK 正文也可能按 `windows-1252` 解出不同文本。声明顺序不能解决冲突,单字节编码还可能把解码失败变成静默的内容损坏。拒绝。 + +**先严格探测,再常规解码。** 这会对成功的正文解码两次。未结束的流式探测还会接受 EOF 处不完整的序列,随后被常规解码器替换。一次 fatal 解码配合显式截断状态已经足够。 + +**读取 BOM 和 HTML meta 声明。** 这会增加 HTML 编码识别能力及依赖或解析器,还需单独规定缺少元数据和非 HTML 内容的策略。继续延期;有范围的 UTF-8 优先规则可以处理所报告的响应,无需宣称与浏览器等价的编码检测。 + +## Consequences + +- 含有 UTF-8 的畸形声明可以返回可读文本;UTF-8 恢复失败时不会回退到其他编码,也不会插入替换字符。 +- 不含 UTF-8 标签的畸形声明仍不受支持,包括重复的传统编码别名。合法的单标签传统编码解码保持不变。 +- [`fetch-http.spec.ts`](../../../../packages/web/web-fetch-http/tests/fetch-http.spec.ts) 覆盖恢复、冲突标签、非法字节、EOF、截断和响应流取消。 +- 已录制的 [`web-fetch`](../../../../snapshots/session/web-fetch/snapshot.yml) 场景通过真实 HTTP 提供方,以 `charset=gbk,utf-8` 提供包含原样 UTF-8 字符的页面,并验证相同的模型可见文本。 +- HTML `` 仍然被忽略。包 README 记录了剩余歧义。 diff --git a/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.i18n.yaml b/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.i18n.yaml index 179198d487..e35994c87c 100644 --- a/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.i18n.yaml @@ -12,8 +12,8 @@ en: 0ab1e1c40cb2dac9 zh: b4180b6681c130b2 /agent-note-model-facing-same-session-goal-tools/decision/tools-and-model-contract: - en: 288a819f644611c9 - zh: d6bd7986ba091519 + en: 8589421c225beac0 + zh: d2a49dec31ba260c /agent-note-model-facing-same-session-goal-tools/decision/execution-authority: en: 63a9e7e85303b9f1 zh: d3f1d0c225103cfe @@ -24,8 +24,8 @@ en: 92650dd6648ca455 zh: 5b57276a6a983fea /agent-note-model-facing-same-session-goal-tools/alternatives-considered: - en: e84b9fc4823bcc1e - zh: a125628e4746bf50 + en: 84f7829c020f282b + zh: 37c4366efc9dd8dc /agent-note-model-facing-same-session-goal-tools/consequences: en: e254571a176b37e5 zh: 01f76aff35e3618d diff --git a/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.md b/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.md index d3dd654e02..0a37311be3 100644 --- a/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.md +++ b/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.md @@ -16,7 +16,7 @@ The tool API also needs to preserve the separation between durable state and liv ### Tools and model contract -`get_goal()` returns the current goal or `null`. A non-null result contains the compare-and-set id and revision, objective, durable phase, admitted and maximum goal rounds, any blocker reason, plus the process-local activation observation. `create_goal(objective, max_goal_rounds?)` creates one long-running same-session objective. `update_goal(goal_id, revision, action, objective?, max_goal_rounds?, blocked_reason?)` supports `edit`, `pause`, `resume`, `complete`, and `blocked`; replacement fields are valid only for `edit`, while a non-empty `blocked_reason` is required only for `blocked` and persists under the stable `model-reported` code. A durable paused goal rejects `resume` with `GOAL_TOOL_RESUME_PAUSED`; the user-facing command or Web control owns that transition. The executor treats exact empty-string optional fields and a zero `max_goal_rounds` as strict-schema fillers: they count as omitted, an edit still requires at least one meaningful replacement, and all non-filler values retain the action restrictions. +`get_goal()` returns the current goal or `null`. A non-null result contains the compare-and-set id and revision, objective, durable phase, admitted and maximum goal rounds, any blocker reason, plus the process-local activation observation. `create_goal(objective, max_goal_rounds?)` creates one long-running same-session objective. `update_goal(goal_id, revision, action, objective?, max_goal_rounds?, blocked_reason?)` supports `edit`, `pause`, `resume`, `complete`, and `blocked`; replacement fields are used only for `edit`, while a non-empty `blocked_reason` is required only for `blocked` and persists under the stable `model-reported` code. A durable paused goal rejects `resume` with `GOAL_TOOL_RESUME_PAUSED`; the user-facing command or Web control owns that transition. For `edit`, exact empty-string objectives and a zero `max_goal_rounds` count as omitted, and at least one meaningful replacement is required. Each action ignores known optional fields it does not use ([rationale](../bug-fix/2026-09-20-unambiguous-tool-arguments.md)). The prompt tells the model that it may infer goal intent from a direct human request in any wording or language, but should not convert routine single-turn work into a goal. It must read the current goal before updating and copy the exact id and revision. On a restored or forked active-but-disarmed goal, a semantic human request to continue is grounds for `resume`. The prompt does not announce the durable paused boundary; execution rejects that attempt with `GOAL_TOOL_RESUME_PAUSED`, and the user-facing resume path owns the transition. Completion is reserved for an achieved objective, and difficulty or uncertainty alone is not a blocker; a block report must name the concrete condition. @@ -48,7 +48,7 @@ Unit coverage pins registration and disposal, exclusive scheduling, generated pr - **Authorize from persisted root or fork metadata** — rejected because a fork that becomes an independently resumed top-level session should accept new human authority, while a currently owned child should not. - **Let autonomous rounds edit or resume the goal** — rejected because continuation authority is narrower than authority to redefine or restart the human objective. - **Treat the blocked threshold as an evaluator** — rejected because event counts cannot prove that an obstacle is semantically unchanged or truly terminal. -- **Reject every present action-specific field** — rejected because strict-schema providers can serialize zero-value placeholders for every optional field; only meaningful values can express a conflicting action. +- **Reject every present action-specific field** — rejected because strict-schema providers can serialize zero-value placeholders for every optional field; only meaningful values can express a conflicting action. The [unused-field decision](../bug-fix/2026-09-20-unambiguous-tool-arguments.md) defines which populated fields are ignored. ## Consequences diff --git a/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.zh.md b/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.zh.md index 8c5c502f37..e840230358 100644 --- a/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.zh.md +++ b/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.zh.md @@ -16,7 +16,7 @@ Status: implemented ### 工具与模型约定 -`get_goal()` 返回当前目标或 `null`。非空结果包含用于比较并交换的 id 与修订号、目标描述、持久阶段、已接纳和最大 Goal Round 数、可能存在的阻塞原因,以及进程本地激活态观察。`create_goal(objective, max_goal_rounds?)` 创建一个长时间运行的同会话目标。`update_goal(goal_id, revision, action, objective?, max_goal_rounds?, blocked_reason?)` 支持 `edit`、`pause`、`resume`、`complete` 和 `blocked`;替换字段仅对 `edit` 有效,非空的 `blocked_reason` 仅在 `blocked` 时必填,并以稳定代码 `model-reported` 持久化。持久 paused goal 会以 `GOAL_TOOL_RESUME_PAUSED` 拒绝 `resume`;面向用户的命令或 Web 控件拥有该转换。执行器把值恰好为空字符串的可选字段和值为 0 的 `max_goal_rounds` 视为严格 schema 占位值:这些值等同于省略;编辑时仍必须提供至少一个有实际意义的替换字段;所有非占位值仍受对应操作的限制。 +`get_goal()` 返回当前目标或 `null`。非空结果包含用于比较并交换的 id 与修订号、目标描述、持久阶段、已接纳和最大 Goal Round 数、可能存在的阻塞原因,以及进程本地激活态观察。`create_goal(objective, max_goal_rounds?)` 创建一个长时间运行的同会话目标。`update_goal(goal_id, revision, action, objective?, max_goal_rounds?, blocked_reason?)` 支持 `edit`、`pause`、`resume`、`complete` 和 `blocked`;替换字段仅在 `edit` 时使用,非空的 `blocked_reason` 仅在 `blocked` 时必填,并以稳定代码 `model-reported` 持久化。持久 paused goal 会以 `GOAL_TOOL_RESUME_PAUSED` 拒绝 `resume`;面向用户的命令或 Web 控件拥有该转换。对于 `edit`,值恰好为空字符串的目标描述和值为 0 的 `max_goal_rounds` 视为省略,且至少需要一个有实际意义的替换字段。每个 action 都忽略它不使用的已知可选字段([理由](../bug-fix/2026-09-20-unambiguous-tool-arguments.zh.md))。 提示词告诉模型:它可以从任何措辞或语言的直接人类请求中推断目标意图,但不应把常规单轮工作转换为目标。更新前必须读取当前目标,并复制准确的 id 和修订号。对于恢复或 fork 后处于活跃但未激活状态的目标,人类在语义上要求继续即可成为执行 `resume` 的依据。提示词不会静态声明持久 paused 的边界;执行时以 `GOAL_TOOL_RESUME_PAUSED` 拒绝该尝试,面向用户的恢复路径拥有该转换。只有目标已经实现时才能标记完成,困难或不确定性本身不构成阻塞;阻塞报告必须说明具体条件。 @@ -48,7 +48,7 @@ Status: implemented - **根据持久的根或 fork 元数据授权**——不予采纳,因为作为顶层会话独立恢复的 fork 应接受新的人类权限,而当前仍受所有权约束的 subagent 则不应接受。 - **允许自主 Round 编辑或恢复目标**——不予采纳,因为继续执行权限比重新定义或重启人类目标的权限更窄。 - **把阻塞阈值当作评估器**——不予采纳,因为事件计数无法证明障碍在语义上未改变或确实不可继续。 -- **拒绝所有已提供的特定操作字段**——不予采纳,因为采用严格 schema 的提供方可能为每个可选字段序列化零值占位符;只有有实际意义的字段值才能表示与指定操作相冲突的另一项操作。 +- **拒绝所有已提供的特定操作字段**——不予采纳,因为采用严格 schema 的提供方可能为每个可选字段序列化零值占位符;只有有实际意义的字段值才能表示与指定操作相冲突的另一项操作。[无关字段决策](../bug-fix/2026-09-20-unambiguous-tool-arguments.zh.md)规定了哪些已填写字段会被忽略。 ## 后果 diff --git a/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.i18n.yaml b/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.i18n.yaml index 379e4f0ad9..0a0b79c7f5 100644 --- a/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.i18n.yaml @@ -15,8 +15,8 @@ en: 2f23fa55e1ce652c zh: 335695fc654ab1db /agent-note-in-history-system-prompt-replacement-for-cache-stable-prompt-changes/decision/the-decision-rule: - en: 554d01427ebebee1 - zh: 664c9bf0a9337a04 + en: bd990101d220c905 + zh: 98f54d523b9ffe52 /agent-note-in-history-system-prompt-replacement-for-cache-stable-prompt-changes/decision/presentation-and-accounting: en: 800d579e2fcf2cce zh: 1e92354d9161c50a diff --git a/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.md b/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.md index 82402feff9..795f6cfe5d 100644 --- a/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.md +++ b/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.md @@ -24,18 +24,19 @@ The loop records the mode in the session: `RequestContext.systemPromptUpdate` jo ### The decision rule -`SystemPromptProjection.project(rendered, { inHistory, startsSeries })` in `packages/core/agent-loop/src/runtime-context.ts` scans the surviving `system/message` nodes of the current surface on every call. It returns ordered per-node commits. With no surviving system node it reserves the head even for an empty rendering. Effective text comes from the latest non-empty system node, falling back to the head; dormant empty tails neither supply effective text nor need another empty replacement. An empty rendering clears every active system node, regardless of route or series state. For a non-empty rendering on an incapable route or at a new request series, consolidation applies even when the effective text is unchanged. Otherwise matching effective text emits nothing. The operations are: +`SystemPromptProjection.project(rendered, { inHistory, startsSeries })` in `packages/core/agent-loop/src/runtime-context.ts` scans the surviving `system/message` nodes of the current surface on every call. It returns ordered per-node commits. With no surviving system node it reserves the head even for an empty rendering. Effective text comes from the latest non-empty system node, falling back to the head; dormant empty tails neither supply effective text nor need another empty replacement. An empty rendering clears every active system node, regardless of route or series state. For a non-empty rendering, an incapable route or a new request series whose effective text differs consolidates; a series start whose latest surviving node already holds the rendering emits nothing and keeps that node in place. Otherwise matching effective text emits nothing. The unchanged-text case is owned by the [series-start prefix decision](../bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.md). The operations are: | Route capability | Prefix state | Operation | |---|---|---| | none | non-empty rendering, any prefix state | log an empty replacement for each non-empty later system node, then rewrite the first system node with the rendering if needed | | `in-history` | the current request series continues | append a new `system/message` before the step's `user/message` events; the append alone needs no `request/header` | -| `in-history` | non-empty rendering, a new series starts | log empty replacements for non-empty later system nodes, then rewrite the first system node if needed, even when the latest effective text is unchanged | +| `in-history` | non-empty rendering, a new series starts and the latest effective text differs | log empty replacements for non-empty later system nodes, then rewrite the first system node if needed | +| `in-history` | non-empty rendering, a new series starts with the rendering already current | no operation: the surviving node stays where the cached history carried it | | any | the rendered prompt is empty | log empty replacements for non-empty later system nodes, then empty the head if needed; no prompt version remains in derived messages | -`startsSeries` is true when the `agent/pre-step` decision declares `startsRequestSeries`, when the surface replace generation moved since the last request (a compaction or any other replacement), or when the visible tool-schema set changed on a route without `toolUpdate` support. Supported tool additions can accompany a prompt append without starting a series. A provider or model swap alone is not a series start for this rule: on a capable destination route the changed prompt is appended, which costs nothing because the route change already misses the cache. A series start already costs the cache, so consolidation keeps only the current prompt in model history. Logged per-node empty replacements remove later prompts from derived messages without a surface delete operation or any replacement of intervening conversation nodes. This also keeps compaction recovery from appending a system update after users already admitted by the failed attempt. +`startsSeries` is true when the `agent/pre-step` decision declares `startsRequestSeries`, when the surface replace generation moved since the last request (a compaction or any other replacement), or when the visible tool-schema set changed on a route without `toolUpdate` support. Supported tool additions can accompany a prompt append without starting a series. A provider or model swap alone is not a series start for this rule: on a capable destination route the changed prompt is appended, which costs nothing because the route change already misses the cache. A series start does not by itself discard the whole provider prefix: a replacement or image-offload decision may invalidate only the tail, so consolidation waits until the effective text must move; when it does, the series is the point to keep only the current prompt in model history and to avoid appending after already-admitted users on a retry. Logged per-node empty replacements remove later prompts from derived messages without a surface delete operation or any replacement of intervening conversation nodes. This also keeps compaction recovery from appending a system update after users already admitted by the failed attempt. -The first attempt admits the prompt after assembly, an accepted `agent/pre-step` decision, `step/start`, the `agent/request` waterfall, and `prepareCall()`. A rejected or empty first input opens no step. Neither async request phase commits the pending system prompt or accepted users, and cancellation during either commits neither. Every attempt synchronously reconciles the same rendered assembly after its own `agent/request` and `prepareCall()`, appends the accepted user batch only on the first attempt, logs header/context as needed, and derives and freezes the request before streaming through the same prepared call. Retries do not repeat assembly, `agent/pre-step`, or user admission. Reconciliation sees both pre-step compaction (`compaction-basic` with `auto: true`) and recovery compaction, and consolidates non-empty prompt text at the head when either starts a new series. Resume is series-continuing — the `resume` header is not a series start — so a prompt that changed across a restart is appended; the provider cache may still be warm across a process boundary. +The first attempt admits the prompt after assembly, an accepted `agent/pre-step` decision, `step/start`, the `agent/request` waterfall, and `prepareCall()`. A rejected or empty first input opens no step. Neither async request phase commits the pending system prompt or accepted users, and cancellation during either commits neither. Every attempt synchronously reconciles the same rendered assembly after its own `agent/request` and `prepareCall()`, appends the accepted user batch only on the first attempt, logs header/context as needed, and derives and freezes the request before streaming through the same prepared call. Retries do not repeat assembly, `agent/pre-step`, or user admission. Reconciliation sees both pre-step compaction (`compaction-basic` with `auto: true`) and recovery compaction, and consolidates non-empty prompt text at the head when either starts a new series whose effective text differs. Resume is series-continuing — the `resume` header is not a series start — so a prompt that changed across a restart is appended; the provider cache may still be warm across a process boundary. An empty head with no active later system node represents no prompt. Dormant empty tails do not supply effective text, so repeated clearing and resume cannot resurrect an older prompt. Restoring non-empty text uses the same admission rule: a continuing capable route may append it; an incapable route or a new series refills the head. Clearing uses ordinary per-node replacements, not a surface delete or an initial empty-head creation. diff --git a/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.zh.md b/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.zh.md index a2c8c60bbf..79ff75b3ec 100644 --- a/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.zh.md +++ b/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.zh.md @@ -24,18 +24,19 @@ Status: implemented ### 决策规则 -`packages/core/agent-loop/src/runtime-context.ts` 中的 `SystemPromptProjection.project(rendered, { inHistory, startsSeries })` 每次调用都扫描当前 surface 上存活的 `system/message` 节点。它返回有序的逐节点提交。没有存活的系统节点时,即使渲染文本为空也预留头节点。有效文本取自最新的非空系统节点,没有时回退到头节点;未生效的空尾节点既不提供有效文本,也无需再次以空内容替换。无论路由或序列状态如何,空渲染文本都会清除每个生效的系统节点。不具备能力的路由或新请求序列面对非空渲染文本时,即使有效文本未变也执行归并。除此之外,有效文本相同时不产生事件。具体操作如下: +`packages/core/agent-loop/src/runtime-context.ts` 中的 `SystemPromptProjection.project(rendered, { inHistory, startsSeries })` 每次调用都扫描当前 surface 上存活的 `system/message` 节点。它返回有序的逐节点提交。没有存活的系统节点时,即使渲染文本为空也预留头节点。有效文本取自最新的非空系统节点,没有时回退到头节点;未生效的空尾节点既不提供有效文本,也无需再次以空内容替换。无论路由或序列状态如何,空渲染文本都会清除每个生效的系统节点。面对非空渲染文本,不具备能力的路由或有效文本不同的新请求序列执行归并;新序列开始时若最新存活节点已经持有该渲染文本,则不产生事件并保留该节点。除此之外,有效文本相同时不产生事件。有效文本未变的新序列由[系列开始前缀决策](../bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.zh.md)拥有。具体操作如下: | 路由能力 | 前缀状态 | 操作 | |---|---|---| | 无 | 非空渲染文本,任意前缀状态 | 为每个非空的后续系统节点记录空内容替换,随后按需用渲染文本重写首个系统节点 | | `in-history` | 当前请求序列延续 | 在该步骤的 `user/message` 事件之前追加新的 `system/message`;仅追加本身不需要记录 `request/header` | -| `in-history` | 非空渲染文本,新序列开始 | 为非空的后续系统节点记录空内容替换,再按需重写首个系统节点,即使最新有效文本未变也执行 | +| `in-history` | 非空渲染文本,新序列开始且最新有效文本不同 | 为非空的后续系统节点记录空内容替换,再按需重写首个系统节点 | +| `in-history` | 非空渲染文本,新序列开始但渲染文本已经是当前文本 | 不产生操作:存活节点保持在已缓存历史携带它的位置 | | 任意 | 渲染后的提示词为空 | 为非空的后续系统节点记录空内容替换,再按需清空头节点;派生消息中不保留任何提示词版本 | -`startsSeries` 在以下情况为真:`agent/pre-step` 决定声明了 `startsRequestSeries`、surface 的替换代数自上次请求以来发生了移动(压缩或任何其他替换)、不支持 `toolUpdate` 的路由上可见工具 schema 集合发生了变化。受支持的工具添加可以与提示词追加一起发生,无需开启新序列。仅 provider 或 model 切换对本规则不算序列开始:目标路由具备能力时,变更后的提示词被追加,这不花任何代价,因为路由变更本身已经使缓存未命中。序列开始已经付出了缓存代价,因此归并让模型历史只保留当前提示词。有日志记录的逐节点空内容替换会从派生消息中移除后续提示词,无需 surface 删除操作,也不替换其间的对话节点。这也使压缩恢复不会在失败尝试已接纳的用户消息之后追加系统更新。 +`startsSeries` 在以下情况为真:`agent/pre-step` 决定声明了 `startsRequestSeries`、surface 的替换代数自上次请求以来发生了移动(压缩或任何其他替换)、不支持 `toolUpdate` 的路由上可见工具 schema 集合发生了变化。受支持的工具添加可以与提示词追加一起发生,无需开启新序列。仅 provider 或 model 切换对本规则不算序列开始:目标路由具备能力时,变更后的提示词被追加,这不花任何代价,因为路由变更本身已经使缓存未命中。序列开始本身并不必然使整段提供方前缀作废:替换或图片省略决定可能只使尾部失效,因此归并会等到有效文本必须移动时才执行;此时借助该序列只保留当前提示词,并避免重试时在已接纳的用户消息之后追加指令。有日志记录的逐节点空内容替换会从派生消息中移除后续提示词,无需 surface 删除操作,也不替换其间的对话节点。这也使压缩恢复不会在失败尝试已接纳的用户消息之后追加系统更新。 -首次尝试在组装、被接纳的 `agent/pre-step` 决策、`step/start`、`agent/request` waterfall 与 `prepareCall()` 之后才接纳提示词。被拒绝或为空的首次输入不打开步骤。两个异步请求阶段都不提交待处理的系统提示词与已接纳用户消息,在任一阶段取消都不会提交这两者。每次尝试都在各自的 `agent/request` 与 `prepareCall()` 之后同步协调同一份已渲染组装结果、仅在首次尝试追加已接纳用户批次、按需记录 header/context、派生并冻结请求,再通过同一个已准备调用发起流式请求。重试不重复组装、`agent/pre-step` 或用户消息准入。协调过程可见 pre-step 压缩(`auto: true` 的 `compaction-basic`)与恢复压缩,并在任一种压缩开启新序列时将非空提示词文本归并到头部。恢复属于序列延续——`resume` header 不是序列开始——因此跨重启发生变化的提示词被追加;提供方缓存在进程边界之后可能仍是热的。 +首次尝试在组装、被接纳的 `agent/pre-step` 决策、`step/start`、`agent/request` waterfall 与 `prepareCall()` 之后才接纳提示词。被拒绝或为空的首次输入不打开步骤。两个异步请求阶段都不提交待处理的系统提示词与已接纳用户消息,在任一阶段取消都不会提交这两者。每次尝试都在各自的 `agent/request` 与 `prepareCall()` 之后同步协调同一份已渲染组装结果、仅在首次尝试追加已接纳用户批次、按需记录 header/context、派生并冻结请求,再通过同一个已准备调用发起流式请求。重试不重复组装、`agent/pre-step` 或用户消息准入。协调过程可见 pre-step 压缩(`auto: true` 的 `compaction-basic`)与恢复压缩,并在任一种压缩开启有效文本不同的新序列时将非空提示词文本归并到头部。恢复属于序列延续——`resume` header 不是序列开始——因此跨重启发生变化的提示词被追加;提供方缓存在进程边界之后可能仍是热的。 空头节点且没有生效的后续系统节点表示没有提示词。未生效的空尾节点不提供有效文本,因此重复清除与恢复会话都不会使旧提示词重新生效。重新提供非空文本使用同一准入规则:延续中的具备能力路由可以追加它;不具备能力的路由或新序列则重新填充头节点。清除使用普通的逐节点替换,而非 surface 删除或初次创建空头节点。 diff --git a/.agents/notes/implemented/feature/2026-10-02-plugin-market-discover.i18n.yaml b/.agents/notes/implemented/feature/2026-10-02-plugin-market-discover.i18n.yaml index 4abceb8733..2bc76443c3 100644 --- a/.agents/notes/implemented/feature/2026-10-02-plugin-market-discover.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-02-plugin-market-discover.i18n.yaml @@ -9,8 +9,8 @@ en: 329c6ff947559b11 zh: 5c4c1053236d319b /agent-note-plugin-market-discover-page-and-index-reader/decision: - en: cc4d17a51dd479b7 - zh: 1fecf669b117f51c + en: dd32bedaa763a4cb + zh: 27b1a81bd744d8c1 /agent-note-plugin-market-discover-page-and-index-reader/alternatives-considered: en: 62e7691dc8efd5c0 zh: b13769634979b950 diff --git a/.agents/notes/implemented/feature/2026-10-02-plugin-market-discover.md b/.agents/notes/implemented/feature/2026-10-02-plugin-market-discover.md index 505ea944e6..95724fa8ec 100644 --- a/.agents/notes/implemented/feature/2026-10-02-plugin-market-discover.md +++ b/.agents/notes/implemented/feature/2026-10-02-plugin-market-discover.md @@ -12,7 +12,7 @@ The plugin manager owns profile package operations and must not remount while an ## Decision -The feature ships as the experimental optional [custom plugin markets bundle](../../../../packages/experimental/plugin-market-bundle/README.md), off by default, which mounts both rows below; with it off, neither the service, the Discover tab, nor the `plugin_market` tool exists, and the Plugins page shows no tabs. A separate Host service, [`pluginMarket`](../../../../packages/boot/plugin-market/README.md), reads indexes. It requires `pluginManager` for read-only calls and never writes the profile. Its `indexes` configuration field is volatile: Settings writes only volatile fields, and the Loader commits a volatile-only change into the running reference without remounting any plugin. Other fields (`fetchTimeoutMs`, `maxBytes`, `cacheTtlMs`) are ordinary configuration. +The feature ships as the experimental optional [custom plugin indexes bundle](../../../../packages/experimental/plugin-market-bundle/README.md), off by default, which mounts both rows below; with it off, neither the service, the Discover tab, nor the `plugin_market` tool exists, and the Plugins page shows no tabs. A separate Host service, [`pluginMarket`](../../../../packages/boot/plugin-market/README.md), reads indexes. It requires `pluginManager` for read-only calls and never writes the profile. Its `indexes` configuration field is volatile: Settings writes only volatile fields, and the Loader commits a volatile-only change into the running reference without remounting any plugin. Other fields (`fetchTimeoutMs`, `maxBytes`, `cacheTtlMs`) are ordinary configuration. Index URLs use `http:` or `https:`, without credentials or fragment. `file:` is excluded because relative icon references would resolve to URLs a browser cannot load. `search` and `entry` accept only a configured URL, so the Host never fetches an address a client supplies. The Host fetches through the process proxy, refuses redirects, bounds the body, and validates with the shared format package; an invalid index affects only its own URL. diff --git a/.agents/notes/implemented/feature/2026-10-02-plugin-market-discover.zh.md b/.agents/notes/implemented/feature/2026-10-02-plugin-market-discover.zh.md index f924fb0641..136df83518 100644 --- a/.agents/notes/implemented/feature/2026-10-02-plugin-market-discover.zh.md +++ b/.agents/notes/implemented/feature/2026-10-02-plugin-market-discover.zh.md @@ -12,7 +12,7 @@ Status: implemented ## 决策 -该功能以实验性的可选[自定义插件市场组合包](../../../../packages/experimental/plugin-market-bundle/README.zh.md)发布,默认关闭,并挂载下面两行;关闭时,服务、「发现」标签页和 `plugin_market` 工具都不存在,插件页也不显示标签页。由独立的 Host 服务 [`pluginMarket`](../../../../packages/boot/plugin-market/README.zh.md) 读取索引。它依赖 `pluginManager` 进行只读调用,从不写入 profile。它的 `indexes` 配置字段是 volatile 字段:Settings 只写入 volatile 字段,Loader 把只涉及 volatile 字段的变更提交到运行中的引用,不重新挂载任何插件。其他字段(`fetchTimeoutMs`、`maxBytes`、`cacheTtlMs`)是普通配置。 +该功能以实验性的可选[自定义插件索引组合包](../../../../packages/experimental/plugin-market-bundle/README.zh.md)发布,默认关闭,并挂载下面两行;关闭时,服务、「发现」标签页和 `plugin_market` 工具都不存在,插件页也不显示标签页。由独立的 Host 服务 [`pluginMarket`](../../../../packages/boot/plugin-market/README.zh.md) 读取索引。它依赖 `pluginManager` 进行只读调用,从不写入 profile。它的 `indexes` 配置字段是 volatile 字段:Settings 只写入 volatile 字段,Loader 把只涉及 volatile 字段的变更提交到运行中的引用,不重新挂载任何插件。其他字段(`fetchTimeoutMs`、`maxBytes`、`cacheTtlMs`)是普通配置。 索引 URL 使用 `http:` 或 `https:`,不含凭据或片段。排除 `file:`,因为相对图标引用会解析为浏览器无法加载的 URL。`search` 和 `entry` 只接受已配置的 URL,因此 Host 从不获取客户端提供的地址。Host 通过进程代理获取,拒绝重定向,限制响应体大小,并用共享的格式包校验;无效索引只影响它自己的 URL。 diff --git a/.agents/notes/implemented/feature/2026-10-21-floating-window-edge-recovery.i18n.yaml b/.agents/notes/implemented/feature/2026-10-21-floating-window-edge-recovery.i18n.yaml new file mode 100644 index 0000000000..dad8343dcf --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-21-floating-window-edge-recovery.i18n.yaml @@ -0,0 +1,37 @@ +# Bilingual-pair consistency record for 2026-10-21-floating-window-edge-recovery.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-10-21-floating-window-edge-recovery.md +/agent-note-spring-based-edge-recovery-for-floating-dock-panels: + en: 73438e22c1bef8d3 + zh: 5f817eb06259f8ef +/agent-note-spring-based-edge-recovery-for-floating-dock-panels/problem: + en: c3b007f5cce80d8b + zh: c08b07f7e71eaa5f +/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision: + en: f88f165ca80a57b8 + zh: 98559f2239b03445 +/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision/legal-region-and-displayed-position: + en: 6dea90dc406eacf5 + zh: 6ecae0fdad78c855 +/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision/drag-with-resistance: + en: 5214241925b52bc3 + zh: bbd66dc72c03f960 +/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision/release-and-spring: + en: ba2b5a3b4923d585 + zh: 99544462a464ac50 +/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision/reduced-motion: + en: 7e29bf1c45b5386d + zh: c913a2ce6d1722d1 +/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision/change-scope: + en: 6459103379aefe41 + zh: 501dee08a977b6a0 +/agent-note-spring-based-edge-recovery-for-floating-dock-panels/testing: + en: da3b2b6781aa99f3 + zh: 37e49fa22f72fb84 +/agent-note-spring-based-edge-recovery-for-floating-dock-panels/alternatives-considered: + en: 3d901f0f5e270e29 + zh: c1fb89b567ea3c70 +/agent-note-spring-based-edge-recovery-for-floating-dock-panels/consequences: + en: 360bd69c918f23fe + zh: 48642fd59ad3279b diff --git a/.agents/notes/implemented/feature/2026-10-21-floating-window-edge-recovery.md b/.agents/notes/implemented/feature/2026-10-21-floating-window-edge-recovery.md new file mode 100644 index 0000000000..a4e9ca4e25 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-21-floating-window-edge-recovery.md @@ -0,0 +1,106 @@ +# Agent Note: Spring-based edge recovery for floating dock panels + +Status: implemented + +English | [中文](2026-10-21-floating-window-edge-recovery.zh.md) + +## Problem + +The dock kit's floating panels are the client's floating windows. `FloatLayer` and the retained `DockLayout` renderer draw them in viewport coordinates through one shared gesture hook, `useFloatGestures`, and the right Sidebar embeds them, so the same panels run in the Web client and inside the Desktop window. Their drag followed the pointer one to one with only a top floor (`--dsh-dockkit-float-top`, which keeps the header below the Windows caption). A panel could therefore be dragged past the left, right or bottom edge until its header was out of reach; a viewport that shrank left a panel outside it; and the creation cascade could place a new panel outside a small viewport. The required behavior is that a panel pushed past an edge visibly resists, and on release is pulled back inside with spring physics instead of being stopped by a wall or left outside. + +The reference implementation examined, Claude Desktop, has no portable edge-recovery rule: its Electron fallback corrects an off-screen window once, without animation, on the right and bottom edges only. The behavior had to be designed, not ported. + +The change keeps these obligations: a panel header is always reachable; one gesture still records at most one history entry; reduced motion is honored; the persisted Sidebar layout format and every embedder stay unchanged; and the motion is deterministic enough to test without a real browser clock. + +## Decision + +The behavior lives entirely in `packages/client/ui-dockkit`, inside `useFloatGestures` and the pure engine helpers it calls. Both float renderers take their rectangles from that hook through `rectOf`, so Web and Desktop share the behavior, and no embedder, shell or persisted format changed. The rule extends the floating panels of [right Sidebar docking](2026-09-04-right-sidebar-docking-infrastructure.md) and the fixed-position floating frames of the [retained tab layout](../architecture/2026-09-20-sidebar-retained-tab-layout.md); it supersedes neither note. + +### Legal region and displayed position + +The legal region of a panel is the viewport (`window.innerWidth` by `window.innerHeight`) with the existing top floor: the Windows caption height plus 20 px when `data-windows-titlebar` is set (20 px in native fullscreen), otherwise 0. `floatBounds` reads only these values and the root's attributes, so starting a gesture forces no layout. `legalFloatRect` projects a rectangle into the region per axis; when a panel is wider or taller than the region it is drawn at the region's size on that axis, so its header controls and its resize corner stay on screen; the stored size is unchanged. + +A panel draws at its stored rectangle projected into the viewport. The stored rectangle is never rewritten for the viewport: a shrinking window pushes the panel in without recording an operation, and a growing window returns it toward its stored position. The hook re-reads the bounds at every press and on every window `resize` event, and a gesture in progress uses the new bounds. Persisted layouts that hold off-screen rectangles display inside the viewport without migration. + +At rest a panel publishes its rectangle to the `.float` rule as CSS variables through `floatStyle`, and the rule clamps its position and size into the viewport (`100vw` by `100dvh`, which follows `window.innerHeight` as the hook does) and below the caption floor once more; an oversized panel takes the viewport's size there as it does in `legalFloatRect`. A bounds reading the hook has not refreshed, such as one taken before a fullscreen change settles, therefore still leaves the panel inside. A gesture or a return writes its position and size inline, outside the clamp. + +### Drag with resistance + +A move computes the desired rectangle from the gesture's start rectangle and the pointer travel, then `resistedRect` splits it per axis into the legal projection and the overflow `o` beyond it and draws it at `legal + sign(o) * K * |o| / (K + |o|)` with `K = FLOAT_RESISTANCE = 120` px. The mapping applies on all four edges, including above the top floor, is continuous, has slope 1 at the edge, and approaches `K`: + +| pointer overflow (px) | panel displacement past the edge (px) | share of the overflow | +|---|---|---| +| 10 | 9.2 | 92.3% | +| 40 | 30.0 | 75.0% | +| 120 | 60.0 | 50.0% | +| 400 | 92.3 | 23.1% | + +A resize clamps the bottom-right corner to the region through `boundedResize` and keeps `FLOAT_MIN_SIZE`; resizing has no resistance, because a corner that lags the pointer reads as a broken handle. + +### Release and spring + +A release records the legal rectangle: `moveFloat` or `resizeFloat` when it differs from the legal rectangle at the press, otherwise only the raise a click records. A click on a panel drawn projected therefore keeps its stored rectangle. A move or resize therefore records only legal rectangles, and undo restores the pre-gesture position in one step. Panel creation (the drop rectangle of `floatTab` and the cascade) can still store a rectangle outside the viewport; the projection draws it inside. When the panel was drawn outside the legal region, the hook keeps a preview and springs it from where it was drawn to the recorded rectangle, then clears the preview. A release inside the region animates nothing. + +The spring in `engine/spring.ts` is underdamped, because its bounce goes inward and is always legal: response 0.32 s and damping ratio 0.72. An overflowing axis starts with the velocity of the drawn panel over the last 100 ms of the drag, so the speed is continuous across the release; it is capped at `SPRING_MAX_VELOCITY` (1500 px/s), and `launchVelocity` caps its outward part at `omega0 * (K - d)` for a drawn overflow `d`. A fling past the edge travels further before it turns back, and because the spring carries an offset `d` with speed `v` at most `d + 0.46 * v / omega0` from its target, the whole return stays within `K` of the edge. An axis that did not overflow keeps still. Per axis the update is: + +``` +a = -omega0^2 * (x - target) - 2 * zeta * omega0 * v +v = v + a * h +x = x + v * h +``` + +`stepSpring` integrates in equal substeps of at most `h = 1/480 s`, so the motion does not depend on the frame rate. One `requestAnimationFrame` loop in the hook clamps a frame to 64 ms, ends at the target when a frame gap exceeds 250 ms or 900 ms have passed, and otherwise stops when each axis is within 1 px of the target and slower than 60 px/s. From rest, a 200 px overflow settles in 367 ms with an inward overshoot within one percentage point of the analytic bound `exp(-pi * zeta / sqrt(1 - zeta^2)) = 3.8%`. The integrator is pure and takes `dt`, so the engine keeps its rule of reading no clock. + +A press on the grip or the corner during a return cancels it and picks the panel up where it is drawn. A move does so through `unresistedRect`: it inverts the resistance, so zero pointer travel draws the same rectangle. A resize keeps the drawn origin and caps only the corner by the viewport; its release records the legal rectangle and springs the origin inside, as does a resize whose viewport shrank past its origin. Either way a release in place resumes the return without recording a second operation. One hook runs at most one return. A window resize ends a running return at its recorded rectangle, a press on another panel ends it at its target, a change of the panel's record that does not project to the target (an undo, a dock, a close) ends it at the new record on the next frame, and unmounting cancels the pending frame. + +### Reduced motion + +When `matchMedia('(prefers-reduced-motion: reduce)')` matches, a move clamps to the legal region with no resistance, and release records the legal rectangle with no animation. Environments without `matchMedia` report no preference. The rule only removes motion; it never removes the legality correction. + +### Change scope + +The change touches one package, `@deepseek-ai/dsh-client-ui-dockkit`, and leaves its exports and `DockIntents` unchanged; the `TabRenderer` contract now states when the kit reuses a body. + +| File | Change | +|---|---| +| `packages/client/ui-dockkit/src/engine/geometry.ts` | `FloatBounds`, `FLOAT_RESISTANCE`, `legalFloatRect`, `resistedRect`, `unresistedRect`, `boundedResize` | +| `packages/client/ui-dockkit/src/engine/spring.ts` | the pure spring integrator, its rest predicate `springSettled`, `launchVelocity` and its timing limits | +| `packages/client/ui-dockkit/src/components/FloatLayer.tsx` | `useFloatGestures`: viewport projection, resistance, release spring, drawn-velocity sampling, reduced motion, frame loop and cancellation; `rectOf` and `floatStyle` for both renderers | +| `packages/client/ui-dockkit/src/components/TabLayout.tsx` | draws the hook's displayed rectangle through `floatStyle` | +| `packages/client/ui-dockkit/src/components/TabBody.tsx` | the memoized body every layout (`FloatLayer`, `TabLayout`, `TabPanel`) draws | +| `packages/client/ui-dockkit/src/contract/adapter.ts` | when `TabRenderer` is called again | +| `packages/client/ui-dockkit/src/components/dockkit.module.css` | the resting clamp of position and size on `.float` | +| `packages/client/ui-dockkit/README.md` pair | the edge rule beside the float renderer description | +| `apps/web/tests/sidebar-right.e2e.ts` | a browser case for the resistance and the return | + +`ui-sidebar-right` and its persisted layout schema, the `apps/web` source, `apps/desktop`, the shared primitives and the theme are untouched. No dependency was added. + +## Testing + +`tests/float-bounds.client.spec.ts` covers the projection (inside, each edge, corner, the top floor, an oversized panel), the resistance (the table values, slope 1 at the edge, monotone growth bounded by `K`, independent axes), its inverse and its cap, the bounded resize, and the legal size kept by the resistance and its inverse. `tests/spring.client.spec.ts` covers settling inside the deadline, the overshoot bound, frame-rate independence at 30, 60 and 120 Hz, the effect of release velocity, determinism, and the launch cap keeping every return within `K`. `tests/app-region-styles.client.spec.ts` pins the resting clamp in the stylesheet. + +`tests/float-recovery.client.spec.tsx` renders `FloatLayer` over a live controller with hand-driven frames and clock: the resisted preview past an edge, exactly one legal `moveFloat` per release and the spring to it with an inward overshoot, undo in one step, fling against slow push, a fast fling staying within `K`, a drag above the top floor, no animation for a release inside, a push that ends at the stored position, a press mid-return picking the panel up without a jump, the stall snap, the deadline, a body not re-rendered through a drag and its return but re-rendered for a new renderer, a corner press during a return picking the panel up where it is drawn and a resize from there springing in, a resize whose viewport shrank past its origin recording a legal rectangle, with no animation under reduced motion, the 20 px floor on a Windows root without a published caption height, a return yielding to an undo, a close and a press on another panel, unmount cancellation, both reduced-motion answers, the viewport projection on shrink and growth without any intent, a click on a projected panel recording nothing, a window resize during a gesture bounding its release, a resize ending a return, and an off-screen stored rectangle drawn inside. `tests/tab-layout.client.spec.tsx` adds that a float drag re-renders no docked or floating body until the renderer changes, and `components.client.spec.tsx` the same for a `DockSurface` divider drag. The existing `FloatLayer` and `TabLayout` specs still pass with their position assertions read from the resting variables, including the rule that starting a gesture forces no layout read; every changed source file is fully covered. `apps/web/tests/sidebar-right.e2e.ts` drags a Sidebar float past the right and bottom edges in Chromium, checks that the drawn panel stays within 120 px beyond them, waits for the release to settle flush against both edges, then publishes a resting rectangle far outside and larger than the viewport and checks that the stylesheet alone draws it exactly over the viewport. + +## Alternatives considered + +**Hard clamp at the edge.** Stopping the panel at the viewport edge is the cheapest correct rule, but it feels like hitting a wall and gives no sense of the boundary before contact. It remains as the reduced-motion path. + +**Clamp during the drag and rebound on release.** Clamping the drag at the edge and converting the outward pointer speed into an inward bounce keeps every frame inside the viewport. It hides how far the user pushed, so the bounce has no visible cause; the resistance shows the push and still bounds the overflow at 120 px. + +**Eased tween on release.** A fixed 240-300 ms ease-out from the released position is predictable, but it carries no velocity, so a fling and a slow push return identically, and a press during it either jumps or restarts. The spring keeps velocity continuous and is interruptible. + +**Store the off-screen position and correct it later.** Recording the released rectangle and fixing it on the next render would persist off-screen positions and make undo restore them. Recording the legal rectangle keeps one history entry per gesture with a legal value. + +**Rewrite stored rectangles when the viewport shrinks.** Moving panels through operations on resize would add history entries the user never made and change persisted layouts on every window resize. Projecting at render achieves the visible result without either, at the cost of the elastic return described below. + +**Native always-on-top OS window.** A real Electron floating window could float above other applications, but only on Desktop; the Web client cannot do it at all, and native frameless dragging gives no per-frame control, so the resistance would be impossible and the spring could only start after release. It is a separate product decision with its own window, IPC and platform work, and this decision does not preclude it. + +**Animation library dependency.** A spring library would replace a pure integrator of a few dozen lines and its tests with a new dependency in a statically linked package. The integrator also has to be clock-free for the engine's deterministic tests. + +**A shared primitive in `ui-primitives`.** Placing the hook in the primitives package would widen the change to a second package with no second consumer. It can move there when another floating surface needs it. + +## Consequences + +Floating panels can no longer be lost off screen, in either client, and a push past an edge reads as a pull back rather than a wall. History, persistence and every embedder are unaffected, and the motion is covered by deterministic tests instead of manual checks. + +A drag and the spring update the preview through React state, so the layout re-renders on every frame, for up to 900 ms after release as well. Every layout draws tab bodies through `TabBody`, which is memoized on the renderer and the tab record, so such a frame re-renders only the panel frames and headers (the header still calls `renderTabTitle`), never the tab bodies; writing a transform on the panel element directly is the fallback if the remaining cost measures as a problem. A panel pushed in by a shrinking window returns toward its stored position when the window grows, which a user who expects it to stay where it was pushed may find surprising. Content inside a panel, such as a webview, can observe up to 900 ms of motion after release. The constants are tuned for a mouse or trackpad; touch input works through the same pointer events but remains untuned. diff --git a/.agents/notes/implemented/feature/2026-10-21-floating-window-edge-recovery.zh.md b/.agents/notes/implemented/feature/2026-10-21-floating-window-edge-recovery.zh.md new file mode 100644 index 0000000000..6ec92d9326 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-21-floating-window-edge-recovery.zh.md @@ -0,0 +1,106 @@ +# Agent Note: 悬浮停靠面板的弹簧式边界收回 + +Status: implemented + +[English](2026-10-21-floating-window-edge-recovery.md) | 中文 + +## 问题 + +dock kit 的悬浮面板就是客户端里的悬浮窗。`FloatLayer` 与保留式 `DockLayout` 渲染器通过同一个手势 hook `useFloatGestures` 以视口坐标绘制它们,右侧 Sidebar 嵌入了它们,因此同一套面板既运行在 Web 客户端中,也运行在 Desktop 窗口内。它们的拖拽过去一比一跟随指针,只有一个顶部下限(`--dsh-dockkit-float-top`,让标题栏保持在 Windows 标题栏之下)。因此面板可以被拖过左、右或下边界,直到标题栏够不着;视口缩小会把面板留在外面;新建面板的级联位置也可能落在小视口之外。期望行为是:面板被推过边界时可见地受到阻力,松手后以弹簧物理被拉回视口内,而不是像撞墙一样被挡住或被留在外面。 + +所考察的参考实现 Claude Desktop 没有可移植的边界收回规则:它的 Electron 回退只对屏幕外窗口做一次无动画修正,且只修正右边界和下边界。该行为必须被设计,而不是移植。 + +变更维持以下义务:面板标题栏始终可达;一个手势仍然最多记录一条历史;遵循减弱动态效果;Sidebar 的持久化布局格式与所有嵌入方保持不变;运动足够确定,无需真实浏览器时钟即可测试。 + +## 决定 + +该行为完全位于 `packages/client/ui-dockkit` 内,在 `useFloatGestures` 及其调用的纯 engine 辅助函数中实现。两个悬浮渲染器都通过 `rectOf` 从该 hook 取得矩形,因此 Web 与 Desktop 共享该行为,任何嵌入方、壳或持久化格式都没有改变。该规则扩展了 [右侧 Sidebar 停靠](2026-09-04-right-sidebar-docking-infrastructure.zh.md) 的悬浮面板与 [保留式标签布局](../architecture/2026-09-20-sidebar-retained-tab-layout.zh.md) 的固定定位悬浮框,不取代其中任何一篇。 + +### 合法区域与显示位置 + +面板的合法区域是视口(`window.innerWidth` × `window.innerHeight`)加上既有的顶部下限:设置了 `data-windows-titlebar` 时为 Windows 标题栏高度加 20 px(原生全屏时为 20 px),否则为 0。`floatBounds` 只读取这些值和根元素属性,因此开始手势不会触发布局。`legalFloatRect` 逐轴把矩形投影进该区域;面板比区域更宽或更高时,在该轴上按区域尺寸绘制,使标题栏控件和缩放角留在屏幕上;存储的尺寸不变。 + +面板绘制在其存储矩形投影到视口后的位置。存储矩形从不因视口而被改写:窗口缩小时面板被推入且不记录操作,窗口变大时面板朝存储位置回移。hook 在每次按下和每次窗口 `resize` 事件时重新读取区域,进行中的手势使用新区域。包含屏幕外矩形的持久化布局无需迁移即在视口内显示。 + +静止时面板通过 `floatStyle` 把矩形以 CSS 变量发布给 `.float` 规则,该规则再次把它的位置和尺寸钳制在视口(`100vw` × `100dvh`;`dvh` 与 hook 读取的 `window.innerHeight` 一致)内并保持在标题栏下限之下;超尺寸面板在这里同样按视口尺寸绘制,与 `legalFloatRect` 一致。因此即使 hook 读到的区域尚未刷新(例如全屏切换完成前读取的值),面板仍在视口内。手势或回弹把位置和尺寸写在行内样式中,不受该钳制。 + +### 带阻力的拖拽 + +移动时由手势起始矩形和指针位移计算期望矩形,然后 `resistedRect` 逐轴把它拆分为合法投影与超出它的溢出量 `o`,并绘制在 `legal + sign(o) * K * |o| / (K + |o|)`,其中 `K = FLOAT_RESISTANCE = 120` px。该映射作用于全部四条边,包括顶部下限之上,连续、在边界处斜率为 1、渐近于 `K`: + +| 指针溢出(px) | 面板越过边界的位移(px) | 占溢出的比例 | +|---|---|---| +| 10 | 9.2 | 92.3% | +| 40 | 30.0 | 75.0% | +| 120 | 60.0 | 50.0% | +| 400 | 92.3 | 23.1% | + +缩放通过 `boundedResize` 把右下角钳制在区域内并保持 `FLOAT_MIN_SIZE`;缩放不加阻力,因为落后于指针的角看起来像坏掉的手柄。 + +### 松手与弹簧 + +松手时记录合法矩形:与按下时的合法矩形不同时记录 `moveFloat` 或 `resizeFloat`,否则只记录点击会记录的提升。因此单击以投影绘制的面板会保留其存储矩形。因此移动或缩放只记录合法矩形,撤销一步即可恢复手势前的位置。创建面板(`floatTab` 的落点矩形与级联)仍可能存储视口外的矩形,由投影把它绘制在视口内。若面板绘制在合法区域之外,hook 保留预览,用弹簧把它从绘制位置带到记录的矩形,然后清除预览。在区域内松手不播放动画。 + +`engine/spring.ts` 中的弹簧是欠阻尼的,因为它的回弹朝向内侧,始终合法:响应时间 0.32 s、阻尼比 0.72。溢出的轴以拖拽最后 100 ms 内绘制面板的速度起步,因此速度在松手前后连续;该速度上限为 `SPRING_MAX_VELOCITY`(1500 px/s),且对绘制溢出量 `d`,`launchVelocity` 把其向外分量限制在 `omega0 * (K - d)` 以内。甩过边界的面板会先走得更远再折返;由于弹簧从偏移 `d`、速度 `v` 出发时距目标至多 `d + 0.46 * v / omega0`,整条回弹轨迹都不超出边界 `K`。没有溢出的轴保持不动。每轴更新为: + +``` +a = -omega0^2 * (x - target) - 2 * zeta * omega0 * v +v = v + a * h +x = x + v * h +``` + +`stepSpring` 以等长且不超过 `h = 1/480 s` 的子步积分,因此运动与帧率无关。hook 中唯一的 `requestAnimationFrame` 循环把单帧钳制到 64 ms,帧间隔超过 250 ms 或已过 900 ms 时直接停在目标,否则在每轴距目标 1 px 内且慢于 60 px/s 时停止。从静止开始,200 px 溢出在 367 ms 内稳定,向内过冲与解析上限 `exp(-pi * zeta / sqrt(1 - zeta^2)) = 3.8%` 相差不超过一个百分点。积分器是纯函数并接收 `dt`,因此 engine 保持不读取时钟的规则。 + +回弹期间按下抓手或右下角会取消回弹,并从绘制位置接住面板。移动通过 `unresistedRect` 做到这一点:它反演阻力,因此零指针位移绘制同一矩形。缩放保留绘制时的原点,只用视口约束右下角;松手时记录合法矩形并用弹簧把原点收回视口,手势中视口缩到原点以内的缩放也是如此。两种情况下原地松手都会恢复回弹且不记录第二次操作。一个 hook 最多运行一个回弹。窗口缩放会让进行中的回弹停在记录的矩形;按下另一个面板会让它停在目标;面板记录的变化若不再投影到目标(撤销、停靠、关闭),会在下一帧让它停在新记录;卸载会取消待处理的帧。 + +### 减弱动态效果 + +`matchMedia('(prefers-reduced-motion: reduce)')` 匹配时,移动钳制在合法区域内且无阻力,松手时记录合法矩形且不播放动画。没有 `matchMedia` 的环境视为无偏好。该规则只移除运动,从不移除合法性修正。 + +### 改动范围 + +变更只涉及一个包 `@deepseek-ai/dsh-client-ui-dockkit`,其导出与 `DockIntents` 保持不变;`TabRenderer` 的约定写明了套件何时复用标签页内容。 + +| 文件 | 变更 | +|---|---| +| `packages/client/ui-dockkit/src/engine/geometry.ts` | `FloatBounds`、`FLOAT_RESISTANCE`、`legalFloatRect`、`resistedRect`、`unresistedRect`、`boundedResize` | +| `packages/client/ui-dockkit/src/engine/spring.ts` | 纯弹簧积分器、静止判定函数 `springSettled`、`launchVelocity` 与时间上限 | +| `packages/client/ui-dockkit/src/components/FloatLayer.tsx` | `useFloatGestures`:视口投影、阻力、松手弹簧、绘制速度采样、减弱动态效果、帧循环与取消;供两个渲染器使用的 `rectOf` 与 `floatStyle` | +| `packages/client/ui-dockkit/src/components/TabLayout.tsx` | 通过 `floatStyle` 绘制 hook 给出的显示矩形 | +| `packages/client/ui-dockkit/src/components/TabBody.tsx` | 各布局(`FloatLayer`、`TabLayout`、`TabPanel`)共用的 memo 化标签页内容 | +| `packages/client/ui-dockkit/src/contract/adapter.ts` | `TabRenderer` 何时被再次调用 | +| `packages/client/ui-dockkit/src/components/dockkit.module.css` | `.float` 上位置与尺寸的静止钳制 | +| `packages/client/ui-dockkit/README.md` 对 | 在悬浮渲染器说明旁补充边界规则 | +| `apps/web/tests/sidebar-right.e2e.ts` | 覆盖阻力与回弹的浏览器用例 | + +`ui-sidebar-right` 及其持久化布局 schema、`apps/web` 源码、`apps/desktop`、共享基础组件与主题均未改动。没有新增依赖。 + +## 测试 + +`tests/float-bounds.client.spec.ts` 覆盖投影(内部、每条边、角、顶部下限、超尺寸面板)、阻力(表中数值、边界处斜率为 1、以 `K` 为上界的单调增长、各轴独立)、其反演与上限,受限缩放,以及阻力与其反演都保持合法尺寸。`tests/spring.client.spec.ts` 覆盖在截止时间内稳定、过冲上限、30/60/120 Hz 下与帧率无关、松手速度的作用、确定性,以及启动速度上限让每条回弹都不超出 `K`。`tests/app-region-styles.client.spec.ts` 固定样式表中的静止钳制。 + +`tests/float-recovery.client.spec.tsx` 在活的控制器上渲染 `FloatLayer`,帧与时钟由测试手动推进:越过边界时带阻力的预览、每次松手恰好一次合法的 `moveFloat` 以及带向内过冲的弹回、一步撤销、甩出与慢推的对比、快速甩出不超出 `K`、拖过顶部下限、区域内松手不播放动画、推到存储位置的手势、回弹中按下接住面板且不跳变、停顿直接跳转、截止时间、拖拽与回弹期间不重渲染标签页内容而换新渲染函数后重渲染、回弹中按下右下角从绘制位置接住面板、从那里缩放后弹回、手势中视口缩到缩放原点以内时记录合法矩形且减弱动态效果下不播放动画、未发布标题栏高度的 Windows 根元素仍保持 20 px 下限、回弹让位于撤销、关闭与按下另一个面板、卸载取消、两种减弱动态效果答复、视口缩小与变大时的投影且不调用任何 intent、单击投影面板不记录任何操作、手势中窗口缩放约束其松手结果、缩放结束回弹,以及屏幕外存储矩形在视口内绘制。`tests/tab-layout.client.spec.tsx` 新增:悬浮面板拖拽期间停靠与悬浮的标签页内容都不重渲染,直到渲染函数改变;`components.client.spec.tsx` 对 `DockSurface` 拖动分隔条做同样的检查。既有的 `FloatLayer` 与 `TabLayout` 测试在位置断言改为读取静止变量后通过,包括开始手势不做布局读取这一规则;每个改动的源文件都被完全覆盖。`apps/web/tests/sidebar-right.e2e.ts` 在 Chromium 中把 Sidebar 悬浮面板拖过右边界和下边界,检查绘制的面板越过两边均不超过 120 px,等待松手后面板贴合两条边静止,再发布一个远在视口外且大于视口的静止矩形,检查仅靠样式表就把它恰好绘制成覆盖整个视口。 + +## 考虑过的替代方案 + +**在边界处硬钳制。** 在视口边界停住面板是成本最低的正确规则,但手感像撞墙,接触之前也感觉不到边界。它保留为减弱动态效果的路径。 + +**拖拽中钳制、松手时回弹。** 在边界处钳制拖拽,并把向外的指针速度转换为向内的回弹,能让每一帧都留在视口内。但它隐藏了用户推了多远,回弹因此没有可见的起因;阻力显示了推动,同时把溢出限制在 120 px 内。 + +**松手后的缓动补间。** 从松手位置开始的固定 240–300 ms 缓出补间可预测,但不携带速度,因此甩出与慢推的返回完全相同,补间中按下要么跳变要么重启。弹簧保持速度连续且可打断。 + +**存储屏幕外位置并在之后修正。** 记录松手矩形、在下一次渲染时修正,会持久化屏幕外位置,并让撤销恢复它们。记录合法矩形则保持每个手势一条历史且值合法。 + +**视口缩小时改写存储矩形。** 在缩放时通过操作移动面板会增加用户从未做过的历史条目,并在每次窗口缩放时改变持久化布局。渲染时投影无需二者即可得到可见结果,代价是下文描述的弹性返回。 + +**原生始终置顶 OS 窗口。** 真正的 Electron 悬浮窗可以浮在其他应用之上,但只在 Desktop 上可行;Web 客户端完全无法做到,而且原生无边框拖拽不提供逐帧控制,因此阻力无法实现,弹簧只能在松手后启动。它是一个独立的产品决策,有自己的窗口、IPC 与平台工作,本决定不排斥它。 + +**动画库依赖。** 弹簧库会用一个静态链接包里的新依赖替换几十行的纯积分器及其测试。积分器还必须不依赖时钟,才能用于 engine 的确定性测试。 + +**放进 `ui-primitives` 的共享基础组件。** 把 hook 放进基础组件包会把改动扩大到第二个包,而没有第二个使用方。等另一个悬浮界面需要它时再迁移。 + +## 后果 + +悬浮面板在两个客户端中都不会再丢失到屏幕外,推过边界读起来是被拉回而不是撞墙。历史、持久化与所有嵌入方不受影响,运动由确定性测试而非手动检查覆盖。 + +拖拽与弹簧都通过 React state 更新预览,因此布局每帧都会重渲染,松手后最多还会持续 900 ms。各布局都通过 `TabBody` 绘制标签页内容,它以渲染函数和标签记录为键做了 memo,因此这样的一帧只重渲染面板框与标题栏(标题栏仍会调用 `renderTabTitle`),从不重渲染标签页内容;如果剩余成本经测量构成问题,退路是直接在面板元素上写 transform。被缩小窗口推入的面板会在窗口变大时朝存储位置回移,期望它留在被推到位置的用户可能会感到意外。面板内的内容(例如 webview)在松手后可能观察到最多 900 ms 的运动。常量针对鼠标或触控板调优;触控输入经由同样的 pointer 事件可用,但仍未调优。 diff --git a/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.i18n.yaml b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.i18n.yaml index 0633a2745d..9e538f26c6 100644 --- a/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.i18n.yaml +++ b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.i18n.yaml @@ -9,8 +9,8 @@ en: dc43ba84345e1405 zh: dbc03572ab7710d2 /agent-note-ship-optional-bundles-with-the-installation/decision: - en: 64a2cb7602842c44 - zh: bfcb3ef4a81773b4 + en: 2f20e356517715a6 + zh: 35c7ff8c4cd8a712 /agent-note-ship-optional-bundles-with-the-installation/alternatives-considered: en: 95b48b61757f1f13 zh: e9fb2d6ea492a4bc diff --git a/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.md b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.md index a94f480378..74f824fc88 100644 --- a/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.md +++ b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.md @@ -10,7 +10,7 @@ The Web plugin page manages only the bundles a person installed into the profile ## Decision -The launcher names in `OPTIONAL_BUNDLES` (`packages/boot/official-bundles/src/bundles.ts`, beside the profile templates) the bundles the installation ships for a person to switch on. Each must be a runtime dependency of `apps/cli` that declares `dsh.bundle.patch`, and no shipped profile template selects it. The plugin manager's `listBundles` reports such a bundle as `optional`: switched off until selected, never removable, resolved from the installation like any installation-supplied bundle. The Web plugin page presents offered optional bundles in its Official group, tagged experimental when the package is experimental, ahead of the profile's own installed bundles. The [persistent-terminal bundle](../../../../packages/experimental/terminal-bundle/README.md) remains available to the Host but has no page switch, even when enabled; its existing profile selection remains intact. +The launcher names in `OPTIONAL_BUNDLES` (`packages/util/official-bundles/src/bundles.ts`, beside the profile templates) the bundles the installation ships for a person to switch on. Each must be a runtime dependency of `apps/cli` that declares `dsh.bundle.patch`, and no shipped profile template selects it. The plugin manager's `listBundles` reports such a bundle as `optional`: switched off until selected, never removable, resolved from the installation like any installation-supplied bundle. The Web plugin page presents offered optional bundles in its Official group, tagged experimental when the package is experimental, ahead of the profile's own installed bundles. The [persistent-terminal bundle](../../../../packages/experimental/terminal-bundle/README.md) remains available to the Host but has no page switch, even when enabled; its existing profile selection remains intact. Default-product isolation keeps its rules with one declared exception: an optional bundle's dependency graph is outside the default product. The static gate skips the `dependencies` edge from `@deepseek-ai/dsh` to a listed bundle and still rejects a runtime import, a shipped composition, a preset, or a default template that names it, an experimental dependency the list does not name, and a listed name that is not a runtime dependency or not a bundle. The workspace-constraints check accepts the same `dependencies` edges and no other runtime section, and the packed-install release check skips them from the installed entry package while requiring each listed bundle to be installed. diff --git a/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.zh.md b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.zh.md index e96a316ccd..129f76c454 100644 --- a/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.zh.md +++ b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.zh.md @@ -10,7 +10,7 @@ Web 插件页只管理用户装进 profile 的组合包。像 Agent Teams 这样 ## 决策 -启动器在 `OPTIONAL_BUNDLES`(`packages/boot/official-bundles/src/bundles.ts`,与 profile 模板并列)里点名安装随附、供用户开启的组合包。每一个都必须是 `apps/cli` 声明了 `dsh.bundle.patch` 的运行时依赖,且不被任何随附 profile 模板选中。插件管理器的 `listBundles` 把这类组合包报告为 `optional`:选中前保持关闭、永不可卸载、像其他安装提供的组合包一样从安装目录解析。Web 插件页在「官方」分组展示可供选择的可选组合包,属于实验包的带实验性标签,排在 profile 自己已安装的组合包之前。[持久终端组合包](../../../../packages/experimental/terminal-bundle/README.zh.md)仍可供 Host 使用,但即使已启用也不提供页面开关;已有的 profile 选择保持不变。 +启动器在 `OPTIONAL_BUNDLES`(`packages/util/official-bundles/src/bundles.ts`,与 profile 模板并列)里点名安装随附、供用户开启的组合包。每一个都必须是 `apps/cli` 声明了 `dsh.bundle.patch` 的运行时依赖,且不被任何随附 profile 模板选中。插件管理器的 `listBundles` 把这类组合包报告为 `optional`:选中前保持关闭、永不可卸载、像其他安装提供的组合包一样从安装目录解析。Web 插件页在「官方」分组展示可供选择的可选组合包,属于实验包的带实验性标签,排在 profile 自己已安装的组合包之前。[持久终端组合包](../../../../packages/experimental/terminal-bundle/README.zh.md)仍可供 Host 使用,但即使已启用也不提供页面开关;已有的 profile 选择保持不变。 默认产品隔离的规则保持不变,只声明一个例外:可选组合包的依赖图在默认产品之外。静态门禁跳过从 `@deepseek-ai/dsh` 到列表中组合包的 `dependencies` 边,仍然拒绝运行时 import、随附组合、preset 或默认模板对它的引用,拒绝列表没有点名的实验依赖,也拒绝不是运行时依赖或不是组合包的列表项。workspace 约束检查接受同样的 `dependencies` 边而不接受其他运行时依赖段;发布时的 packed-install 检查对已安装入口包跳过这些边,并要求列表中的每个组合包都已安装。 diff --git a/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.i18n.yaml b/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.i18n.yaml index 121838e838..f7726e4c5a 100644 --- a/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.i18n.yaml +++ b/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.i18n.yaml @@ -9,8 +9,8 @@ en: e5c984fa32cc5e69 zh: 25d5742b2106d830 /agent-note-pr-artifact-builds-and-aggregate-typescript-checks/decision: - en: 8353d57b20ca01c3 - zh: e0b74906846d759c + en: 2b047b7d8ffaaeb9 + zh: 035e1a99cb0ffe84 /agent-note-pr-artifact-builds-and-aggregate-typescript-checks/alternatives-considered: en: f61da066f9ddcd62 zh: 816fd6e0063017cd diff --git a/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.md b/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.md index 0b403e7892..00378de709 100644 --- a/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.md +++ b/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.md @@ -20,7 +20,7 @@ The Python executable builder selects `build:artifacts` artifact compilation wit PR artifact builds in CI invoke the root manifest's `build:artifacts`; a PR that edits these root manifest scripts activates the separate native-addon platform matrix, a trade-off [the build split](2026-10-11-build-artifacts-check-split.md) records. The vendor rehearsal and benchmark lanes invoke the internal build helpers directly. -Job inventory, runner selectors, and benchmark sample counts stay fixed; gate and worker ceilings do not increase. The two compatibility cases run one job at a time; both x64 Python runtime targets start after the keyless Python SDK job succeeds in CI Python. Four Linux lanes, one compatibility job, three Windows lanes, and the Python SDK job permit at most nine worker jobs initially. Once the SDK job finishes, those four Linux lanes, one compatibility job, and three Windows lanes run beside the two runtime targets, permitting at most ten. Each runtime caller's plan and wheel stages precede its target and each use one job. This permits runtime validation to overlap the Node 24.9 build within the original ten-job ceiling. Coverage partitions reuse compact file-cost metadata within their platform and runner pool. Parallel release packing uses pnpm's existing bounded scheduler; serial publication keeps family order. +Benchmark sample counts stay fixed. The Linux artifact consumers emit artifacts only; the aggregate test and script type checks belong to the master lanes, and lint plus duplication run in their own lane, which compiles package declarations because oxlint's type-aware rules read them, so a red lint no longer costs a rerun of the snapshot and artifact consumers. The two compatibility cases run one job at a time; both x64 Python runtime targets start after the keyless Python SDK job succeeds in CI Python. Five Linux lanes, one compatibility job, three Windows lanes, and the Python SDK job permit at most eleven worker jobs initially. Once the SDK job finishes, those five Linux lanes, one compatibility job, and three Windows lanes run beside the two runtime targets, permitting at most eleven. Each runtime caller's plan and wheel stages precede its target and each use one job. This permits runtime validation to overlap the Node 24.9 build within the eleven-job ceiling. Coverage partitions reuse compact file-cost metadata within their platform and runner pool. Parallel release packing uses pnpm's existing bounded scheduler; serial publication keeps family order. Each Node version runs the same eight source compatibility specs in one serial Vitest invocation. Both file parallelism and the CLI worker limit are fixed to one, and the gate sets `VITEST_MAX_WORKERS=1` because that environment variable overrides Vitest's CLI limit. Files retain fork isolation; the build-backed Node 24.9 lazy-search smoke keeps its separate build dependency. The original seven-spec paired samples preserve all 253 assertion outcomes and reduce startup-only median time from 11.52 to 8.69 seconds, without increasing owned descendant-process peak. diff --git a/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.zh.md b/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.zh.md index 56fa7cbaa5..45ea09f6f6 100644 --- a/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.zh.md +++ b/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.zh.md @@ -20,7 +20,7 @@ Python executable builder 在验证 runtime closure 后,通过 `--build-artifa CI 的 PR 产物构建调用 root manifest 中的 `build:artifacts`;修改 root manifest 中这些 script 的 PR 会激活独立的 native-addon 平台矩阵,[构建拆分](2026-10-11-build-artifacts-check-split.zh.md)记录这一取舍。vendor 演练与 benchmark lane 直接调用内部 build helper。 -job 清单、runner 选择和 benchmark sample 数量保持固定;gate 与 worker 上限不提高。两个 compatibility case 每次运行一个 job;两个 x64 Python runtime target 都在 CI Python 中于 keyless Python SDK job 成功后启动。四个 Linux lane、一个 compatibility job、三个 Windows lane 与 Python SDK job,初始最多占用九个 worker job。SDK job 完成后,这四个 Linux lane、一个 compatibility job 与三个 Windows lane 与两个 runtime target 并行,最多占用十个 job。每个 runtime 调用方的 plan 与 wheel 阶段先于其 target,各占一个 job。这允许 runtime 验证与 Node 24.9 构建重叠,同时保持原有十个 job 的上限。覆盖率分区在各自的平台和 runner pool 内复用精简的文件成本元数据。并行 release 打包使用 pnpm 现有的有界调度器;串行发布保持 family 顺序。 +benchmark sample 数量保持固定。Linux 产物消费者只产出产物;聚合的 test 与 script 类型检查归 master lane;lint 与 duplication 单独占用一个 lane,该 lane 会先编译包声明(oxlint 的类型感知规则要读它们),因此 lint 变红不再让 snapshot 与 artifact 消费者整体重跑。两个 compatibility case 每次运行一个 job;两个 x64 Python runtime target 都在 CI Python 中于 keyless Python SDK job 成功后启动。五个 Linux lane、一个 compatibility job、三个 Windows lane 与 Python SDK job,初始最多占用十一个 worker job。SDK job 完成后,这五个 Linux lane、一个 compatibility job 与三个 Windows lane 与两个 runtime target 并行,最多占用十一个 job。每个 runtime 调用方的 plan 与 wheel 阶段先于其 target,各占一个 job。这允许 runtime 验证与 Node 24.9 构建重叠,同时保持十一个 job 的上限。覆盖率分区在各自的平台和 runner pool 内复用精简的文件成本元数据。并行 release 打包使用 pnpm 现有的有界调度器;串行发布保持 family 顺序。 每个 Node 版本在一次串行 Vitest 调用中运行相同的八个 source compatibility spec。文件并行和 CLI worker 上限均固定为一,gate 还设置 `VITEST_MAX_WORKERS=1`,因为该环境变量会覆盖 Vitest 的 CLI 上限。文件保持 fork 隔离;依赖构建的 Node 24.9 lazy-search smoke 保留独立的 build 依赖。原来七个 spec 的成对样本保持全部 253 个 assertion outcome,将启动开销比较的 median 从 11.52 秒降至 8.69 秒,且不增加所拥有 descendant process 的峰值。 diff --git a/.agents/notes/implemented/process/2026-10-20-weighted-approval-status-gate-with-check-run-label.i18n.yaml b/.agents/notes/implemented/process/2026-10-20-weighted-approval-status-gate-with-check-run-label.i18n.yaml index cc5e19892d..2a070e80e2 100644 --- a/.agents/notes/implemented/process/2026-10-20-weighted-approval-status-gate-with-check-run-label.i18n.yaml +++ b/.agents/notes/implemented/process/2026-10-20-weighted-approval-status-gate-with-check-run-label.i18n.yaml @@ -2,21 +2,21 @@ # section, a hash of its English and Chinese blocks outside code blocks and generated regions. # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-10-20-weighted-approval-status-gate-with-check-run-label.md -/agent-note-weighted-approval-keeps-its-commit-status-gate-and-adds-a-decision-check-run: - en: a1f0f9fd657c7d35 - zh: e8fa02fb5bde6075 -/agent-note-weighted-approval-keeps-its-commit-status-gate-and-adds-a-decision-check-run/problem: - en: 8e854872edfc0729 - zh: 6f3ed495fcb690a4 -/agent-note-weighted-approval-keeps-its-commit-status-gate-and-adds-a-decision-check-run/decision: - en: 03de94946d7532d7 - zh: cf2f585f715d3295 -/agent-note-weighted-approval-keeps-its-commit-status-gate-and-adds-a-decision-check-run/verification: - en: 8298cff64cce6467 - zh: a121d509c2302c00 -/agent-note-weighted-approval-keeps-its-commit-status-gate-and-adds-a-decision-check-run/alternatives-considered: - en: 197255cd82aabef7 - zh: dc03f4bf77150f22 -/agent-note-weighted-approval-keeps-its-commit-status-gate-and-adds-a-decision-check-run/consequences: - en: 25e1ac1c8cab089a - zh: 84e10cccb1b9eda7 +/agent-note-weighted-approval-keeps-its-commit-status-gate-and-publishes-the-decision-label-from-an-app: + en: 1ea2e345d6bc1058 + zh: 65f872a0606660b8 +/agent-note-weighted-approval-keeps-its-commit-status-gate-and-publishes-the-decision-label-from-an-app/problem: + en: f2dc92b64d32bd68 + zh: 7f24eaaa49a5776f +/agent-note-weighted-approval-keeps-its-commit-status-gate-and-publishes-the-decision-label-from-an-app/decision: + en: 5f7ebd56d43445cf + zh: 869e144309b85c28 +/agent-note-weighted-approval-keeps-its-commit-status-gate-and-publishes-the-decision-label-from-an-app/verification: + en: c80da76f52dac191 + zh: 1f7f8458211e1f5b +/agent-note-weighted-approval-keeps-its-commit-status-gate-and-publishes-the-decision-label-from-an-app/alternatives-considered: + en: e3b37e68b3e76d05 + zh: bb6c917c3fc6b685 +/agent-note-weighted-approval-keeps-its-commit-status-gate-and-publishes-the-decision-label-from-an-app/consequences: + en: 79a97b43e268dd04 + zh: b85691eac68c313f diff --git a/.agents/notes/implemented/process/2026-10-20-weighted-approval-status-gate-with-check-run-label.md b/.agents/notes/implemented/process/2026-10-20-weighted-approval-status-gate-with-check-run-label.md index 386ff345df..e48b4563ad 100644 --- a/.agents/notes/implemented/process/2026-10-20-weighted-approval-status-gate-with-check-run-label.md +++ b/.agents/notes/implemented/process/2026-10-20-weighted-approval-status-gate-with-check-run-label.md @@ -1,4 +1,4 @@ -# Agent Note: Weighted approval keeps its commit status gate and adds a decision check run +# Agent Note: Weighted approval keeps its commit status gate and publishes the decision label from an App Status: implemented @@ -6,32 +6,36 @@ English | [中文](2026-10-20-weighted-approval-status-gate-with-check-run-label ## Problem -The `weighted approval` commit status is the record this repository's branch rules require, and below the approval threshold it stays `pending`. A commit status has no action-required state, so readers cannot tell an approval wait from running work. Moving the gate to a check run does not work: after that change, the check run completed as `success` on the pull-request head and both the REST API and `gh pr checks` listed it, while the merge box kept reporting the same `weighted approval decision` context as `Expected — Waiting for status to be reported`, and two pull requests needed an administrator bypass. That change was reverted. +The `weighted approval` commit status is the record this repository's branch rules require, and below the approval threshold it stays `pending`. A commit status has no action-required state, so readers cannot tell an approval wait from running work. + +A check run carries that state, but GitHub attaches a check run created through the API to the earliest Actions check suite on the head, and a check suite created by a `pull_request_target` run is not associated with the pull request. Measured on 2026-10-20 and 2026-10-21: when the earliest suite belonged to a `pull_request` workflow the merge box listed the label, and when it belonged to the `pull_request_target` publisher it listed none, while the Checks page listed it either way; which suite is earliest is a race among the workflows a push starts. Moving the gate to a required check run published with the job token hit the same race: the merge box reported the context as `Expected — Waiting for status to be reported` while the REST API and `gh pr checks` listed it complete, so two pull requests needed an administrator bypass; that change was reverted. ## Decision The publisher keeps writing the `weighted approval` commit status exactly as before: `pending` while the policy is unmet, `success` when it holds, and `error` when setup or evaluation fails. Branch rules keep requiring that status. That behavior, including keeping an unmet policy `pending`, is what the [archived decision](../../archived/process/2026-09-09-blocked-weighted-approvals-remain-pending.md) records; this change adds the label beside it instead of changing the gate. -The publisher additionally writes a `weighted approval decision` check run for the same evaluation: `action_required` while the policy is unmet, `success` when it holds, and `failure` when setup or evaluation fails. The check run's title carries the score or the blocker. Branch rules do not require it, so it never blocks a merge; it names the blocked state beside the status that does. +The publisher writes the `weighted approval decision` check run with a token minted from a dedicated approval App (`actions/create-github-app-token` with `vars.DSH_APPROVAL_APP_CLIENT_ID`, `secrets.DSH_APPROVAL_APP_PRIVATE_KEY`, and `vars.DSH_APPROVAL_APP_SLUG`, scoped to `checks: write`). The check suite then belongs to the App and is associated with the pull-request head, so the merge box lists the label without depending on which Actions workflow started first. The conclusion is `action_required` while the policy is unmet, `success` when it holds, and `failure` when setup or evaluation fails; the title carries the score or the blocker. Branch rules do not require the check run, so it never blocks a merge. -A head keeps one GitHub Actions run with the check-run name: the publisher updates the head's existing run and creates one only when none exists. The setup phase creates the run as `in_progress` on a head without one and deals with a published success by rewriting its conclusion to `action_required`, because GitHub accepts but does not apply a return to `in_progress`. A failed check-run write is logged and never changes the status, so a token without the checks permission, or a check-run API failure, leaves the gate as the status wrote it. The publisher identifies its own runs by the `external_id` marker it sets on creation, which excludes check runs that workflow jobs produce for a same-named job. It revokes a published `success` before dependency setup, because GitHub accepts but does not apply a return to `in_progress`. +The status and the check run are written through separate API clients: the status gate uses the job token, and only the check-run calls use the App token. A failed App token step or check-run write is logged and never changes the status. When the token or the slug is unavailable the publisher keeps the job token and updates `github-actions` runs only, so the gate keeps working and the label stays on the Checks page; the job token cannot update an App run, so such a head keeps the App run it already has. + +The publisher selects the check runs created by the publishing token by `app.slug`: the App token matches the App's runs and the job token matches `github-actions` runs, because neither token can update a run the other created. It updates every selected run of that app and creates one only when none exists; job-token runs written by earlier evaluations stay untouched and can coexist with the App run on a head created before the App was configured. The setup phase creates the run as `in_progress` on a head without one and deals with a published success by rewriting its conclusion to `action_required`, because GitHub accepts but does not apply a return to `in_progress`. Runs the publisher creates carry the `external_id` marker it sets on creation. ## Verification -[Approval policy tests](../../../../.github/review-ownership/check-approval.test.mjs) pin the unchanged status states, the check-run conclusion for a met and an unmet policy, the phase writes, revoking a published success through its conclusion, one run per head, and invalid list responses. [Workflow tests](../../../../scripts/ci-workflow.spec.ts) pin the `checks: write` and `statuses: write` permissions and the setup phase commands. +[Approval policy tests](../../../../.github/review-ownership/check-approval.test.mjs) pin the unchanged status states, the check-run conclusion for a met and an unmet policy, the phase writes, revoking a published success through its conclusion, one run per head, invalid list responses, the status fallback when the label write fails, and the split between the status client and the check-run client. [Workflow tests](../../../../scripts/ci-workflow.spec.ts) pin the `checks: write` and `statuses: write` permissions, the App token step and its single secret reference, the `DECISION_TOKEN` wiring, and the setup phase commands. -The check-run limit was measured on 2026-10-20 with the reverted attempt on this repository: the `weighted approval decision` check run completed as `success` on the pull-request head, the REST API and `gh pr checks` listed it, and the merge box kept reporting the same context as expected. +The check-run association limit was measured on 2026-10-20 with the reverted and the previous attempts on this repository: a required check run published with the job token stayed `Expected` in the merge box, and a non-required check run published with the job token was absent from the merge box's check list while the Checks page listed it. ## Alternatives considered -**Require the check run instead of the commit status.** Measured above: the ruleset does not match a check run published through the default-branch workflow's token, so the gate cannot be satisfied. +**Publish the label with the job token and accept the Checks page only.** That is the state this change replaces; the merge box never lists the label, so the conversation page shows only the pending status. -**Publish the commit status as `failure` while the policy is unmet.** The status would complete, but this changes the required record's meaning and would report an unmet, reversible condition as a malfunction. +**Require the App check run instead of the commit status.** The App check run is associated with the pull request, so it could carry the gate. That needs a ruleset change to the App's integration and a migration for open heads; this change keeps the proven status gate and only moves the label onto the App. + +**Publish the commit status as `failure` while the policy is unmet.** The status would complete, but this changes the required record's meaning and reports an unmet, reversible condition as a malfunction. **Publish only the check run and leave the status untouched.** The status would keep its last state from an earlier evaluation, so the gate and the label could disagree. -**Publish the required check run from a dedicated GitHub App.** A check run whose app the ruleset names would let the required entry carry the action-required conclusion itself. The repository has no App with the checks permission; with one, the label could move onto the required record and the status could be retired. - ## Consequences -A job that ends between the `pending` write and the fallback step, such as a lost runner or a cancellation that skips the final step, leaves the status `pending`; that is the original symptom of this status, not a regression from the added label. While reviewers are pending, the merge box reports `weighted approval` as pending (the gate) and the `weighted approval decision` entry as `action_required`, with the score or blocker in its title; `gh pr checks` lists both. A published success is revoked by rewriting the check run's conclusion, and the status follows the unchanged policy states. +The merge box now lists `weighted approval` (the gate, pending while reviewers are pending) and `weighted approval decision` (`action_required`, with the score or blocker in its title). If the App token cannot be minted, the label falls back to the job token and stays on the Checks page only; the gate is unaffected. A job that ends between the `pending` write and the fallback step, such as a lost runner or a cancellation that skips the final step, leaves the status `pending`; that is the original symptom of this status, not a regression. diff --git a/.agents/notes/implemented/process/2026-10-20-weighted-approval-status-gate-with-check-run-label.zh.md b/.agents/notes/implemented/process/2026-10-20-weighted-approval-status-gate-with-check-run-label.zh.md index 75089f2f13..6b186d8a23 100644 --- a/.agents/notes/implemented/process/2026-10-20-weighted-approval-status-gate-with-check-run-label.zh.md +++ b/.agents/notes/implemented/process/2026-10-20-weighted-approval-status-gate-with-check-run-label.zh.md @@ -1,4 +1,4 @@ -# Agent Note: Weighted approval 保留其 commit status 门禁并新增决策 check run +# Agent Note: Weighted approval 保留 commit status 门禁,并由 App 发布决策标签 Status: implemented @@ -6,32 +6,36 @@ Status: implemented ## 问题 -`weighted approval` commit status 是本仓库分支规则要求的记录,在批准阈值下方时保持 `pending`。commit status 没有 action-required 状态,读者无法区分等待批准与正在运行的工作。把门禁改成 check run 并不可行:该改动后 check run 在 PR head 上以 `success` 完成,REST API 与 `gh pr checks` 都能列出它,而合并框始终把同一上下文报告为 `Expected — Waiting for status to be reported`,两个 PR 需要管理员绕过才能合并。该改动已回退。 +`weighted approval` commit status 是本仓库分支规则要求的记录,在批准阈值下方时保持 `pending`。commit status 没有 action-required 状态,读者无法区分等待批准与正在运行的工作。 + +check run 可以承载这个状态,但 GitHub 会把通过 API 创建的 check run 挂到该 head 上最早的 Actions check suite,而 `pull_request_target` 的 run 创建的 check suite 不与该 PR 关联。2026-10-20 与 2026-10-21 实测:最早 suite 属于 `pull_request` workflow 时合并框会列出该标签,属于 `pull_request_target` 的 publisher 时合并框一条都不列,而 Checks 页两种情况下都能列出;哪个 suite 最早是同一次 push 触发的多个 workflow 之间的竞态。把门禁改成用 job token 发布的必需 check run 也撞上同一个竞态:合并框把该上下文报告为 `Expected — Waiting for status to be reported`,而 REST API 与 `gh pr checks` 都显示已完成,两个 PR 需要管理员绕过,该改动已回退。 ## 决定 publisher 继续完全按原样写 `weighted approval` commit status:策略未满足时为 `pending`,满足时为 `success`,安装或评估失败时为 `error`。分支规则继续要求该 status。该行为——包括未满足的策略保持 `pending`——正是[已归档决定](../../archived/process/2026-09-09-blocked-weighted-approvals-remain-pending.md)记录的;本次变更在该门禁旁边新增标签,而不改变门禁。 -publisher 为同一次评估额外写一个 `weighted approval decision` check run:策略未满足时为 `action_required`,满足时为 `success`,安装或评估失败时为 `failure`。check run 的标题携带分数或 blocker。分支规则不要求它,因此它从不阻止合并;它在会阻止合并的那条 status 旁边命名被阻止的状态。 +publisher 用从专用批准 App 铸造的 token(`actions/create-github-app-token`,使用 `vars.DSH_APPROVAL_APP_CLIENT_ID`、`secrets.DSH_APPROVAL_APP_PRIVATE_KEY` 与 `vars.DSH_APPROVAL_APP_SLUG`,权限限定为 `checks: write`)写 `weighted approval decision` check run。check suite 因此归 App 所有并与 PR head 关联,合并框会列出该标签,不再取决于哪个 Actions workflow 先启动。策略未满足时结论为 `action_required`,满足时为 `success`,安装或评估失败时为 `failure`;标题携带分数或 blocker。分支规则不要求该 check run,因此它从不阻止合并。 -每个 head 只保留一个同名 GitHub Actions run:publisher 更新 head 上已有的 run,仅在不存在时创建。setup 阶段对没有 run 的 head 以 `in_progress` 创建,并把已发布的 success 的 conclusion 改写为 `action_required`,因为 GitHub 接受但不执行改回 `in_progress` 的更新。check run 写入失败会被记录,且从不改变 status,因此没有 checks 权限的 token 或 check-run API 失败时,门禁保持 status 写入的结果。publisher 用创建时设置的 `external_id` 标记识别自己的 run,从而排除 workflow job 为同名 job 产生的 check run。它在依赖安装前撤销已发布的 `success`,因为 GitHub 接受但不执行改回 `in_progress` 的更新。 +status 与 check run 通过两个独立的 API client 写入:status 门禁使用 job token,只有 check-run 调用使用 App token。token 步骤失败或 check-run 写入失败会被记录,且从不改变 status,因此 App 权限缺失时门禁照常工作,标签只出现在 Checks 页。 + +publisher 按 `app.slug` 选择由当前发布 token 创建的 run:App token 只匹配 App 的 run,job token 只匹配 `github-actions` 的 run,因为两种 token 都无法更新对方创建的 run。它更新所选 app 的所有同名 run,仅在不存在时创建;App 配置之前由 job token 写入的 run 保持不变,可能与 App run 在同一个 head 上共存。setup 阶段对没有 run 的 head 以 `in_progress` 创建,并把已发布的 success 的 conclusion 改写为 `action_required`,因为 GitHub 接受但不执行改回 `in_progress` 的更新。publisher 创建的 run 带创建时设置的 `external_id` 标记。 ## 验证 -[批准策略测试](../../../../.github/review-ownership/check-approval.test.mjs)锁定未改动的 status 状态、策略满足与未满足两种情况下 check run 的 conclusion、阶段写入、通过 conclusion 撤销已发布的成功、每个 head 只有一个 run,以及无效的列表响应。[工作流测试](../../../../scripts/ci-workflow.spec.ts)锁定 `checks: write` 与 `statuses: write` 权限以及 setup 阶段命令。 +[批准策略测试](../../../../.github/review-ownership/check-approval.test.mjs)锁定未改动的 status 状态、策略满足与未满足两种情况下 check run 的 conclusion、阶段写入、通过 conclusion 撤销已发布的成功、每个 head 只有一个 run、无效的列表响应、标签写入失败时 status 的兜底,以及 status client 与 check-run client 的分离。[工作流测试](../../../../scripts/ci-workflow.spec.ts)锁定 `checks: write` 与 `statuses: write` 权限、App token 步骤及其唯一的密钥引用、`DECISION_TOKEN` 的接线,以及 setup 阶段命令。 -check run 的限制于 2026-10-20 在本仓库用被回退的尝试实测:`weighted approval decision` check run 在 PR head 上以 `success` 完成,REST API 与 `gh pr checks` 都能列出它,而合并框始终把同一个 `weighted approval decision` 上下文报告为 expected。 +check run 的关联限制于 2026-10-20 在本仓库用回退的尝试与上一版尝试实测:用 job token 发布的必需 check run 在合并框里保持 `Expected`;用 job token 发布的非必需 check run 不在合并框的检查列表中,而 Checks 页能列出它。 ## 考虑过的替代方案 -**把 check run 作为必需检查。** 见上面的实测:ruleset 不匹配默认分支 workflow 的 token 发布的 check run,门禁无法满足。 +**用 job token 发布标签、只接受 Checks 页可见。** 这正是本次变更要替换的状态;合并框永远不列该标签,会话页只显示 pending 的 status。 + +**把 App check run 设为必需检查来替代 commit status。** App check run 已关联 PR,可以承载门禁。但那需要把 ruleset 改成该 App 的 integration 并为开放 head 做迁移;本次保留已验证的 status 门禁,只把标签移到 App。 **策略未满足时把 commit status 发布为 `failure`。** status 会完成,但改变了必需记录的含义,并把尚未满足且可撤销的条件报告为故障。 **只发布 check run 而不动 status。** status 会保留上一次评估的状态,门禁与标签可能不一致。 -**由专用 GitHub App 发布必需 check run。** 由 ruleset 指定 app 的 check run 可以让必需条目本身携带 action-required 结论。本仓库没有具备 checks 权限的 App;有了之后可以把标签移到必需记录上并停用 status。 - ## 后果 -job 在 `pending` 写入与兜底步骤之间结束(例如 runner 丢失,或取消导致最后一步未执行)会让 status 保持 `pending`;这是该 status 既有的表现,不是新增标签带来的回归。评审未完成时,合并框把 `weighted approval` 报告为 pending(门禁),并把 `weighted approval decision` 条目报告为 `action_required`,标题里是分数或 blocker;`gh pr checks` 会列出两者。已发布的 success 通过改写 check run 的 conclusion 撤销,status 继续按未改动的策略状态变化。 +合并框现在同时列出 `weighted approval`(门禁,评审未完成时为 pending)与 `weighted approval decision`(`action_required`,标题里是分数或 blocker)。App token 步骤失败或 check-run 写入失败会被记录,且从不改变 status。缺少 token 或 slug 时 publisher 保留 job token、只更新 `github-actions` 的 run,因此门禁照常工作、标签留在 Checks 页;job token 无法更新 App run,这类 head 会保留已有的 App run。job 在 `pending` 写入与兜底步骤之间结束(例如 runner 丢失,或取消导致最后一步未执行)会让 status 保持 `pending`;这是该 status 既有的表现,不是新增标签带来的回归。 diff --git a/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.i18n.yaml b/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.i18n.yaml index 380a20a91f..a541d181e6 100644 --- a/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.i18n.yaml +++ b/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.i18n.yaml @@ -12,17 +12,17 @@ en: 34e5bde1535a2bb1 zh: 559deb25b2ec50ba /agent-note-domain-kv-storage-capability-seam-and-the-workspace-entity/proposal/dsh-storage-the-storage-hub: - en: 191afc01a150e4a0 - zh: da3fbc33875a4f60 + en: 5eb0b18c2adf5111 + zh: 856ee7b1464b8bfc /agent-note-domain-kv-storage-capability-seam-and-the-workspace-entity/proposal/dsh-storage-json: en: a18ec1e534a5488b zh: 2f5beb445e30554b /agent-note-domain-kv-storage-capability-seam-and-the-workspace-entity/proposal/dsh-storage-sqlite: - en: 6a26dd7ef357db74 - zh: 951b31136e2415f9 + en: 1a4bebbbf52db7a2 + zh: 425c32b0dc17b49e /agent-note-domain-kv-storage-capability-seam-and-the-workspace-entity/proposal/dsh-domain-the-domain-data-form: - en: 2ee24f36cd93f7dd - zh: 45c83bd745de41f9 + en: b99e07359dc78dc8 + zh: 4af881d0b6d5b628 /agent-note-domain-kv-storage-capability-seam-and-the-workspace-entity/proposal/future-work-session-side-deletion-design-settled-not-implemented-this-phase: en: a3824326587b6539 zh: 9736e3060bd57651 diff --git a/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md b/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md index 950345b57f..0908177c71 100644 --- a/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md +++ b/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md @@ -44,9 +44,9 @@ A backend is one **medium owner** (a file-tree root / one db file) exposing prim The backend contract (asserted clause by clause by the shared conformance suite, one suite for both backends): 1. `open` creates when the medium holds nothing (lazy materialization allowed: may defer to the first write, but `loadAll` must immediately serve empty tables); loads when the medium exists. -2. A stored version ≠ descriptor.version → `StorageError('version-mismatch')`; no migration, no rebuild. +2. Unit-wide checks accept `descriptor.version` and the owner's `compatibleVersions`; other stamps reject with `StorageError('version-mismatch')`. Ordinary compatible reads preserve saved stamps and values. [Domain versioning](../../../../docs/subsystems/storage.md#domain-versioning) defines write stamping and JSON per-record exceptions. 3. Durability: after a write primitive resolves, a process crash followed by a re-open must observe the write in `loadAll`. -4. The backend does not promise write ordering within a unit — **the caller serializes**; the backend only guarantees each single call is atomic (JSON whole-file replace / SQLite single statement). +4. The backend does not promise write ordering within a unit — **the caller serializes**; whole-unit mutations atomically publish their data and current stamp (JSON whole-file replacement / SQLite transaction for batch deletion or advancing the stamp); per-record batches can be partially applied if interrupted before resolution. 5. `deleteRecord` is idempotent; `putRecord` overwrites. 6. Any string key / any JSON value is safe (keys never reach file paths, a structural property). 7. `close` is idempotent; any operation after close → `StorageError('closed')`. @@ -88,8 +88,8 @@ CREATE TABLE IF NOT EXISTS "u__" ( key TEXT PRIMARY KEY, value TEXT NOT NULL) STRICT; -- value = record JSON document ``` -- Unit versions live in `units` rows; a descriptor mismatch → `version-mismatch`. Row granularity is document-per-row, preserving precise per-key durable updates (the path left open for high-frequency point-update tables like the session sidecar); when query needs appear, JSON1 reads the value column directly. -- Write primitives are single statements and thus atomic; no cross-statement transactions needed (the domain layer has no cross-table transactions, see the out-of-scope list). +- Unit versions live in `units` rows; an unaccepted version rejects with `version-mismatch`. Row granularity is document-per-row, preserving precise per-key durable updates (the path left open for high-frequency point-update tables like the session sidecar); when query needs appear, JSON1 reads the value column directly. +- Current-version single-record writes use single statements. Batch deletes and the first mutation of an accepted older unit use one transaction; the first mutation commits its data and current stamp together. This does not add cross-table domain transactions. ### `dsh-domain`: the domain data form @@ -117,6 +117,7 @@ export interface DomainTableSpec { readonly valueSchema: Zo export interface DomainSpec { readonly name: string // ^[a-z][a-z0-9_]*$ readonly version: number + readonly compatibleVersions?: readonly number[] readonly global?: DomainGlobalSpec readonly tables: Record> } @@ -157,8 +158,8 @@ Rules: - **Single-level mapping**: key → record, no nested tables; hierarchical needs use composite keys or fields inside the value. The two backends stay isomorphic as a result (one JSON object level ↔ one SQLite row). - **Records are plain data**: immutable, directly JSON-serializable POJOs; values returned by `get`/`entries` must not be mutated in place (TypeScript readonly projection, no runtime freezing). Behavior-carrying domain objects belong to consumer packages. -- **Serialized writes**: one promise chain per domain; `put`/`delete`/`update`/`global.set` all queue on it; `update`'s fn runs on the chain, so concurrency cannot interleave. No active-record (pulling out a mutable object that auto-persists — uncontrollable persist timing, in conflict with the whole-unit atomic-rewrite model). -- **Version fails loud**: a stored version differing from the spec throws outright; no migration, no rebuild (the data is not regenerable; pre-release rejects old formats). +- **Serialized writes**: one promise chain per domain; `put`/`delete`/`deleteMany`/`update`/`global.set` all queue on it; `update`'s fn runs on the chain, so concurrency cannot interleave. No active-record (pulling out a mutable object that auto-persists — uncontrollable persist timing, in conflict with the whole-unit atomic-rewrite model). +- **Version compatibility**: the domain owner declares readable older versions through `compatibleVersions` and decodes historical values with its current schemas. Storage does not convert record values; [domain versioning](../../../../docs/subsystems/storage.md#domain-versioning) defines stamp publication and mixed-generation requirements. - **Change events**: after each write's durability resolves, emit `domain/changed` (`@mode emit`), one per record, no old value (matching the repository's "new snapshot + operation discriminant" convention, template `goal/changed`); the payload `DomainChanged` is a put/deleted discriminated union — domain + table + key (both `''` for global changes) + operation, with the put branch carrying the new snapshot value and the deleted branch carrying none (`packages/storage/storage-domain/src/events.ts`). This is next phase's RPC push-frame event source. The error vocabulary is `DomainError`, codes: `already-open` / `facet-unsupported` / `invalid-record` (with `{ table, key }`) / `missing-key` / `closed`. ### Future work: session-side deletion (design settled, not implemented this phase) diff --git a/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md b/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md index a44086a0d6..51dcc0362a 100644 --- a/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md +++ b/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md @@ -44,9 +44,9 @@ host 侧唯一的持久化面是 session 事件日志(`packages/session/sessio 后端约定(共享约定测试逐条断言,两后端同套件): 1. `open` 对不存在的介质创建(懒物化允许:可延迟到首写,但 `loadAll` 立即可用返回空表);对已存在介质载入。 -2. 介质上版本 ≠ descriptor.version → `StorageError('version-mismatch')`,不迁移不重建。 +2. 单元级检查接受 `descriptor.version` 和拥有方声明的 `compatibleVersions`;其他版本戳以 `StorageError('version-mismatch')` 拒绝。普通兼容读取保留已存版本戳和值。[领域版本](../../../../docs/subsystems/storage.zh.md#domain-versioning)定义写入盖戳和 JSON 逐记录例外。 3. 持久性:写原语 resolve 后进程崩溃再 open,`loadAll` 必须反映该写入。 -4. 后端不承诺 unit 内写并发序——**调用方负责串行**;后端只保证单次调用原子(JSON 整文件替换 / SQLite 单语句)。 +4. 后端不承诺 unit 内写并发序——**调用方负责串行**;整单元修改原子发布其数据和当前版本戳(JSON 整文件替换 / SQLite 在批量删除或推进版本戳时使用事务);逐记录批次在完成前中断时可能只应用一部分。 5. `deleteRecord` 幂等;`putRecord` 覆写。 6. 任意字符串 key / 任意 JSON 值安全(key 不进文件路径,结构性质)。 7. `close` 幂等;close 后任何操作 → `StorageError('closed')`。 @@ -88,8 +88,8 @@ CREATE TABLE IF NOT EXISTS "u__
" ( key TEXT PRIMARY KEY, value TEXT NOT NULL) STRICT; -- value = record JSON document ``` -- unit 版本存 `units` 行,descriptor 不符 → `version-mismatch`。行粒度 document-per-row,保住按 key 精确落盘更新(为 session sidecar 这类高频点更新大表留路);查询需求出现时 JSON1 直查 value 列。 -- 写原语单语句即原子,无跨语句事务需求(domain 层无跨表事务,见不做清单)。 +- unit 版本存 `units` 行,未接受的版本以 `version-mismatch` 拒绝。行粒度 document-per-row,保住按 key 精确落盘更新(为 session sidecar 这类高频点更新大表留路);查询需求出现时 JSON1 直查 value 列。 +- 当前版本的单记录写入使用单条语句。批量删除和对已接受旧单元的首次修改使用一个事务;首次修改一同提交数据和当前版本戳。这不增加跨表领域事务。 ### `dsh-domain`:领域数据形式 @@ -117,6 +117,7 @@ export interface DomainTableSpec { readonly valueSchema: Zo export interface DomainSpec { readonly name: string // ^[a-z][a-z0-9_]*$ readonly version: number + readonly compatibleVersions?: readonly number[] readonly global?: DomainGlobalSpec readonly tables: Record> } @@ -157,8 +158,8 @@ export interface KvTable { - **一级 mapping**:key → 记录,不做嵌套表;层级需求用复合 key 或值内字段。两后端因此同构(JSON object 一层 ↔ SQLite 一行)。 - **记录是纯数据**:可直接 JSON 序列化的不可变 POJO;`get`/`entries` 返回值不得原地改(TypeScript readonly 投影,不做运行时冻结)。带行为的领域对象属于消费方包。 -- **写串行**:域内一条 promise 链,`put`/`delete`/`update`/`global.set` 全排队;`update` 的 fn 在链上执行,并发不交错。不做 active-record(取出可变对象自动落盘——落盘时机不可控,与整域原子覆写冲突)。 -- **版本 fail loud**:盘上版本与 spec 不符直接报错,不迁移不重建(数据不可再生,pre-release 拒绝旧格式)。 +- **写串行**:域内一条 promise 链,`put`/`delete`/`deleteMany`/`update`/`global.set` 全排队;`update` 的 fn 在链上执行,并发不交错。不做 active-record(取出可变对象自动落盘——落盘时机不可控,与整域原子覆写冲突)。 +- **版本兼容**:领域拥有方通过 `compatibleVersions` 声明可读的旧版本,并用当前 schema 解码历史值。Storage 不转换记录值;[领域版本](../../../../docs/subsystems/storage.zh.md#domain-versioning)定义版本戳发布和混合代际要求。 - **变更事件**:每次写落盘 resolve 后 emit `domain/changed`(`@mode emit`),逐条发、不带旧值(对齐仓库"新快照 + 操作判别"惯例,范本 `goal/changed`);payload `DomainChanged` 是 put/deleted 判别联合——域名 + 表名 + key(global 变更两者为 `''`)+ operation,put 支带新快照 value、deleted 支无 value(`packages/storage/storage-domain/src/events.ts`)。此为下期 RPC 推帧的事件源。错误词汇 `DomainError`,码表:`already-open` / `facet-unsupported` / `invalid-record`(带 `{ table, key }`)/ `missing-key` / `closed`。 ### Future work:session 侧删除(设计定案,本期不实施) diff --git a/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.i18n.yaml b/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.i18n.yaml index 30e665ca0b..f318bc236a 100644 --- a/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.i18n.yaml +++ b/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.i18n.yaml @@ -9,14 +9,14 @@ en: 212258ada8f174eb zh: 9a02b100533118fe /agent-note-interactive-side-sessions-and-merge-back/proposal: - en: 5fa7d2000db6b265 - zh: a892b74299e0f984 + en: 7f24e61247bf2d84 + zh: aaa397f7d4aaf351 /agent-note-interactive-side-sessions-and-merge-back/alternatives-considered: en: de50cab213a61b91 zh: 85b912193092dfe2 /agent-note-interactive-side-sessions-and-merge-back/acceptance-criteria: - en: 17d0937a1f28b1ac - zh: 9710ab0af3268da1 + en: 3dbfd9c97279519f + zh: 719f54d2c0a68e0a /agent-note-interactive-side-sessions-and-merge-back/risks: en: 2435d8e2aba0d1c1 zh: 3854c476bea061d4 diff --git a/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.md b/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.md index fd1b79a820..0e6c85bfa2 100644 --- a/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.md +++ b/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.md @@ -12,7 +12,7 @@ A user may want to explore a question from a live session without changing its m A **side session** is an ordinary live session forked at the source's last completed turn, attached to its own agent, framed as a read-only advisor, and able to **merge back** one condensed note. -- **Fork and attach:** create the child with the parent's balanced completed-turn prefix, `parentSession`, `meta.isSeeded: true`, and the exact sibling `inheritedEventCount`. This composes `ctx.agents.create({ seed, inheritedEventCount, meta })`; it adds no core service or session-store method. +- **Fork and attach:** create the child with the parent's balanced completed-turn prefix, `meta.isSeeded: true`, and the exact sibling `inheritedEventCount`. The caller retains any handback target separately from the copied Session under the [independent-fork decision](../../implemented/architecture/2026-10-23-independent-session-forks.md). This composes `ctx.agents.create({ seed, inheritedEventCount, meta })`; it adds no core service or session-store method. - **Advisor framing:** inject one plugin-sourced `context/message` after creation that tells the child to explain without mutating or continuing the task. Keeping the system prompt byte-identical preserves the provider prefix cache over inherited history. - **Merge-back:** ask the child for a length-capped handback, then inject one plugin-sourced `context/message` into the parent. The next parent request sees it at its logged position, preserving replay and [request reconstructability](../../implemented/architecture/2026-07-05-reconstructable-requests.md) without a new session event. - **Presentation:** invocation, session switching, and handback rendering belong to the first client UI. This Agent Note specifies only the client-independent mechanics. @@ -28,7 +28,7 @@ Rewind productization, session-tree views, a model-facing side-session tool, and ## Acceptance criteria -- Forking leaves the source untouched and creates a child with the balanced completed-turn prefix, `parentSession`, `isSeeded: true`, the exact `inheritedEventCount`, and a byte-identical system prompt. +- Forking leaves the source untouched and creates a child with the balanced completed-turn prefix, `isSeeded: true`, the exact `inheritedEventCount`, and a byte-identical system prompt. - Advisor framing adds exactly one plugin-sourced `context/message` at the head of the child's appended history, rather than changing its system prompt. - Merge-back adds exactly one length-capped `context/message` with source `plugin: sidechat`; the next parent request and replay see it at the same position. - Parent and child run concurrently without log or stream cross-talk. diff --git a/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.zh.md b/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.zh.md index 5837897709..8bd39eca70 100644 --- a/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.zh.md +++ b/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.zh.md @@ -12,7 +12,7 @@ Status: proposed **侧会话(side session)**是一个普通的活跃会话,从源会话的最后一个已完成轮次 fork 而来,绑定到自己的 agent(智能体),定位为只读顾问,并能**合并回写**一条精简笔记。 -- **Fork 并绑定:**用 parent 的平衡 completed-turn prefix、`parentSession`、`meta.isSeeded: true` 与精确 sibling `inheritedEventCount` 创建 child。这组合 `ctx.agents.create({ seed, inheritedEventCount, meta })`;不新增 core service 或 Session-store method。 +- **Fork 并绑定:**用 parent 的平衡 completed-turn prefix、`meta.isSeeded: true` 与精确 sibling `inheritedEventCount` 创建 child。这组合 `ctx.agents.create({ seed, inheritedEventCount, meta })`;不新增 core service 或 Session-store method。 依据[独立 fork 决策](../../implemented/architecture/2026-10-23-independent-session-forks.zh.md),调用方将交回目标保存在所复制 Session 之外。 - **顾问定位:**创建后注入一条插件来源的 `context/message`,告知子会话只做解释,不执行变更或继续任务。保持系统提示词逐字节一致,可在继承的历史上保留提供方的前缀缓存。 - **合并回写:**向子会话请求一条有长度上限的 handback,然后向父会话注入一条插件来源的 `context/message`。父会话的下一次请求在日志所记录的位置看到该消息,保持回放与[请求可重建性](../../implemented/architecture/2026-07-05-reconstructable-requests.zh.md),无需新增会话事件。 - **呈现:**调用方式、会话切换与 handback 渲染属于首个客户端拥有的界面。本 Agent Note 仅规定与界面无关的机制。 @@ -28,7 +28,7 @@ Status: proposed ## 验收标准 -- Fork 不改变 source Session,创建的 child 带有平衡 completed-turn prefix、`parentSession`、`isSeeded: true`、精确 `inheritedEventCount` 与逐字节相同 system prompt。 +- Fork 不改变 source Session,创建的 child 带有平衡 completed-turn prefix、`isSeeded: true`、精确 `inheritedEventCount` 与逐字节相同 system prompt。 - 顾问定位在子会话追加历史的头部恰好添加一条插件来源的 `context/message`,而非修改其系统提示词。 - 合并回写恰好添加一条有长度上限的 `context/message`,来源为 `plugin: sidechat`;父会话的下一次请求与回放在相同位置看到它。 - 父会话与子会话并发运行,日志和流之间无串扰。 diff --git a/.agents/skills/dsh-session-projection/SKILL.md b/.agents/skills/dsh-session-projection/SKILL.md index e709e70598..90d483f4ac 100644 --- a/.agents/skills/dsh-session-projection/SKILL.md +++ b/.agents/skills/dsh-session-projection/SKILL.md @@ -1,19 +1,30 @@ --- name: dsh-session-projection -description: Use when creating, extending, or reviewing a DeepSeek Harness session projection, or migrating a fold helper to one. +description: Use when creating, extending, or reviewing a DeepSeek Harness session projection, or migrating session-derived recovery state to one. --- -# DeepSeek Harness Session Projections +# Session Projection Rules -Follow the [projection API](../../../packages/session/session-projection/README.md) for registration and lifecycle details. +## Summary -1. Decide whether to extend an existing projection or create one; check whether an existing owner already maintains the needed state. -2. Follow the README's [service ownership rules](../../../packages/session/session-projection/README.md#register-and-read): keep projection definitions and handles private to the owning service's implementation, and expose domain methods to consumers. -3. Require `sessionProjections` when the service needs projected state to function. Optional registration is for contributions the service can operate without. -4. Evaluate retained state size as the session grows. Do not accumulate state proportional to session length, including collections of event sequence numbers. Growth is acceptable only when slow enough to remain negligible. When the data would keep growing, consider incremental loading instead of retaining the complete state. -5. `apply` is synchronous; historical reads belong in asynchronous consumers. When later reads need event payloads, consider retaining sequence numbers within rule 4's state-size limits and letting consumers resolve them asynchronously. -6. When replacing a helper such as `foldSessionTitle` with a projection, remove the superseded helper. -7. After migrating to Session persistence, stop using `fold` in names and descriptions of the migrated logic. -8. Do not add calls to deprecated synchronous readers (`snapshotEvents`, `eventAt`, `ownEvents`) or wrappers exposing the same access ([decision](../../notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md)). Assume the full event log is not resident in memory and random reads may require asynchronous disk access. -9. Consider state size, replay cost, and per-event work; add complexity only for a concrete performance need. -10. Asynchronous `register()` is usually called in `[Service.init]`. If event listeners are registered afterward, check initialization ordering: when needed, install listeners before awaiting registration; if a listener needs the returned handle, await its readiness in a callback that supports asynchronous waiting. Otherwise, an event may fire before the listener is installed and be missed. Determine whether this race exists from the actual initialization flow and event trigger paths; do not move listeners earlier or add waits mechanically. +Keep recoverable session facts in Projection and expose them through their owning services. Read the [API and lifecycle](../../../packages/session/session-projection/README.md) for the supported preparation, registration, read, and cleanup contracts. + +1. Put all persisted or restorable session-derived state in Projection, including host-only state. Reuse an existing owner when suitable. Keep external resources and process-scoped ownership outside persisted state. Persist facts, not registration handles, promises, or runtime resources. + +2. Do not expose projection definitions or handles as production read APIs. Keep the ready handle private; consumers use the owning service's domain methods. A handle is a process-local reader, recreated during activation. Require `sessionProjections` when the service depends on it; optional registration is only for optional contributions. Do not hide a missing required dependency with another recovery path. + +3. State recovery through `init` and `apply` is synchronous and deterministic. Do not perform I/O or trigger Cordis hooks, models, or tools. Runtime hooks own those effects. Replay must not repeat them. Return the same state reference for unrelated events. Keep views synchronous and preserve their references when visible values do not change. + +4. Persist JSON state that its schema accepts. Follow the README's state-version and checkpoint-watermark rules. Restoring a checkpoint and replaying its suffix must match full replay. Change the version when state fields or recovery semantics change. + +5. Prefer fixed-size or sublinear state. Growth is acceptable only when slow enough to remain negligible. Necessary linear state must have a current use and explicit memory, replay, and per-event costs. Do not retain history-sized indexes, including event sequence collections, by habit. Do not discard required data or change behavior to reduce size. Start with a complete implementation; optimize for a concrete need. + +6. Caches must be discardable and rebuildable without changing behavior. A sequence reference alone is insufficient when a synchronous consumer needs the referenced payload. Store the required current value within rule 5, or prepare the payload through an explicit asynchronous path. Do not hide full-log reads in a cache miss. Do not add `snapshotEvents`, `eventAt`, `ownEvents`, or equivalent wrappers: history need not stay in memory. An async wrapper does not make synchronous history reads asynchronous. Existing host replay may remain for named supported callers, with an owner and removal condition; this does not permit [Client cache-miss full-log reads](../../../docs/defensive-patterns/conversation-and-session.md#cold-reads-are-the-last-resort). Remove superseded recovery helpers; cache reconstruction must not duplicate recovery rules. + +7. Await required registration before exposing synchronous readers or installing callbacks that use its handle, usually in `[Service.init]`. Let registration rejection fail that activation. Events can arrive during the await; install listeners earlier only when needed to avoid missed events. Await only in callbacks that support it. Do not move listeners or add waits mechanically. Keep fiber cleanup ownership, await explicit disposal, and do not create effects after the owner is disposed. + +8. Keep registration readiness and Session recovery separate. The asynchronous Session-loading or preparation owner completes historical recovery before it publishes the Session to synchronous readers. Use the registry's supported lifecycle; do not add hydration or hidden I/O to domain getters. Recovery prepares state; getters read it. Preserve the registry's error scope for each unit and Session. + +9. Identify all official consumers before switching a read path, including plugins, CLI/GUI, and both SDKs. Preserve synchronous callers until they migrate explicitly; a Promise cannot implement a synchronous API. A new required service or activation step needs consumer updates and an upgrade guide. Keep compatibility tied to actual supported callers, not test-only compositions. + +10. Verify values, notifications, error scope and timing, and recovery through affected real entry points. Keep existing behavior assertions. Do not move consumer-only errors into eager Projection processing. For lifecycle changes, test delayed registration, rejection, replacement, and disposal during an await. Use actual Session/store lifecycles and explicit barriers instead of partial Session mocks or microtask counts. Check error logs as well as released state. Recovery tests cover usable, missing, and incompatible checkpoints plus suffix replay, without runtime effects. diff --git a/.gitattributes b/.gitattributes index e878c9db19..2bead994d2 100644 --- a/.gitattributes +++ b/.gitattributes @@ -13,3 +13,6 @@ docs/persistence-schema.json linguist-generated=true docs/persistence-changes/*.schema.json linguist-generated=true docs/persistence-changes/releases/*.schema.json linguist-generated=true docs/persistence-changes/historical-formats/*.schema.json linguist-generated=true + +# Unified patch blank context lines require their leading space. +patches/*.patch whitespace=-blank-at-eol diff --git a/.github/AGENTS.md b/.github/AGENTS.md index 35f0103169..9b891d3a6e 100644 --- a/.github/AGENTS.md +++ b/.github/AGENTS.md @@ -4,4 +4,6 @@ Run jobs on Windows runners (`windows-*` labels) under native `pwsh`. Native Win The manual [Windows packaging workflow](workflows/windows-package.yml) uses the dedicated self-hosted Windows x64 label `dsh-win-package-trial` under native `pwsh`; preserve this routing separately from the automatic CI lanes. +The merge checks run from three workflows named `Policy`, which run on `pull_request_target` so their definitions come from master, and call the `deepseek-harness-check` action directly: `pr-check-on-head-branch.yml` on pull-request updates gives `Policy / Master Change` and `Policy / Pre-Merge Check`, `pr-check-after-approve.yml` on pull-request updates and submitted or dismissed reviews gives `Policy / Approve Check` and `Policy / Reviewer Evaluate`, and `pr-check-on-base-branch.yml` on master pushes re-runs the head-branch checks as `Policy / Recheck`. Branch rules require those check names, so keep the job names and the workflow name. Each check reads its mode from a repository variable: `MERGE_POLICY_MASTER_DIFF`, `MERGE_POLICY_PRE_MERGE`, `MERGE_POLICY_HEAD_DIFF`, and `MERGE_POLICY_REVIEW`, each `off` (skip), `report` (run without failing the job), or `block` (fail the job); a missing value or an unknown one counts as `report`. `Policy / Pre-Merge Check` merges the commit `Policy / Master Change` reports, so it runs only after that job and stays off while `MERGE_POLICY_MASTER_DIFF` is `off`; a merge it cannot do and a build that fails both follow its own mode, so `report` warns and skips the build while `block` fails the job. + The manual Desktop publication workflow selects a successful package run and attempt, then routes each retained build through `DESKTOP_PUBLISH_RUNNERS` to its original machine's unique label. Keep Windows run steps on native PowerShell and Mac run steps on the default POSIX shell; shared entrypoints are Node scripts. Test and production jobs use separate `desktop-test` and `desktop-production` approval Environments after a credential-free preparation job. diff --git a/.github/review-ownership/README.md b/.github/review-ownership/README.md index c115acf172..79103f593a 100644 --- a/.github/review-ownership/README.md +++ b/.github/review-ownership/README.md @@ -16,7 +16,7 @@ The [`weighted-approval` workflow](../workflows/weighted-approval.yml) publishes ## Approval scoring -The weighted approval workflow exposes two pull-request checks. The `weighted approval publisher` Actions job reports whether evaluation and status publication completed, while the `weighted approval` commit status carries the approval decision on the pull request head. Branch rules must require only the commit status with GitHub Actions as its expected source; a context-only requirement can accept a same-named status from another integration. The publisher marks the head pending before Python setup or lexer installation, so failed setup or an interrupted history fetch cannot leave a previous success in place. Setup and evaluation failures publish an error status. A completed evaluation returns `pending` below two approval points, while the pull request is a draft, or while a write-capable reviewer has an effective `CHANGES_REQUESTED` review; the blocker keeps the status pending even when counted approvals reach the threshold. It returns `success` only when the threshold is met, the pull request is ready, and no such blocker exists. If evaluation fails, the publisher writes an `error` status. The publisher also writes a `weighted approval decision` check run that reports the same decision as a conclusion — `action_required` while the policy is unmet, `success` when it holds, and `failure` on setup or evaluation failures — with the score or blocker in its title. Branch rules do not require that check run, so it never blocks a merge; it names the blocked state beside the status that gates the merge. A failed check-run write is logged and never changes the status. +The weighted approval workflow exposes two pull-request checks. The `weighted approval publisher` Actions job reports whether evaluation and status publication completed, while the `weighted approval` commit status carries the approval decision on the pull request head. Branch rules must require only the commit status with GitHub Actions as its expected source; a context-only requirement can accept a same-named status from another integration. The publisher marks the head pending before Python setup or lexer installation, so failed setup or an interrupted history fetch cannot leave a previous success in place. Setup and evaluation failures publish an error status. A completed evaluation returns `pending` below two approval points, while the pull request is a draft, or while a write-capable reviewer has an effective `CHANGES_REQUESTED` review; the blocker keeps the status pending even when counted approvals reach the threshold. It returns `success` only when the threshold is met, the pull request is ready, and no such blocker exists. If evaluation fails, the publisher writes an `error` status. The publisher also writes a `weighted approval decision` check run that reports the same decision as a conclusion — `action_required` while the policy is unmet, `success` when it holds, and `failure` on setup or evaluation failures — with the score or blocker in its title. Branch rules do not require that check run, so it never blocks a merge; it names the blocked state beside the status that gates the merge. The check run is published with a token minted from a dedicated approval App (`DSH_APPROVAL_APP_CLIENT_ID`, `DSH_APPROVAL_APP_PRIVATE_KEY`, `DSH_APPROVAL_APP_SLUG`, scope `checks: write`): GitHub attaches a check run created with the job token to the earliest Actions check suite on the head, and when that suite belongs to this `pull_request_target` workflow the merge box omits it, so the App identity makes the association stable. The App publishes only runs whose `app.slug` is the App; job-token runs from earlier evaluations stay untouched and can coexist on a head. When the token or slug is missing, the publisher falls back to the job token and updates job-token runs only, which keeps the label on the Checks page. The App token step runs with `continue-on-error`, so a missing App configuration fails only that step and leaves the job-token fallback; a failed check-run write is logged by the publisher and never changes the status. Reviewers whose calculated base repository permission is `write` or `admin` count. The [approval policy](approval-policy.json) gives `@07akioni`, `@imccyu`, `@tianyicui`, `@tianyicui-bot`, `@turtle1999`, and `@turtle2099` two points each; every other write-capable reviewer gets one point. The pull-request author’s own review and reviewers without write permission do not count. @@ -44,7 +44,7 @@ Each sender contributes at most once, using their own fixed weight or production ## Security -All actions in the status-writing job are pinned to commit SHAs. The job checks out only the repository default branch. It does not check out or execute pull-request code and does not use repository secrets. Only when there is no blocker, reviewer points plus author credit are insufficient, and an approval has the policy’s default weight, it fetches complete history using the job token, passes Git objects to the trusted classifier as data, and resolves commit authors in batches of 50. Fetch credentials exist only in the Git child environment. Missing history, parsing failures, or incomplete author queries fail evaluation rather than producing a partial score. The review-event workflow has no `GITHUB_TOKEN` permissions and passes only a decimal pull-request number in its run title. The publisher accepts only successful `pull_request_review` runs from the review-event workflow file, identified by `workflow_run.path`; GitHub can populate `workflow_run.name` with the expanded run title. The publisher rejects an invalid run title and a number that does not resolve to the workflow run's current pull-request head. Pull-request reviews and comments are treated as API data and escaped in logs. All publisher triggers and steps, including dependency setup, have pull-request write permission; the policy uses it to dismiss eligible senders' prior decision reviews and request recipients. Every evaluation verifies command authors and latest editors by immutable account ID through GraphQL, matching the body to the REST comment history before counting points or acting. Missing or inconsistent editor metadata fails evaluation. Non-author edits are ignored. Only active eligible delegations are reconciled; superseded or revoked commands have no effects. Dismissal failures publish an error; request failures remain separate from the approval decision. +All actions in the status-writing job are pinned to commit SHAs. The job checks out only the repository default branch. It does not check out or execute pull-request code. Its only secret is the dedicated approval App private key, used to mint a token scoped to `checks: write` for the decision check run; the status gate keeps using the job token. Only when there is no blocker, reviewer points plus author credit are insufficient, and an approval has the policy’s default weight, it fetches complete history using the job token, passes Git objects to the trusted classifier as data, and resolves commit authors in batches of 50. Fetch credentials exist only in the Git child environment. Missing history, parsing failures, or incomplete author queries fail evaluation rather than producing a partial score. The review-event workflow has no `GITHUB_TOKEN` permissions and passes only a decimal pull-request number in its run title. The publisher accepts only successful `pull_request_review` runs from the review-event workflow file, identified by `workflow_run.path`; GitHub can populate `workflow_run.name` with the expanded run title. The publisher rejects an invalid run title and a number that does not resolve to the workflow run's current pull-request head. Pull-request reviews and comments are treated as API data and escaped in logs. All publisher triggers and steps, including dependency setup, have pull-request write permission; the policy uses it to dismiss eligible senders' prior decision reviews and request recipients. Every evaluation verifies command authors and latest editors by immutable account ID through GraphQL, matching the body to the REST comment history before counting points or acting. Missing or inconsistent editor metadata fails evaluation. Non-author edits are ignored. Only active eligible delegations are reconciled; superseded or revoked commands have no effects. Dismissal failures publish an error; request failures remain separate from the approval decision. Approval policy changes take effect only after they merge into the default branch. This prevents an untrusted pull request from changing the program or policy for its own run. diff --git a/.github/review-ownership/check-approval.mjs b/.github/review-ownership/check-approval.mjs index 1f499ff170..d876e8e8c3 100644 --- a/.github/review-ownership/check-approval.mjs +++ b/.github/review-ownership/check-approval.mjs @@ -308,10 +308,10 @@ export async function evaluateApproval({ event, policySource, api, getOwnership /** * Evaluate and publish the required commit status, publishing an error status when evaluation fails. - * @param {{event: unknown, policySource: string, api: (path: string, options?: {method?: string, body?: unknown}) => Promise, runUrl: string, write?: (line: string) => void, getOwnership?: typeof productionOwnership, getMergedCount?: typeof countMergedAuthorPulls}} options Runtime inputs. + * @param {{event: unknown, policySource: string, api: (path: string, options?: {method?: string, body?: unknown}) => Promise, checkApi?: (path: string, options?: {method?: string, body?: unknown}) => Promise, checkAppSlug?: string, runUrl: string, write?: (line: string) => void, getOwnership?: typeof productionOwnership, getMergedCount?: typeof countMergedAuthorPulls}} options Runtime inputs; checkApi publishes the decision check run, defaulting to api, and checkAppSlug selects the runs that client can update. * @returns {Promise>>} Published approval decision. */ -export async function runApprovalCheck({ event, policySource, api, runUrl, getOwnership = productionOwnership, getMergedCount = countMergedAuthorPulls, write = line => process.stdout.write(`${line}\n`) }) { +export async function runApprovalCheck({ event, policySource, api, checkApi = api, checkAppSlug = 'github-actions', runUrl, getOwnership = productionOwnership, getMergedCount = countMergedAuthorPulls, write = line => process.stdout.write(`${line}\n`) }) { const pull = pullRequestFromEvent(event) await publishStatus(api, pull, 'pending', 'Evaluating approval points.', runUrl) let result @@ -334,7 +334,7 @@ export async function runApprovalCheck({ event, policySource, api, runUrl, getOw } } catch (error) { await publishStatus(api, pull, 'error', 'Approval evaluation failed.', runUrl) - await tryPublishCheck(api, pull, 'failure', 'Approval evaluation failed.', runUrl, write) + await tryPublishCheck(checkApi, pull, 'failure', 'Approval evaluation failed.', runUrl, write, checkAppSlug) throw error } write(result.authorCredit @@ -346,7 +346,7 @@ export async function runApprovalCheck({ event, policySource, api, runUrl, getOw writeList(write, 'Blocking change requests', result.blockers.map(login => `@${login}`)) writeList(write, 'Ignored reviewers without write access', result.ignoredReviewers.map(login => `@${login}`)) await publishStatus(api, pull, result.state, result.description, runUrl) - await tryPublishCheck(api, pull, result.state === 'success' ? 'success' : 'action_required', result.description, runUrl, write) + await tryPublishCheck(checkApi, pull, result.state === 'success' ? 'success' : 'action_required', result.description, runUrl, write, checkAppSlug) write(`Published ${JSON.stringify(STATUS_CONTEXT)} status ${JSON.stringify(result.state)}.`) try { await requestDelegatedReviews(result, api, write) @@ -358,15 +358,15 @@ export async function runApprovalCheck({ event, policySource, api, runUrl, getOw /** * Revoke a previous success before dependency installation, or report its failure. - * @param {{event: unknown, api: (path: string, options: object) => Promise, runUrl: string, phase: string, write?: (line: string) => void}} options Publication inputs. + * @param {{event: unknown, api: (path: string, options: object) => Promise, checkApi?: (path: string, options: object) => Promise, checkAppSlug?: string, runUrl: string, phase: string, write?: (line: string) => void}} options Publication inputs; checkApi publishes the decision check run and checkAppSlug selects the runs it can update. * @returns {Promise} Completion of the status write and the corresponding check-run write. */ -export async function publishApprovalPhase({ event, api, runUrl, phase, write = line => process.stdout.write(`${line}\n`) }) { +export async function publishApprovalPhase({ event, api, checkApi = api, checkAppSlug = 'github-actions', runUrl, phase, write = line => process.stdout.write(`${line}\n`) }) { const pull = pullRequestFromEvent(event) if (phase === 'pending') { await publishStatus(api, pull, 'pending', 'Preparing approval evaluation.', runUrl) try { - await revokeApproval(api, pull, runUrl) + await revokeApproval(checkApi, pull, runUrl, checkAppSlug) } catch (error) { write(`Decision check run not revoked; the commit status is unchanged: ${JSON.stringify(error instanceof Error ? error.message : String(error))}`) } @@ -374,7 +374,7 @@ export async function publishApprovalPhase({ event, api, runUrl, phase, write = } if (phase === 'error') { await publishStatus(api, pull, 'error', 'Approval setup or evaluation failed.', runUrl) - return tryPublishCheck(api, pull, 'failure', 'Approval setup or evaluation failed.', runUrl, write) + return tryPublishCheck(checkApi, pull, 'failure', 'Approval setup or evaluation failed.', runUrl, write, checkAppSlug) } throw new Error('invalid approval setup phase') } @@ -486,20 +486,20 @@ async function reviewerPermission(api, repository, login) { // The required gate is the commit status; this check run reports the same decision as a conclusion // label and is not required. A failed label write is reported and never changes the gate, including // for a replayed workflow whose token has no checks permission. -async function tryPublishCheck(api, pull, conclusion, title, runUrl, write) { +async function tryPublishCheck(checkApi, pull, conclusion, title, runUrl, write, appSlug) { try { - await publishCheck(api, pull, conclusion, title, runUrl) + await publishCheck(checkApi, pull, conclusion, title, runUrl, appSlug) } catch (error) { write(`Decision check run not published; the commit status is unchanged: ${JSON.stringify(error instanceof Error ? error.message : String(error))}`) } } -async function publishCheck(api, pull, conclusion, title, runUrl) { +async function publishCheck(checkApi, pull, conclusion, title, runUrl, appSlug) { requireHttpsRunUrl(runUrl) const body = { status: 'completed', conclusion, details_url: runUrl, output: { title, summary: `${title} [Workflow run](${runUrl})` } } - const runs = await decisionRuns(api, pull) + const runs = await decisionRuns(checkApi, pull, appSlug) if (runs.length === 0) { - await api(`/repos/${pull.repository}/check-runs`, { + await checkApi(`/repos/${pull.repository}/check-runs`, { method: 'POST', body: { name: CHECK_NAME, head_sha: pull.headSha, external_id: CHECK_RUN_MARKER, ...body }, }) @@ -507,21 +507,21 @@ async function publishCheck(api, pull, conclusion, title, runUrl) { } for (const run of runs) { if (!Number.isSafeInteger(run.id)) throw new Error('check run has no valid id') - await api(`/repos/${pull.repository}/check-runs/${run.id}`, { method: 'PATCH', body }) + await checkApi(`/repos/${pull.repository}/check-runs/${run.id}`, { method: 'PATCH', body }) } } // A head without a decision starts in progress; a published success becomes action_required, so an // interrupted evaluation cannot leave a success that its current inputs no longer support. -async function revokeApproval(api, pull, runUrl) { +async function revokeApproval(checkApi, pull, runUrl, appSlug) { requireHttpsRunUrl(runUrl) const title = 'Preparing approval evaluation.' const output = { title, summary: `${title} [Workflow run](${runUrl})` } - const runs = await decisionRuns(api, pull) + const runs = await decisionRuns(checkApi, pull, appSlug) if (runs.length === 0) { - await api(`/repos/${pull.repository}/check-runs`, { + await checkApi(`/repos/${pull.repository}/check-runs`, { method: 'POST', - body: { name: CHECK_NAME, head_sha: pull.headSha, status: 'in_progress', details_url: runUrl, output }, + body: { name: CHECK_NAME, head_sha: pull.headSha, external_id: CHECK_RUN_MARKER, status: 'in_progress', details_url: runUrl, output }, }) return } @@ -529,7 +529,7 @@ async function revokeApproval(api, pull, runUrl) { if (!Number.isSafeInteger(run.id)) throw new Error('check run has no valid id') // The label is not a gate; only a published success has to stop claiming the policy holds. if (run.conclusion !== 'success') continue - await api(`/repos/${pull.repository}/check-runs/${run.id}`, { + await checkApi(`/repos/${pull.repository}/check-runs/${run.id}`, { method: 'PATCH', body: { status: 'completed', conclusion: 'action_required', details_url: runUrl, output }, }) @@ -537,13 +537,14 @@ async function revokeApproval(api, pull, runUrl) { } // A completed check run never returns to in_progress: GitHub answers 200 and leaves it completed. -async function decisionRuns(api, pull) { - const listed = await api(`/repos/${pull.repository}/commits/${pull.headSha}/check-runs?check_name=${encodeURIComponent(CHECK_NAME)}&filter=all&per_page=100`) +async function decisionRuns(checkApi, pull, appSlug) { + const listed = await checkApi(`/repos/${pull.repository}/commits/${pull.headSha}/check-runs?check_name=${encodeURIComponent(CHECK_NAME)}&filter=all&per_page=100`) if (!isRecord(listed) || !Array.isArray(listed.check_runs) || listed.total_count !== listed.check_runs.length) { throw new Error('check-run list response is invalid or incomplete') } - return listed.check_runs.filter(run => isRecord(run) && isRecord(run.app) && run.app.slug === 'github-actions' - && (run.external_id === CHECK_RUN_MARKER || run.external_id === '')) + // Only runs created by the publishing token can be updated: the job token cannot patch an App run + // and the App token cannot patch an Actions run, so the slug selects the runs this token owns. + return listed.check_runs.filter(run => isRecord(run) && isRecord(run.app) && run.app.slug === appSlug) } function requireHttpsRunUrl(runUrl) { @@ -640,6 +641,17 @@ async function main() { token: process.env.GITHUB_TOKEN ?? '', apiUrl: process.env.GITHUB_API_URL, }) + // The decision check run is published by the dedicated approval App so GitHub associates its check + // suite with the pull request instead of whichever Actions suite started first. Both the token and + // the App slug must be configured; otherwise the publisher keeps the job token, whose runs only + // show on the Checks page. + const appToken = process.env.DECISION_TOKEN + const appSlug = process.env.DECISION_APP_SLUG + const useApp = Boolean(appToken && appSlug) + const checkApi = useApp + ? createGitHubApi({ token: appToken, apiUrl: process.env.GITHUB_API_URL }) + : api + const checkAppSlug = useApp ? appSlug : 'github-actions' if (isRecord(event) && isRecord(event.issue)) { event = await approvalEventFromComment({ event, api }) } else if (isRecord(event) && isRecord(event.workflow_run)) { @@ -653,7 +665,7 @@ async function main() { } const phase = process.argv[2] if (phase) { - await publishApprovalPhase({ event, api, runUrl: process.env.GITHUB_RUN_URL ?? '', phase }) + await publishApprovalPhase({ event, api, checkApi, checkAppSlug, runUrl: process.env.GITHUB_RUN_URL ?? '', phase }) if (phase === 'pending' && process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, 'active=true\n') return } @@ -661,6 +673,8 @@ async function main() { event, policySource, api, + checkApi, + checkAppSlug, runUrl: process.env.GITHUB_RUN_URL ?? '', }) } diff --git a/.github/review-ownership/check-approval.test.mjs b/.github/review-ownership/check-approval.test.mjs index 979661be10..cf5f74583e 100644 --- a/.github/review-ownership/check-approval.test.mjs +++ b/.github/review-ownership/check-approval.test.mjs @@ -497,6 +497,92 @@ test('publishes setup phases without evaluating or installing dependencies', asy await assert.rejects(publishApprovalPhase({ ...options, phase: 'success' }), /invalid approval setup phase/u) }) +test('updates the App-owned run instead of creating another', async () => { + const calls = [] + const appRuns = [{ id: 42, app: { slug: 'dsh-weighted-approval' }, conclusion: 'success', external_id: 'weighted-approval-decision' }] + await runPublisher({ + event: pullRequestEvent(), policySource, runUrl: 'https://github.example/run/1', write: () => {}, + checkAppSlug: 'dsh-weighted-approval', + getOwnership: async () => ({ totalLines: 0, reviewerLines: {} }), + getMergedCount: async () => 0, + api: async (path, options = {}) => { + if (path.includes('/reviews?')) return [review('writer', 'APPROVED')] + if (path.includes('/collaborators/writer/permission')) return { permission: 'write' } + if (path.includes('/comments?')) return [] + if (path.includes('/statuses/')) return {} + throw new Error(`unexpected status API path ${path}`) + }, + checkApi: async (path, options = {}) => { + calls.push({ path, method: options.method, body: options.body }) + if (isCheckRunsList(path)) return { total_count: appRuns.length, check_runs: appRuns } + if (path.includes('/check-runs')) return {} + throw new Error(`unexpected check API path ${path}`) + }, + }) + assert.deepEqual(calls.map(call => call.path), [ + `/repos/deepseek-harness/deepseek-harness/commits/${HEAD_SHA}/check-runs?check_name=weighted%20approval%20decision&filter=all&per_page=100`, + '/repos/deepseek-harness/deepseek-harness/check-runs/42', + ]) + assert.equal(calls[1].method, 'PATCH') + assert.equal(calls[1].body.name, undefined) +}) + +test('ignores job-token runs when the App token publishes', async () => { + const calls = [] + const jobRuns = [{ id: 7, app: { slug: 'github-actions' }, conclusion: 'success', external_id: 'weighted-approval-decision' }] + await runPublisher({ + event: pullRequestEvent(), policySource, runUrl: 'https://github.example/run/1', write: () => {}, + checkAppSlug: 'dsh-weighted-approval', + getOwnership: async () => ({ totalLines: 0, reviewerLines: {} }), + getMergedCount: async () => 0, + api: async (path) => { + if (path.includes('/reviews?')) return [review('writer', 'APPROVED')] + if (path.includes('/collaborators/writer/permission')) return { permission: 'write' } + if (path.includes('/comments?')) return [] + if (path.includes('/statuses/')) return {} + throw new Error(`unexpected status API path ${path}`) + }, + checkApi: async (path, options = {}) => { + calls.push({ path, method: options.method, body: options.body }) + if (isCheckRunsList(path)) return { total_count: jobRuns.length, check_runs: jobRuns } + if (path.includes('/check-runs')) return {} + throw new Error(`unexpected check API path ${path}`) + }, + }) + assert.equal(calls.at(-1).method, 'POST') + assert.equal(calls.at(-1).body.name, 'weighted approval decision') + assert.equal(calls.at(-1).body.external_id, 'weighted-approval-decision') +}) + +test('publishes the check run through the App token when one is provided', async () => { + const statusCalls = [] + const checkCalls = [] + await runPublisher({ + event: pullRequestEvent(), policySource, runUrl: 'https://github.example/run/1', write: () => {}, + getOwnership: async () => ({ totalLines: 0, reviewerLines: {} }), + getMergedCount: async () => 0, + api: async (path, options = {}) => { + statusCalls.push({ path, body: options.body }) + if (path.includes('/reviews?')) return [review('writer', 'APPROVED')] + if (path.includes('/collaborators/writer/permission')) return { permission: 'write' } + if (path.includes('/comments?')) return [] + if (path.includes('/statuses/')) return {} + throw new Error(`unexpected status API path ${path}`) + }, + checkApi: async (path, options = {}) => { + checkCalls.push({ path, body: options.body }) + if (isCheckRunsList(path)) return emptyCheckRuns + if (path.includes('/check-runs')) return {} + throw new Error(`unexpected check API path ${path}`) + }, + }) + assert.equal(statusCalls.at(-1).body.context, 'weighted approval') + assert.equal(checkCalls.at(-1).body.name, 'weighted approval decision') + assert.equal(checkCalls.at(-1).body.conclusion, 'action_required') + assert.ok(statusCalls.every(call => !call.path.includes('/check-runs'))) + assert.ok(checkCalls.every(call => !call.path.includes('/statuses/'))) +}) + test('keeps the status gate when the label write fails', async () => { const writes = [] const states = [] @@ -561,6 +647,7 @@ test('revokes a published success check run and updates one run per head', async `/repos/deepseek-harness/deepseek-harness/statuses/${HEAD_SHA}`, `/repos/deepseek-harness/deepseek-harness/commits/${HEAD_SHA}/check-runs?check_name=weighted%20approval%20decision&filter=all&per_page=100`, '/repos/deepseek-harness/deepseek-harness/check-runs/7', + '/repos/deepseek-harness/deepseek-harness/check-runs/10', ]) for (const call of calls.slice(2)) { assert.equal(call.method, 'PATCH') diff --git a/.github/workflows/build-exe-for-python-sdk.yml b/.github/workflows/build-exe-for-python-sdk.yml index 0c869d008a..6bcdbee5ac 100644 --- a/.github/workflows/build-exe-for-python-sdk.yml +++ b/.github/workflows/build-exe-for-python-sdk.yml @@ -264,6 +264,10 @@ jobs: - name: Build single-exe env: DSH_BUILD_CLIENT_PROFILE: official + # Brotli runs at quality 9 through the vendored pkg patch: the same + # payload measured 16.3 s at quality 9 against 132.8 s at pkg's default + # quality 11, for an archive 10% larger. Which quality each lane uses is + # therefore not a workflow choice. run: >- pnpm exec tsx scripts/build-exe-for-python-sdk.ts --targets=${{ matrix.target }} ${{ inputs.ci && github.event_name == 'pull_request' && '--build-artifacts' || '' }} diff --git a/.github/workflows/build-preview-cloudflare.yml b/.github/workflows/build-preview-cloudflare.yml index c2ff5d3231..5625d75a9c 100644 --- a/.github/workflows/build-preview-cloudflare.yml +++ b/.github/workflows/build-preview-cloudflare.yml @@ -3,7 +3,9 @@ name: Build PR preview # Every push to a pull request publishes that pull request's preview to # Cloudflare Pages under its own branch alias, behind Cloudflare Access. The # upload carries build products only: the workflow never grants the deployment -# platform access to this repository's sources. +# platform access to this repository's sources. This lane also owns the +# aggregate test and script type checks that the required Linux consumers no +# longer repeat on every pull request. on: pull_request: @@ -32,7 +34,13 @@ env: jobs: preview: - runs-on: ubuntu-24.04 + # The required outcome is the build, which runs four TypeScript programs + # (Host and Client package compilation, then each face's aggregate test and + # script check) after the Typert pass. Publishing is best effort: transport, + # Access, and comment failures warn instead of failing the check. + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404' + || 'ubuntu-24.04' }} name: cloudflare pages preview steps: - uses: actions/checkout@v7.0.1 @@ -70,8 +78,11 @@ jobs: # apps/web consumes workspace packages as built lib products, and # build:preview packs the image through the packer's installed bin # (lib/bin.js), so neither half exists before the artifact build runs. - - name: Build workspace - run: pnpm run build:artifacts + # The required Linux consumers emit artifacts only; the complete build + # here also runs the aggregate test and script checks, which share the + # Typert output and the two package compilations. + - name: Build workspace and check aggregate programs + run: pnpm run build - name: Build the preview page and pack the VFS image env: @@ -88,6 +99,8 @@ jobs: cp apps/web/dist/preview.html apps/web/dist/index.html - name: Upload to Cloudflare Pages + id: upload + continue-on-error: true env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} @@ -112,6 +125,8 @@ jobs: # Accept-Encoding is sent because a browser sends it; the assertion is # about what the platform does with a body that is already compressed. - name: Verify the protected deployment serves the image + id: verify + continue-on-error: true env: CF_ACCESS_CLIENT_ID: ${{ secrets.CF_ACCESS_CLIENT_ID }} CF_ACCESS_CLIENT_SECRET: ${{ secrets.CF_ACCESS_CLIENT_SECRET }} @@ -151,6 +166,8 @@ jobs: # idempotent: a pull request opened before this workflow existed never # sees an `opened` event, and every later push must not restate the URL. - name: Comment the preview URL + id: comment + continue-on-error: true env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} PR: ${{ github.event.pull_request.number }} @@ -168,3 +185,12 @@ jobs: "$marker" \ "[Preview for #$PR](https://pr-$PR.${CF_PROJECT}.pages.dev) (requires Cloudflare Access sign-in)" \ | gh pr comment "$PR" --body-file - + + # Publishing stays outside the required verdict: a Cloudflare, Access, or + # comment failure warns, while a build failure still fails this check. + - name: Report preview publication failures + if: steps.upload.outcome == 'failure' || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure' + run: | + message='preview publication failed; the build passed, see the upload, verify, and comment steps' + echo "::warning::$message" + echo "$message" >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/ci-windows.yml b/.github/workflows/ci-windows.yml index fa2473a3a3..a4ed098609 100644 --- a/.github/workflows/ci-windows.yml +++ b/.github/workflows/ci-windows.yml @@ -76,7 +76,7 @@ jobs: - name: Parse Windows runner supervision scripts shell: pwsh run: | - foreach ($path in @('apps/desktop/scripts/windows-runner-task.ps1', 'apps/desktop/scripts/run-windows-runner-task.ps1', 'apps/desktop/tests/windows-runner-task.ps1', 'apps/desktop/tests/windows-runner-launcher.ps1')) { + foreach ($path in @('apps/desktop/scripts/windows-runner-task.ps1', 'apps/desktop/scripts/run-windows-runner-task.ps1', 'apps/desktop/scripts/start-windows-packaging-runner.ps1', 'apps/desktop/scripts/windows-runner-network.ps1', 'apps/desktop/scripts/run-windows-runner-network-process.ps1', 'apps/desktop/tests/windows-runner-task.ps1', 'apps/desktop/tests/windows-runner-launcher.ps1', 'apps/desktop/tests/windows-runner-network.ps1', 'apps/desktop/tests/windows-runner-network-process.ps1')) { $tokens = $null $parseErrors = $null $null = [Management.Automation.Language.Parser]::ParseFile((Join-Path $env:GITHUB_WORKSPACE $path), [ref]$tokens, [ref]$parseErrors) @@ -85,6 +85,15 @@ jobs: - name: Verify windowless Windows runner launcher shell: pwsh run: ./apps/desktop/tests/windows-runner-launcher.ps1 + - name: Verify Windows packaging priority inheritance + shell: pwsh + run: ./apps/desktop/tests/windows-packaging-priority.ps1 + - name: Verify Windows runner network supervision + shell: pwsh + run: | + ./apps/desktop/tests/windows-runner-network.ps1 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + ./apps/desktop/tests/windows-runner-network-process.ps1 - name: Run Windows observational gates on built artifacts id: observational continue-on-error: true diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ae9db81e61..916971cfa4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -202,12 +202,81 @@ jobs: path: .coverage-times.json key: coverage-times-Linux-${{ runner.environment }}-${{ vars.DSH_CI_FAILOVER_LINUX || 'enterprise' }}-${{ github.run_id }}-${{ github.run_attempt }} + # Lint and duplication get their own lane instead of riding the artifact + # consumers: a red lint no longer costs the snapshot and artifact consumers a + # full rerun. The lane compiles package declarations because oxlint's + # type-aware rules read them. + node-24-lint: + if: github.event_name == 'pull_request' + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-8vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') + || 'dsh-ubuntu-24-04-16core' }} + name: node 24 / lint + env: + # Shared hosts expose host CPUs, not an isolated allocation. + DSH_GATE_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '8' || '' }} + DSH_OXLINT_THREADS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '8' || '' }} + steps: + # Runner cleanup owns tool caches and fixtures, including cancelled runs. + - name: Use runner-owned temporary storage + run: | + echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV" + + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + + - name: Redirect Node compile cache to runner temp + run: echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV" + + - uses: pnpm/action-setup@v5.0.0 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + + - uses: actions/setup-node@v7.0.0 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Configure pnpm store path + id: pnpm-store + run: | + store_root="$HOME/.local/share/pnpm/store" + echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV" + store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent) + echo "path=$store_path" >> "$GITHUB_OUTPUT" + + - uses: actions/cache/restore@v6.1.0 + if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]' + with: + path: ${{ steps.pnpm-store.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + # oxlint's type-aware rules resolve workspace imports through the package + # declarations, so this lane compiles them without bundling anything. + - name: Compile package declarations + run: pnpm run typecheck + + - name: Run lint and duplication + run: pnpm run check:ci:lint:contracts-ready + node-24-bench: if: github.event_name == 'pull_request' - runs-on: ubuntu-24.04 + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404' + || 'ubuntu-24.04' }} name: node 24 / benchmarks # Wall-clock budgets need an otherwise idle runner, so this job runs the - # benchmark lane alone instead of joining a concurrent gate aggregate. + # benchmark lane alone instead of joining a concurrent gate aggregate, and + # keeps its own two-file parallelism inside that runner. The self-hosted + # failover pool is shared, so the benchmarks stay on hosted Linux there. timeout-minutes: 20 steps: - uses: actions/checkout@v7.0.1 @@ -503,7 +572,7 @@ jobs: && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') || 'ubuntu-latest' }} - needs: [node-24, node-24-coverage, node-24-bench, node-24-consumers, node-compat] + needs: [node-24, node-24-coverage, node-24-lint, node-24-bench, node-24-consumers, node-compat] if: ${{ !cancelled() && github.event_name == 'pull_request' }} steps: - name: Fail if any needed job did not succeed diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 726bd070a5..32df0173e9 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -122,6 +122,6 @@ jobs: DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }} DEEPSEEK_BASE_URL: https://api.deepseek.com/anthropic DSH_PRIMARY_RUNTIME: ${{ github.workspace }}/.cache/e2e-office/primary-runtime - DSH_E2E_MAX_WORKERS: 4 + DSH_E2E_MAX_WORKERS: 6 DSH_EXAMPLE_MODE: lib run: pnpm run test:e2e diff --git a/.github/workflows/macos-package.yml b/.github/workflows/macos-package.yml index b0c3164729..eeb451266e 100644 --- a/.github/workflows/macos-package.yml +++ b/.github/workflows/macos-package.yml @@ -9,6 +9,12 @@ on: options: [test, production] default: test required: true + zip_compression_level: + description: 'ZIP 压缩等级:只影响 ZIP 和自动升级下载,不影响 DMG;3 打包较快,7 压缩更强' + type: choice + options: ['3', '7'] + default: '3' + required: true skip_notarization: description: '跳过公证和 stapling:仅限内部调试,禁止发布到 test / production 或用于自动更新;需要发布请勿勾选' type: boolean @@ -57,6 +63,7 @@ jobs: run: shell: bash env: + PACKAGE_MACOS_ZIP_COMPRESSION_LEVEL: ${{ inputs.zip_compression_level }} PACKAGE_SKIP_NOTARIZATION: ${{ inputs.skip_notarization }} PACKAGE_SOURCE_REF: ${{ inputs.source_ref }} PACKAGE_VERSION_MODE: ${{ inputs.version_mode }} @@ -95,6 +102,12 @@ jobs: - uses: actions/setup-node@v7.0.0 with: node-version: '24' + - name: Configure persistent package caches + env: + DSH_DESKTOP_PACKAGE_CACHE_DIR: ${{ runner.tool_cache }}/dsh-desktop-package-cache + run: | + echo "DSH_DESKTOP_PACKAGE_CACHE_DIR=$DSH_DESKTOP_PACKAGE_CACHE_DIR" >> "$GITHUB_ENV" + echo "PNPM_CONFIG_STORE_DIR=$DSH_DESKTOP_PACKAGE_CACHE_DIR/workspace-pnpm-store" >> "$GITHUB_ENV" - name: Install locked dependencies run: pnpm install --frozen-lockfile - name: Validate preset and resolve build version @@ -138,5 +151,6 @@ jobs: name: macos-arm64-${{ steps.settings.outputs.mode }}-${{ steps.settings.outputs.version }}-${{ github.run_id }}-${{ github.run_attempt }} include-hidden-files: true path: ${{ steps.retained.outputs.directory }}/* + compression-level: 0 if-no-files-found: error retention-days: 14 diff --git a/.github/workflows/pr-check-after-approve.yml b/.github/workflows/pr-check-after-approve.yml new file mode 100644 index 0000000000..1255ae9373 --- /dev/null +++ b/.github/workflows/pr-check-after-approve.yml @@ -0,0 +1,94 @@ +name: Policy +on: + pull_request_target: + branches: [master] + types: [opened, synchronize, reopened, ready_for_review] + pull_request_review: + types: [submitted, dismissed] +permissions: + contents: read + pull-requests: read +concurrency: + group: pr-check-after-approve-${{ github.event.pull_request.number }} + cancel-in-progress: true +jobs: + approve: + name: Approve Check + # Each check runs only while its repository variable is neither empty nor `off`; otherwise the job is skipped. + if: ${{ vars.MERGE_POLICY_HEAD_DIFF != '' && vars.MERGE_POLICY_HEAD_DIFF != 'off' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + pull-requests: read + steps: + # The head checkout is only the Git repository the check fetches into; it needs no files and runs no code. + - uses: actions/checkout@v7.0.1 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 1 + filter: blob:none + sparse-checkout: README.md + sparse-checkout-cone-mode: false + + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + package-manager-cache: false + + - uses: deepseek-harness/deepseek-harness-check@master + env: + CHECK_MODE: ${{ vars.MERGE_POLICY_HEAD_DIFF }} + with: + check: head-diff + base-branch: ${{ github.event.pull_request.base.ref }} + head-sha: ${{ github.event.pull_request.head.sha }} + pr-number: ${{ github.event.pull_request.number }} + pr-author: ${{ github.event.pull_request.user.login }} + + review: + name: Reviewer Evaluate + if: ${{ vars.MERGE_POLICY_REVIEW != '' && vars.MERGE_POLICY_REVIEW != 'off' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + pull-requests: read + # The check posts its verdict as a check run of its own. + checks: write + steps: + # The head checkout is only the Git repository the check fetches into; it needs no files and runs no code. + - uses: actions/checkout@v7.0.1 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 1 + filter: blob:none + sparse-checkout: README.md + sparse-checkout-cone-mode: false + + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + package-manager-cache: false + + # The check app's token makes the review check run its own row instead of joining this workflow's suite. + - id: token + continue-on-error: true + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 + with: + client-id: ${{ vars.DSH_APPROVAL_APP_CLIENT_ID }} + private-key: ${{ secrets.DSH_APPROVAL_APP_PRIVATE_KEY }} + owner: deepseek-harness + repositories: deepseek-harness + permission-checks: write + + - uses: deepseek-harness/deepseek-harness-check@master + env: + CHECK_MODE: ${{ vars.MERGE_POLICY_REVIEW }} + CHECK_TOKEN: ${{ steps.token.outputs.token }} + with: + check: review + base-branch: ${{ github.event.pull_request.base.ref }} + head-sha: ${{ github.event.pull_request.head.sha }} + pr-number: ${{ github.event.pull_request.number }} + pr-author: ${{ github.event.pull_request.user.login }} diff --git a/.github/workflows/pr-check-on-base-branch.yml b/.github/workflows/pr-check-on-base-branch.yml new file mode 100644 index 0000000000..32d4d46165 --- /dev/null +++ b/.github/workflows/pr-check-on-base-branch.yml @@ -0,0 +1,30 @@ +name: Policy +on: + push: + branches: [master] + workflow_dispatch: +permissions: {} +concurrency: + group: pr-check-on-base-branch-${{ github.ref_name }} +jobs: + recheck: + name: Recheck + # Re-runs the head-branch checks, so it follows their variables. + if: ${{ vars.MERGE_POLICY_MASTER_DIFF != '' && vars.MERGE_POLICY_MASTER_DIFF != 'off' || vars.MERGE_POLICY_PRE_MERGE != '' && vars.MERGE_POLICY_PRE_MERGE != 'off' }} + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + actions: write + contents: read + pull-requests: read + steps: + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + package-manager-cache: false + + - uses: deepseek-harness/deepseek-harness-check@master + with: + check: recheck + base-branch: ${{ github.ref_name }} + recheck-label-token: ${{ secrets.DSH_RECHECK_LABEL_TOKEN }} diff --git a/.github/workflows/pr-check-on-head-branch.yml b/.github/workflows/pr-check-on-head-branch.yml new file mode 100644 index 0000000000..5ab02a6a94 --- /dev/null +++ b/.github/workflows/pr-check-on-head-branch.yml @@ -0,0 +1,107 @@ +name: Policy +on: + pull_request_target: + branches: [master] + types: [opened, synchronize, reopened, ready_for_review, review_requested, auto_merge_enabled, labeled] +permissions: + contents: read +concurrency: + group: pr-check-on-head-branch-${{ github.event.pull_request.number }} + cancel-in-progress: true +jobs: + master: + name: Master Change + # Each check runs only while its repository variable is neither empty nor `off`; otherwise the job is skipped. + if: ${{ vars.MERGE_POLICY_MASTER_DIFF != '' && vars.MERGE_POLICY_MASTER_DIFF != 'off' && !github.event.pull_request.draft }} + runs-on: ubuntu-latest + timeout-minutes: 15 + outputs: + base_sha: ${{ steps.check.outputs.base_sha }} + since: ${{ steps.check.outputs.since }} + steps: + # The head checkout is only the Git repository the check fetches into; it needs no files and runs no code. + - uses: actions/checkout@v7.0.1 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 1 + filter: blob:none + sparse-checkout: README.md + sparse-checkout-cone-mode: false + + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + package-manager-cache: false + + - id: check + uses: deepseek-harness/deepseek-harness-check@master + env: + CHECK_MODE: ${{ vars.MERGE_POLICY_MASTER_DIFF }} + with: + check: master-diff + base-branch: ${{ github.event.pull_request.base.ref }} + head-sha: ${{ github.event.pull_request.head.sha }} + + pre-merge: + name: Pre-Merge Check + needs: master + if: ${{ vars.MERGE_POLICY_PRE_MERGE != '' && vars.MERGE_POLICY_PRE_MERGE != 'off' && needs.master.result == 'success' }} + runs-on: blacksmith-4vcpu-ubuntu-2404 + timeout-minutes: 60 + # This job installs and compiles the pull request: it reads contents only and receives no secret. + permissions: + contents: read + steps: + - uses: actions/checkout@v7.0.1 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 1 + + # Merging is the precondition of the build below, so a failure here warns and skips it in `report` mode and fails + # in `block` mode. + - id: merge + name: Merge the checked base-branch commit + env: + CHECK_MODE: ${{ vars.MERGE_POLICY_PRE_MERGE }} + BASE_SHA: ${{ needs.master.outputs.base_sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + SINCE: ${{ needs.master.outputs.since }} + run: | + stop() { + if [ "$CHECK_MODE" = block ]; then + echo "::error title=Pre-Merge Check::$1" + exit 1 + fi + echo "::warning title=Pre-Merge Check::$1" + exit 0 + } + if [[ ! "$BASE_SHA" =~ ^[0-9a-f]{40}$ || ! "$SINCE" =~ ^[0-9]+$ ]]; then + stop "the master diff check reported no base commit, so nothing was merged or compiled" + fi + git fetch --no-tags --no-write-fetch-head --shallow-since="$SINCE" origin "$HEAD_SHA" "$BASE_SHA" || + stop "the base commit $BASE_SHA could not be fetched, so nothing was merged or compiled" + git -c user.name=pr-check -c user.email=pr-check@users.noreply.github.com merge --no-ff --no-edit -m "Merge $BASE_SHA into $HEAD_SHA" "$BASE_SHA" || + stop "the pull request cannot merge $BASE_SHA; merge master into it and push, then this check runs again" + echo "merged=true" >> "$GITHUB_OUTPUT" + + - uses: pnpm/action-setup@v5.0.0 + if: steps.merge.outputs.merged == 'true' + + - uses: actions/setup-node@v7.0.0 + if: steps.merge.outputs.merged == 'true' + with: + node-version: '24' + package-manager-cache: false + + - name: Run the pre-merge command + if: steps.merge.outputs.merged == 'true' + env: + CHECK_MODE: ${{ vars.MERGE_POLICY_PRE_MERGE }} + run: | + if ! bash -euxo pipefail -c 'pnpm install --frozen-lockfile && pnpm exec tsx scripts/compile-referenced-projects.ts host-contracts && pnpm exec tsx scripts/compile-referenced-projects.ts client'; then + if [ "$CHECK_MODE" = block ]; then + echo "::error title=Pre-Merge Check::the merged tree does not install or compile" + exit 1 + fi + echo "::warning title=Pre-Merge Check::the merged tree does not install or compile; this check does not block" + fi diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b9def1dec1..c88dec8687 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -30,7 +30,8 @@ jobs: name: Dependency layout # Persistent runners accept only trusted, credential-free rehearsals. runs-on: >- - ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.repository == 'deepseek-harness/deepseek-harness' && github.actor != 'dependabot[bot]' && ((github.event_name == 'push' && github.ref == 'refs/heads/master') @@ -80,11 +81,20 @@ jobs: - name: Install (immutable) run: pnpm install --frozen-lockfile - - name: Verify dependency policy - run: pnpm run verify-package-dependencies - - - name: Verify npm install layout - run: pnpm run verify-npm-install-layout + # The two verifications read different inputs (manifests versus an npm + # install in a scratch directory), so they run beside each other. + - name: Verify dependency policy and npm install layout + run: | + pnpm run verify-package-dependencies & + dependencies_pid=$! + pnpm run verify-npm-install-layout & + layout_pid=$! + dependencies_status=0 + wait "$dependencies_pid" || dependencies_status=$? + layout_status=0 + wait "$layout_pid" || layout_status=$? + if (( dependencies_status != 0 )); then exit "$dependencies_status"; fi + exit "$layout_status" pack: name: Pack npm tarballs diff --git a/.github/workflows/weighted-approval.yml b/.github/workflows/weighted-approval.yml index 2a20d83d5b..09ceac27ae 100644 --- a/.github/workflows/weighted-approval.yml +++ b/.github/workflows/weighted-approval.yml @@ -37,10 +37,26 @@ jobs: with: ref: ${{ github.event.repository.default_branch }} persist-credentials: false + # The decision check run is published by a dedicated approval App so GitHub associates its + # check suite with the pull request and no other workflow owns that identity; the job token + # alone keeps the run out of the merge box. The App holds only Checks write. A missing App + # permission leaves the token empty and the publisher falls back to the job token. + - name: Create decision check token + id: decision-token + continue-on-error: true + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 + with: + client-id: ${{ vars.DSH_APPROVAL_APP_CLIENT_ID }} + private-key: ${{ secrets.DSH_APPROVAL_APP_PRIVATE_KEY }} + owner: deepseek-harness + repositories: deepseek-harness + permission-checks: write - name: Revoke previous approval status id: revoke env: GITHUB_TOKEN: ${{ github.token }} + DECISION_TOKEN: ${{ steps.decision-token.outputs.token }} + DECISION_APP_SLUG: ${{ vars.DSH_APPROVAL_APP_SLUG }} GITHUB_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: node .github/review-ownership/check-approval.mjs pending # SECURITY: dependency setup runs in the status-writing job. @@ -57,11 +73,15 @@ jobs: if: steps.revoke.outputs.active == 'true' env: GITHUB_TOKEN: ${{ github.token }} + DECISION_TOKEN: ${{ steps.decision-token.outputs.token }} + DECISION_APP_SLUG: ${{ vars.DSH_APPROVAL_APP_SLUG }} GITHUB_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: node .github/review-ownership/check-approval.mjs - name: Publish approval setup failure if: failure() && steps.revoke.outputs.active == 'true' env: GITHUB_TOKEN: ${{ github.token }} + DECISION_TOKEN: ${{ steps.decision-token.outputs.token }} + DECISION_APP_SLUG: ${{ vars.DSH_APPROVAL_APP_SLUG }} GITHUB_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: node .github/review-ownership/check-approval.mjs error diff --git a/.github/workflows/windows-package.yml b/.github/workflows/windows-package.yml index bc76eca87b..c38fd7d5a0 100644 --- a/.github/workflows/windows-package.yml +++ b/.github/workflows/windows-package.yml @@ -42,6 +42,22 @@ on: type: string default: '' required: false + cache_namespace: + description: '缓存测量命名空间:留空使用共享缓存;新名称用于冷缓存,再次使用同名测热缓存,不清除现有缓存' + type: string + default: '' + required: false + build_root: + description: '独立构建根目录:填写绝对路径,每次任务创建独立源码副本;留空使用 runner 工作区' + type: string + default: '' + required: false + compression_level: + description: '安装器压缩等级:3 打包较快,7 压缩更强;覆盖本轮机器配置' + type: choice + options: ['3', '7'] + default: '3' + required: true permissions: contents: read @@ -65,6 +81,9 @@ jobs: DSH_PACKAGING_PRESET: ${{ inputs.preset }} PACKAGE_TEST_RELEASE_ID: ${{ inputs.test_release_id }} PACKAGE_SIGNING: ${{ inputs.signing }} + PACKAGE_CACHE_NAMESPACE: ${{ inputs.cache_namespace }} + PACKAGE_BUILD_ROOT: ${{ inputs.build_root }} + PACKAGE_WINDOWS_COMPRESSION_LEVEL: ${{ inputs.compression_level }} steps: - name: Reset packaging checkout working-directory: ${{ runner.temp }} @@ -77,6 +96,20 @@ jobs: } node -e "const fs = require('node:fs'); fs.rmSync(process.argv[1], { recursive: true, force: true, maxRetries: 3 }); fs.mkdirSync(process.argv[1])" $workspace if ($LASTEXITCODE -ne 0) { throw 'Checkout cleanup failed' } + - name: Checkout workflow helpers + uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + ref: ${{ github.workflow_sha }} + sparse-checkout: apps/desktop/scripts + - name: Stage workflow helpers + run: | + $helpers = Join-Path $env:RUNNER_TEMP "packaging-helpers-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" + New-Item -ItemType Directory -Path $helpers -ErrorAction Stop | Out-Null + foreach ($name in @('windows-packaging-priority.ps1', 'windows-build-workspace.mjs')) { + Copy-Item -LiteralPath (Join-Path 'apps/desktop/scripts' $name) -Destination $helpers -ErrorAction Stop + } + "PACKAGE_CI_HELPERS=$helpers" >> $env:GITHUB_ENV - uses: actions/checkout@v7.0.1 id: checkout with: @@ -107,16 +140,50 @@ jobs: - uses: actions/setup-node@v7.0.0 with: node-version: '24' - - name: Install locked dependencies + - name: Select packaging workspace + id: build_workspace + env: + PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }} run: | + if (!$env:PACKAGE_BUILD_ROOT) { + "directory=$env:GITHUB_WORKSPACE" >> $env:GITHUB_OUTPUT + } else { + node "$env:PACKAGE_CI_HELPERS/windows-build-workspace.mjs" + exit $LASTEXITCODE + } + - name: Configure persistent pnpm store + # PNPM_HOME belongs to this run; keep downloaded packages outside its temporary directory. + env: + DSH_DESKTOP_PACKAGE_CACHE_DIR: ${{ runner.tool_cache }}/dsh-desktop-package-cache + run: | + $storeRoot = Join-Path ([IO.Path]::GetPathRoot($env:GITHUB_WORKSPACE)) '.pnpm-store' + $namespace = $env:PACKAGE_CACHE_NAMESPACE + if ($namespace) { + if ($namespace -cnotmatch '^[a-z0-9][a-z0-9-]{0,63}\z') { throw 'Cache namespace must contain 1-64 lowercase letters, digits or hyphens' } + if ($namespace -match '^(con|prn|aux|nul|com[1-9]|lpt[1-9])$') { throw 'Cache namespace cannot be a Windows device name' } + $storeRoot = Join-Path $storeRoot $namespace + $env:DSH_DESKTOP_PACKAGE_CACHE_DIR = Join-Path $env:DSH_DESKTOP_PACKAGE_CACHE_DIR $namespace + } + "DSH_DESKTOP_PACKAGE_CACHE_DIR=$env:DSH_DESKTOP_PACKAGE_CACHE_DIR" >> $env:GITHUB_ENV + "PNPM_CONFIG_STORE_DIR=$storeRoot" >> $env:GITHUB_ENV + - name: Install locked dependencies + working-directory: ${{ steps.build_workspace.outputs.directory }} + run: | + & "$env:PACKAGE_CI_HELPERS/windows-packaging-priority.ps1" -BestEffort + node -e "const os=require('node:os'); console.log(JSON.stringify({node:process.version,availableParallelism:os.availableParallelism(),logicalCpus:os.cpus().length,totalMemoryBytes:os.totalmem(),freeMemoryBytes:os.freemem()}))" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + pnpm store path + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } pnpm install --frozen-lockfile exit $LASTEXITCODE - name: Validate preset and resolve build version id: settings + working-directory: ${{ steps.build_workspace.outputs.directory }} env: PACKAGE_BUILD_VERSION: ${{ inputs.build_version }} run: node apps/desktop/scripts/prepare-windows-ci.mjs - name: Check packaging configuration and toolchain + working-directory: ${{ steps.build_workspace.outputs.directory }} env: PACKAGE_VERSION: ${{ steps.settings.outputs.version }} run: | @@ -125,15 +192,23 @@ jobs: pnpm @packageArgs exit $LASTEXITCODE - name: Build installer and verify packaged runtime + working-directory: ${{ steps.build_workspace.outputs.directory }} env: PACKAGE_VERSION: ${{ steps.settings.outputs.version }} + PACKAGE_BUILD_TEMP: ${{ steps.build_workspace.outputs.temporaryDirectory }} run: | + & "$env:PACKAGE_CI_HELPERS/windows-packaging-priority.ps1" -BestEffort + if ($env:PACKAGE_BUILD_TEMP) { + $env:TEMP = $env:PACKAGE_BUILD_TEMP + $env:TMP = $env:PACKAGE_BUILD_TEMP + } $packageArgs = @('run', 'package:desktop:win:x64', '--build-version', $env:PACKAGE_VERSION) if ($env:PACKAGE_SIGNING -eq 'unsigned') { $packageArgs += '--unsigned' } pnpm @packageArgs exit $LASTEXITCODE - name: Retain complete package outside the checkout id: retained + working-directory: ${{ steps.build_workspace.outputs.directory }} env: PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }} PACKAGE_VERSION: ${{ steps.settings.outputs.version }} @@ -144,7 +219,7 @@ jobs: with: name: windows-package-logs-${{ github.run_id }}-${{ github.run_attempt }} include-hidden-files: true - path: apps/desktop/.desktop-build/packaging-runs/ + path: ${{ steps.build_workspace.outputs.directory || github.workspace }}/apps/desktop/.desktop-build/packaging-runs/ if-no-files-found: warn retention-days: 14 - name: Retain verified unsigned installer @@ -152,6 +227,7 @@ jobs: uses: actions/upload-artifact@v7.0.1 with: name: windows-x64-unsigned-${{ steps.settings.outputs.version }}-${{ github.run_id }}-${{ github.run_attempt }} + compression-level: 0 include-hidden-files: true path: ${{ steps.retained.outputs.directory }}/* if-no-files-found: error @@ -161,7 +237,13 @@ jobs: uses: actions/upload-artifact@v7.0.1 with: name: windows-x64-signed-${{ steps.settings.outputs.version }}-${{ github.run_id }}-${{ github.run_attempt }} + compression-level: 0 include-hidden-files: true path: ${{ steps.retained.outputs.directory }}/* if-no-files-found: error retention-days: 14 + - name: Remove isolated packaging workspace + if: success() && inputs.build_root != '' + env: + PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }} + run: node "$env:PACKAGE_CI_HELPERS/windows-build-workspace.mjs" --remove diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 51737ac1ed..1295efff31 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -75,6 +75,7 @@ External packages installed for runtime use or embedded in distributed Host or b | [`@xterm/xterm`](https://github.com/xtermjs/xterm.js) | MIT | | [`@yarnpkg/parsers`](https://github.com/yarnpkg/berry) | BSD-2-Clause | | [`acorn`](https://github.com/acornjs/acorn) | MIT | +| [`acorn-walk`](https://github.com/acornjs/acorn) | MIT | | [`ajv`](https://github.com/ajv-validator/ajv) | MIT | | [`anser`](https://github.com/IonicaBizau/anser) | MIT | | [`big.js`](https://github.com/MikeMcl/big.js) | MIT | @@ -112,6 +113,7 @@ External packages installed for runtime use or embedded in distributed Host or b | [`micromark-factory-space`](https://github.com/micromark/micromark/tree/main/packages/micromark-factory-space) | MIT | | [`micromark-util-character`](https://github.com/micromark/micromark/tree/main/packages/micromark-util-character) | MIT | | [`micromark-util-classify-character`](https://github.com/micromark/micromark/tree/main/packages/micromark-util-classify-character) | MIT | +| [`micromark-util-decode-string`](https://github.com/micromark/micromark/tree/main/packages/micromark-util-decode-string) | MIT | | [`micromark-util-sanitize-uri`](https://github.com/micromark/micromark/tree/main/packages/micromark-util-sanitize-uri) | MIT | | [`micromark-util-symbol`](https://github.com/micromark/micromark/tree/main/packages/micromark-util-symbol) | MIT | | [`mime`](https://github.com/broofa/mime) | MIT | diff --git a/apps/cli/package.json b/apps/cli/package.json index f6d4f804f1..e372b13247 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh", "description": "dsh CLI: profile launch, plugin management, and configuration inspection", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, @@ -107,7 +107,8 @@ "@deepseek-ai/dsh-experimental-session-search": "workspace:*", "@deepseek-ai/dsh-experimental-tool-worktree": "workspace:*", "@deepseek-ai/dsh-cua-bundle": "workspace:*", - "@deepseek-ai/dsh-experimental-plugin-market-bundle": "workspace:*" + "@deepseek-ai/dsh-experimental-plugin-market-bundle": "workspace:*", + "@deepseek-ai/dsh-personalized-recommendations": "workspace:*" }, "devDependencies": { "@deepseek-ai/dsh-skill-badge": "workspace:*", diff --git a/apps/cli/tests/built-bin.e2e.ts b/apps/cli/tests/built-bin.e2e.ts index 7a80f1c760..a97d158697 100644 --- a/apps/cli/tests/built-bin.e2e.ts +++ b/apps/cli/tests/built-bin.e2e.ts @@ -443,6 +443,9 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)', }, SPAWN_TIMEOUT_MS + 30_000) it('serves the SDK protocol with an absolute-path overlay plugin and exits after shutdown', async () => { + // On the official endpoint the route requests its model listing with this key; + // the loopback mock keeps the run offline and records any model call. + const server = await startMockLlmServer({ sequence: ['success'] }) const home = mkdtempSync(join(tmpdir(), 'dsh-built-sdk-')) const pluginPath = join(home, 'plugin #100%.mjs') const marker = join(home, 'plugin-loaded') @@ -465,6 +468,7 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)', DSH_HOME: home, DSH_TELEMETRY_DISABLED: '1', DEEPSEEK_API_KEY: 'built-sdk-profile-no-call', + DEEPSEEK_BASE_URL: server.baseURL, }, extendEnv: false, }) @@ -504,10 +508,12 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)', expect(result.signal, stderr).toBeUndefined() expect(result.exitCode, stderr).toBe(0) expect(stderr).toBe('') + expect(server.requests).toEqual([]) expect(readFileSync(marker, 'utf8')).toBe('loaded') } finally { child.kill('SIGKILL') await child + await server.close() rmSync(home, { recursive: true, force: true }) } }, SPAWN_TIMEOUT_MS + 30_000) diff --git a/apps/cli/tests/desktop-host.e2e.ts b/apps/cli/tests/desktop-host.e2e.ts index 615270aae0..c1f42d812d 100644 --- a/apps/cli/tests/desktop-host.e2e.ts +++ b/apps/cli/tests/desktop-host.e2e.ts @@ -29,6 +29,7 @@ it.each([false, true])('settles startup after parent IPC disconnect (boot failur writeFileSync(join(root, 'package.json'), '{"type":"module"}') writeFileSync(join(modules, 'dsh-app-boot', 'package.json'), '{"type":"module","exports":"./index.js"}') writeFileSync(join(modules, 'dsh-app-boot', 'index.js'), ` + export class StartupError extends Error {} export const loadProfileDirectory = () => ({ skippedBundles: [] }); export const reportSkippedBundles = () => {}; export const loadLayeredEnv = () => ({}); @@ -64,7 +65,11 @@ it.each([false, true])('settles startup after parent IPC disconnect (boot failur const boot = await new Promise<{ packageManager: { command: string; args: string[]; env: Record } }>((resolve, reject) => { - child.once('message', resolve) + child.on('message', (message) => { + if (typeof message === 'object' && message !== null && 'type' in message && message.type === 'booting' && 'packageManager' in message) { + resolve(message as { packageManager: { command: string; args: string[]; env: Record } }) + } + }) child.once('error', reject) child.once('exit', (code) => { reject(new Error(`Host exited before booting: ${String(code)} ${stderr}`)) }) }) diff --git a/apps/cli/tests/profiles/acp/tests/stdout.expected.e2e.ts b/apps/cli/tests/profiles/acp/tests/stdout.expected.e2e.ts index 9468f874cc..c97e093237 100644 --- a/apps/cli/tests/profiles/acp/tests/stdout.expected.e2e.ts +++ b/apps/cli/tests/profiles/acp/tests/stdout.expected.e2e.ts @@ -1,4 +1,4 @@ -/** Account catalog diagnostics preserve the shipped ACP profile's JSON-RPC stream. */ +/** Account catalog and MCP resource-listing diagnostics keep the shipped ACP profile's stdout JSON-RPC only. */ import { once } from 'node:events' import { mkdir, mkdtemp, writeFile } from 'node:fs/promises' import { createServer } from 'node:http' @@ -6,10 +6,22 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' +import { startMockLlmServer } from '@deepseek-ai/dsh-llm-mock-server' import { launchAcpTestAgent, type AgentUnderTest, type LaunchedAcpTestAgent } from '@deepseek-ai/dsh-session-snapshot' import { expect, it } from 'vitest' import { cleanupAcpExampleTest } from './cleanup.ts' +const repoRoot = fileURLToPath(new URL('../../../../../../', import.meta.url)) +const binScript = join(repoRoot, 'apps/cli/src/bin.ts') +const tsconfigPath = join(repoRoot, 'tsconfig.json') + +/** Parse every stdout line as a JSON-RPC frame; a diagnostic line fails the parse with its leading text. */ +function jsonRpcFrames(launched: LaunchedAcpTestAgent): Record[] { + const frames = launched.rawStdout().trim().split('\n').map(line => JSON.parse(line) as Record) + for (const frame of frames) expect(frame).toMatchObject({ jsonrpc: '2.0' }) + return frames +} + it('keeps account model-listing diagnostics on stderr during API-key session creation', async () => { const cwd = await mkdtemp(join(tmpdir(), 'dsh-acp-stdout-')) const token = 'acp-catalog-fixture-token' @@ -100,3 +112,48 @@ it('keeps account model-listing diagnostics on stderr during API-key session cre if (failures.length > 0) throw new AggregateError(failures, 'ACP catalog test cleanup failed') } }) + +it('keeps MCP resource-listing diagnostics off stdout for a tools-only client server', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'dsh-acp-stdout-')) + const llm = await startMockLlmServer({ + sequence: ['tool_call_success', 'success'], + toolName: 'list_mcp_resources', + toolArguments: JSON.stringify({ server: 'fixture' }), + }) + let launched: LaunchedAcpTestAgent | undefined + try { + const configPath = join(cwd, 'mcp.patch.yml') + await writeFile(configPath, JSON.stringify([ + { id: 'llm-deepseek', config: { baseURL: llm.baseURL, models: [{ id: 'fixture-api-key-model' }] } }, + { id: 'acp', config: { provider: 'deepseek-official', model: 'fixture-api-key-model' } }, + { id: 'session-persistence-jsonl', config: { root: join(cwd, 'sessions'), compression: 'none' } }, + ]) + '\n') + launched = launchAcpTestAgent({ + agent: { binScript, configPath, profile: 'acp', tsconfigPath }, + cwd, + env: { DEEPSEEK_API_KEY: 'acp-fixture-api-key', DEEPSEEK_BASE_URL: llm.baseURL, DSH_TELEMETRY_DISABLED: '1' }, + }) + await launched.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + // The fixture server advertises only the tools capability. + const mcpServer = join(repoRoot, 'packages/mcp/mcp-client/tests/fixture-server.ts') + const created = await launched.client.newSession({ + cwd, mcpServers: [{ name: 'fixture', command: process.execPath, args: [mcpServer], env: [] }], + }) + await expect(launched.client.prompt({ + sessionId: created.sessionId, + prompt: [{ type: 'text', text: 'list the fixture resources' }], + })).resolves.toEqual({ stopReason: 'end_turn' }) + expect(launched.updates).toContainEqual(expect.objectContaining({ sessionUpdate: 'tool_call_update', status: 'completed' })) + await launched.client.closeSession({ sessionId: created.sessionId }) + await launched.close() + + expect(launched.child.exitCode).toBe(0) + expect(llm.requests.map(request => request.behavior)).toEqual(['tool_call_success', 'success']) + expect(jsonRpcFrames(launched).length).toBeGreaterThanOrEqual(5) + } finally { + const cleanup = await Promise.allSettled([cleanupAcpExampleTest(launched, cwd), llm.close()]) + const failures: unknown[] = [] + for (const result of cleanup) if (result.status === 'rejected') failures.push(result.reason) + if (failures.length > 0) throw new AggregateError(failures, 'ACP MCP test cleanup failed') + } +}) diff --git a/apps/cli/tests/profiles/headless/tests/expected/goal-tools/stream-json.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/goal-tools/stream-json.expected.jsonl index ab06b02706..c54f84df0b 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/goal-tools/stream-json.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/goal-tools/stream-json.expected.jsonl @@ -4,7 +4,7 @@ {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"Probe strict-schema fillers against missing-goal revision 1, then create a durable goal to finish the snapshot proof and inspect it."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} -{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} +{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/context","seq":11,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title","seq":12,"time":0,"data":{"title":"Probe strict-schema fillers against miss","messageSeqs":[8],"source":{"kind":"fallback"}}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl index 6ea0d43a17..e747f996ad 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl @@ -4,7 +4,7 @@ {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"say pong"}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} -{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} +{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":"{{tools}}"},"reason":"initial"}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/context","seq":11,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":1000000}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title","seq":12,"time":0,"data":{"title":"say pong","messageSeqs":[8],"source":{"kind":"fallback"}}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/missing-credential/stream-json.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/missing-credential/stream-json.expected.jsonl index f24d221b96..bc7c728199 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/missing-credential/stream-json.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/missing-credential/stream-json.expected.jsonl @@ -4,7 +4,7 @@ {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"say pong"}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} -{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} +{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":"{{tools}}"},"reason":"initial"}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/context","seq":11,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":1000000}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title","seq":12,"time":0,"data":{"title":"say pong","messageSeqs":[8],"source":{"kind":"fallback"}}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/provider-retry/stream-json.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/provider-retry/stream-json.expected.jsonl index a667224c5f..5792ae3774 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/provider-retry/stream-json.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/provider-retry/stream-json.expected.jsonl @@ -4,7 +4,7 @@ {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"retry the transient provider failure"}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} -{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} +{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/context","seq":11,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title","seq":12,"time":0,"data":{"title":"retry the transient provider failure","messageSeqs":[8],"source":{"kind":"fallback"}}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/semantic-checkpoint/session.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/semantic-checkpoint/session.expected.jsonl index 2afe21d157..11ae2ec827 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/semantic-checkpoint/session.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/semantic-checkpoint/session.expected.jsonl @@ -18,7 +18,7 @@ {"type":"step/start","data":{"turn":2,"step":1}} {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"Continue safely from the interrupted operation."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial","startsSeries":true}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Perform one side-effecting remote mutati","messageSeqs":[3],"source":{"kind":"fallback"}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-diagnostic/parent.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-diagnostic/parent.expected.jsonl index 5ea5179b2e..9da1c6379a 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-diagnostic/parent.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-diagnostic/parent.expected.jsonl @@ -16,7 +16,7 @@ {"type":"step/start","data":{"turn":2,"step":1}} {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"Call list_agents once and report what it shows."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial","startsSeries":true}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Start a background job.","messageSeqs":[3],"source":{"kind":"fallback"}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl index 3b3a9e5c7b..3f3dee9c95 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl @@ -16,7 +16,7 @@ {"type":"step/start","data":{"turn":2,"step":1}} {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"Delegate the write probe to a subagent."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"resume","startsSeries":true}} {"type":"developer/message","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"bash"},{"type":"tool-addition","toolName":"create_goal"},{"type":"tool-addition","toolName":"edit"},{"type":"tool-addition","toolName":"get_goal"},{"type":"tool-addition","toolName":"glob"},{"type":"tool-addition","toolName":"grep"},{"type":"tool-addition","toolName":"interrupt_agent"},{"type":"tool-addition","toolName":"job_kill"},{"type":"tool-addition","toolName":"job_list"},{"type":"tool-addition","toolName":"job_output"},{"type":"tool-addition","toolName":"list_agents"},{"type":"tool-addition","toolName":"read"},{"type":"tool-addition","toolName":"read_image"},{"type":"tool-addition","toolName":"send_message"},{"type":"tool-addition","toolName":"skill"},{"type":"tool-addition","toolName":"subagent"},{"type":"tool-addition","toolName":"subagent_fork"},{"type":"tool-addition","toolName":"todo_write"},{"type":"tool-addition","toolName":"update_goal"},{"type":"tool-addition","toolName":"web_fetch"},{"type":"tool-addition","toolName":"web_search"},{"type":"tool-addition","toolName":"workflow"},{"type":"tool-addition","toolName":"working_directory"},{"type":"tool-addition","toolName":"write"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":18},"surfaceOp":"append"} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/stream-json.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/stream-json.expected.jsonl index f06a75700f..441cab1aa2 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/stream-json.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/stream-json.expected.jsonl @@ -4,7 +4,7 @@ {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"Start one continuable subagent and acknowledge its completion notice. Do not call list_agents or send_message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} -{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} +{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/context","seq":11,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title","seq":12,"time":0,"data":{"title":"Start one continuable subagent and","messageSeqs":[8],"source":{"kind":"fallback"}}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/workspace-context-resume/offline-edit/session.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/workspace-context-resume/offline-edit/session.expected.jsonl index 5ed8464fb7..cbb82cb603 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/workspace-context-resume/offline-edit/session.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/workspace-context-resume/offline-edit/session.expected.jsonl @@ -17,7 +17,7 @@ {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"Acknowledge the current workspace instruction."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nUpdated instructions from: AGENTS.md\n\nThis file changed after it was loaded. Use the following content instead of the previously loaded instructions from this file.\n\nNew workspace instruction after offline edit.\n\n"}],"source":{"kind":"agent-instructions","form":"instructions","changes":[{"action":"replace","scope":".\u0000AGENTS.md","path":"AGENTS.md","digest":"d8375b516f158718bd3463bc8eb7ed42c011b29f"}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial","startsSeries":true}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Remember the workspace instruction.","messageSeqs":[3],"source":{"kind":"fallback"}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/workspace-context-resume/precedence-change/session.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/workspace-context-resume/precedence-change/session.expected.jsonl index f52d5f06e9..3bd9c55f95 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/workspace-context-resume/precedence-change/session.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/workspace-context-resume/precedence-change/session.expected.jsonl @@ -17,7 +17,7 @@ {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"Acknowledge the current workspace instruction."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThis complete workspace instruction baseline replaces all earlier workspace instruction baselines. The following workspace instructions may be relevant to your work. Use them as guidance when applicable. More specific instructions take precedence over broader ones. They do not override system, developer, or direct user instructions.\n\nInstructions from: AGENTS.md\n\nCurrent AGENTS rule.\n\n\nInstructions from: CLAUDE.md\n\nCurrent CLAUDE rule.\n\n"}],"source":{"kind":"agent-instructions","form":"instructions","baseline":true,"baselineIdentity":"{\"projectRoot\":\"\",\"projectRootMarkers\":[\".git\"],\"maxBytes\":65536,\"maxSourceBytes\":1048576,\"instructionFileCandidates\":[\"AGENTS.md\",\"CLAUDE.md\"],\"localInstructionFileCandidates\":[\"AGENTS.local.md\",\"CLAUDE.local.md\"]}","changes":[{"action":"set","scope":".\u0000AGENTS.md","path":"AGENTS.md","digest":"7f53d2327837129750aef117f9754a001c46cf68"},{"action":"set","scope":".\u0000CLAUDE.md","path":"CLAUDE.md","digest":"5b1e9e3fd759eee6b43ceff899e47fb10c64701a"}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial","startsSeries":true}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Remember the workspace instruction.","messageSeqs":[3],"source":{"kind":"fallback"}}} diff --git a/apps/cli/tests/profiles/subagent-preset-switch.overlay.yml b/apps/cli/tests/profiles/subagent-preset-switch.overlay.yml new file mode 100644 index 0000000000..0222357267 --- /dev/null +++ b/apps/cli/tests/profiles/subagent-preset-switch.overlay.yml @@ -0,0 +1,27 @@ +- insert: + - id: preset-delegate-a + name: '@deepseek-ai/dsh-agent-preset' + config: + id: delegate-a + plugins: + - name: '@deepseek-ai/dsh-tool-subagent' + config: + provider: spawn + allowedAgentPresets: [standard, ptc, minimal] + - name: '@deepseek-ai/dsh-tool-subagent' + config: + provider: fork + toolName: subagent_fork + - id: preset-delegate-b + name: '@deepseek-ai/dsh-agent-preset' + config: + id: delegate-b + plugins: + - name: '@deepseek-ai/dsh-tool-subagent' + config: + provider: spawn + allowedAgentPresets: [standard, ptc, minimal] + - name: '@deepseek-ai/dsh-tool-subagent' + config: + provider: fork + toolName: subagent_fork diff --git a/apps/cli/tests/web-agent-presets.e2e.ts b/apps/cli/tests/web-agent-presets.e2e.ts index b06fd1b4e4..baac502987 100644 --- a/apps/cli/tests/web-agent-presets.e2e.ts +++ b/apps/cli/tests/web-agent-presets.e2e.ts @@ -355,6 +355,49 @@ describe('the shipped Web composition', () => { } }) + it.each(['standard', 'ptc'] as const)('retains delegation tools after repeated preset round trips ending in %s', async (target) => { + const adapter = new MinimalCompactionAdapter() + const unregister = ctx.llm.registerAdapter(['preset-round-trip'], adapter) + onTestFinished(unregister) + const direct = await ctx.agents.create({ + sessionId: SessionId(`preset-direct-${target}-${randomUUID()}`), + agentOptions: { provider: 'preset-round-trip', model: 'preset-round-trip' }, + setup: agentCtx => ctx.agentPresets.mount(agentCtx, target).then(() => undefined), + }) + onTestFinished(() => direct.dispose()) + const handle = await ctx.agents.create({ + sessionId: SessionId(`preset-round-trip-${target}-${randomUUID()}`), + agentOptions: { provider: 'preset-round-trip', model: 'preset-round-trip' }, + setup: agentCtx => ctx.agentPresets.mount(agentCtx, target).then(() => undefined), + }) + onTestFinished(() => handle.dispose()) + const { agent } = handle + const other = target === 'standard' ? 'ptc' : 'standard' + for (const preset of [other, target, other, target]) { + await ctx.agentPresets.select(agent, preset) + expect(toolNames(ctx, agent)).toEqual(expect.arrayContaining(['subagent', 'subagent_fork'])) + } + expect(ctx.tools.schemas(agent)).toEqual(ctx.tools.schemas(direct.agent)) + const assembly = await ctx.systemPrompt.assemble({ scope: agent }) + if (target === 'ptc') { + const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text ?? '' + expect(sdk).toContain('subagent:') + expect(sdk).toContain('subagent_fork:') + } + direct.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Reply with Ready.' }], source: { kind: 'user' } })) + await direct.agent.whenIdle() + const directRequest = adapter.requests.find(request => request.purpose === undefined) + expect(directRequest).toBeDefined() + adapter.requests.length = 0 + agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Reply with Ready.' }], source: { kind: 'user' } })) + await agent.whenIdle() + const request = adapter.requests.find(request => request.purpose === undefined) + expect(request).toBeDefined() + expect(request?.tools).toEqual(directRequest?.tools) + const header = agent.session.snapshotEvents().find(event => event.type === 'request/header') + expect(header?.data.header.tools).toEqual(request?.tools) + }) + it('composes the exact RL prompt and persistent shell from `minimal`', async () => { const handle = await ctx.agents.create({ sessionId: SessionId('preset-minimal'), @@ -683,6 +726,41 @@ describe('the shipped Web composition', () => { }) }) +describe('preset-selected delegation through the Web Loader', () => { + it('exposes configured delegation tools when each preset switch resolves', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-delegation-switch-')) + try { + const configured = await bootWeb(root, loadOverlayPatches('delegation-switch', + join(REPO_ROOT, 'apps/cli/tests/profiles/subagent-preset-switch.overlay.yml'))) + try { + const adapter = new MinimalCompactionAdapter() + configured.llm.registerAdapter(['preset-switch'], adapter) + const { agent } = await configured.agents.create({ + sessionId: SessionId(`configured-switch-${randomUUID()}`), + agentOptions: { provider: 'preset-switch', model: 'preset-switch' }, + setup: owner => configured.agentPresets.mount(owner, 'delegate-a').then(() => undefined), + }) + const views: Array<{ preset: string; names: string[] }> = [] + for (const preset of ['delegate-b', 'delegate-a', 'delegate-b', 'delegate-a', 'ptc', 'standard', 'delegate-a']) { + await configured.agentPresets.select(agent, preset) + views.push({ preset, names: toolNames(configured, agent) }) + } + agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Reply with Ready.' }], source: { kind: 'user' } })) + await agent.whenIdle() + for (const { preset, names } of views) { + expect(names, `tools after selecting ${preset}`).toEqual(expect.arrayContaining(['subagent', 'subagent_fork'])) + } + const request = adapter.requests.find(request => request.purpose === undefined) + expect(request?.tools?.map(tool => tool.name)).toEqual(expect.arrayContaining(['subagent', 'subagent_fork'])) + expect(request?.tools?.find(tool => tool.name === 'subagent')) + .toHaveProperty('parameters.properties.agent_preset.enum', ['standard', 'ptc', 'minimal']) + const header = agent.session.snapshotEvents().find(event => event.type === 'request/header') + expect(header?.data.header.tools).toEqual(request?.tools) + } finally { await configured.fiber.dispose() } + } finally { await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }) } + }) +}) + describe.each(['web', 'desktop'] as const)('%s native subagent bundles', (surface) => { const products = ['codex', 'claude-code'] as const type Product = typeof products[number] diff --git a/apps/cli/tsconfig.json b/apps/cli/tsconfig.json index 254a5a4f73..c52e4793e2 100644 --- a/apps/cli/tsconfig.json +++ b/apps/cli/tsconfig.json @@ -21,7 +21,7 @@ "path": "../../packages/boot/app-boot" }, { - "path": "../../packages/boot/official-bundles" + "path": "../../packages/util/official-bundles" }, { "path": "../../packages/boot/cmdline" diff --git a/apps/desktop-host/package.json b/apps/desktop-host/package.json index f6e0f4c73a..ef3bfd7af1 100644 --- a/apps/desktop-host/package.json +++ b/apps/desktop-host/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-desktop-host", "description": "Private Node-mode host process for the Electron desktop application", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "private": true, "license": "MIT", "type": "module", @@ -25,7 +25,8 @@ "@deepseek-ai/dsh-tool-workspace-dependencies": "workspace:*", "@deepseek-ai/dsh-skill-office": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", - "@deepseek-ai/dsh-workspace": "workspace:*" + "@deepseek-ai/dsh-workspace": "workspace:*", + "@deepseek-ai/dsh-plugin-manager": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis-plugin-loader": "workspace:~", diff --git a/apps/desktop-host/src/fatal-diagnostic.ts b/apps/desktop-host/src/fatal-diagnostic.ts new file mode 100644 index 0000000000..e72533dae0 --- /dev/null +++ b/apps/desktop-host/src/fatal-diagnostic.ts @@ -0,0 +1,59 @@ +/** Bounded Host failure details sent to the Desktop crash reporter. */ + +import { inspect } from 'node:util' +import { StartupError } from '@deepseek-ai/dsh-app-boot' + +/** Maximum characters carried by one fatal diagnostic, including its truncation notice. */ +export const MAX_FATAL_DIAGNOSTIC_CHARS = 64 * 1024 + +/** Original-error budget when startup metadata needs space in the same report. */ +const MAX_ORIGINAL_ERROR_CHARS = 8 * 1024 + +/** Startup entry details leave room for composition and provider observations. */ +const MAX_STARTUP_ENTRY_CHARS = 8 * 1024 + +/** + * Render the original error and explicitly selected startup metadata. + * Selected metadata excludes configuration values and arbitrary startup logger arguments. + * @param error - Failure received by the Host entry point. + * @returns Bounded text with an explicit notice when the report is shortened. + */ +export function formatFatalDiagnostic(error: unknown): string { + const original = inspect(error, { depth: 4, maxArrayLength: 50 }) + const sections: string[] = [] + const seen = new Set() + function visit(value: unknown): void { + if (!(value instanceof Error) || seen.has(value)) return + seen.add(value) + if (value instanceof StartupError) { + if (value.startup !== undefined) { + sections.push(`Configuration file: ${value.startup.configurationPath}`) + } + const entries = inspect(value.entries, { depth: 6, maxArrayLength: null, maxStringLength: 4096 }) + sections.push('--- startup entries ---', entries.length <= MAX_STARTUP_ENTRY_CHARS ? entries + : `${entries.slice(0, MAX_STARTUP_ENTRY_CHARS).replace(/[\uD800-\uDBFF]$/u, '')}\n… (startup entries truncated at ${MAX_STARTUP_ENTRY_CHARS} characters)`) + if (value.composition !== undefined) { + const { plugins, services, omittedPlugins, omittedServices } = value.composition + const sources = [...new Set(plugins.map(plugin => plugin.source))] + sections.push('--- startup composition ---', + 'Provider lists contain observed registrations only; an empty list means the provider is unknown.', + 'Source identifies the Loader tree, not necessarily the overriding patch.', + `Omitted plugin rows: ${omittedPlugins}; omitted missing-service observations: ${omittedServices}.`, + '--- missing services ---', ...services.map(service => JSON.stringify(service)), + '--- plugin sources (sourceIndex) ---', ...sources.map((source, index) => JSON.stringify({ index, source })), + '--- plugins (inactive first) ---', ...plugins.map(({ source, ...plugin }) => JSON.stringify({ ...plugin, sourceIndex: sources.indexOf(source) }))) + } else { + sections.push('Startup composition diagnostic unavailable.') + } + } + visit(value.cause) + if (value instanceof AggregateError) value.errors.forEach(visit) + } + visit(error) + sections.unshift(sections.length === 0 || original.length <= MAX_ORIGINAL_ERROR_CHARS ? original + : `${original.slice(0, MAX_ORIGINAL_ERROR_CHARS).replace(/[\uD800-\uDBFF]$/u, '')}\n… (original error truncated at ${MAX_ORIGINAL_ERROR_CHARS} characters)`) + const text = sections.join('\n') + if (text.length <= MAX_FATAL_DIAGNOSTIC_CHARS) return text + const notice = `\n… (Host diagnostic truncated at ${MAX_FATAL_DIAGNOSTIC_CHARS} characters)` + return text.slice(0, MAX_FATAL_DIAGNOSTIC_CHARS - notice.length).replace(/[\uD800-\uDBFF]$/u, '') + notice +} diff --git a/apps/desktop-host/src/index.ts b/apps/desktop-host/src/index.ts index 3109537b63..31bbbffe15 100644 --- a/apps/desktop-host/src/index.ts +++ b/apps/desktop-host/src/index.ts @@ -1,7 +1,9 @@ /** Launch the Desktop profile through the Web application and report its URL to Electron. */ import { delimiter, join } from 'node:path' -import { inspect } from 'node:util' +import { randomUUID } from 'node:crypto' +import type { PluginOperationRunId } from '@deepseek-ai/dsh-plugin-manager/diagnostic' +import { formatFatalDiagnostic } from './fatal-diagnostic.ts' import { loadLayeredEnv, loadProfileDirectory, reportSkippedBundles } from '@deepseek-ai/dsh-app-boot' import { runProfile } from '@deepseek-ai/dsh/profile-boot' import type {} from '@deepseek-ai/dsh-client-connection' @@ -15,8 +17,11 @@ import { installDesktopUpdateTaskControl } from './update-tasks.ts' import { installDesktopQuitInspection } from './quit-inspection.ts' import { installPlatformSessionPublisher } from './platform-session.ts' import { installOfficeEngineResolution } from './office-engine.ts' +import { installOperationDiagnostics } from './operation-diagnostics.ts' async function main(): Promise { + const runId = randomUUID() as PluginOperationRunId + if (process.connected) process.send?.({ type: 'starting', runId }, (error) => { if (error !== null) console.error(error) }) const runtimeDir = process.argv[2] as string const projectDir = process.argv[3] as string installOfficeEngineResolution(runtimeDir) @@ -123,6 +128,7 @@ async function main(): Promise { }) process.once('disconnect', () => { void stop() }) const { ctx } = await application + installOperationDiagnostics(ctx, record => send({ type: 'plugin-operation', record }), 32, runId) control.updateTasks = installDesktopUpdateTaskControl(ctx) control.quitInspection = installDesktopQuitInspection(ctx) await ctx.plugin(desktopOffice, { @@ -137,16 +143,13 @@ async function main(): Promise { if (process.connected) process.send?.({ type: 'ready', url, injections: ctx.webServer.collectIndexInjections(ctx.connection.browserPeer) }, (error) => { if (error !== null) console.error(error) }) } -/** Upper bound of the startup diagnostic carried over IPC; the head holds the message and stack. */ -const MAX_FATAL_DIAGNOSTIC_CHARS = 64 * 1024 - if (import.meta.main) { main().catch((error: unknown) => { const message = error instanceof Error ? error.message : String(error) // The shell receives the complete inspected error here, not through stderr: // stderr bytes and this IPC message race, and the shell reports the first // failure it sees. - const diagnostic = inspect(error, { depth: 4, maxArrayLength: 50 }).slice(0, MAX_FATAL_DIAGNOSTIC_CHARS) + const diagnostic = formatFatalDiagnostic(error) if (process.connected) process.send?.({ type: 'fatal', message, diagnostic }, (error) => { if (error !== null) console.error(error) }) console.error(error) process.exitCode = 1 diff --git a/apps/desktop-host/src/operation-diagnostics.ts b/apps/desktop-host/src/operation-diagnostics.ts new file mode 100644 index 0000000000..3d29e97bc0 --- /dev/null +++ b/apps/desktop-host/src/operation-diagnostics.ts @@ -0,0 +1,34 @@ +/** Bounded delivery of management facts to the shell which owns durable diagnostics. */ +import type { Context } from '@deepseek-ai/cordis' +import { parsePluginOperationRecord, type PluginOperationRecord, type PluginOperationRunId } from '@deepseek-ai/dsh-plugin-manager/diagnostic' + +/** + * Observe manager operations after Host startup, with bounded concurrent IPC deliveries. + * @param ctx - Context owning the subscription and its pending deliveries. + * @param send - IPC transport promise which settles when delivery succeeds or fails. + * @param maxPending - Maximum number of outstanding deliveries; excess events are counted and omitted. + * @param runId - Host lifetime identity announced before profile startup. + */ +export function installOperationDiagnostics( + ctx: Context, send: (record: PluginOperationRecord) => Promise, maxPending: number, runId: PluginOperationRunId, +): void { + if (!Number.isSafeInteger(maxPending) || maxPending < 1) throw new RangeError('Invalid diagnostic delivery budget') + const pending = new Set>() + let dropped = 0 + let closed = false + ctx.on('plugin-manager/operation', (operation) => { + if (closed || pending.size >= maxPending) { dropped++; return } + const record = parsePluginOperationRecord({ runId, operation, transportDropped: dropped }) + if (record === undefined) { dropped++; return } + const delivery = Promise.resolve().then(async () => { + try { await send(record) } + catch (_error) { dropped++ /* IPC failure does not change the management operation. */ } + }) + pending.add(delivery) + void delivery.then(() => { pending.delete(delivery) }) + }) + ctx.effect(() => async () => { + closed = true + await Promise.allSettled(pending) + }) +} diff --git a/apps/desktop-host/tests/fatal-diagnostic.spec.ts b/apps/desktop-host/tests/fatal-diagnostic.spec.ts new file mode 100644 index 0000000000..1f41358300 --- /dev/null +++ b/apps/desktop-host/tests/fatal-diagnostic.spec.ts @@ -0,0 +1,105 @@ +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished } from 'vitest' +import { boot, StartupError } from '@deepseek-ai/dsh-app-boot' +import { formatFatalDiagnostic, MAX_FATAL_DIAGNOSTIC_CHARS } from '../src/fatal-diagnostic.ts' +import { renderCrashReport } from '../../desktop/src/crash-report.ts' + +it.each([ + ['import', 'throw new Error("qualification-import-failure")'], + ['initialize', 'export function apply() { throw new Error("qualification-initialize-failure", { cause: new Error("qualification-root-cause") }) }'], +])('retains real plugin %s failure evidence in the Desktop report after Loader disposal', async (stage, source) => { + const directory = await mkdtemp(join(tmpdir(), 'desktop-plugin-failure-')) + onTestFinished(async () => { await rm(directory, { recursive: true, force: true }) }) + await writeFile(join(directory, 'failure.mjs'), source + '\n') + const config = join(directory, 'cordis.yml') + await writeFile(config, '- id: agent-loop\n name: ./failure.mjs\n') + const failure: unknown = await boot('diagnostic-test', config).then(async (ctx) => { + await ctx.fiber.dispose() + throw new Error('Expected fixture plugin to fail startup') + }, (error: unknown) => error) + expect(failure).toBeInstanceOf(StartupError) + const diagnostic = formatFatalDiagnostic(failure) + const report = renderCrashReport({ source: 'host', phase: 'startup', error: failure, + hostDiagnostic: diagnostic, rendererConsole: [], operationHistoryPlanned: true, + time: new Date('2026-10-19T00:00:00Z'), + app: { name: 'qualification', version: 'test', platform: 'win32', arch: 'x64', electron: 'test', node: process.version, locale: 'zh-CN' }, + }) + expect(report).toContain(`qualification-${stage}-failure`) + expect(report).toContain('./failure.mjs') + expect(report).toContain('--- startup composition ---') + if (stage === 'initialize') expect(report).toContain('qualification-root-cause') +}) + +it('includes non-enumerable startup entries without copying arbitrary startup logger arguments', () => { + const error = new StartupError('required plugin did not activate', [{ + id: 'agent-loop', module: '@deepseek-ai/dsh-agent-loop', required: true, fiberState: undefined, + outcome: { kind: 'pending', missing: ['agents', 'sessions'] }, + }]) + error.startup = { configurationPath: '/profile/cordis.yml', messages: [{ + ts: 1, name: 'plugin', type: 'warn', args: ['private-plugin-output'], + }] } + const report = formatFatalDiagnostic(new Error('Host startup failed', { cause: error })) + expect(report).toContain('--- startup entries ---') + expect(report).toContain('@deepseek-ai/dsh-agent-loop') + expect(report).toContain("missing: [ 'agents', 'sessions' ]") + expect(report).toContain('Configuration file: /profile/cordis.yml') + expect(report).not.toContain('private-plugin-output') +}) + +it('marks truncation within the complete IPC budget and preserves Unicode', () => { + const error = new Error('😀'.repeat(MAX_FATAL_DIAGNOSTIC_CHARS)) + const report = formatFatalDiagnostic(error) + expect(report.length).toBeLessThanOrEqual(MAX_FATAL_DIAGNOSTIC_CHARS) + expect(report).toContain('Host diagnostic truncated at 65536 characters') + expect(report.isWellFormed()).toBe(true) +}) + +it('keeps missing-service evidence ahead of a truncated plugin inventory', () => { + const error = new StartupError('failure '.repeat(2000), [{ + id: 'waiting-entry', module: './waiting.mjs', required: true, fiberState: undefined, + outcome: { kind: 'pending', missing: ['agents'] }, + }]) + error.startup = { configurationPath: '/profile/critical-cordis.yml', messages: [] } + error.composition = { + services: [{ consumer: 'agent-loop', service: 'agents', providers: [] }], + plugins: Array.from({ length: 256 }, (_, index) => ({ + id: `plugin-${index}`, module: 'long-package-name'.repeat(30), version: '1.0.0', + state: 'disabled', source: '/profile/cordis.yml', missing: [], + })), + omittedPlugins: 3, omittedServices: 2, + } + const report = formatFatalDiagnostic(error) + expect(report).toContain('original error truncated at 8192 characters') + expect(report).toContain('Configuration file: /profile/critical-cordis.yml') + expect(report).toContain('waiting-entry') + expect(report).toContain('"service":"agents","providers":[]') + expect(report).toContain('Omitted plugin rows: 3; omitted missing-service observations: 2.') + expect(report).toContain('"source":"/profile/cordis.yml"') + expect(report).toContain('Host diagnostic truncated at 65536 characters') + expect(report.length).toBeLessThanOrEqual(MAX_FATAL_DIAGNOSTIC_CHARS) +}) + +it('terminates traversal through cyclic and aggregate causes', () => { + const error = new AggregateError([], 'cycle') + error.errors.push(error) + error.cause = error + expect(formatFatalDiagnostic(error)).toContain('cycle') +}) + +it.each(['many entries', 'long stack'])('retains composition evidence after %s', (scenario) => { + const failure = new Error('startup failure') + failure.stack = 'x'.repeat(70000) + const error = new StartupError('startup failed', scenario === 'long stack' + ? [{ id: 'failed', module: './failed.mjs', required: true, fiberState: undefined, outcome: { kind: 'failed', error: failure } }] + : Array.from({ length: 256 }, (_, index) => ({ id: `pending-${index}`, module: 'module'.repeat(60), required: true, fiberState: undefined, outcome: { kind: 'pending' as const, missing: ['agents'] } }))) + error.startup = { configurationPath: '/profile/cordis.yml', messages: [] } + error.composition = { plugins: [{ id: 'provider', module: 'example', version: '1.0.0', state: 'active', source: '/profile/cordis.yml', missing: [] }], services: [{ consumer: 'consumer', service: 'agents', providers: [] }], omittedPlugins: 0, omittedServices: 0 } + const report = formatFatalDiagnostic(error) + expect(report).toContain('Configuration file: /profile/cordis.yml') + expect(report).toContain('startup entries truncated') + expect(report).toContain('"service":"agents"') + expect(report).toContain('"version":"1.0.0"') + expect(report.length).toBeLessThanOrEqual(65536) +}) diff --git a/apps/desktop-host/tests/operation-diagnostics.spec.ts b/apps/desktop-host/tests/operation-diagnostics.spec.ts new file mode 100644 index 0000000000..fbf8f038f4 --- /dev/null +++ b/apps/desktop-host/tests/operation-diagnostics.spec.ts @@ -0,0 +1,41 @@ +import { Context } from '@deepseek-ai/cordis' +import type { PluginOperation } from '@deepseek-ai/dsh-plugin-manager/types' +import type { PluginOperationRunId } from '@deepseek-ai/dsh-plugin-manager/diagnostic' +import { expect, it, onTestFinished, vi } from 'vitest' +import { installOperationDiagnostics } from '../src/operation-diagnostics.ts' + +const operation: PluginOperation = { + id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9' as PluginOperation['id'], + time: '2026-10-19T00:00:00.000Z', reason: 'plugin', phase: 'started', target: 'managed', stage: 'enable', +} +const runId = 'c254ab28-97c9-4382-95e6-2db9c66f98c8' as PluginOperationRunId + +it('bounds outstanding deliveries and drains them on context disposal', async () => { + const ctx = new Context() + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + onTestFinished(async () => { release.resolve(undefined); await ctx.fiber.dispose() }) + const send = vi.fn(async () => { entered.resolve(undefined); await release.promise }) + installOperationDiagnostics(ctx, send, 1, runId) + ctx.emit('plugin-manager/operation', operation) + await entered.promise + for (let i = 0; i < 1000; i++) ctx.emit('plugin-manager/operation', operation) + expect(send).toHaveBeenCalledTimes(1) + expect(send).toHaveBeenCalledWith(expect.objectContaining({ runId })) + let stopped = false + const stopping = ctx.fiber.dispose().then(() => { stopped = true }) + await Promise.resolve(undefined) + expect(stopped).toBe(false) + release.resolve(undefined) + await stopping + ctx.emit('plugin-manager/operation', operation) + expect(send).toHaveBeenCalledTimes(1) +}) + +it('contains transport rejections during teardown', async () => { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + installOperationDiagnostics(ctx, async () => { throw new Error('disconnected') }, 1, runId) + ctx.emit('plugin-manager/operation', operation) + await expect(ctx.fiber.dispose()).resolves.toBeUndefined() +}) diff --git a/apps/desktop-host/tsconfig.json b/apps/desktop-host/tsconfig.json index 58eaa722db..7b88b7a2e8 100644 --- a/apps/desktop-host/tsconfig.json +++ b/apps/desktop-host/tsconfig.json @@ -31,6 +31,9 @@ { "path": "../../packages/credentials/deepseek-account" }, + { + "path": "../../packages/boot/plugin-manager" + }, { "path": "../../packages/fs/fs" }, diff --git a/apps/desktop/.env.macos.example b/apps/desktop/.env.macos.example index da5502ce5d..cc3d21f3e8 100644 --- a/apps/desktop/.env.macos.example +++ b/apps/desktop/.env.macos.example @@ -1,7 +1,7 @@ # Release configuration only; local --unsigned builds ignore this file. # Copy to .env.macos (Git ignored). Use UTF-8 and quote secrets containing # or spaces. # Paths may be absolute or relative to apps/desktop. Values are not shell-expanded. -DSH_DESKTOP_APP_ID=com.deepseek.harness +DSH_DESKTOP_APP_ID=com.deepseek.dsh DSH_DESKTOP_AUTO_UPDATE_ENV=test DOWNLOAD_TEST_ORIGIN= # Required for test releases: 32 lowercase hexadecimal characters from a secure random generator. @@ -14,6 +14,7 @@ DOWNLOAD_TEST_RELEASE_ID= # Workspace tarball workers; omit to use 4. Must be a positive integer. DSH_DESKTOP_MACOS_PACK_CONCURRENCY=4 +DSH_DESKTOP_MACOS_ZIP_COMPRESSION_LEVEL=3 # Optional independent proxy origins; empty values preserve inherited networking. # Downloads: HTTP/HTTPS proxy for Electron, runtime assets, pnpm and builder downloads. DSH_DESKTOP_MACOS_DOWNLOAD_PROXY= diff --git a/apps/desktop/.env.windows.example b/apps/desktop/.env.windows.example index 4950c70b27..9d1a976d5d 100644 --- a/apps/desktop/.env.windows.example +++ b/apps/desktop/.env.windows.example @@ -1,6 +1,6 @@ # Copy to .env.windows (Git ignored). Use UTF-8 and quote secrets containing # or spaces. # Credential file paths may be absolute or relative to apps/desktop. Values are not shell-expanded. -DSH_DESKTOP_APP_ID=com.deepseek.harness +DSH_DESKTOP_APP_ID=com.deepseek.dsh DSH_DESKTOP_AUTO_UPDATE_ENV=test DOWNLOAD_TEST_ORIGIN= # Required for test releases: 32 lowercase hexadecimal characters from a secure random generator. @@ -31,6 +31,9 @@ DSH_DESKTOP_WINDOWS_TOKEN_PIN= # Cache-hit restore and verification workers (1-8). Hardware signing remains serial. DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_CONCURRENCY=4 +# Installer archive compression (0-9); lower values trade size for packaging time. +DSH_DESKTOP_WINDOWS_COMPRESSION_LEVEL=3 + # Optional upload configuration; packaging does not require these credentials. # DOWNLOAD_TEST_COS_BUCKET= # DOWNLOAD_TEST_COS_SECRET_ID= diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index f554ad3863..e7fced6b8e 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -12,11 +12,11 @@ en: 7bc8bf30de693222 zh: e85993d8852b6cab /deepseek-harness-desktop/table-of-contents: - en: 05fd227f99ee535a - zh: 60d7d62bc0026973 + en: 127ea90553cb6af7 + zh: 7b1c5aec8558c684 /deepseek-harness-desktop/application-overview: - en: e9b22f232837e131 - zh: fc5f3834b969d2d2 + en: b57525e17b9638ab + zh: 274fe8344f7c2202 /deepseek-harness-desktop/terminal-command: en: 5f2d25a1d8472647 zh: 2acb5c5d7d1917e2 @@ -33,11 +33,11 @@ en: 372297005b57a08b zh: 074a635ac17e4362 /deepseek-harness-desktop/installation-ownership: - en: 7cbb1f9e5006bd34 - zh: 01e9e15a75a90450 + en: 160b500cdcd6a39a + zh: 6c267f1762ec3689 /deepseek-harness-desktop/installation-ownership/runtime-and-plugin-activation: - en: a1a47b09f4a72ba4 - zh: 7b1cf27f0b72cf31 + en: 4951cd3ee659eb33 + zh: 96bdd6358dad587a /deepseek-harness-desktop/installation-ownership/host-environment: en: 98cf848762482d48 zh: 74f9100a39ec8c2f @@ -45,8 +45,8 @@ en: faf7676ba18bbf2f zh: f1d7b75ad348c548 /deepseek-harness-desktop/develop/startup-onboarding: - en: d87d51b901b72ecd - zh: 525da1c4d56af659 + en: 67dc7ef3e293236a + zh: 1b224db684a2d1d7 /deepseek-harness-desktop/develop/welcome-window-appearance: en: 617a89aeb28131b9 zh: 4d84bd5d86501c86 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 931401ec77..f961a72a92 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -18,6 +18,7 @@ Desktop runs the Harness workspace in a native application. This reference cover - [Key technical decisions](#key-technical-decisions) - [Bundled command runtime](#bundled-command-runtime) - [Installation ownership](#installation-ownership) +- [Recovery and diagnostics](docs/diagnostics/README.md) - [Develop](#develop) - [Package](#package) - [Windows installer interface](#windows-installer-interface) @@ -30,6 +31,8 @@ Desktop runs the Harness workspace in a native application. This reference cover ## Application overview +Electron caches the last confirmed UI language in `userData/desktop/locale-cache` so startup recovery dialogs can use it before Host settings are available. Missing, invalid, or unreadable caches fall back to the system language; cache write failures do not block startup. A successful Host startup or a UI language change refreshes the cache. Until then, a changed system language may differ from the cached language. + Desktop analytics follows the [product collection policy](../../packages/client/product-analytics/README.md), including its live application setting. Web usage is excluded. Update installation waits for its local analytics intake before locking API admission and stopping the Host. Intake has a one-second deadline; failure does not prevent installation, and collector delivery is not awaited. The desktop application is an Electron shell around the complete dsh Web application. An Electron RunAsNode child starts the shared profile runner, and Electron immediately loads the packaged Web entry at `dsh-app://app/`. Its shared loading page waits for Host boot injections, then starts the client without navigating to another document. Electron forwards application HTTP requests to the authenticated Web Host, dropping connection-level response headers (`transfer-encoding`, `connection`, `keep-alive`) that describe the Node fetch rather than the resource, and marking plugin bundle responses `no-store` because their per-launch revisions would only accumulate in Chromium's disk cache; WebSocket streams connect to that Host with credentials attached only for the owned application window. Node IPC carries boot injections, readiness, and shutdown. Desktop listens on an OS-assigned port by default, so it cannot collide with Web’s `3080` or a reserved port; a `webserver.config.port` patch can override it. @@ -40,7 +43,7 @@ The first application-menu command, **About DeepSeek Harness**, opens Electron's Desktop’s local native directory flow opens an Electron folder dialog attached to the application window, restoring, showing, and focusing that window first. Concurrent requests share one dialog; cancellation returns no path and failures remain retryable. Ordinary Web uses the Host chooser. Browse mode lists Host directories. On Linux without zenity or kdialog, automatic selection uses browse instead of the Electron dialog. -Desktop ships one pnpm distribution at `resources/runtime/primary-runtime/dependencies/pnpm`. Build-time production installation, the installed `dsh` CLI, Creator and the Web Plugin Manager execute its `bin/pnpm.mjs` with Electron Node mode; package operations do not require pnpm on PATH. The private Node launcher environment applies only to package operations. Agent workspace dependencies copy the same self-contained primary-runtime payload into the Harness home and execute pnpm with its standalone Node. +Desktop ships one pnpm distribution at `resources/runtime/primary-runtime/dependencies/pnpm`, without the native packages of other targets. Build-time production installation, the installed `dsh` CLI, Creator and the Web Plugin Manager execute its `bin/pnpm.mjs` with Electron Node mode; package operations do not require pnpm on PATH. The private Node launcher environment applies only to package operations. Agent workspace dependencies copy the same self-contained primary-runtime payload into the Harness home and execute pnpm with its standalone Node. Embedded Platform documents use a persistent WebContentsView partition keyed by a hash of the Platform origin and stable account ID. localStorage preferences, including dismissed notices, survive view closure and application restart; different accounts and origins use separate storage. The Host supplies the account ID from its latest successful profile read; while no ID is known, the document opens in a disposable partition that keeps no preference across opens. Opening a persistent partition clears cookies, filesystem, IndexedDB, Cache Storage, the HTTP and shader caches, service workers, and HTTP authentication before the document loads; a disposable partition clears all of its storage. Closing a view destroys the document, removes its request interceptors, and schedules the same cleanup, so authentication left by an unclean exit is cleared before the next document loads. The next open and application shutdown await that cleanup, and an update install waits for it before the installer takes over the exit. A failed cleanup rejects that open and blocks the same account until a later cleanup succeeds; other accounts keep opening. Sign-out destroys the document but retains account-scoped preferences for the next sign-in. A document already open in a disposable partition stays mounted when the account ID arrives for the same credential; the next open uses the account-scoped partition. The [storage decision](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.md) describes the retention policy. Host sends account credentials through private Node IPC; account RPC and the Harness renderer receive no token. Before page scripts execute, the Platform preload performs one synchronous IPC to read the prepared main-process credential. It exposes displayMode, synchronous getAuthToken() and getLocale() getters, and onLocaleChange(listener), which returns an unsubscribe function. Both getters read preload memory without further IPC. The bootstrap includes the resolved Desktop language (`zh_CN` or `en_US`); Settings language changes update the preload cache and notify the open Platform document without reloading. Platform applies this language before its first render and does not persist it as a browser preference. The main-process handler performs only sender validation and an in-memory read; it never waits for Host, disk, or network. Trusted-page initialization failures retain embedded mode and make the getter throw, preventing browser-credential fallback. Only the owned Platform main frame on the configured issuer origin can initialize. Sign-out, credential replacement, Host shutdown, and view closure destroy the document. Cross-origin document navigation is blocked. HTTPS links requesting a new window open in the system browser without the embedded session or token; other schemes and URL credentials are rejected. Native views occupy the viewport below the Account feature’s return bar. @@ -152,7 +155,7 @@ The product UI retains Web actions, including "Open In..." through the shared au Update copy preserves the complete version, including prerelease suffixes, without adding v or V. When no update is available, the dialog title reports the result and the body shows the current version. -Electron chooses typed English, Chinese, or Japanese shell copy from its application locale and falls back to English. The macOS application bundle declares English, Simplified Chinese, and Japanese in `CFBundleLocalizations`, allowing macOS to match the initial application language to the user’s preferred languages. Saved Client UI language preferences still take precedence for the main interface. Windows NSIS installer resources live in one JSON file per language under `installer/locales/`; packaging generates NSIS strings and discovers the installer language list from these files. English, Simplified Chinese, and Japanese resources must have matching keys and format placeholders; `pnpm run check:i18n` validates them. The native installer test builds and exercises each configured language. Platform account pages and onboarding artwork use English for languages other than Chinese. On Windows, the main document's language updates desktop menus, recovery and update prompts. The repository Client UI i18n gate checks desktop sources. +Electron chooses typed shell copy in the eight [shipped Client languages](../../packages/client/locale/README.md) from its application locale and falls back to English. The macOS application bundle declares all eight languages in `CFBundleLocalizations`, allowing macOS to match the initial application language to the user’s preferred languages. Saved Client UI language preferences still take precedence for the main interface. Windows NSIS installer resources live in one JSON file per language under `installer/locales/`; packaging generates NSIS strings and discovers the installer language list from these files. All shipped language resources must have matching keys, format placeholders, and command examples; `pnpm run check:i18n` validates them. The native installer test builds and exercises each configured language. Platform account pages and onboarding artwork use English for languages other than Chinese. On Windows, the main document's language updates desktop menus, recovery and update prompts. The repository Client UI i18n gate checks desktop sources. Windows and macOS relay native fullscreen transitions and the state after each page load to the renderer, so overlays can adapt their caption clearance. @@ -172,13 +175,7 @@ The signed `resources/app.asar/dsh/desktop-runtime.json` binds the shell version The [Web plugin UI](../../packages/client/ui-plugin-manager/README.md) owns the management interface. Desktop profile initialization and recovery preserve installed plugin files. -Fatal main-window creation, main-document loading, preload, renderer, Web initialization, or backend failures open one native recovery dialog per application process. It shows a bounded tail of the first error, notes any truncation, and offers Exit, Restart, and Disable third-party plugins, back up profile patch, and restart. Startup failures retain the Web loading page and spinner; runtime failures retain the current page. Expected shutdowns, cancelled navigation, and ordinary requests do not trigger recovery. The shared Web plugin manager reports package-operation errors; Host startup failures after plugin changes enter native recovery. There is no startup timeout heuristic. A listener failure containing `listen EADDRINUSE` replaces the diagnostics and reinstall advice with guidance to quit other running DSH instances, and offers only Exit and Restart. - -Native dialog details include at most 1,200 UTF-16 code units and eight diagnostic lines, plus the path of the crash report described below when one was written. Host error diagnostics retain only the last 64 Ki characters written to stderr. Earlier output is discarded so a long-running Host does not grow the shell’s diagnostic buffer indefinitely. - -Before the first fatal dialog opens, Electron writes a crash report to the platform logs directory (`app.getPath('logs')`: `~/Library/Logs/DeepSeek Harness` on macOS, `logs` under the application’s `userData` directory on Windows and Linux), waiting at most one second for the write; a slow or failed write shows the dialog without a path. The file `crash--.log` records the source (`host` for a Host exit, `web-boot` for a renderer boot failure, `renderer` for a renderer or document failure, `main` for a shell error), whether the backend had reached ready, application and runtime versions, the error with its enumerable properties and cause chain (cut at 256 KiB), the Host’s own inspected error (at most 64 KiB) when the Host reported a startup failure over IPC before exiting, and the primary window’s recent error-level console output (at most 64 KiB). A Host exit report therefore contains the retained stderr tail, which may include plugin output. A fatal failure during shutdown writes a report without opening a dialog. Files are owner-only where the platform supports it; startup keeps the ten newest reports and removes older ones without touching other files in the directory. - -Recovery waits for Host shutdown before changing plugin activation. The native recovery action calls the shared app-boot recovery function under the profile transaction lock. It disables third-party bundles and renames the profile’s `cordis.patch.yml` to `cordis.patch.yml.bak-` (with an ordinal on collisions) without parsing it; the next startup creates an empty patch. Installed packages and earlier backups remain. The home-level patch is unchanged. The Electron console records the backup path (or its absence) and the unchanged home-level patch. Invalid profile data, rename failures, or write failures are reported as recovery-operation errors; completed changes remain, and Desktop does not restart as though recovery succeeded. Desktop has no profile-reset action or emergency HTML document. +Desktop fatal failures use native recovery with Exit, Restart, Disable third-party plugins, back up profile patch, and restart, and Get diagnostic report. See [recovery and diagnostics](docs/diagnostics/README.md) for triggers, report locations and contents, recent operation records, and shutdown limits. ### Host environment @@ -220,7 +217,7 @@ Repeated launches and `dsh://open` keep the workspace hidden until the startup c Desktop checks configured model API-key references after the Host starts and before opening the workspace. With no configured key, the welcome window offers the API-key page. Save and continue writes through the existing credential service using the official DeepSeek provider's configured reference, then opens the workspace. Set up later opens the workspace without saving the draft or a completion setting; the next process launch checks credentials again. Back to sign in returns to the entry and clears the unsaved key and validation message. Buttons keep their labels and block competing actions while saving or opening the workspace. The Desktop preload marker suppresses the Web credential dialog, while retaining the Models settings page and the welcome notice. -The welcome window reads the shared `locale.preference` before it appears. An explicit English, Chinese, or Japanese choice wins; otherwise Desktop picks the first supported OS language and falls back to English. The main UI reads the same preference and OS language order through its isolated preload before mounting. Language changes in Settings update the shell’s current dictionary and menu; automatic selection writes no preference. The welcome window has no language selector. +The welcome window reads the shared `locale.preference` before it appears. An explicit supported language choice wins; otherwise Desktop picks the first supported OS language and falls back to English. The main UI reads the same preference and OS language order through its isolated preload before mounting. Language changes in Settings update the shell’s current dictionary and menu; automatic selection writes no preference. The welcome window has no language selector. The browser-login waiting page offers a copy-link action for the current pending authorization, a loading indicator, and cancellation. Clipboard failures leave the copy action available for retry. Copy feedback resets after two seconds; the copied state disables the link until it resets. Welcome text uses Montserrat Light with system fallbacks; large action buttons keep the system font, while text buttons use Montserrat Light. English introductory copy is 24px throughout. Chinese introductory copy is 24px with a 26px product name. Login action buttons are 240px wide with 14px labels. Authorization status headings use 20px Montserrat Regular text. The API-key page uses a 20px heading and a 14px back action, with 84px between the secondary button’s bottom edge and the window bottom. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 262eee3ac7..a7500d5d28 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -18,6 +18,7 @@ Desktop 在原生应用中运行 Harness 工作区。本参考文档说明应用 - [关键技术决策](#key-technical-decisions) - [内置命令运行时](#bundled-command-runtime) - [安装归属](#installation-ownership) +- [故障恢复与诊断](docs/diagnostics/README.zh.md) - [开发](#develop) - [打包](#package) - [Windows 安装界面](#windows-installer-interface) @@ -30,6 +31,8 @@ Desktop 在原生应用中运行 Harness 工作区。本参考文档说明应用 ## 应用概览 +Electron 在 `userData/desktop/locale-cache` 缓存最近确认的界面语言,使启动恢复弹窗在 Host 设置尚不可用时也能使用该语言。缓存缺失、无效或不可读时回退到系统语言;缓存写入失败不阻断启动。Host 成功启动或界面语言变更时会刷新缓存;在此之前,变更后的系统语言可能与缓存语言不同。 + 桌面埋点遵循[产品采集策略](../../packages/client/product-analytics/README.zh.md)及其动态应用配置,不包含 Web 使用情况。安装更新会等待该操作的本地埋点接收请求结束,再锁定 API 准入并停止 Host。接收请求的时限为一秒,失败不会阻止安装,也不等待收集端完成发送。 桌面应用是完整 dsh Web 应用外的一层 Electron 壳。Electron RunAsNode 子进程启动共享 profile runner,Electron 立即从 `dsh-app://app/` 加载打包内的 Web 入口。共享加载页等待 Host 启动注入,然后在同一文档中启动客户端。Electron 将应用 HTTP 请求转发给已认证的 Web Host,转发时丢弃描述 Node fetch 连接而非资源本身的响应头(`transfer-encoding`、`connection`、`keep-alive`),并把插件 bundle 响应标记为 `no-store`,因为其每次启动都变化的 revision 只会在 Chromium 磁盘缓存中累积;WebSocket 流连接到该 Host,仅为归属的应用窗口附加凭据。Node IPC 承载启动注入、就绪与关闭。Desktop 默认监听系统分配的端口,因此不会与 Web 的 `3080` 或系统保留端口冲突;可通过 `webserver.config.port` patch 覆盖。 @@ -40,7 +43,7 @@ Desktop 绑定 `127.0.0.1`,即 Electron 为就绪 URL 与 WebSocket 凭据过 Desktop 的本地原生目录流程打开绑定应用窗口的 Electron 文件夹对话框,并先恢复、显示和聚焦该窗口。并发请求共用一个对话框;取消不返回路径,失败后可以重试。普通 Web 使用 Host 选择器。浏览模式列出 Host 目录。Linux 缺少 zenity 或 kdialog 时,自动选择使用浏览模式,不使用 Electron 对话框。 -Desktop 在 `resources/runtime/primary-runtime/dependencies/pnpm` 中携带一份 pnpm 分发包。构建时的生产依赖安装、安装版 `dsh` CLI、Creator 和 Web 插件管理器通过 Electron Node 模式执行其中的 `bin/pnpm.mjs`;包操作不要求 PATH 上存在 pnpm。私有 Node 启动器环境仅用于包操作。agent(智能体)的工作区依赖将同一份完整 primary-runtime 复制到 Harness 主目录,并使用其中的独立 Node 执行 pnpm。 +Desktop 在 `resources/runtime/primary-runtime/dependencies/pnpm` 中携带一份 pnpm 分发包,不含其他目标平台的原生包。构建时的生产依赖安装、安装版 `dsh` CLI、Creator 和 Web 插件管理器通过 Electron Node 模式执行其中的 `bin/pnpm.mjs`;包操作不要求 PATH 上存在 pnpm。私有 Node 启动器环境仅用于包操作。agent(智能体)的工作区依赖将同一份完整 primary-runtime 复制到 Harness 主目录,并使用其中的独立 Node 执行 pnpm。 Platform 内嵌文档使用持久化 WebContentsView 分区,分区名由 Platform 来源和稳定账号 ID 的哈希决定。localStorage 中的页面偏好(包括已关闭的通知)在关闭视图和重启应用后保留;不同账号和来源使用独立存储。账号 ID 来自 Host 最近一次成功的资料读取;尚无该 ID 时,文档在一次性分区中打开,该分区不跨次保留偏好。打开持久分区会先清理 Cookie、文件系统、IndexedDB、Cache Storage、HTTP 与着色器缓存、Service Worker 及 HTTP 认证状态;一次性分区则清理其全部存储。关闭视图会销毁文档、移除请求拦截器并安排相同的清理,因此异常退出遗留的认证会在下一个文档加载前被清除。下次打开和应用退出都会等待该清理完成,更新安装也会在安装器接管退出前等待。清理失败会使该次打开失败,并在后续清理成功前阻止同一账号打开;其他账号不受影响。退出登录会销毁文档,但保留账号偏好供下次登录使用。同一凭证下账号 ID 迟到时,已以一次性分区打开的文档保持挂载;下次打开使用账号分区。[存储决策](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.zh.md)说明保留策略。Host 通过私有 Node IPC 发送账号凭证;账号 RPC 和 Harness 渲染进程不接收 token。Platform preload 在页面脚本执行前通过一次同步 IPC 读取主进程中已准备的凭证。它暴露 displayMode、同步的 getAuthToken() 和 getLocale() getter,以及返回取消订阅函数的 onLocaleChange(listener)。两个 getter 都只读取 preload 内存,不再调用 IPC。bootstrap 包含 Desktop 已解析的语言(`zh_CN` 或 `en_US`);Settings 语言变更会更新 preload 缓存并通知已打开的 Platform 文档,无需重载。Platform 在首屏渲染前应用该语言,且不将其持久化为浏览器偏好。主进程处理器仅校验调用来源并读取内存,不等待 Host、磁盘或网络。可信页面初始化失败时保留内嵌模式,由 getter 抛错,避免回退到浏览器凭证。只有受控 Platform 页面中、位于所配置签发来源的主 frame 能完成初始化。退登、凭证替换、Host 关闭及视图关闭都会销毁文档。跨来源文档导航被阻止。请求新窗口的 HTTPS 链接在系统浏览器中打开,不携带内嵌会话或 token;其他协议及带 URL 凭证的链接被拒绝。原生视图占据 Account 功能返回栏下方的视口。 @@ -152,7 +155,7 @@ Electron 拥有 `$DSH_HOME/profiles/desktop`。其 `dependencies` 包含 pnpm 升级文案完整展示版本号(包括预发布后缀),不额外添加 v 或 V。无可用更新时,弹窗标题显示检查结果,正文显示当前版本。 -Electron 根据应用语言选择类型化的英文、中文或日文 shell 文案,并回退到英文。macOS 应用包通过 `CFBundleLocalizations` 声明支持英语、简体中文和日语,让 macOS 根据用户的首选语言匹配初始应用语言。主界面仍优先使用已保存的 Client UI 语言偏好。 Windows NSIS 安装器在 `installer/locales/` 下按语言保存独立 JSON 资源;打包从这些文件生成 NSIS 文案和安装器语言清单。英文、简体中文和日语资源的键与格式占位符必须一致,`pnpm run check:i18n` 负责检查。原生安装器测试逐个构建并验证配置中的语言。账户平台页面和引导插图对中文以外的语言使用英文。在 Windows 上,主文档的语言会更新桌面菜单、恢复与更新提示。仓库 Client UI i18n 检查覆盖桌面端源码。 +Electron 根据应用语言选择类型化的八种[内置 Client 语言](../../packages/client/locale/README.zh.md)的 shell 文案,并回退到英文。macOS 应用包通过 `CFBundleLocalizations` 声明支持全部八种语言,让 macOS 根据用户的首选语言匹配初始应用语言。主界面仍优先使用已保存的 Client UI 语言偏好。Windows NSIS 安装器在 `installer/locales/` 下按语言保存独立 JSON 资源;打包从这些文件生成 NSIS 文案和安装器语言清单。全部内置语言资源的键、格式占位符和命令示例必须一致,`pnpm run check:i18n` 负责检查。原生安装器测试逐个构建并验证配置中的语言。账户平台页面和引导插图对中文以外的语言使用英文。在 Windows 上,主文档的语言会更新桌面菜单、恢复与更新提示。仓库 Client UI i18n 检查覆盖桌面端源码。 Windows 和 macOS 会在原生全屏切换及每次页面加载后向渲染器同步全屏状态,让浮层调整顶栏避让距离。 @@ -172,13 +175,7 @@ macOS 上自定义菜单保留 Electron 的标准 Window 菜单及应用隐藏 [Web 插件 UI](../../packages/client/ui-plugin-manager/README.zh.md)负责管理界面。Desktop profile 初始化和恢复保留已安装插件文件。 -主窗口创建、主文档加载、preload、渲染器、Web 初始化或后端的致命失败,会在每个应用进程中打开一次原生恢复对话框。对话框显示首次错误末尾的限长摘要,标明截断情况,并提供退出、重启、禁用第三方插件、备份 profile patch 并重启。启动失败保留 Web 加载页和动画;运行中失败保留当前页面。预期关闭、取消导航和普通请求错误不会触发恢复。共享 Web 插件管理器报告包操作错误;插件变更后的 Host 启动失败会进入原生恢复。不通过启动超时推断故障。 包含 `listen EADDRINUSE` 的监听失败以退出其他正在运行的 DSH 实例的提示替代诊断和重装建议,仅提供退出和重启。 - -原生弹窗详情最多包含 1,200 个 UTF-16 代码单元和八行诊断,若已写入下述崩溃报告则附上其路径。Host 错误诊断仅保留 stderr 输出的最后 64 Ki 个字符。更早的输出会被丢弃,避免长期运行的 Host 使壳的诊断缓冲区无限增长。 - -首个致命弹窗打开前,Electron 会向平台日志目录(`app.getPath('logs')`:macOS 为 `~/Library/Logs/DeepSeek Harness`,Windows 与 Linux 为应用 `userData` 目录下的 `logs`)写入一份崩溃报告,最多等待写入一秒;写入缓慢或失败时弹窗不带路径。文件 `crash--.log` 记录来源(`host` 为 Host 退出、`web-boot` 为渲染进程启动失败、`renderer` 为渲染进程或文档失败、`main` 为壳自身错误)、后端是否已就绪、应用与运行时版本、包含可枚举属性与 cause 链的错误(截至 256 KiB)、Host 在退出前通过 IPC 报告启动失败时自己的 inspect 错误(最多 64 KiB),以及主窗口最近的 error 级 console 输出(最多 64 KiB)。因此 Host 退出报告包含保留的 stderr 尾部,其中可能含有插件输出。关闭过程中的致命失败只写报告、不弹窗。平台支持时文件仅所有者可读;启动时保留最新十份报告并删除更早的,不触碰目录中的其他文件。 - -恢复操作等待 Host 关闭后才修改插件启用状态。原生恢复操作在 profile 事务锁内调用共享 app-boot 恢复函数。它禁用第三方 bundle,并将 profile 的 `cordis.patch.yml` 重命名为 `cordis.patch.yml.bak-`(重名时追加序号),无需解析;下次启动创建空 patch。已安装包和已有备份保留。home 级 patch 不变。Electron 控制台记录备份路径(或原文件不存在)以及 home 级 patch 未修改。profile 数据无效、重命名失败或写入失败会作为恢复操作错误报告;已完成的修改保留,Desktop 不会假装恢复成功后重启。Desktop 不提供 profile 重置操作或应急 HTML 文档。 +Desktop 的致命故障通过原生恢复对话框提供退出、重启、禁用第三方插件并备份 profile patch 后重启,以及获取诊断报告。触发范围、报告位置与内容、近期操作记录和退出限制见[故障恢复与诊断](docs/diagnostics/README.zh.md)。 ### Host 环境 @@ -220,7 +217,7 @@ API Key 输入框初始为空,并通过 `autocomplete="new-password"` 请求 C Desktop 在 Host 启动后、打开工作区前检查模型 API Key 引用是否已配置。没有已配置的密钥时,欢迎窗口提供 API Key 页面。“保存并继续”通过现有凭证服务写入 DeepSeek 官方提供方配置的引用,然后打开工作区。“稍后配置”打开工作区,但不保存草稿或完成标记;下次进程启动时会重新检查凭证。“返回登录”回到入口并清空未保存的密钥和校验提示。保存或打开工作区期间,按钮保持原文案并禁用竞争操作。Desktop preload 标记使 Web 凭证弹窗不再显示,同时保留模型设置页和欢迎须知。 -欢迎窗口在显示前读取共享的 `locale.preference`。用户明确选择的英文、中文或日文优先;否则 Desktop 按系统语言顺序匹配支持的语言,并以英文兜底。主界面在挂载前通过隔离 preload 读取同一偏好和系统语言顺序。在设置中切换语言会更新桌面壳的当前词典和菜单;自动选择不会写入偏好。欢迎窗口不提供语言切换入口。 +欢迎窗口在显示前读取共享的 `locale.preference`。用户明确选择的受支持语言优先;否则 Desktop 按系统语言顺序匹配支持的语言,并以英文兜底。主界面在挂载前通过隔离 preload 读取同一偏好和系统语言顺序。在设置中切换语言会更新桌面壳的当前词典和菜单;自动选择不会写入偏好。欢迎窗口不提供语言切换入口。 等待浏览器登录时,欢迎页提供当前待授权请求的链接复制入口、加载指示和取消操作;剪贴板写入失败后可以重试复制,复制结果提示在两秒后恢复;已复制状态下链接禁用,恢复后可再次点击。Welcome 文字使用 Montserrat Light 并回退到系统字体,底部大按钮保留系统字体,文字按钮使用 Montserrat Light。英文欢迎正文及产品名均为 24px,中文欢迎正文为 24px、产品名为 26px。登录操作按钮宽 240px,文字为 14px。授权状态标题使用 20px Montserrat Regular 字重。API Key 页的标题为 20px,返回操作为 14px,次级按钮底边距窗口底部 84px。 diff --git a/apps/desktop/config/macos-packaging/production.env.example b/apps/desktop/config/macos-packaging/production.env.example index 18360eadef..a5a5477fbe 100644 --- a/apps/desktop/config/macos-packaging/production.env.example +++ b/apps/desktop/config/macos-packaging/production.env.example @@ -1,8 +1,9 @@ # Copy to production.env and configure the production service before selecting this preset. -DSH_DESKTOP_APP_ID=com.deepseek.harness +DSH_DESKTOP_APP_ID=com.deepseek.dsh DSH_DESKTOP_AUTO_UPDATE_ENV=production DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN= DSH_DESKTOP_MACOS_PACK_CONCURRENCY=4 +DSH_DESKTOP_MACOS_ZIP_COMPRESSION_LEVEL=3 DSH_DESKTOP_MACOS_DOWNLOAD_PROXY= DSH_DESKTOP_MACOS_NOTARIZATION_PROXY= # Optional absolute private directory; setup fills this in for machine presets. Omit to use checkout-local storage. diff --git a/apps/desktop/config/macos-packaging/test.env.example b/apps/desktop/config/macos-packaging/test.env.example index aa40a119ce..4c5de070a5 100644 --- a/apps/desktop/config/macos-packaging/test.env.example +++ b/apps/desktop/config/macos-packaging/test.env.example @@ -1,5 +1,5 @@ # Copy to test.env; paths in secret configuration resolve beside macos-signing.env. -DSH_DESKTOP_APP_ID=com.deepseek.harness +DSH_DESKTOP_APP_ID=com.deepseek.dsh DSH_DESKTOP_AUTO_UPDATE_ENV=test DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN= DSH_DESKTOP_MANDATORY_UPDATE_CONFIG='{"allowedAuthOrigins":["https://login.example.com"]}' @@ -7,6 +7,7 @@ DOWNLOAD_TEST_ORIGIN= # Generate a 32-character lowercase hexadecimal release ID; retain it for upgrade testing. DOWNLOAD_TEST_RELEASE_ID= DSH_DESKTOP_MACOS_PACK_CONCURRENCY=4 +DSH_DESKTOP_MACOS_ZIP_COMPRESSION_LEVEL=3 DSH_DESKTOP_MACOS_DOWNLOAD_PROXY= # Temporarily changes the active network service's system HTTP/HTTPS proxies. DSH_DESKTOP_MACOS_NOTARIZATION_PROXY= diff --git a/apps/desktop/config/windows-packaging/production.env.example b/apps/desktop/config/windows-packaging/production.env.example index 2e05825590..dbbcfb73d5 100644 --- a/apps/desktop/config/windows-packaging/production.env.example +++ b/apps/desktop/config/windows-packaging/production.env.example @@ -1,7 +1,9 @@ # Copy to production.env in the same machine configuration directory and fill in the values. -DSH_DESKTOP_APP_ID=com.deepseek.harness +DSH_DESKTOP_APP_ID=com.deepseek.dsh DSH_DESKTOP_AUTO_UPDATE_ENV=production DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN= DSH_DESKTOP_MANDATORY_UPDATE_CONFIG='{}' # DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR= DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_CONCURRENCY=4 +# Installer archive compression (0-9). +DSH_DESKTOP_WINDOWS_COMPRESSION_LEVEL=3 diff --git a/apps/desktop/config/windows-packaging/test.env.example b/apps/desktop/config/windows-packaging/test.env.example index 718481f13a..5a4e2ccf90 100644 --- a/apps/desktop/config/windows-packaging/test.env.example +++ b/apps/desktop/config/windows-packaging/test.env.example @@ -1,6 +1,6 @@ # Copy to test.env in the same machine configuration directory and fill in the values. # Public test configuration. No PIN or upload credentials belong here. -DSH_DESKTOP_APP_ID=com.deepseek.harness +DSH_DESKTOP_APP_ID=com.deepseek.dsh DSH_DESKTOP_AUTO_UPDATE_ENV=test DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN= # Replace login.example.com with the real login origin before packaging. @@ -11,3 +11,5 @@ DOWNLOAD_TEST_RELEASE_ID= # Optional absolute private cache directory. Omit to retain the account default cache. # DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR= DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_CONCURRENCY=4 +# Installer archive compression (0-9). +DSH_DESKTOP_WINDOWS_COMPRESSION_LEVEL=3 diff --git a/apps/desktop/docs/diagnostics/README.i18n.yaml b/apps/desktop/docs/diagnostics/README.i18n.yaml new file mode 100644 index 0000000000..44994b4b1e --- /dev/null +++ b/apps/desktop/docs/diagnostics/README.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write apps/desktop/docs/diagnostics/README.md +/: + en: 29d76ee1849cd8fd + zh: a2b8cbabe79557f9 +/desktop-recovery-and-diagnostics: + en: 4d4fd8a92047e5c6 + zh: 15ec51d703ccd70b +/desktop-recovery-and-diagnostics/summary: + en: e61d0f55e426aa6f + zh: dc13c7e054eac9d1 +/desktop-recovery-and-diagnostics/table-of-contents: + en: 8f3a2a84eaf575af + zh: 3087306f10e7c2cf +/desktop-recovery-and-diagnostics/recover-from-a-failure: + en: 9d0645dba352979d + zh: e1556207a04d9a71 +/desktop-recovery-and-diagnostics/report-contents: + en: 1a2eb71ac2dccf63 + zh: 5cf59639d3e49591 +/desktop-recovery-and-diagnostics/recent-operation-records: + en: f1c19c1516a51ab6 + zh: b350f7c18086d274 +/desktop-recovery-and-diagnostics/collection-and-shutdown: + en: bac4a49f63d4aaf8 + zh: df1ae908ee2148e1 diff --git a/apps/desktop/docs/diagnostics/README.md b/apps/desktop/docs/diagnostics/README.md new file mode 100644 index 0000000000..e0e72c3f1e --- /dev/null +++ b/apps/desktop/docs/diagnostics/README.md @@ -0,0 +1,76 @@ +--- +description: "Use this reference when recovering Desktop failures or collecting reports; it explains report contents, operation history, and shutdown limits." +--- + +# Desktop recovery and diagnostics + +English | [中文](README.zh.md) + +## Summary + +This reference describes Desktop native failure recovery, diagnostic reports, recent plugin operation records, and collection and shutdown limits. + +## Table of Contents + +- [Recover from a failure](#recovery) +- [Report contents](#report-contents) +- [Recent operation records](#operation-records) +- [Collection and shutdown](#collection-and-shutdown) + + + +## Recover from a failure + +Fatal main-window creation, main-document loading, preload, renderer, Web initialization, or backend failures open one native recovery dialog per application process. It shows a bounded tail of the first error, notes any truncation, and offers “Exit”, “Restart”, “Disable third-party plugins, back up profile patch, and restart”, and “Get diagnostic report” while report writing is pending or after it succeeds. Startup failures retain the Web loading page and spinner; runtime failures retain the current page. Expected shutdowns, cancelled navigation, and ordinary requests do not trigger recovery. The shared Web plugin manager reports package-operation errors; Host startup failures after plugin changes enter native recovery. There is no startup timeout heuristic. A listener failure containing `listen EADDRINUSE` replaces the diagnostics and reinstall advice with guidance to quit other running DSH instances, and offers “Exit”, “Restart”, and “Get diagnostic report” while report writing is pending or after it succeeds. + +Recovery uses the last confirmed Desktop language from the local cache before Host settings are available; an absent or invalid cache falls back to system languages. + +Recovery waits for Host shutdown before changing plugin activation. The native recovery action calls the shared app-boot recovery function under the profile transaction lock. It disables third-party bundles and renames the profile’s `cordis.patch.yml` to `cordis.patch.yml.bak-` (with an ordinal on collisions) without parsing it; the next startup creates an empty patch. Installed packages and earlier backups remain. The home-level patch is unchanged. The Electron console records the backup path (or its absence) and the unchanged home-level patch. Invalid profile data, rename failures, or write failures are reported as recovery-operation errors; completed changes remain, and Desktop does not restart as though recovery succeeded. Desktop has no profile-reset action or emergency HTML document. + + + +## Report contents + +Native dialog details include at most 1,200 UTF-16 code units and eight diagnostic lines, plus the crash report path or its pending/unavailable status. Retrieving a pending or unavailable report preserves any recovery-operation failure headline and details. Configuration paths and startup entries precede the composition inventory so plugin rows cannot displace them when output is truncated. Host error diagnostics retain only the last 64 Ki characters written to stderr. Earlier output is discarded so a long-running Host does not grow the shell’s diagnostic buffer indefinitely. + +Before the first fatal dialog opens, Electron writes a crash report to the platform logs directory (`app.getPath('logs')`: `~/Library/Logs/DeepSeek Harness` on macOS, `logs` under the application’s `userData` directory on Windows and Linux), waiting at most one second for the write; a slow or failed write shows the dialog with an explicit pending or unavailable status. Get diagnostic report checks the same write and reveals a saved file in the system file manager without restarting or stopping the Host; a write that completes after the initial deadline remains available. The user attaches that file to a support ticket. The attachment contains the original failure; later recovery-operation errors remain in the dialog and require a separate screenshot. Retrieving a saved report shows its sharing or reveal-failure heading while retaining the recovery error details. If writing fails, the dialog hides Get diagnostic report and suggests providing a screenshot. + +The file `crash--.log` records the source (`host` for a Host exit, `web-boot` for a renderer boot failure, `renderer` for a renderer or document failure, `main` for a shell error), whether the backend had reached ready, application and runtime versions, the error with its enumerable properties and cause chain (cut at 256 KiB), the Host’s own error and explicitly selected startup metadata (at most 64 Ki characters, including a truncation notice; startup errors reserve space for metadata by limiting the original error and startup-entry details to 8 Ki characters each, with explicit truncation notices) when the Host reported a startup failure over IPC before exiting, and the primary window’s recent error-level console output (at most 64 KiB). + +A Host exit report therefore contains the retained stderr tail, which may include plugin output. A fatal failure during shutdown writes a report without opening a dialog. Files are owner-only where the platform supports it; startup keeps the ten newest reports and removes older ones without touching other files in the directory. + + + +## Recent operation records + +Operation records and the application single-instance lock are isolated by `userData`; the shared platform logs directory does not store operation records. The reader only reads the two operation files under `userData/plugin-operations`. Repairing an unfinished append preserves complete lines in the current segment and the previous segment. + +Version-exemption changes reuse the bundle enable/disable record fields. When the exemption and installed versions match, the record cannot distinguish an exemption change from a bundle toggle. + +Host `transportDropped` is a lower bound as of the last successful delivery; Desktop rejects malformed or mismatched-run records without adding them to that counter. + +The journal retains two 256 KiB segments, accepts records up to 4 KiB, and bounds queued writes to 64 KiB. + +Exit, recovery restart and installer preparation wait at most 500 ms for queued writes; a timeout disables further writes and later drains return immediately without another wait, while an already-issued OS request may still settle. + +Records cover manager operations observed after Host startup, not direct CLI commands or manual file changes. Package-manager output remains in its existing detailed logs and is not copied into this summary. Missing records, a start without an end, and damaged history do not establish a successful operation. This collection does not diagnose kernel hangs, OOM or native crashes. + +Persistence failures also disable the writer for the rest of this shell lifetime, including after recovery or installer failure. This bounds repeated failing I/O and avoids appending behind an uncertain partial write. Restarting the application creates a new writer. Omission and repair counters cover only the current shell lifetime. Retained segments provide a larger local troubleshooting window than the deliberately smaller report attachment. + + + +## Collection and shutdown + +After saving the basic report, the shell attempts to append recent plugin-management records in an isolated Worker packaged as `lib/operation-report-worker.js` inside `app.asar`. The completion marker and omission counters distinguish a finished collection from missing or partial material. + +The Host announces its run ID before profile loading; reported Host errors carry that ID as `hostRunId`, matching operation records from the same lifetime. Failure before this announcement leaves the run identity unknown. Recent operations are context, not proof of cause. + +Collection reads only two owned files under `userData/plugin-operations`, at most 64 KiB and 100 records; the complete appended section is limited to 64 KiB. + +The 500 ms collection budget reserves its final 100 ms for cooperative cancellation before requesting forced Worker termination; completion waits for its exit. Application exit, recovery exit or restart, and confirmed update installation also cancel collection and wait at most 500 ms for Worker exit. A rejected shutdown cleanup is logged without skipping the remaining cleanup waits. Shutdown prevents late basic-report saves from starting another collector. An update installation failure permits future collection again. + +Worker messages interrupt collection between bounded records; an in-flight file open, stat, read or close must settle, and synchronous parsing cannot be preempted within one record. The final append uses an abort signal but can leave partial bytes. Forced termination remains the fallback when cooperative cleanup does not finish. + +The basic report remains available independently. Only one collector runs at a time; concurrent reports keep their basic content without an auxiliary section. A rejected termination request does not release that slot until exit is observed. Get diagnostic report can reveal the basic file before the append finishes. The completion marker confirms only that collection ended, not that all operations were captured; queued bytes and omission counters describe missing material. + +See [local verification](../../tests/README.md#verification-diagnostics) for fault setup and acceptance steps, and the [Desktop README](../../README.md) for the application overview and development entry points. diff --git a/apps/desktop/docs/diagnostics/README.zh.md b/apps/desktop/docs/diagnostics/README.zh.md new file mode 100644 index 0000000000..8e25e9721a --- /dev/null +++ b/apps/desktop/docs/diagnostics/README.zh.md @@ -0,0 +1,76 @@ +--- +description: "排查 Desktop 故障或收集报告时阅读,了解恢复操作、报告内容、操作历史和退出限制。" +--- + +# Desktop 故障恢复与诊断 + +[English](README.md) | 中文 + +## 概述 + +本参考文档说明 Desktop 的原生故障恢复、诊断报告、近期插件操作记录,以及采集和退出时的限制。 + +## 目录 + +- [遇到故障怎么办](#recovery) +- [报告包含什么](#report-contents) +- [近期操作记录](#operation-records) +- [采集与退出行为](#collection-and-shutdown) + + + +## 遇到故障怎么办 + +主窗口创建、主文档加载、preload、渲染器、Web 初始化或后端的致命失败,会在每个应用进程中打开一次原生恢复对话框。对话框显示首次错误末尾的限长摘要,标明截断情况,并提供“退出”“重启”“禁用第三方插件、备份 profile patch 并重启”,以及报告仍在保存或已保存时的“获取诊断报告”。启动失败保留 Web 加载页和动画;运行中失败保留当前页面。预期关闭、取消导航和普通请求错误不会触发恢复。共享 Web 插件管理器报告包操作错误;插件变更后的 Host 启动失败会进入原生恢复。不通过启动超时推断故障。包含 `listen EADDRINUSE` 的监听失败以退出其他正在运行的 DSH 实例的提示替代诊断和重装建议,提供“退出”“重启”,以及报告仍在保存或已保存时的“获取诊断报告”。 + +Host 设置可用前,恢复对话框使用本地缓存中最后确认的 Desktop 语言;缓存不存在或无效时回退到系统语言。 + +恢复操作等待 Host 关闭后才修改插件启用状态。原生恢复操作在 profile 事务锁内调用共享 app-boot 恢复函数。它禁用第三方 bundle,并将 profile 的 `cordis.patch.yml` 重命名为 `cordis.patch.yml.bak-`(重名时追加序号),无需解析;下次启动创建空 patch。已安装包和已有备份保留。home 级 patch 不变。Electron 控制台记录备份路径(或原文件不存在)以及 home 级 patch 未修改。profile 数据无效、重命名失败或写入失败会作为恢复操作错误报告;已完成的修改保留,Desktop 不会假装恢复成功后重启。Desktop 不提供 profile 重置操作或应急 HTML 文档。 + + + +## 报告包含什么 + +原生弹窗详情最多包含 1,200 个 UTF-16 代码单元和八行诊断,并附上崩溃报告路径或仍在保存、无法保存的状态。获取仍在保存或无法保存的报告时,保留恢复操作失败的标题和详情。配置路径和启动条目排在组合清单之前,避免输出截断时被插件记录挤掉。Host 错误诊断仅保留 stderr 输出的最后 64 Ki 个字符。更早的输出会被丢弃,避免长期运行的 Host 使壳的诊断缓冲区无限增长。 + +首个致命弹窗打开前,Electron 会向平台日志目录(`app.getPath('logs')`:macOS 为 `~/Library/Logs/DeepSeek Harness`,Windows 与 Linux 为应用 `userData` 目录下的 `logs`)写入一份崩溃报告,最多等待写入一秒;写入缓慢或失败时明确显示仍在保存或无法保存。“获取诊断报告”检查同一次写入,并在系统文件管理器中定位已保存的文件,不停止 Host 或重启;超过首次等待期限后写入完成的文件仍可获取。用户可将文件作为工单附件。附件只包含最初的故障;后续恢复操作错误保留在对话框中,需要另行截图。获取已保存报告会显示分享或打开失败的标题,同时保留恢复错误详情。写入失败时隐藏获取报告按钮,并提示提供窗口截图。 + +文件 `crash--.log` 记录来源(`host` 为 Host 退出、`web-boot` 为渲染进程启动失败、`renderer` 为渲染进程或文档失败、`main` 为壳自身错误)、后端是否已就绪、应用与运行时版本、包含可枚举属性与 cause 链的错误(截至 256 KiB)、Host 在退出前通过 IPC 报告启动失败时的错误及显式选择的启动元数据(最多 64 Ki 个字符,包含截断提示;启动错误的原始错误文本和启动条目详情分别限制为 8 Ki 个字符,并明确标注截断,为结构化元数据保留空间),以及主窗口最近的 error 级 console 输出(最多 64 KiB)。 + +因此 Host 退出报告包含保留的 stderr 尾部,其中可能含有插件输出。关闭过程中的致命失败只写报告、不弹窗。平台支持时文件仅所有者可读;启动时保留最新十份报告并删除更早的,不触碰目录中的其他文件。 + + + +## 近期操作记录 + +操作记录目录与应用单实例锁均按 `userData` 隔离;共享平台日志目录不用于保存操作记录。读取器只读取 `userData/plugin-operations` 下的两个操作记录文件。修复未写完的尾行时保留当前段的完整行与上一段。 + +版本豁免变更复用 bundle 启停记录字段。豁免版本与安装版本相同时,记录无法区分豁免变更与 bundle 开关。 + +Host 的 `transportDropped` 只表示最近一次成功发送时的计数下界;Desktop 拒绝的非法或运行 ID 不匹配记录不计入该值。 + +操作历史保留两个 256 KiB 文件段,单条记录不超过 4 KiB,排队写入不超过 64 KiB。 + +退出、恢复重启和安装准备最多等待排队写入 500 ms;超时会停用后续写入,此后的排空调用立即返回,不会再次等待;但已经发出的操作系统请求仍可能随后结束。 + +记录覆盖 Host 启动后观察到的管理器操作,不包含直接执行的 CLI 命令或手工文件修改。包管理器输出保留在原有详细日志中,不复制到摘要。缺失记录、只有开始没有结束的操作以及损坏的历史,都不能说明操作已成功。此收集不诊断内核卡死、OOM 或原生崩溃。 + +持久化失败也会在本次壳生命周期内停用写入,包括恢复或安装器失败后继续运行的情况,以限制重复失败的 I/O,并避免在可能残缺的写入后追加记录。重启应用会创建新写入器。遗漏和修复计数仅覆盖当前壳生命周期。保留文件段提供比报告附件更大的本地排障历史窗口。 + + + +## 采集与退出行为 + +基本报告保存后,壳会尝试通过独立 Worker 追加近期插件管理记录;该 Worker 以 `lib/operation-report-worker.js` 打包在 `app.asar` 中。完成标记和遗漏计数用于区分已完成收集与缺失或不完整的材料。 + +Host 在加载 profile 前报告运行 ID;Host 错误中的 `hostRunId` 与该次运行的操作记录使用同一标识。在此通知之前发生的失败,其运行标识仍为未知。近期操作只是上下文,不是因果证据。 + +收集只读取 `userData/plugin-operations` 下归其管理的两个文件,最多读取 64 KiB 和 100 条记录;完整追加内容不超过 64 KiB。 + +500 ms 收集预算中的最后 100 ms 用于协作取消,随后才请求强制终止 Worker;只有 Worker 退出后才确认收集结束。应用退出、恢复退出或重启、确认安装更新也会取消收集,并最多等待 500 ms 确认 Worker 退出。退出清理中的拒绝会被记录,但不会跳过其他清理等待。退出过程中,延迟保存完成的基本报告不会再启动收集器。更新安装失败后可再次收集。 + +Worker 在有界记录之间处理取消消息;已经发出的文件打开、状态读取、读取或关闭操作必须等待完成,单条记录的同步解析不能被抢占。最后的追加写入传入取消信号,但仍可能留下部分字节。协作清理未及时完成时仍需强制终止。 + +基本报告独立可用。同时只运行一个收集器;并发报告保留基本内容,不追加辅助部分。终止请求被拒绝时,必须观察到退出才能释放该名额。“获取诊断报告”可能在追加完成前定位基本文件。完成标记仅表示收集结束,不表示捕获了全部操作;排队字节数和遗漏计数说明缺失材料。 + +故障构造与验收步骤见[本地验证](../../tests/README.zh.md#verification-diagnostics);应用概览与开发入口见 [Desktop README](../../README.zh.md)。 diff --git a/apps/desktop/installer/locales/de_DE.json b/apps/desktop/installer/locales/de_DE.json new file mode 100644 index 0000000000..faf725b88e --- /dev/null +++ b/apps/desktop/installer/locales/de_DE.json @@ -0,0 +1,40 @@ +{ + "nsisLanguage": "GERMAN", + "strings": { + "INSTALLER_INSTALL": "Jetzt installieren", + "INSTALLER_FINISH": "Fertigstellen", + "INSTALLER_NATIVE_PROGRESS": "Installation wird vorbereitet… %d%%", + "INSTALLER_PROGRESS_EXTRACT": "Dateien extrahieren… %d%%", + "INSTALLER_PROGRESS_COPY": "Dateien werden installiert… %d%%", + "INSTALLER_PROGRESS_REGISTER": "Abschluss der Installation… %d%%", + "INSTALLER_PROGRESS_CLEAN": "Bereinigen temporärer Dateien… %d%%", + "INSTALLER_CHOOSE_PATH": "Standort wählen", + "INSTALLER_BROWSE": "Durchsuchen", + "INSTALLER_LAUNCH": "Jetzt starten", + "INSTALLER_LAUNCH_FAILED": "DeepSeek Harness konnte nicht gestartet werden. Versuchen Sie es noch einmal oder deaktivieren Sie „Jetzt starten“ und schließen Sie das Installationsprogramm.", + "INSTALLER_UI_ERROR": "Das Installationsprogramm konnte sein Fenster nicht initialisieren. Schließen Sie es und versuchen Sie es erneut.", + "INSTALLER_THEME_ERROR": "Verwenden Sie /THEME=auto, /THEME=light oder /THEME=dark.", + "INSTALLER_FAILED": "Die Installation wurde nicht abgeschlossen. Schließen Sie dieses Installationsprogramm und versuchen Sie es erneut. Wenn das Problem weiterhin besteht, laden Sie das Installationsprogramm erneut herunter.", + "INSTALLER_RUNNING": "DeepSeek Harness läuft. Beenden Sie es über die Taskleiste und versuchen Sie es erneut.", + "INSTALLER_DIRECTORY_FAILED": "Das Installationsverzeichnis konnte nicht ersetzt werden.", + "INSTALLER_DIRECTORY_HINT": "Überprüfen Sie den Zugriff auf das Installationsverzeichnis und schließen Sie Programme mithilfe seiner Dateien. Führen Sie dann das Installationsprogramm erneut aus. Kopieren Sie die Fehlerdetails, wenn das Problem weiterhin besteht.", + "INSTALLER_DIRECTORY_RESTORE_HINT": "Die vorherige Installation konnte nicht wiederhergestellt werden. Behalten Sie das in den Fehlerdetails angezeigte Sicherungsverzeichnis bei und wenden Sie sich vor der erneuten Installation an den Support.", + "INSTALLER_PATH_INVALID": "Wählen Sie einen vollständigen lokalen Ordnerpfad. Laufwerksstämme, Systemordner, Links und Sonderzeichen werden nicht unterstützt.", + "INSTALLER_PATH_OWNERSHIP": "Wählen Sie einen leeren Ordner oder den registrierten DeepSeek Harness-Installationsordner.", + "INSTALLER_PATH_WRITABLE": "Dieser Ort ist nicht beschreibbar. Wählen Sie einen Ordner, der für den aktuellen Benutzer verfügbar ist.", + "INSTALLER_DISK_SPACE": "Es ist nicht genügend freier Speicherplatz vorhanden. Wählen Sie einen anderen Standort.", + "INSTALLER_PER_USER": "Dieses Installationsprogramm unterstützt nur den aktuellen Benutzer. Deinstallieren Sie zunächst die vorhandene All-User-Installation.", + "INSTALLER_EXTRACT_FAILED": "Die Anwendungsdateien konnten nicht extrahiert werden.", + "INSTALLER_EXTRACT_HINT": "Möglicherweise hat die Sicherheitssoftware eine Datei blockiert oder die Festplatte ist voll. Schließen Sie dieses Installationsprogramm und versuchen Sie es erneut. Wenn es weiterhin fehlschlägt, senden Sie uns die Fehlerdetails unten.", + "INSTALLER_EXTRACT_COPY": "Fehlerdetails kopieren", + "INSTALLER_EXTRACT_EXPAND": "Details anzeigen", + "INSTALLER_EXTRACT_COLLAPSE": "Details ausblenden", + "INSTALLER_EXTRACT_SAVED": "Der vollständige Bericht wurde unter %s gespeichert", + "INSTALLER_EXTRACT_UNSAVED": "Der vollständige Bericht konnte nicht gespeichert werden. Verwenden Sie „Fehlerdetails kopieren“, um sie beizubehalten.", + "INSTALLER_EXTRACT_COPIED": "Fehlerdetails wurden in die Zwischenablage kopiert." + }, + "uninstaller": { + "welcome": "Willkommen", + "finished": "entfernt worden" + } +} diff --git a/apps/desktop/installer/locales/es_ES.json b/apps/desktop/installer/locales/es_ES.json new file mode 100644 index 0000000000..d4fbfd972f --- /dev/null +++ b/apps/desktop/installer/locales/es_ES.json @@ -0,0 +1,40 @@ +{ + "nsisLanguage": "SPANISHINTERNATIONAL", + "strings": { + "INSTALLER_INSTALL": "Instalar ahora", + "INSTALLER_FINISH": "Finalizar", + "INSTALLER_NATIVE_PROGRESS": "Preparando la instalación… %d%%", + "INSTALLER_PROGRESS_EXTRACT": "Extrayendo archivos… %d%%", + "INSTALLER_PROGRESS_COPY": "Instalando archivos… %d%%", + "INSTALLER_PROGRESS_REGISTER": "Terminando la instalación… %d%%", + "INSTALLER_PROGRESS_CLEAN": "Limpieza de archivos temporales… %d%%", + "INSTALLER_CHOOSE_PATH": "Elige ubicación", + "INSTALLER_BROWSE": "Examinar", + "INSTALLER_LAUNCH": "Lanzar ahora", + "INSTALLER_LAUNCH_FAILED": "No se pudo iniciar DeepSeek Harness. Vuelva a intentarlo o desmarque Iniciar ahora y cierre el instalador.", + "INSTALLER_UI_ERROR": "El instalador no pudo inicializar su ventana. Ciérralo y vuelve a intentarlo.", + "INSTALLER_THEME_ERROR": "Utilice /THEME=auto, /THEME=light o /THEME=dark.", + "INSTALLER_FAILED": "La instalación no terminó. Cierre este instalador y vuelva a intentarlo. Si el problema persiste, descargue el instalador nuevamente.", + "INSTALLER_RUNNING": "DeepSeek Harness se está ejecutando. Salga de la bandeja del sistema y vuelva a intentarlo.", + "INSTALLER_DIRECTORY_FAILED": "No se pudo reemplazar el directorio de instalación.", + "INSTALLER_DIRECTORY_HINT": "Verifique el acceso al directorio de instalación y cierre los programas usando sus archivos, luego ejecute el instalador nuevamente. Copie los detalles del error si el problema persiste.", + "INSTALLER_DIRECTORY_RESTORE_HINT": "No se pudo restaurar la instalación anterior. Mantenga el directorio de respaldo que se muestra en los detalles del error y comuníquese con el soporte antes de volver a instalar.", + "INSTALLER_PATH_INVALID": "Elija una ruta de carpeta local completa. No se admiten raíces de unidades, carpetas del sistema, enlaces ni caracteres especiales.", + "INSTALLER_PATH_OWNERSHIP": "Elija una carpeta vacía o la carpeta de instalación registrada de DeepSeek Harness.", + "INSTALLER_PATH_WRITABLE": "Esta ubicación no se puede escribir. Elija una carpeta disponible para el usuario actual.", + "INSTALLER_DISK_SPACE": "No hay suficiente espacio libre en disco. Elija otra ubicación.", + "INSTALLER_PER_USER": "Este instalador solo admite el usuario actual. Primero desinstale la instalación existente para todos los usuarios.", + "INSTALLER_EXTRACT_FAILED": "No se pudieron extraer los archivos de la aplicación.", + "INSTALLER_EXTRACT_HINT": "Es posible que el software de seguridad haya bloqueado un archivo o que el disco esté lleno. Cierra este instalador y vuelve a intentarlo. Si sigue fallando, envíenos los detalles del error a continuación.", + "INSTALLER_EXTRACT_COPY": "Copiar detalles del error", + "INSTALLER_EXTRACT_EXPAND": "Mostrar detalles", + "INSTALLER_EXTRACT_COLLAPSE": "Ocultar detalles", + "INSTALLER_EXTRACT_SAVED": "El informe completo se guardó en %s.", + "INSTALLER_EXTRACT_UNSAVED": "No se pudo guardar el informe completo. Utilice Copiar detalles del error para conservarlo.", + "INSTALLER_EXTRACT_COPIED": "Los detalles del error se copiaron al portapapeles." + }, + "uninstaller": { + "welcome": "Bienvenido", + "finished": "ha sido desinstalado" + } +} diff --git a/apps/desktop/installer/locales/fr_FR.json b/apps/desktop/installer/locales/fr_FR.json new file mode 100644 index 0000000000..326ead62a8 --- /dev/null +++ b/apps/desktop/installer/locales/fr_FR.json @@ -0,0 +1,40 @@ +{ + "nsisLanguage": "FRENCH", + "strings": { + "INSTALLER_INSTALL": "Installer maintenant", + "INSTALLER_FINISH": "Terminer", + "INSTALLER_NATIVE_PROGRESS": "Préparation de l'installation… %d%%", + "INSTALLER_PROGRESS_EXTRACT": "Extraction de fichiers… %d%%", + "INSTALLER_PROGRESS_COPY": "Installation des fichiers… %d%%", + "INSTALLER_PROGRESS_REGISTER": "Finition de l'installation… %d%%", + "INSTALLER_PROGRESS_CLEAN": "Nettoyage des fichiers temporaires… %d%%", + "INSTALLER_CHOOSE_PATH": "Choisissez un emplacement", + "INSTALLER_BROWSE": "Parcourir", + "INSTALLER_LAUNCH": "Lancez-vous maintenant", + "INSTALLER_LAUNCH_FAILED": "DeepSeek Harness n'a pas pu être lancé. Réessayez ou désactivez Lancer maintenant et fermez le programme d'installation.", + "INSTALLER_UI_ERROR": "Le programme d'installation n'a pas pu initialiser sa fenêtre. Fermez-le et réessayez.", + "INSTALLER_THEME_ERROR": "Utilisez /THEME=auto, /THEME=light ou /THEME=dark.", + "INSTALLER_FAILED": "L'installation n'est pas terminée. Fermez ce programme d'installation et réessayez. Si le problème persiste, téléchargez à nouveau le programme d'installation.", + "INSTALLER_RUNNING": "DeepSeek Harness est en cours d'exécution. Quittez-le de la barre d'état système et réessayez.", + "INSTALLER_DIRECTORY_FAILED": "Le répertoire d'installation n'a pas pu être remplacé.", + "INSTALLER_DIRECTORY_HINT": "Vérifiez l'accès au répertoire d'installation et fermez les programmes à l'aide de ses fichiers, puis réexécutez le programme d'installation. Copiez les détails de l'erreur si le problème persiste.", + "INSTALLER_DIRECTORY_RESTORE_HINT": "L'installation précédente n'a pas pu être restaurée. Conservez le répertoire de sauvegarde indiqué dans les détails de l'erreur et contactez l'assistance avant de procéder à une nouvelle installation.", + "INSTALLER_PATH_INVALID": "Choisissez un chemin de dossier local complet. Les racines du lecteur, les dossiers système, les liens et les caractères spéciaux ne sont pas pris en charge.", + "INSTALLER_PATH_OWNERSHIP": "Choisissez un dossier vide ou le dossier d'installation DeepSeek Harness enregistré.", + "INSTALLER_PATH_WRITABLE": "Cet emplacement n'est pas accessible en écriture. Choisissez un dossier disponible pour l'utilisateur actuel.", + "INSTALLER_DISK_SPACE": "Il n'y a pas assez d'espace disque libre. Choisissez un autre emplacement.", + "INSTALLER_PER_USER": "Ce programme d'installation prend en charge uniquement l'utilisateur actuel. Désinstallez d’abord l’installation existante pour tous les utilisateurs.", + "INSTALLER_EXTRACT_FAILED": "Les fichiers de l'application n'ont pas pu être extraits.", + "INSTALLER_EXTRACT_HINT": "Un logiciel de sécurité a peut-être bloqué un fichier ou le disque est peut-être plein. Fermez ce programme d'installation et réessayez. Si l'échec persiste, envoyez-nous les détails de l'erreur ci-dessous.", + "INSTALLER_EXTRACT_COPY": "Copier les détails de l'erreur", + "INSTALLER_EXTRACT_EXPAND": "Afficher les détails", + "INSTALLER_EXTRACT_COLLAPSE": "Masquer les détails", + "INSTALLER_EXTRACT_SAVED": "Le rapport complet a été enregistré dans %s", + "INSTALLER_EXTRACT_UNSAVED": "Le rapport complet n'a pas pu être enregistré. Utilisez Copier les détails de l'erreur pour le conserver.", + "INSTALLER_EXTRACT_COPIED": "Les détails de l'erreur ont été copiés dans le presse-papiers." + }, + "uninstaller": { + "welcome": "Bienvenue", + "finished": "a été supprimé" + } +} diff --git a/apps/desktop/installer/locales/pt_BR.json b/apps/desktop/installer/locales/pt_BR.json new file mode 100644 index 0000000000..dda249e46f --- /dev/null +++ b/apps/desktop/installer/locales/pt_BR.json @@ -0,0 +1,40 @@ +{ + "nsisLanguage": "PORTUGUESEBR", + "strings": { + "INSTALLER_INSTALL": "Instale agora", + "INSTALLER_FINISH": "Concluir", + "INSTALLER_NATIVE_PROGRESS": "Preparando a instalação… %d%%", + "INSTALLER_PROGRESS_EXTRACT": "Extraindo arquivos… %d%%", + "INSTALLER_PROGRESS_COPY": "Instalando arquivos… %d%%", + "INSTALLER_PROGRESS_REGISTER": "Concluindo a instalação… %d%%", + "INSTALLER_PROGRESS_CLEAN": "Limpando arquivos temporários… %d%%", + "INSTALLER_CHOOSE_PATH": "Escolha o local", + "INSTALLER_BROWSE": "Procurar", + "INSTALLER_LAUNCH": "Lançar agora", + "INSTALLER_LAUNCH_FAILED": "DeepSeek Harness não pôde ser iniciado. Tente novamente ou desmarque Iniciar agora e feche o instalador.", + "INSTALLER_UI_ERROR": "O instalador não conseguiu inicializar sua janela. Feche-o e tente novamente.", + "INSTALLER_THEME_ERROR": "Use /THEME=auto, /THEME=light ou /THEME=dark.", + "INSTALLER_FAILED": "A instalação não foi concluída. Feche este instalador e tente novamente. Se o problema persistir, baixe o instalador novamente.", + "INSTALLER_RUNNING": "DeepSeek Harness está em execução. Saia da bandeja do sistema e tente novamente.", + "INSTALLER_DIRECTORY_FAILED": "O diretório de instalação não pôde ser substituído.", + "INSTALLER_DIRECTORY_HINT": "Verifique o acesso ao diretório de instalação e feche os programas usando seus arquivos e execute o instalador novamente. Copie os detalhes do erro se o problema persistir.", + "INSTALLER_DIRECTORY_RESTORE_HINT": "A instalação anterior não pôde ser restaurada. Mantenha o diretório de backup mostrado nos detalhes do erro e entre em contato com o suporte antes de instalar novamente.", + "INSTALLER_PATH_INVALID": "Escolha um caminho completo para a pasta local. Raízes de unidade, pastas de sistema, links e caracteres especiais não são suportados.", + "INSTALLER_PATH_OWNERSHIP": "Escolha uma pasta vazia ou a pasta de instalação DeepSeek Harness registrada.", + "INSTALLER_PATH_WRITABLE": "Este local não é gravável. Escolha uma pasta disponível para o usuário atual.", + "INSTALLER_DISK_SPACE": "Não há espaço livre suficiente em disco. Escolha outro local.", + "INSTALLER_PER_USER": "Este instalador oferece suporte apenas ao usuário atual. Desinstale primeiro a instalação existente para todos os usuários.", + "INSTALLER_EXTRACT_FAILED": "Os arquivos do aplicativo não puderam ser extraídos.", + "INSTALLER_EXTRACT_HINT": "O software de segurança pode ter bloqueado um arquivo ou o disco pode estar cheio. Feche este instalador e tente novamente. Se continuar falhando, envie-nos os detalhes do erro abaixo.", + "INSTALLER_EXTRACT_COPY": "Copiar detalhes do erro", + "INSTALLER_EXTRACT_EXPAND": "Mostrar detalhes", + "INSTALLER_EXTRACT_COLLAPSE": "Ocultar detalhes", + "INSTALLER_EXTRACT_SAVED": "O relatório completo foi salvo em %s", + "INSTALLER_EXTRACT_UNSAVED": "Não foi possível salvar o relatório completo. Use Copiar detalhes do erro para mantê-lo.", + "INSTALLER_EXTRACT_COPIED": "Os detalhes do erro foram copiados para a área de transferência." + }, + "uninstaller": { + "welcome": "Bem-vindo", + "finished": "foi desinstalado" + } +} diff --git a/apps/desktop/installer/locales/ru_RU.json b/apps/desktop/installer/locales/ru_RU.json new file mode 100644 index 0000000000..e5fec3f8d1 --- /dev/null +++ b/apps/desktop/installer/locales/ru_RU.json @@ -0,0 +1,40 @@ +{ + "nsisLanguage": "RUSSIAN", + "strings": { + "INSTALLER_INSTALL": "Установить сейчас", + "INSTALLER_FINISH": "Готово", + "INSTALLER_NATIVE_PROGRESS": "Подготовка установки… %d%%", + "INSTALLER_PROGRESS_EXTRACT": "Извлечение файлов… %d%%", + "INSTALLER_PROGRESS_COPY": "Установка файлов… %d%%", + "INSTALLER_PROGRESS_REGISTER": "Завершение установки… %d%%", + "INSTALLER_PROGRESS_CLEAN": "Очистка временных файлов… %d%%", + "INSTALLER_CHOOSE_PATH": "Выберите местоположение", + "INSTALLER_BROWSE": "Обзор", + "INSTALLER_LAUNCH": "Запустить сейчас", + "INSTALLER_LAUNCH_FAILED": "DeepSeek Harness не удалось запустить. Повторите попытку или снимите флажок «Запустить сейчас» и закройте программу установки.", + "INSTALLER_UI_ERROR": "Установщику не удалось инициализировать свое окно. Закройте его и попробуйте еще раз.", + "INSTALLER_THEME_ERROR": "Используйте /THEME=auto, /THEME=light или /THEME=dark.", + "INSTALLER_FAILED": "Установка не завершена. Закройте этот установщик и повторите попытку. Если проблема не устранена, загрузите установщик еще раз.", + "INSTALLER_RUNNING": "DeepSeek Harness работает. Закройте его из системного трея и повторите попытку.", + "INSTALLER_DIRECTORY_FAILED": "Не удалось заменить каталог установки.", + "INSTALLER_DIRECTORY_HINT": "Проверьте доступ к каталогу установки и закройте программы, использующие его файлы, затем снова запустите установщик. Скопируйте сведения об ошибке, если проблема не устранена.", + "INSTALLER_DIRECTORY_RESTORE_HINT": "Предыдущую установку восстановить не удалось. Сохраните каталог резервной копии, указанный в сведениях об ошибке, и обратитесь в службу поддержки перед повторной установкой.", + "INSTALLER_PATH_INVALID": "Выберите полный путь к локальной папке. Корни дисков, системные папки, ссылки и специальные символы не поддерживаются.", + "INSTALLER_PATH_OWNERSHIP": "Выберите пустую папку или зарегистрированную папку установки DeepSeek Harness.", + "INSTALLER_PATH_WRITABLE": "Это местоположение недоступно для записи. Выберите папку, доступную текущему пользователю.", + "INSTALLER_DISK_SPACE": "Недостаточно свободного места на диске. Выберите другое место.", + "INSTALLER_PER_USER": "Этот установщик поддерживает только текущего пользователя. Сначала удалите существующую установку для всех пользователей.", + "INSTALLER_EXTRACT_FAILED": "Файлы приложения не удалось извлечь.", + "INSTALLER_EXTRACT_HINT": "Возможно, программное обеспечение безопасности заблокировало файл или диск переполнен. Закройте этот установщик и повторите попытку. Если ошибка продолжает возникать, отправьте нам сведения об ошибке ниже.", + "INSTALLER_EXTRACT_COPY": "Скопировать сведения об ошибке", + "INSTALLER_EXTRACT_EXPAND": "Показать детали", + "INSTALLER_EXTRACT_COLLAPSE": "Скрыть детали", + "INSTALLER_EXTRACT_SAVED": "Полный отчет сохранен в %s.", + "INSTALLER_EXTRACT_UNSAVED": "Полный отчет не удалось сохранить. Используйте Скопировать сведения об ошибке, чтобы сохранить их.", + "INSTALLER_EXTRACT_COPIED": "Подробности об ошибке скопированы в буфер обмена." + }, + "uninstaller": { + "welcome": "Вас приветствует мастер удаления", + "finished": "удалена" + } +} diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 18a188eb76..b626dab3f9 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-desktop", "description": "Electron desktop shell for a bundled dsh runtime and external plugins", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "private": true, "license": "MIT", "author": { @@ -84,6 +84,8 @@ "@deepseek-ai/dsh-client-shortcuts": "workspace:*", "@deepseek-ai/dsh-atomic-write": "workspace:*", "@deepseek-ai/dsh-client-product-analytics": "workspace:*", + "@deepseek-ai/dsh-plugin-manager": "workspace:*", + "zod": "4.4.3", "@deepseek-ai/dsh-util-file-drag": "workspace:*" } } diff --git a/apps/desktop/packaging/README.i18n.yaml b/apps/desktop/packaging/README.i18n.yaml index 96c2ee0cf0..7a9ff55492 100644 --- a/apps/desktop/packaging/README.i18n.yaml +++ b/apps/desktop/packaging/README.i18n.yaml @@ -15,8 +15,8 @@ en: a6203dc2e690c7e1 zh: 07b516549b8e3328 /desktop-packaging/choose-a-build-path: - en: 17c6bcdefa05a8f8 - zh: 4ee18f832276144d + en: 0b35c7471c09b27a + zh: cc4a382b99fc3210 /desktop-packaging/release-versions: en: 3f38ab26ee195b39 zh: f00eddafa8f3b9ca @@ -24,20 +24,20 @@ en: 5b4f0f80a117f202 zh: ff05be196c181087 /desktop-packaging/windows-actions-packaging: - en: e1b101593f6f755e - zh: 121f225de399de1e + en: 364223725374d9ac + zh: c4d4cc58d7cbafbd /desktop-packaging/macos-self-hosted-packaging: - en: a3af9523fdc60036 - zh: 5e18d4740e9b7f57 + en: bb1dcdfef3f3a113 + zh: 9c151800a61e2505 /desktop-packaging/unsigned-windows-test-installer: - en: 6843a0fdc03ead58 - zh: 957f92fc8126e23e + en: f429bc0c280e2dfa + zh: 4adbcc9e906bdf80 /desktop-packaging/local-macos-dmg-without-release-signing: en: 2feaa0412247d81f zh: 461dde8e13fd4734 /desktop-packaging/macos-release-signing-and-diagnostics: - en: f4a2b14da34ba883 - zh: 6292f3a7b4038213 + en: 29fa6bd8919f3ec0 + zh: 9e31e037fa3d9378 /desktop-packaging/directory-builds-and-preparation: en: 5860c306375ddd63 zh: a76e3cdbbe25c79e @@ -45,14 +45,14 @@ en: b42f103358d0dfd7 zh: a534164ad9eb00da /desktop-packaging/runtime-file-selection-and-installation-checks: - en: bfd89e1d139c5729 - zh: 5d6cced5462ba13e + en: 83e1075417039410 + zh: 3088a7ae0a2cc3c5 /desktop-packaging/desktop-runtime-preparation: - en: a7aa3066e649ffe8 - zh: 4334637910058c09 + en: ab73b67d899e611d + zh: d77b0525c6b81e91 /desktop-packaging/installation-and-release-verification: en: eb35eb973b796643 zh: c1c52311632b7296 /desktop-packaging/dev-note: - en: b75c8458928b72b9 - zh: 003ba4e17b4b5269 + en: 691194744993dfaa + zh: e5798faf99546ff8 diff --git a/apps/desktop/packaging/README.md b/apps/desktop/packaging/README.md index a77d260591..14c1eac90b 100644 --- a/apps/desktop/packaging/README.md +++ b/apps/desktop/packaging/README.md @@ -32,6 +32,8 @@ Build Desktop installers locally or through Windows or macOS Actions, choose dep Run local commands from the repository root after installing locked dependencies. Use platform-specific commands for a local build, or platform Actions for the registered self-hosted runner. Choose test or production deployment independently from signed or unsigned mode. Read [Windows signing and runner operations](../windows-signing/README.md#trust-and-isolation) before any Windows signed build or shared-runner use. Installation is separate from packaging; [publication](../publishing/README.md) is a further explicit operation. +Set `DSH_DESKTOP_PACKAGE_CACHE_DIR` to an absolute build-cache directory for reuse across checkouts; see [cache configuration and lifecycle](#desktop-runtime-preparation). + ## Release versions @@ -113,18 +115,26 @@ Select the workflow in Actions, choose the source branch, preset, signing mode a Open the completed run in Actions and download its Artifacts. `windows-x64-signed---` and `windows-x64-unsigned---` contain the corresponding EXE; `windows-package-logs--` contains packaging diagnostics. The upload steps are `Retain verified signed installer`, `Retain verified unsigned installer`, and `Retain packaging diagnostics`; their step durations and timestamped logs show upload time. These artifacts are not a Release or download-site publication. +For path-sensitive Windows build measurements, `build_root` optionally selects an absolute directory outside existing Git checkouts. Each run clones the validated source commit into a new `windows-package--/source` directory; ignored files and previous build outputs are not copied. Only the packaging process uses a sibling run-owned `temp` directory through `TEMP` and `TMP`; Actions steps and post-job hooks retain their original temporary directories. Dependency and signing caches retain their existing locations. Successful runs remove only their owned checkout after artifact uploads, retrying transient filesystem failures up to three times with 100 ms increasing delays; persistent cleanup errors fail the Job and may leave a partially removed directory. Failed builds retain their checkout for inspection. Leave the input empty to build in the original Actions checkout. Include checkout creation and cleanup in the complete Job timing. + +For cache measurements, `cache_namespace` selects a retained subdirectory for both dependency stores and upstream downloads; leave it empty for normal shared caches. Use a new name for a cold sample and repeat that name for warm samples. Names contain 1–64 lowercase letters, digits or hyphens, start with a letter or digit, and cannot be Windows device names. This does not reset the separate signature cache or OS file cache; report those states and Job start-to-completion time alongside phase timings and artifact size. Before dependency installation, the workflow records the Node version, available CPU parallelism, logical CPU count, and total/free memory. + +The dependency-install and packaging steps normalize their own shell to normal CPU, I/O and memory priority before launching children. Priority and isolated-workspace helpers are copied from the exact workflow commit into a run-specific temporary directory, independently of the selected product source. Missing helpers stop CI setup; unavailable priority adjustment emits a warning and marks scheduling unsuitable for performance comparison, but does not stop packaging. This does not modify the runner task or other processes. Version, preset and retained-artifact adapters remain tied to product source and its formats. + +Installer uploads store the already-compressed release files without ZIP recompression; this preserves installer bytes and signatures. Diagnostic uploads retain their ordinary compression. + ## macOS self-hosted packaging -The `Package Desktop · macOS` [manual workflow](../../../.github/workflows/macos-package.yml) targets an Apple Silicon runner labeled `dsh-mac-package-trial`. It selects `test` or `production`, resolves `build_version=auto` from the UTC date, run number and attempt, and uses the existing signing, notarization and packaged-runtime checks. Successful DMG/ZIP files and diagnostic logs are retained for 14 days; this workflow does not publish a release. The operator must register the runner and verify a complete Actions run before relying on it. +The `Package Desktop · macOS` [manual workflow](../../../.github/workflows/macos-package.yml) targets an Apple Silicon runner labeled `dsh-mac-package-trial`. It selects `test` or `production`, resolves `build_version=auto` from the UTC date, run number and attempt, and uses the existing signing, notarization and packaged-runtime checks. Installer upload disables redundant ZIP compression; diagnostic logs retain normal compression. Successful DMG/ZIP files and diagnostic logs are retained for 14 days; this workflow does not publish a release. The operator must register the runner and verify a complete Actions run before relying on it. The `zip_compression_level` dropdown defaults to `3` and also offers `7`; it overrides the machine preset for this run and affects only the ZIP and automatic-update downloads, not the DMG. Run `node apps/desktop/scripts/setup-macos-packaging.mjs "$HOME/dsh-ci"` to prepare private `runner/`, `packaging/{presets,secrets,certificates}` and `cache/macos-signatures` directories without overwriting existing files; append `--check` to inspect them. Fill the [preset](../config/macos-packaging/test.env.example) and [signing](../config/macos-packaging/macos-signing.env.example) templates outside the checkout. Set secret and certificate files to mode `0600`. `DSH_PACKAGING_CONFIG_DIR` selects the absolute `packaging` directory and `DSH_PACKAGING_PRESET` selects its preset; missing files fail without falling back to `.env.macos`. Signed and preparation-only Mac builds read `secrets/macos-signing.env`; relative credential paths resolve beside that file. Public presets reject signing credentials, and signing files cannot override public settings. Local unsigned Mac builds retain their configuration-free behavior. Run `bash apps/desktop/scripts/start-macos-packaging-runner.sh "$HOME/dsh-ci/runner" "$HOME/dsh-ci/packaging" --check` to check the host tools and configuration files. The script selects the active Xcode and its macOS SDK together and compiles a small linker probe. After registration, omit `--check` to run in the foreground with a cleared inherited environment and prevent idle sleep while the runner is alive. Stop it with Ctrl-C before installing the service below. The runner owns its `_work` checkout, separate from daily development. The account can read its signing files, so run only trusted code. The existing notarization proxy restoration rules apply; after forced termination, inspect retained recovery records before another build. New setup templates set `DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR` to the absolute `cache/macos-signatures` directory outside checkout. For existing installations, rerun setup and add that field to each preset; existing files are preserved. This retains signatures across clean checkouts; cache verification and limits are described under [macOS signing](#macos-release-signing). -The `skip_notarization` workflow option defaults to `false`; the equivalent CLI flag is `--skip-notarization`. It retains Developer ID signing, DMG signature verification and packaged-runtime verification, but omits Apple notarization and stapling and does not require Apple notarization credentials. DMG/ZIP filenames carry `-unnotarized`, are stored under `.desktop-build/targets//unnotarized-artifacts/`, and are uploaded with an `unnotarized-debug` label. These artifacts are for internal debugging only: Gatekeeper may block downloaded copies, and they are not qualified for distribution or update publishing. No release completion record is written. The flag rejects unsigned, Windows and preparation-only builds. +ZIP compression uses the same configured level with or without notarization; the App is assembled once, then DMG and ZIP are built separately so the ZIP setting does not change DMG compression. The `skip_notarization` workflow option defaults to `false`; the equivalent CLI flag is `--skip-notarization`. It retains Developer ID signing, DMG signature verification and packaged-runtime verification, but omits Apple notarization and stapling and does not require Apple notarization credentials. DMG/ZIP filenames carry `-unnotarized`, are stored under `.desktop-build/targets//unnotarized-artifacts/`, and are uploaded with an `unnotarized-debug` label. These artifacts are for internal debugging only: Gatekeeper may block downloaded copies, and they are not qualified for distribution or update publishing. No release completion record is written. The flag rejects unsigned, Windows and preparation-only builds. Install the user service from the checkout as the same account that registered the runner, without `sudo`: @@ -146,7 +156,7 @@ On Windows x64, use the complete unsigned packaging command for local installati pnpm run package:desktop:win:x64:unsigned ``` -The command reads `.env.windows` and requires `DSH_DESKTOP_APP_ID` and the [mandatory-update policy settings](../README.md#mandatory-update-policy), including a real HTTPS service origin. The local run and CI use Node 24; the remaining tools are the root `packageManager` version of pnpm, Git, PowerShell, tar, Python, Visual C++ Build Tools and a Windows SDK. Set `PYTHON` when Python is absent from `PATH`. It writes the installer to `.desktop-build/targets/win-x64/unsigned-artifacts/`, omits ordinary automatic-update configuration, strips signing credentials, and creates no release completion record. EV and upload credentials are unnecessary. Signed packaging and upload retain their release requirements. +The command reads `.env.windows` and requires `DSH_DESKTOP_APP_ID` and the [mandatory-update policy settings](../README.md#mandatory-update-policy), including a real HTTPS service origin. The local run and CI use Node 24; the remaining tools are the root `packageManager` version of pnpm, Git, PowerShell 7 (`pwsh`), tar, Python, Visual C++ Build Tools and a Windows SDK. Set `PYTHON` when Python is absent from `PATH`. It writes the installer to `.desktop-build/targets/win-x64/unsigned-artifacts/`, omits ordinary automatic-update configuration, strips signing credentials, and creates no release completion record. EV and upload credentials are unnecessary. Signed packaging and upload retain their release requirements. Run `pnpm install --frozen-lockfile`, then `pnpm run package:desktop:win:x64:unsigned --check` to validate configuration and tooling before the full command above. Packaging performs its own complete build and isolated runtime smoke without an online model. Stage logs remain under `.desktop-build/packaging-runs/`; a successful build alone does not qualify the installer. Dependency installation and runtime preparation need access to npm, GitHub release assets and nodejs.org; use the existing registry and proxy configuration when the network requires it. Caches and tool locations belong to the build machine, not tracked personal paths. @@ -179,11 +189,12 @@ Mac package commands print `DESKTOP_PACKAGING_RECORD` with a unique directory un App and DMG notarization each record a submission ID and separate `notarytool:upload:*` and `notarytool:wait:*` durations. Upload uses `submit --no-wait` and includes authentication, local validation, transfer and server acceptance; it is not pure transfer time. Waiting starts after that command returns and includes polling and remaining Apple processing; Apple can start processing before upload submission returns. Apple status and diagnostic logs are retained, including rejection; signature checks, acceptance checks and stapling remain owned by `@electron/notarize`. Directory-only package commands use this same measured App notarization path. Individual subprocess output remains live in the terminal, while phase failures and nested errors are retained in the journal. Both platforms record parent-process packaging failures and print redacted diagnostics, including proxy recovery instructions, to the terminal. The configuration-only `check:package` command creates no run log. -Mac packaging reads three tuning fields from `.env.macos`: +Mac packaging reads these tuning fields from `.env.macos`: | Setting | Default | Scope | |---|---|---| | `DSH_DESKTOP_MACOS_PACK_CONCURRENCY` | `4` | Workers for first-party and vendor workspace tarballs; requires a positive integer. | +| `DSH_DESKTOP_MACOS_ZIP_COMPRESSION_LEVEL` | `3` | Final update ZIP compression, integer `0`–`9`; lower levels trade larger downloads for shorter builds. App notarization archives and DMG compression are unchanged. | | `DSH_DESKTOP_MACOS_DOWNLOAD_PROXY` | Empty | HTTP/HTTPS proxy origin for Electron, runtime assets, pnpm installation and builder downloads. | | `DSH_DESKTOP_MACOS_NOTARIZATION_PROXY` | Empty | HTTP proxy origin for Apple tools through temporary system proxy settings. | @@ -254,18 +265,26 @@ When extraction fails, the installer writes a report with the 7-Zip result and i Windows packaging fixes the 7-Zip filter to `BCJ` for compatibility with the bundled NSIS decoder. This preserves ARM64 binaries carried by dependencies in x64 installers; automatic ARM64 filtering produces entries that this decoder cannot extract. +`DSH_DESKTOP_WINDOWS_COMPRESSION_LEVEL` in the Windows dotenv or machine preset selects installer archive compression from `0` to `9`. If omitted, the existing `ELECTRON_BUILDER_COMPRESSION_LEVEL` environment override remains effective, otherwise the default is `3` for both test and production. The manual Windows workflow's `compression_level` dropdown defaults to `3` and also offers `7`, matching the Mac ZIP choices; it overrides the file setting for that run. Direct local builds retain explicit machine settings. Mac ZIP workflow overrides must be `3` or `7`; an empty value is invalid even on macOS. Any defined Mac ZIP workflow override, including an empty value, rejects Windows; nonempty Windows workflow overrides reject macOS. Lower levels trade installer size for packaging time; qualify the complete signed workflow and artifact size before changing a release preset. + NSIS removes its temporary extraction tree during installation, before the completion page or an automatic launch. The installed production packages remain ordinary files; startup does not extract them again. Installation still writes the complete application tree. ## Desktop runtime preparation +Windows prepares Electron and primary-runtime concurrently; macOS prepares them serially. CLI preparation and `versions.json` publication require both payloads to succeed. If either Windows payload fails, preparation waits for the other to settle before reporting failure and publishes neither CLI resources nor versions. Nested preparation timings overlap and must not be added together. + +`DSH_DESKTOP_PACKAGE_CACHE_DIR` in the packaging process environment selects a nonempty absolute directory for shared `downloads` and `pnpm-store` caches; omission uses `.desktop-build`. Temporary installation projects, lockfiles and configuration remain separate per run. Runtime installation verifies store integrity and copies package files so later signing cannot modify cached bytes; cleanup retains these caches. Both packaging workflows use `runner.tool_cache/dsh-desktop-package-cache`; Windows repository dependency installation uses a separate `.pnpm-store` at the workspace drive root. Both installation logs identify their store and report package reuse. A fresh runtime lockfile still resolves dependencies on every run. Share writable caches only among trusted build jobs; integrity checks do not isolate untrusted writers. Clean caches only when no job is using them. Operators manage cache disk usage; no automatic eviction runs. + Desktop [patch policy](../scripts/runtime-patch-policy.ts) explicitly classifies every workspace patch as shared, workspace-only, or runtime-only. Shared entries reuse the root patch bytes and verify their hash against the root lockfile; runtime-only entries use separate repository files without changing workspace installation. Workspace-only patches belong to build tools or dependencies already embedded in client bundles. Unclassified or stale entries, missing files, changed hashes, incompatible resolved versions, and workspace-only packages entering the runtime stop packaging. The [preparation script](../scripts/prepare-runtime-patches.ts) writes only to the temporary project; pnpm applies the selected patches and rejects application failures. Desktop dependency overrides are declared separately in the patch-policy module, not inferred from patch versions. The pi-ai constraint keeps its runtime version at the version qualified by the shared patch. Desktop still resolves a fresh runtime lockfile for each build, then installs with `--frozen-lockfile`; dependency resolution across separate builds is not yet reproducible. CLI packed-installation tests and other distribution flows retain their own configuration. Every package command builds the repository, packs the first-party production closures rooted at dsh and the private Desktop Host, and prepares the target Electron distribution plus primary-runtime with its shared pnpm CLI. `prepare:dsh` installs the production graph once at build time, prepares materialized packages for electron-builder to archive under `app.asar/dsh`, removes package-manager metadata, and writes `desktop-runtime.json` with shared package versions and final file hashes. Signed macOS builds sign and verify native files before inventory generation; electron-builder excludes this already-signed tree from nested re-signing. Resource mappings explicitly include `dsh/node_modules`, which the default root-directory filter omits; the prepared runtime inventory is checked after native signing. Native executables and libraries are unpacked beside ASAR; Python, standalone Node and pnpm remain in external runtime resources. Windows packaging checks every prepared PE against its ASAR unpacked entry and byte-identical disk copy, including unsigned builds. Builder glob rules match braces in PE filenames as single-character wildcards, so a matching neighboring file may also be unpacked. Prepared runtime smoke uses the verified target descriptor rather than the build host architecture. Signed installer, notarization, installed upgrade, and target-specific native-module qualification require the release environment. +Windows runtime sealing reads at most eight files concurrently, before and after native signing. A read failure drains outstanding reads without replacing the descriptor; successful sealing still requires the subsequent complete integrity and smoke checks. + Signed macOS packaging writes `Contents/Resources/app-update.yml` while assembling the App and before code signing, including the directory build that feeds the parallel ZIP and DMG lanes. The signing hook verifies the exact feed and updater cache directory. Both lane copies and the promoted App are checked again before the release completion record is written; a missing or mismatched configuration prevents artifact promotion and therefore prevents upload. An unpacked artifact contains Electron, the materialized dsh production tree, pnpm, and the shell application. Installer size and filesystem size differ; release qualification measures both, plus the profile’s plugin storage and first-launch latency. The runtime trades more application files for eliminating core package installation on the user’s machine. @@ -280,4 +299,4 @@ Keep the generated installer, its version and packaging records together. Review ## Dev Note -None. +XXX: Evaluate disk-space monitoring, a maintenance entry point and automatic eviction if disk shortages, sustained cache growth or frequent manual cleanup occur. Any automated cleanup would need coordination with every cache user. diff --git a/apps/desktop/packaging/README.zh.md b/apps/desktop/packaging/README.zh.md index 54e9d740f8..0f059c74a4 100644 --- a/apps/desktop/packaging/README.zh.md +++ b/apps/desktop/packaging/README.zh.md @@ -32,6 +32,8 @@ description: "在本地或 Windows/macOS Actions 中生成 Desktop 安装包 安装锁定依赖后,从仓库根目录运行本地命令。本地构建使用平台命令,已注册的自托管 runner 使用对应平台的 Actions。test/production 部署与 signed/unsigned 模式分别选择。任何 Windows 签名构建或共享 runner 使用前,先阅读 [Windows 签名与 runner 运维](../windows-signing/README.zh.md#trust-and-isolation)。安装与打包分开进行;[发布](../publishing/README.zh.md)还需要单独的显式操作。 +将 `DSH_DESKTOP_PACKAGE_CACHE_DIR` 设为绝对构建缓存目录以跨 checkout 复用;详见[缓存配置与生命周期](#desktop-runtime-preparation)。 + ## 发布版本 @@ -113,18 +115,26 @@ runner 的受监督启动和恢复见 [Windows runner 机器准备](../windows-s 在 Actions 打开完成的运行并下载 Artifacts。`windows-x64-signed---` 与 `windows-x64-unsigned---` 包含对应 EXE;`windows-package-logs--` 包含打包诊断。上传步骤名为 `Retain verified signed installer`、`Retain verified unsigned installer` 和 `Retain packaging diagnostics`;步骤耗时与带时间戳的日志显示上传用时。这些产物不等于发布 Release 或下载站内容。 +测量 Windows 构建路径对性能的影响时,可用 `build_root` 指定现有 Git checkout 之外的绝对目录。每轮任务将已验证的源码提交克隆到新的 `windows-package--/source` 目录;不会复制忽略文件或此前的构建输出。仅打包进程通过 `TEMP` 和 `TMP` 使用同轮所属的同级 `temp` 目录;Actions 步骤及 Job 后置钩子保留原临时目录。依赖缓存和签名缓存沿用原有位置。成功任务在产物上传后仅删除本轮所属的 checkout,临时文件系统错误最多重试三次,等待时间按 100 ms 递增;持续清理失败会使 Job 失败,并可能留下部分删除的目录。构建失败时保留 checkout 供检查。输入留空时使用原 Actions checkout。完整 Job 耗时须包含 checkout 创建和清理。 + +测量缓存时,`cache_namespace` 为两个依赖 store 和上游下载选择保留的子目录;留空使用正常共享缓存。新名称用于冷缓存采样,再次使用同名用于热缓存采样。名称由 1–64 个小写字母、数字或连字符组成,以字母或数字开头,且不能为 Windows 设备名。这不会重置独立的签名缓存或操作系统文件缓存;应将其状态、Job 开始至完成的总耗时与阶段耗时和产物体积一并报告。workflow 在依赖安装前记录 Node 版本、可用 CPU 并行数、逻辑 CPU 数及总内存和空闲内存。 + +依赖安装和打包步骤在启动子进程前,将自身 shell 的 CPU、I/O 和内存优先级调整为普通值。优先级及独立构建目录辅助脚本从 workflow 的精确提交复制到本轮临时目录,与选中的产品源码分离。缺失辅助脚本会终止 CI 准备;无法调整优先级时明确告警并标记调度条件不适合性能对比,但继续打包。这不会修改 runner 任务或其他进程。版本、preset 和产物留存适配器仍跟随产品源码及其格式。 + +安装器上传直接存储已经压缩的发布文件,不再进行 ZIP 二次压缩;安装器字节和签名保持不变。诊断日志上传保留通常的压缩方式。 + ## macOS 自托管打包 -`Package Desktop · macOS` [手动工作流](../../../.github/workflows/macos-package.yml) 使用带有 `dsh-mac-package-trial` 标签的 Apple Silicon runner。它选择 `test` 或 `production`,以 UTC 日期、运行编号和重试次数解析 `build_version=auto`,并复用现有签名、公证和打包运行时检查。成功的 DMG/ZIP 与诊断日志保留 14 天;工作流不发布 release。操作人员须注册 runner,并验收完整 Actions 运行后再依赖该流程。 +`Package Desktop · macOS` [手动工作流](../../../.github/workflows/macos-package.yml) 使用带有 `dsh-mac-package-trial` 标签的 Apple Silicon runner。它选择 `test` 或 `production`,以 UTC 日期、运行编号和重试次数解析 `build_version=auto`,并复用现有签名、公证和打包运行时检查。安装包上传关闭重复 ZIP 压缩;诊断日志保留普通压缩。成功的 DMG/ZIP 与诊断日志保留 14 天;工作流不发布 release。操作人员须注册 runner,并验收完整 Actions 运行后再依赖该流程。 `zip_compression_level` 下拉选项默认为 `3`,也可选择 `7`;本次运行以该选项覆盖机器预设,只影响 ZIP 和自动升级下载,不影响 DMG。 运行 `node apps/desktop/scripts/setup-macos-packaging.mjs "$HOME/dsh-ci"` 创建私有 `runner/`、`packaging/{presets,secrets,certificates}` 和 `cache/macos-signatures` 目录,不覆盖已有文件;追加 `--check` 仅检查。在 checkout 外填写 [preset](../config/macos-packaging/test.env.example) 和[签名](../config/macos-packaging/macos-signing.env.example)模板,将秘密和证书文件权限设为 `0600`。`DSH_PACKAGING_CONFIG_DIR` 指定 `packaging` 的绝对目录,`DSH_PACKAGING_PRESET` 选择其中的 preset;缺少文件立即失败,不回退到 `.env.macos`。Mac 签名和仅准备构建读取 `secrets/macos-signing.env`,相对凭据路径以该文件所在目录为基准。公开 preset 拒绝签名凭据,签名文件不能覆盖公开配置。本地未签名 Mac 构建保留无需配置的行为。 运行 `bash apps/desktop/scripts/start-macos-packaging-runner.sh "$HOME/dsh-ci/runner" "$HOME/dsh-ci/packaging" --check` 检查宿主工具和配置文件。脚本同时选择当前 Xcode 及其 macOS SDK,并编译小型链接探针。注册后省略 `--check`,清理继承环境并在前台启动 runner,存活期间阻止空闲睡眠。安装下方服务前,先用 Ctrl-C 停止。runner 拥有 `_work` 下的源码目录,与日常开发分开。该账户可读取签名文件,因此只执行可信代码。沿用现有公证代理恢复规则;强制终止后,先检查保留的恢复记录再构建。新建模板将 `DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR` 设为 checkout 外 `cache/macos-signatures` 的绝对路径。已有部署重新运行 setup 后,在各 preset 中补上该字段;已有文件保持不变。这样可跨干净检出保留签名;缓存验证和容量限制见 [macOS 签名](#macos-release-signing)。 -工作流选项 `skip_notarization` 默认为 `false`;对应 CLI 参数是 `--skip-notarization`。该模式保留 Developer ID 签名、DMG 签名验证和打包运行时验证,跳过 Apple 公证和 stapling,不要求 Apple 公证凭据。DMG/ZIP 文件名带 `-unnotarized`,存放于 `.desktop-build/targets//unnotarized-artifacts/`,上传产物标为 `unnotarized-debug`。这些产物仅供内部调试:Gatekeeper 可能阻止下载副本运行,不能视为可分发包或用于更新发布。该模式不写入发布完成记录,不能与未签名、Windows 或仅准备构建组合。 +无论是否公证,ZIP 都使用同一压缩配置;App 只组装一次,再分别生成 DMG 和 ZIP,确保 ZIP 设置不改变 DMG 压缩。工作流选项 `skip_notarization` 默认为 `false`;对应 CLI 参数是 `--skip-notarization`。该模式保留 Developer ID 签名、DMG 签名验证和打包运行时验证,跳过 Apple 公证和 stapling,不要求 Apple 公证凭据。DMG/ZIP 文件名带 `-unnotarized`,存放于 `.desktop-build/targets//unnotarized-artifacts/`,上传产物标为 `unnotarized-debug`。这些产物仅供内部调试:Gatekeeper 可能阻止下载副本运行,不能视为可分发包或用于更新发布。该模式不写入发布完成记录,不能与未签名、Windows 或仅准备构建组合。 在 checkout 中,以注册 runner 的同一账户安装用户服务,不使用 `sudo`: @@ -146,7 +156,7 @@ bash apps/desktop/scripts/macos-runner-service.sh status "$HOME/dsh-ci/runner" pnpm run package:desktop:win:x64:unsigned ``` -该命令读取 `.env.windows`,要求设置 `DSH_DESKTOP_APP_ID` 和[强制更新策略配置](../README.zh.md#mandatory-update-policy),包括真实的 HTTPS 服务 origin。本机验收和 CI 使用 Node 24;其他工具为根 `packageManager` 固定版本的 pnpm、Git、PowerShell、tar、Python、Visual C++ Build Tools 和 Windows SDK。Python 不在 `PATH` 中时设置 `PYTHON`。命令将安装包写入 `.desktop-build/targets/win-x64/unsigned-artifacts/`,省略普通自动更新配置,清除签名凭据,且不生成发布完成记录。无需 EV 或上传凭据。签名打包和上传仍遵循正式发布要求。 +该命令读取 `.env.windows`,要求设置 `DSH_DESKTOP_APP_ID` 和[强制更新策略配置](../README.zh.md#mandatory-update-policy),包括真实的 HTTPS 服务 origin。本机验收和 CI 使用 Node 24;其他工具为根 `packageManager` 固定版本的 pnpm、Git、PowerShell 7(`pwsh`)、tar、Python、Visual C++ Build Tools 和 Windows SDK。Python 不在 `PATH` 中时设置 `PYTHON`。命令将安装包写入 `.desktop-build/targets/win-x64/unsigned-artifacts/`,省略普通自动更新配置,清除签名凭据,且不生成发布完成记录。无需 EV 或上传凭据。签名打包和上传仍遵循正式发布要求。 先运行 `pnpm install --frozen-lockfile`,再运行 `pnpm run package:desktop:win:x64:unsigned --check` 校验配置和工具,最后执行上面的完整命令。打包自行执行完整构建和隔离的运行时 smoke,不调用在线模型。阶段日志保留在 `.desktop-build/packaging-runs/`;仅构建成功不代表安装包验证通过。依赖安装和运行时准备需要访问 npm、GitHub release 资源和 nodejs.org;网络需要时使用现有 registry 和代理配置。缓存与工具位置属于构建机器配置,不在跟踪文件中固定个人路径。 @@ -179,11 +189,12 @@ Mac 打包命令通过 `DESKTOP_PACKAGING_RECORD` 输出 `apps/desktop/.desktop- App 和 DMG 公证分别记录 submission ID,以及独立的 `notarytool:upload:*` 和 `notarytool:wait:*` 耗时。上传使用 `submit --no-wait`,包含认证、本地校验、传输和服务端受理,并非纯传输时间。等待从该命令返回后开始,包含轮询及剩余的 Apple 处理时间;Apple 可能在上传提交命令返回前已开始处理。日志保留 Apple 状态与诊断信息,包括拒绝结果;签名检查、接受状态校验和 stapling 仍由 `@electron/notarize` 负责。仅生成目录的打包命令也使用同一条可计时的 App 公证路径。各子进程输出仍实时显示在终端,阶段失败及嵌套错误保留在事件日志中。两个平台均记录父进程打包失败,并在终端显示脱敏诊断,包括代理恢复操作指引。仅检查配置的 `check:package` 命令不创建运行日志。 -Mac 打包从 `.env.macos` 读取三个调优字段: +Mac 打包从 `.env.macos` 读取以下调优字段: | 设置 | 默认值 | 作用范围 | |---|---|---| | `DSH_DESKTOP_MACOS_PACK_CONCURRENCY` | `4` | 第一方与 vendor workspace tarball 的打包 worker 数;必须是正整数。 | +| `DSH_DESKTOP_MACOS_ZIP_COMPRESSION_LEVEL` | `3` | 最终更新 ZIP 的压缩等级,整数 `0`–`9`;较低等级以更大的下载体积换取更短的构建时间。App 公证归档和 DMG 压缩不变。 | | `DSH_DESKTOP_MACOS_DOWNLOAD_PROXY` | 空 | Electron、运行时资源、pnpm 安装及 builder 下载使用的 HTTP/HTTPS 代理 origin。 | | `DSH_DESKTOP_MACOS_NOTARIZATION_PROXY` | 空 | 通过临时系统代理设置供 Apple 工具使用的 HTTP 代理 origin。 | @@ -254,18 +265,26 @@ Windows 安装器在启动时和选定目标目录后检查应用是否正在运 Windows 打包将 7-Zip 过滤器固定为 `BCJ`,以兼容内置的 NSIS 解码器。这样可以保留 x64 安装包中由依赖携带的 ARM64 二进制文件;自动 ARM64 过滤会生成该解码器无法解压的条目。 +Windows dotenv 或机器 preset 中的 `DSH_DESKTOP_WINDOWS_COMPRESSION_LEVEL` 选择 `0` 至 `9` 的安装包归档压缩等级。省略时,现有 `ELECTRON_BUILDER_COMPRESSION_LEVEL` 环境覆盖仍然生效,否则 test 和 production 均默认为 `3`。手动 Windows workflow 的 `compression_level` 下拉默认选 `3`,也提供 `7`,与 Mac ZIP 选项一致;它对本轮覆盖文件中的设置。直接本地打包保留显式机器配置。Mac ZIP workflow 覆盖值必须为 `3` 或 `7`;空值在 macOS 上也非法。任何已定义的 Mac ZIP workflow 覆盖值(包括空值)均拒绝用于 Windows;非空的 Windows workflow 覆盖值拒绝用于 macOS。较低等级以安装包体积换取打包时间;修改发布 preset 前应验证完整签名 workflow 和产物体积。 + NSIS 在安装阶段清理临时解压目录,完成后才显示完成页或自动启动应用。已安装的生产依赖保持为普通文件;启动时不会再次解压。安装仍会写入完整的应用目录树。 ## Desktop 运行时准备 +Windows 并行准备 Electron 和 primary-runtime;macOS 串行准备二者。只有两份运行时资源均成功,才会准备 CLI 并写入 `versions.json`。任一 Windows 运行时准备失败时,流程会等待另一路结束后再报告失败,且不写入 CLI 资源或版本记录。嵌套准备阶段的计时存在重叠,不能直接相加。 + +打包进程环境中的 `DSH_DESKTOP_PACKAGE_CACHE_DIR` 为共享的 `downloads` 和 `pnpm-store` 缓存指定非空绝对目录;省略时使用 `.desktop-build`。临时安装项目、lockfile 和配置仍逐次独立创建。运行时安装校验 store 完整性并复制包文件,防止后续签名修改缓存字节;清理时保留这些缓存。两个打包工作流使用 `runner.tool_cache/dsh-desktop-package-cache`;Windows 仓库依赖安装使用工作区盘根目录下独立的 `.pnpm-store`。两次安装日志均标明各自的 store 并报告包复用情况。每次运行仍通过新的运行时 lockfile 解析依赖。可写缓存仅供可信构建任务共享;完整性校验不能隔离不可信的写入者。仅在没有任务使用缓存时清理。缓存磁盘用量由操作者管理,不自动淘汰。 + Desktop [补丁策略](../scripts/runtime-patch-policy.ts) 将每份工作区补丁明确归为共享、仅工作区或仅运行时。共享项复用根目录补丁字节,并对照根锁文件校验 hash;仅运行时项使用仓库内的独立文件,不改变工作区安装。仅工作区补丁用于构建工具或已嵌入客户端 bundle 的依赖。未分类或过期的条目、文件缺失、hash 改变、解析版本不兼容,以及仅工作区包进入运行时,都会阻止打包。[准备脚本](../scripts/prepare-runtime-patches.ts) 只写入临时项目;pnpm 负责应用选中的补丁,应用失败时会报错。 Desktop 依赖 overrides 在补丁策略模块中单独声明,不从补丁版本推导。pi-ai 约束使运行时版本保持在共享补丁已验证的版本。Desktop 仍会在每次构建时重新解析运行时锁文件,再通过 `--frozen-lockfile` 安装;不同构建之间的依赖解析尚不保证可复现。CLI 打包安装测试及其他交付流程保留各自的配置。 每条打包命令都会构建仓库,打包以 dsh 和私有 Desktop Host 为根的第一方生产依赖闭包,并准备目标专用的 Electron 分发包和包含共享 pnpm CLI 的 primary-runtime。`prepare:dsh` 在构建时安装一次生产依赖图,准备物化包供 electron-builder 归档到 `app.asar/dsh`,移除包管理器元数据,并生成包含共享包版本和最终文件哈希的 `desktop-runtime.json`。macOS 签名构建先签名并验证原生文件,再生成清单;electron-builder 不对已签名的此目录重复进行嵌套签名。资源映射明确包含默认根目录过滤器会忽略的 `dsh/node_modules`;准备完成的运行时清单在原生签名后检查。原生可执行文件及库解包到 ASAR 旁;Python、独立 Node 和 pnpm 保留在外部 runtime 资源中。Windows 打包逐项检查准备好的 PE,确认其 ASAR 条目已标记为解包,且磁盘副本字节一致;未签名构建也执行此检查。Builder glob 规则用单字符通配符匹配 PE 文件名中的花括号,因此同目录中名称匹配的文件也可能被解包。准备好的运行时 smoke 沿用已验证的目标描述符,不使用构建宿主的架构。签名安装包、公证、已安装应用升级和各目标原生模块的验收需要发布环境。 +Windows 运行时在原生签名前后封存文件清单,每次最多并发读取八个文件。读取失败时会等待未完成的读取结束,不替换描述符;封存成功后仍须完成后续的完整性与 smoke 检查。 + macOS 签名打包在组装 App 时、代码签名前写入 `Contents/Resources/app-update.yml`,供并行 ZIP 与 DMG 路线使用的目录构建也执行此操作。签名钩子验证准确的更新源和 updater 缓存目录。写入发布完成记录前,流程会再次检查两条路线的副本和最终移入的 App;配置缺失或不匹配会阻止移入产物,因而也会阻止上传。 未压缩产物包含 Electron、物化后的 dsh 生产依赖树、pnpm,以及壳应用。安装包大小与文件系统占用不同;发布验收需要测量两者,以及 profile 插件存储和首次启动耗时。此布局用更多应用内文件换取消除用户机器上的核心包安装过程。 @@ -280,4 +299,4 @@ Windows 以不带版本后缀的产品名称显示已安装应用,版本保留 ## 开发备注 -无。 +XXX:出现磁盘空间不足、缓存持续增长或频繁人工清理时,评估空间监测、维护入口和自动淘汰。任何自动清理方案都需要与所有使用缓存的任务协调。 diff --git a/apps/desktop/scripts/desktop-build-paths.d.mts b/apps/desktop/scripts/desktop-build-paths.d.mts index c7b8173ca1..910f3032ee 100644 --- a/apps/desktop/scripts/desktop-build-paths.d.mts +++ b/apps/desktop/scripts/desktop-build-paths.d.mts @@ -1,6 +1,6 @@ import type { DesktopAutoUpdateTarget } from './desktop-auto-update-environment.mjs' -/** Mutable target directories plus the shared immutable download cache. */ +/** Mutable target directories plus shared download and package caches. */ export interface DesktopTargetBuildPaths { readonly root: string readonly artifacts: string @@ -15,6 +15,7 @@ export interface DesktopTargetBuildPaths { readonly packedVendor: string readonly packedLandlock: string readonly downloads: string + readonly pnpmStore: string } /** @@ -33,9 +34,10 @@ export function resolveDesktopBuildTarget( /** * Return the mutable preparation and artifact directories owned by one release target. * @param target - Supported Desktop target name. - * @returns Target paths plus the shared immutable download cache. + * @param environment - Packaging environment with an optional absolute cache directory. + * @returns Target paths plus shared download and package caches. */ -export function desktopTargetBuildPaths(target: DesktopAutoUpdateTarget): DesktopTargetBuildPaths +export function desktopTargetBuildPaths(target: DesktopAutoUpdateTarget, environment?: NodeJS.ProcessEnv): DesktopTargetBuildPaths /** * Return the platform and architecture of the payload one release target prepares. diff --git a/apps/desktop/scripts/desktop-build-paths.mjs b/apps/desktop/scripts/desktop-build-paths.mjs index e577b1d3fe..bf2361a695 100644 --- a/apps/desktop/scripts/desktop-build-paths.mjs +++ b/apps/desktop/scripts/desktop-build-paths.mjs @@ -1,6 +1,6 @@ -/** Resolve build-owned Desktop paths without sharing mutable state across release targets. */ +/** Resolve target-owned Desktop outputs and shared package caches. */ -import { join, resolve } from 'node:path' +import { isAbsolute, join, resolve } from 'node:path' const APP_ROOT = resolve(import.meta.dirname, '..') const BUILD_ROOT = join(APP_ROOT, '.desktop-build') @@ -38,10 +38,15 @@ function assertSupportedTarget(target) { /** * Return the mutable preparation and artifact directories owned by one release target. * @param {'mac-arm64' | 'mac-x64' | 'win-x64'} target - Supported Desktop target name. - * @returns {{ root: string, artifacts: string, unsignedArtifacts: string, unnotarizedArtifacts: string, runtime: string, packageSet: string, dsh: string, dshPnpm: string, electron: string, packedDsh: string, packedVendor: string, packedLandlock: string, downloads: string }} Target paths plus the shared immutable download cache. + * @param {NodeJS.ProcessEnv} environment - Packaging environment with an optional absolute cache directory. + * @returns {{ root: string, artifacts: string, unsignedArtifacts: string, unnotarizedArtifacts: string, runtime: string, packageSet: string, dsh: string, dshPnpm: string, electron: string, packedDsh: string, packedVendor: string, packedLandlock: string, downloads: string, pnpmStore: string }} Target paths plus shared download and package caches. */ -export function desktopTargetBuildPaths(target) { +export function desktopTargetBuildPaths(target, environment = process.env) { assertSupportedTarget(target) + const cacheRoot = environment.DSH_DESKTOP_PACKAGE_CACHE_DIR ?? BUILD_ROOT + if (!cacheRoot.trim() || !isAbsolute(cacheRoot) || cacheRoot.includes('\0')) { + throw new Error('desktop package: DSH_DESKTOP_PACKAGE_CACHE_DIR must be a nonempty absolute directory') + } const root = join(BUILD_ROOT, 'targets', target) const packed = join(root, 'packed') return { @@ -57,7 +62,8 @@ export function desktopTargetBuildPaths(target) { packedDsh: join(packed, 'dsh'), packedVendor: join(packed, 'vendor'), packedLandlock: join(packed, 'landlock'), - downloads: join(BUILD_ROOT, 'downloads'), + downloads: join(cacheRoot, 'downloads'), + pnpmStore: join(cacheRoot, 'pnpm-store'), } } @@ -87,7 +93,7 @@ export function resolveDesktopTargetBuildPaths( hostPlatform = process.platform, hostArch = process.arch, ) { - return desktopTargetBuildPaths(resolveDesktopBuildTarget(env, hostPlatform, hostArch)) + return desktopTargetBuildPaths(resolveDesktopBuildTarget(env, hostPlatform, hostArch), env) } /** diff --git a/apps/desktop/scripts/desktop-package-environment.d.mts b/apps/desktop/scripts/desktop-package-environment.d.mts index 995c117d07..ec9da721f1 100644 --- a/apps/desktop/scripts/desktop-package-environment.d.mts +++ b/apps/desktop/scripts/desktop-package-environment.d.mts @@ -10,6 +10,9 @@ export function localMacOSPackageEnvironment(environment?: NodeJS.ProcessEnv): N /** * Read a machine preset when selected, otherwise the target's required dotenv; no ambient release fallback. * PACKAGE_TEST_RELEASE_ID overrides the test preset only; blank retains its configured ID. + * PACKAGE_MACOS_ZIP_COMPRESSION_LEVEL overrides the Mac file setting with 3 or 7; an empty value is invalid. + * Any defined Mac ZIP override rejects Windows, including an empty value; nonempty Windows overrides reject macOS. + * PACKAGE_WINDOWS_COMPRESSION_LEVEL selects 3 or 7 for Windows workflow builds; blank retains the file setting. * @param platform Target platform. * @param environment Parent environment, retained only for unrelated build tools. * @param appRoot Desktop application directory; relative credential paths resolve here. diff --git a/apps/desktop/scripts/desktop-package-environment.mjs b/apps/desktop/scripts/desktop-package-environment.mjs index 32f58ce874..9877b25d09 100644 --- a/apps/desktop/scripts/desktop-package-environment.mjs +++ b/apps/desktop/scripts/desktop-package-environment.mjs @@ -12,11 +12,12 @@ import { validateMacOSSignatureCacheDirectory } from './macos-signature-cache-di import { resolveMacOSPackageSettings } from './macos-package-settings.mjs' import { resolveWindowsSignatureCacheDirectory } from './windows-signature-cache-directory.mjs' import { resolveWindowsPackageSettings } from './windows-package-settings.mjs' +import { resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs' const APP_ROOT = fileURLToPath(new URL('..', import.meta.url)) const SHARED_SETTING = /^(?:DSH_DESKTOP_(?:APP_ID|AUTO_UPDATE_ENV|NPM_REGISTRY|MANDATORY_UPDATE_(?:CONFIG|(?:TEST|PROD)_ORIGIN))|DOWNLOAD_TEST_RELEASE_ID|DOWNLOAD_(?:TEST|PROD)_(?:ORIGIN|COS_BUCKET|COS_SECRET_ID|COS_SECRET_KEY))$/u -const WINDOWS_SETTING = /^DSH_DESKTOP_WINDOWS_(?:CER_FILE|SIGNTOOL|KEY_CONTAINER|TOKEN_PIN|SIGNATURE_CACHE_DIR|SIGNATURE_CACHE_CONCURRENCY|PACK_CONCURRENCY)$/u -const MACOS_SETTING = /^(?:DSH_DESKTOP_MACOS_(?:SIGNING_IDENTITY|TEAM_ID|SIGNATURE_CACHE_DIR|PACK_CONCURRENCY|DOWNLOAD_PROXY|NOTARIZATION_PROXY)|APPLE_(?:API_KEY|API_KEY_ID|API_ISSUER|ID|APP_SPECIFIC_PASSWORD|TEAM_ID|KEYCHAIN|KEYCHAIN_PROFILE)|CSC_(?:LINK|KEY_PASSWORD))$/u +const WINDOWS_SETTING = /^DSH_DESKTOP_WINDOWS_(?:CER_FILE|SIGNTOOL|KEY_CONTAINER|TOKEN_PIN|SIGNATURE_CACHE_DIR|SIGNATURE_CACHE_CONCURRENCY|PACK_CONCURRENCY|COMPRESSION_LEVEL)$/u +const MACOS_SETTING = /^(?:DSH_DESKTOP_MACOS_(?:SIGNING_IDENTITY|TEAM_ID|SIGNATURE_CACHE_DIR|PACK_CONCURRENCY|ZIP_COMPRESSION_LEVEL|DOWNLOAD_PROXY|NOTARIZATION_PROXY)|APPLE_(?:API_KEY|API_KEY_ID|API_ISSUER|ID|APP_SPECIFIC_PASSWORD|TEAM_ID|KEYCHAIN|KEYCHAIN_PROFILE)|CSC_(?:LINK|KEY_PASSWORD))$/u const AMBIENT_RELEASE_SETTING = /^(?:DSH_DESKTOP_(?:APP_ID|AUTO_UPDATE_ENV|MANDATORY_UPDATE_.*|WINDOWS_.*|MACOS_.*)|APPLE_.*|(?:WIN_)?CSC_.*|DOWNLOAD_(?:TEST|PROD)_.*)$/iu const FILE_SETTINGS = ['DSH_DESKTOP_WINDOWS_CER_FILE', 'DSH_DESKTOP_WINDOWS_SIGNTOOL', 'APPLE_API_KEY', 'APPLE_KEYCHAIN', 'CSC_LINK'] @@ -35,7 +36,10 @@ export function localMacOSPackageEnvironment(environment = process.env) { /** * Read a machine preset when selected, otherwise the target's required dotenv; no ambient release fallback. + * PACKAGE_MACOS_ZIP_COMPRESSION_LEVEL overrides the Mac file setting with 3 or 7; an empty value is invalid. + * Any defined Mac ZIP override rejects Windows, including an empty value; nonempty Windows overrides reject macOS. * PACKAGE_TEST_RELEASE_ID overrides the test preset only; blank retains its configured ID. + * PACKAGE_WINDOWS_COMPRESSION_LEVEL selects 3 or 7 for Windows workflow builds; blank retains the file setting. * @param {'win32' | 'darwin'} platform Target platform. * @param {NodeJS.ProcessEnv} environment Parent environment, retained only for unrelated build tools. * @param {string} appRoot Desktop application directory; relative credential paths resolve here. @@ -43,6 +47,17 @@ export function localMacOSPackageEnvironment(environment = process.env) { * @returns {NodeJS.ProcessEnv} Isolated environment with file-owned release settings. */ export function loadDesktopPackageEnvironment(platform, environment = process.env, appRoot = APP_ROOT, options = {}) { + const compression = environment.PACKAGE_WINDOWS_COMPRESSION_LEVEL + if (compression !== undefined && compression !== '') { + if (platform !== 'win32' || !['3', '7'].includes(compression)) { + throw new Error('desktop package: PACKAGE_WINDOWS_COMPRESSION_LEVEL requires Windows and a choice of 3 or 7') + } + } + const zipCompression = environment.PACKAGE_MACOS_ZIP_COMPRESSION_LEVEL + if (zipCompression !== undefined) { + if (platform !== 'darwin') throw new Error('desktop package: PACKAGE_MACOS_ZIP_COMPRESSION_LEVEL requires macOS') + if (!['3', '7'].includes(zipCompression)) throw new Error('desktop package: workflow ZIP compression must be 3 or 7') + } const preset = environment.DSH_PACKAGING_PRESET let path = join(appRoot, platform === 'win32' ? '.env.windows' : '.env.macos') if (preset !== undefined) { @@ -53,8 +68,8 @@ export function loadDesktopPackageEnvironment(platform, environment = process.en } const platformSetting = platform === 'win32' ? WINDOWS_SETTING : MACOS_SETTING const publicPlatformSetting = platform === 'win32' - ? /^DSH_DESKTOP_WINDOWS_(?:SIGNATURE_CACHE_(?:DIR|CONCURRENCY)|PACK_CONCURRENCY)$/u - : /^DSH_DESKTOP_MACOS_(?:SIGNATURE_CACHE_DIR|PACK_CONCURRENCY|DOWNLOAD_PROXY|NOTARIZATION_PROXY)$/u + ? /^DSH_DESKTOP_WINDOWS_(?:SIGNATURE_CACHE_(?:DIR|CONCURRENCY)|PACK_CONCURRENCY|COMPRESSION_LEVEL)$/u + : /^DSH_DESKTOP_MACOS_(?:SIGNATURE_CACHE_DIR|PACK_CONCURRENCY|ZIP_COMPRESSION_LEVEL|DOWNLOAD_PROXY|NOTARIZATION_PROXY)$/u const settings = readSettings(path, name => preset === undefined ? SHARED_SETTING.test(name) || platformSetting.test(name) : /^(?:DSH_DESKTOP_(?:APP_ID|AUTO_UPDATE_ENV|NPM_REGISTRY|MANDATORY_UPDATE_(?:CONFIG|(?:TEST|PROD)_ORIGIN))|DOWNLOAD_TEST_(?:ORIGIN|RELEASE_ID))$/u.test(name) || publicPlatformSetting.test(name)) @@ -68,6 +83,10 @@ export function loadDesktopPackageEnvironment(platform, environment = process.en : MACOS_SETTING.test(name) && !publicPlatformSetting.test(name))) } } + if (compression !== undefined && compression !== '') settings.DSH_DESKTOP_WINDOWS_COMPRESSION_LEVEL = compression + if (zipCompression !== undefined) { + settings.DSH_DESKTOP_MACOS_ZIP_COMPRESSION_LEVEL = zipCompression + } const releaseId = environment.PACKAGE_TEST_RELEASE_ID?.trim() if (releaseId) { if (preset !== 'test') throw new Error('desktop package: test release ID override requires the test preset') @@ -134,6 +153,7 @@ function requireReadableFile(environment, name) { * @returns {void} */ export function validateDesktopPackageEnvironment(environment, target, options = {}) { + resolveDesktopTargetBuildPaths(environment, target.platform, target.arch) resolveDesktopAppId(environment) resolveNpmRegistry(environment) if (target.platform !== 'darwin' || !options.unsigned) resolveDesktopPolicyEnvironment(environment) diff --git a/apps/desktop/scripts/electron-builder-config.mjs b/apps/desktop/scripts/electron-builder-config.mjs index 4444b68ae1..cf0c19e895 100644 --- a/apps/desktop/scripts/electron-builder-config.mjs +++ b/apps/desktop/scripts/electron-builder-config.mjs @@ -70,7 +70,7 @@ export function createElectronBuilderConfig( if (resolvedPlatform === 'win32') installWindowsDirectoryInstaller() const macOSSigning = packagesMacOS && !unsigned ? resolveMacOSSigningEnvironment(env) : undefined if (packagesMacOS && !unsigned && !skipNotarization) resolveMacOSNotarizationEnvironment(env) - const buildPaths = desktopTargetBuildPaths(resolveDesktopBuildTarget(env, hostPlatform, hostArch)) + const buildPaths = desktopTargetBuildPaths(resolveDesktopBuildTarget(env, hostPlatform, hostArch), env) const output = desktopArtifactOutput(buildPaths, { unsigned, skipNotarization }) let primaryRuntimeDestination let dshDestination @@ -139,6 +139,7 @@ export function createElectronBuilderConfig( }, files: [ 'lib/main.js', + 'lib/operation-report-worker.js', 'lib/welcome/**/*', 'lib/preload-app.cjs', 'lib/preload-mandatory.cjs', @@ -165,7 +166,7 @@ export function createElectronBuilderConfig( category: 'public.app-category.developer-tools', // macOS matches the application locale against this bundle, not Electron Framework resources. extendInfo: { - CFBundleLocalizations: ['en', 'zh_CN', 'ja'], + CFBundleLocalizations: ['en', 'zh_CN', 'ja', 'es', 'fr', 'de', 'ru', 'pt'], NSMicrophoneUsageDescription: 'DeepSeek Harness uses your microphone to transcribe speech into message drafts.', }, // Ad-hoc signing keeps the modified Electron executable runnable without a Developer ID. diff --git a/apps/desktop/scripts/installer-locales.mjs b/apps/desktop/scripts/installer-locales.mjs index f9f9b55138..5785a99021 100644 --- a/apps/desktop/scripts/installer-locales.mjs +++ b/apps/desktop/scripts/installer-locales.mjs @@ -10,7 +10,8 @@ const defaultDirectory = fileURLToPath(new URL('../installer/locales/', import.m * @returns {{id: string, nsisLanguage: string, strings: Record, uninstaller: Record}[]} Complete language resources. */ export function readInstallerLocales(directory = defaultDirectory) { - const locales = readdirSync(directory).filter(name => name.endsWith('.json')).sort().map(name => { + const locales = readdirSync(directory).filter(name => name.endsWith('.json')).sort((a, b) => + a === 'en_US.json' ? -1 : b === 'en_US.json' ? 1 : a.localeCompare(b)).map(name => { if (!/^[a-z]{2}_[A-Z]{2}\.json$/u.test(name)) throw new Error(`${name}: invalid installer language filename`) /** @type {unknown} */ const resource = JSON.parse(readFileSync(`${directory}/${name}`, 'utf8')) @@ -25,6 +26,7 @@ export function readInstallerLocales(directory = defaultDirectory) { const result = {} for (const [key, text] of Object.entries(value)) { if (typeof text !== 'string' || text.trim() === '') throw new Error(`${name}: ${key} must be nonempty text`) + if (/[\u200b\ufeff]/u.test(text)) throw new Error(`${name}: ${key} contains an invisible locale character`) result[key] = text } return result @@ -34,7 +36,7 @@ export function readInstallerLocales(directory = defaultDirectory) { return { id: name.slice(0, -5), nsisLanguage: resource.nsisLanguage, strings, uninstaller: dictionary('uninstaller' in resource ? resource.uninstaller : undefined) } }) - for (const id of ['en_US', 'zh_CN', 'ja_JP']) { + for (const id of ['en_US', 'zh_CN', 'ja_JP', 'es_ES', 'fr_FR', 'de_DE', 'ru_RU', 'pt_BR']) { if (!locales.some(locale => locale.id === id)) throw new Error(`installer locales: missing ${id}.json`) } const english = locales.find(locale => locale.id === 'en_US') @@ -49,8 +51,8 @@ export function readInstallerLocales(directory = defaultDirectory) { const actual = locale[field] if (Object.keys(expected).sort().join(',') !== Object.keys(actual).sort().join(',')) throw new Error(`${locale.id}: ${field} keys differ from English`) for (const [key, text] of Object.entries(expected)) { - const placeholders = (/** @type {string} */ value) => (value.match(/%.?/gu) ?? []).join(',') - if (placeholders(text) !== placeholders(actual[key])) throw new Error(`${locale.id}: ${key} changes format placeholders`) + const placeholders = (/** @type {string} */ value) => (value.match(/%.?|(? { version: buildVersion, productVersion, node: process.version, commit: packaged.commit, dirty: packaged.dirty, - }, { parallel: target.platform === 'darwin', secrets }) + }, { parallel: true, secrets }) console.log(`DESKTOP_PACKAGING_RECORD ${run.directory}`) const previousDirectory = process.env.DSH_DESKTOP_PACKAGING_RUN_DIR process.env.DSH_DESKTOP_PACKAGING_RUN_DIR = run.directory @@ -380,7 +380,7 @@ async function main(): Promise { await packagingStep(run.directory, 'toolchain', () => requireDesktopToolchain(target.platform, environment), secrets) if (target.platform === 'darwin') { const settings = resolveMacOSPackageSettings(environment) - recordPackagingEvent(run.directory, { type: 'macos-settings', packConcurrency: settings.packConcurrency, + recordPackagingEvent(run.directory, { type: 'macos-settings', packConcurrency: settings.packConcurrency, zipCompressionLevel: settings.zipCompressionLevel, downloadProxyConfigured: settings.downloadProxy !== undefined, notarizationProxyConfigured: settings.notarizationProxy !== undefined }) await packagingStep(run.directory, 'macos-package', () => invocation.unsigned @@ -400,7 +400,7 @@ async function main(): Promise { run.finish(success) } if (success && target.platform === 'darwin' && !invocation.directory && !invocation.prepareOnly) { - const paths = desktopTargetBuildPaths(target.name) + const paths = desktopTargetBuildPaths(target.name, environment) const output = desktopArtifactOutput(paths, invocation) const filename = `deepseek-harness-${buildVersion}-mac-${target.arch}${output.suffix}.dmg` console.log(`DMG: ${join(output.directory, filename)}`) @@ -426,7 +426,7 @@ export async function packageTarget( const mac = target.platform === 'darwin' ? resolveMacOSPackageSettings(environment) : undefined const packConcurrency = mac?.packConcurrency ?? resolveWindowsPackageSettings(environment).packConcurrency const packArguments = ['--concurrency', String(packConcurrency)] - const buildPaths = desktopTargetBuildPaths(target.name) + const buildPaths = desktopTargetBuildPaths(target.name, environment) const releaseRecordPath = join(buildPaths.artifacts, desktopBuildRecordFilename(target.name)) if (!invocation.prepareOnly && !invocation.unsigned && !invocation.skipNotarization) { rmSync(releaseRecordPath, { force: true }) @@ -443,6 +443,9 @@ export async function packageTarget( } const downloadEnv = macOSDownloadEnvironment(targetEnv, mac?.downloadProxy) const electronBuilderEnv = desktopElectronBuilderEnvironment(downloadEnv, invocation.unsigned) + if (target.platform === 'win32') { + electronBuilderEnv.ELECTRON_BUILDER_COMPRESSION_LEVEL = String(resolveWindowsPackageSettings(environment).compressionLevel) + } for (const name of WINDOWS_SIGNING_ENV_NAMES) { if (!invocation.unsigned && environment[name] !== undefined) electronBuilderEnv[name] = environment[name] } @@ -476,36 +479,56 @@ export async function packageTarget( }) } await execute(invocation.unsigned ? ['run', 'build', '--profile', 'local'] : ['run', 'build:official'], buildEnv, REPOSITORY_ROOT) - await execute([ - ...(invocation.unsigned - ? ['exec', 'tsx', 'apps/desktop/scripts/pack-local-packages.ts'] - : ['run', 'release:pack', '--family', 'dsh']), - '--out', buildPaths.packedDsh, ...packArguments, - ], buildEnv, REPOSITORY_ROOT) - await execute([ - '--dir', - 'apps/desktop-host', - 'pack', - '--pack-destination', - buildPaths.packedDsh, - ], buildEnv, REPOSITORY_ROOT) - await execute(['run', 'release:pack', '--family', 'vendor', '--out', buildPaths.packedVendor, ...packArguments], buildEnv, REPOSITORY_ROOT) - rmSync(buildPaths.packedLandlock, { recursive: true, force: true }) - mkdirSync(buildPaths.packedLandlock, { recursive: true }) - await execute(['--dir', 'native/system', 'run', 'build:ts'], buildEnv, REPOSITORY_ROOT) - await execute([ - '--dir', - 'native/system/packages/entry', - 'pack', - '--pack-destination', - buildPaths.packedLandlock, - ], buildEnv, REPOSITORY_ROOT) - await execute(['run', 'prepare:runtime', ...(signPrimaryRuntime ? ['--defer-primary-runtime-smoke'] : [])], downloadEnv) + let preparationFailure: { error: unknown } | undefined + const executePreparation = async (args: readonly string[], env: NodeJS.ProcessEnv, cwd?: string): Promise => { + if (preparationFailure !== undefined) throw preparationFailure.error + try { await execute(args, env, cwd) } + catch (error) { preparationFailure ??= { error }; throw error } + } + const pack = async (): Promise => { + await executePreparation([ + ...(invocation.unsigned + ? ['exec', 'tsx', 'apps/desktop/scripts/pack-local-packages.ts'] + : ['run', 'release:pack', '--family', 'dsh']), + '--out', buildPaths.packedDsh, ...packArguments, + ], buildEnv, REPOSITORY_ROOT) + await executePreparation([ + '--dir', + 'apps/desktop-host', + 'pack', + '--pack-destination', + buildPaths.packedDsh, + ], buildEnv, REPOSITORY_ROOT) + await executePreparation(['run', 'release:pack', '--family', 'vendor', '--out', buildPaths.packedVendor, ...packArguments], buildEnv, REPOSITORY_ROOT) + rmSync(buildPaths.packedLandlock, { recursive: true, force: true }) + mkdirSync(buildPaths.packedLandlock, { recursive: true }) + await executePreparation(['--dir', 'native/system', 'run', 'build:ts'], buildEnv, REPOSITORY_ROOT) + await executePreparation([ + '--dir', + 'native/system/packages/entry', + 'pack', + '--pack-destination', + buildPaths.packedLandlock, + ], buildEnv, REPOSITORY_ROOT) + } + const prepareRuntime = () => executePreparation( + ['run', 'prepare:runtime', ...(signPrimaryRuntime ? ['--defer-primary-runtime-smoke'] : [])], downloadEnv) + if (target.platform === 'win32') { + const results = await Promise.allSettled([pack(), prepareRuntime()]) + for (const result of results) if (result.status === 'rejected') throw result.reason + } else { + await pack() + await prepareRuntime() + } if (signPrimaryRuntime) await execute(['run', 'sign:primary-runtime'], electronBuilderEnv) await execute(['run', 'prepare:packages'], targetEnv) await execute(['run', 'prepare:dsh', ...(signPrimaryRuntime ? ['--defer-runtime-smoke'] : [])], downloadEnv) if (signPrimaryRuntime) await execute(['run', 'sign:primary-runtime', '--dsh'], electronBuilderEnv) if (invocation.prepareOnly) return + const buildMacArtifact = (artifact: DesktopPrepackagedArtifact) => execute( + desktopElectronBuilderArguments(target, false, artifact), artifact.format === 'zip' + ? { ...electronBuilderEnv, ELECTRON_BUILDER_COMPRESSION_LEVEL: String(mac?.zipCompressionLevel) } + : electronBuilderEnv) if (target.platform === 'darwin' && !invocation.unsigned && !invocation.skipNotarization && !invocation.directory) { await execute([ ...desktopElectronBuilderArguments(target, true), @@ -518,7 +541,7 @@ export async function packageTarget( version: resolveDesktopBuildVersion(environment, packageVersion(join(APP_ROOT, 'package.json'), 'desktop package')), artifactsRoot: buildPaths.artifacts, environment: electronBuilderEnv, - }, artifact => execute(desktopElectronBuilderArguments(target, false, artifact), electronBuilderEnv)), undefined, undefined, proxyEvent) + }, buildMacArtifact), undefined, undefined, proxyEvent) } else if (target.platform === 'darwin' && !invocation.unsigned && !invocation.skipNotarization) { await execute([...desktopElectronBuilderArguments(target, true), '--config.mac.notarize=false'], electronBuilderEnv) await execute(['exec', 'tsx', 'scripts/smoke-packaged-runtime.ts'], targetEnv) @@ -526,7 +549,15 @@ export async function packageTarget( await withMacOSNotarizationProxy(mac?.notarizationProxy, () => notarizeMacOS({ appPath, ...resolveMacOSNotarizationEnvironment(environment) }), undefined, undefined, proxyEvent) } else { - await signedStage('artifacts', () => execute(desktopElectronBuilderArguments(target, invocation.directory), electronBuilderEnv)) + if (target.platform === 'darwin' && invocation.skipNotarization && !invocation.directory) { + await execute(desktopElectronBuilderArguments(target, true), electronBuilderEnv) + const appPath = join(artifactsRoot, target.arch === 'arm64' ? 'mac-arm64' : 'mac', 'DeepSeek Harness.app') + for (const format of ['dmg', 'zip'] as const) { + await buildMacArtifact({ format, appPath, output: artifactsRoot }) + } + } else { + await signedStage('artifacts', () => execute(desktopElectronBuilderArguments(target, invocation.directory), electronBuilderEnv)) + } await execute(['exec', 'tsx', 'scripts/smoke-packaged-runtime.ts', ...(invocation.unsigned ? ['--unsigned'] : []), ...(invocation.skipNotarization ? ['--skip-notarization'] : [])], targetEnv) } diff --git a/apps/desktop/scripts/prepare-dsh.ts b/apps/desktop/scripts/prepare-dsh.ts index 365c5a45f2..a069888036 100644 --- a/apps/desktop/scripts/prepare-dsh.ts +++ b/apps/desktop/scripts/prepare-dsh.ts @@ -3,6 +3,7 @@ import { resolveMacOSSignatureCacheDirectory } from './macos-signature-cache-directory.mjs' import { packagingStep } from './packaging-step.mjs' import { spawn } from 'node:child_process' +import { createHash } from 'node:crypto' import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { delimiter, join, relative, resolve } from 'node:path' @@ -22,7 +23,7 @@ import { smokePrimaryRuntime } from './prepare-primary-runtime.ts' import { smokePreparedRuntime } from './smoke-prepared-runtime.ts' import { prepareRuntimeManifests } from './prepare-runtime-manifests.ts' import { prepareRuntimePatches, verifyRuntimePatches } from './prepare-runtime-patches.ts' -import { writeDesktopRuntime, verifyDesktopRuntime } from '../src/runtime-tree.ts' +import { writeDesktopRuntime, writeDesktopRuntimeAsync, verifyDesktopRuntime } from '../src/runtime-tree.ts' import { resolveDesktopAppId, resolveMacOSSigningEnvironment, @@ -39,7 +40,7 @@ const APP_ROOT = resolve(import.meta.dirname, '..') const BUILD_PATHS = resolveDesktopTargetBuildPaths() const DSH_OUTPUT_ROOT = BUILD_PATHS.dsh const BUILD_ROOT = mkdtempSync(join(tmpdir(), 'dsh-desktop-runtime-')) -const STORE_ROOT = join(BUILD_ROOT, 'store') +const STORE_ROOT = BUILD_PATHS.pnpmStore const RUNTIME_ROOT = BUILD_PATHS.runtime const PNPM_BUILD_STATE = BUILD_PATHS.dshPnpm const PACKAGE_SET_ROOT = BUILD_PATHS.packageSet @@ -82,6 +83,8 @@ function runPnpm(args: readonly string[]): Promise { PNPM, `--config.registry=${registry}`, `--config.store-dir=${STORE_ROOT}`, + '--config.verify-store-integrity=true', + '--config.package-import-method=copy', '--config.enable-global-virtual-store=false', `--config.userconfig=${userConfig}`, command, @@ -113,6 +116,7 @@ function runPnpm(args: readonly string[]): Promise { async function main(): Promise { try { + console.log(`desktop runtime: pnpm store ${STORE_ROOT}`) await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:reset', async () => { rmSync(DSH_OUTPUT_ROOT, { recursive: true, force: true }) rmSync(PNPM_BUILD_STATE, { recursive: true, force: true }) @@ -127,8 +131,10 @@ async function main(): Promise { }) await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:lockfile', () => runPnpm(['install', '--lockfile-only'])) verifyRuntimePatches(BUILD_ROOT, patches) + const lockfile = readFileSync(join(BUILD_ROOT, 'pnpm-lock.yaml'), 'utf8') + console.log(`desktop runtime: lockfile sha256 ${createHash('sha256').update(lockfile).digest('hex')}`) verifyDesktopCoreLockfile( - readFileSync(join(BUILD_ROOT, 'pnpm-lock.yaml'), 'utf8'), + lockfile, readDesktopCorePackageSet(BUILD_ROOT, release.version), ) await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:install', () => runPnpm(['install', '--prod', '--frozen-lockfile', '--trust-lockfile'])) @@ -164,7 +170,10 @@ async function main(): Promise { } await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:manifests', () => prepareRuntimeManifests(DSH_OUTPUT_ROOT)) await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:primary-smoke', async () => smokePrimaryRuntime(join(RUNTIME_ROOT, 'primary-runtime'))) - await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:write-descriptor', async () => writeDesktopRuntime(DSH_OUTPUT_ROOT, release, packageSet.packages.map(entry => entry.name), target)) + await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:write-descriptor', async () => { + const writeRuntime = target.platform === 'win32' ? writeDesktopRuntimeAsync : writeDesktopRuntime + return writeRuntime(DSH_OUTPUT_ROOT, release, packageSet.packages.map(entry => entry.name), target) + }) const descriptor = await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:verify-before-smoke', () => verifyDesktopRuntime(DSH_OUTPUT_ROOT, release.version, target)) if (!process.argv.includes('--defer-runtime-smoke')) { await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:smoke', () => smokePreparedRuntime(DSH_OUTPUT_ROOT, NODE, RUNTIME_ROOT, descriptor)) diff --git a/apps/desktop/scripts/prepare-runtime.ts b/apps/desktop/scripts/prepare-runtime.ts index ba92fef0e6..4e33853272 100644 --- a/apps/desktop/scripts/prepare-runtime.ts +++ b/apps/desktop/scripts/prepare-runtime.ts @@ -53,9 +53,18 @@ async function main(): Promise { const target = desktopTargetPlatform(resolveDesktopBuildTarget()) rmSync(RUNTIME_ROOT, { recursive: true, force: true }) mkdirSync(RUNTIME_ROOT, { recursive: true }) - const nodeVersion = await prepareElectron(target) - await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'prepare:primary-runtime', + const preparePrimary = () => packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'prepare:primary-runtime', () => preparePrimaryRuntime({ deferSmoke: values['defer-primary-runtime-smoke'] })) + let nodeVersion: string + if (target.platform === 'win32') { + const [electron, primary] = await Promise.allSettled([prepareElectron(target), preparePrimary()]) + if (electron.status === 'rejected') throw electron.reason + if (primary.status === 'rejected') throw primary.reason + nodeVersion = electron.value + } else { + nodeVersion = await prepareElectron(target) + await preparePrimary() + } const { pnpm } = await readPrimaryRuntime(join(RUNTIME_ROOT, 'primary-runtime')) if (pnpm === undefined) throw new Error('desktop runtime: primary-runtime manifest has no pnpm version') await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'prepare:cli', async () => { prepareCli(target) }) diff --git a/apps/desktop/scripts/prepare-windows-ci.mjs b/apps/desktop/scripts/prepare-windows-ci.mjs index ac571095f4..b89227885a 100644 --- a/apps/desktop/scripts/prepare-windows-ci.mjs +++ b/apps/desktop/scripts/prepare-windows-ci.mjs @@ -5,6 +5,7 @@ import { execFileSync } from 'node:child_process' import { desktopCiVersion as windowsCiVersion } from './desktop-ci-version.mjs' export { desktopCiVersion as windowsCiVersion } from './desktop-ci-version.mjs' import { loadDesktopPackageEnvironment, validateDesktopPackageEnvironment } from './desktop-package-environment.mjs' +import { resolveWindowsPackageSettings } from './windows-package-settings.mjs' if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) { const appRoot = resolve(import.meta.dirname, '..') @@ -22,6 +23,7 @@ if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.fi } } validateDesktopPackageEnvironment(environment, { platform: 'win32', arch: 'x64' }, { unsigned: mode === 'unsigned' }) + console.log(`Windows installer compression level: ${resolveWindowsPackageSettings(environment).compressionLevel}`) if (!process.env.GITHUB_OUTPUT || !process.env.GITHUB_STEP_SUMMARY) throw new Error('Run this adapter from GitHub Actions') appendFileSync(process.env.GITHUB_OUTPUT, `version=${version}\n`) appendFileSync(process.env.GITHUB_STEP_SUMMARY, `Windows x64 ${mode} installer\n\nVersion: ${version}\n\nCommit: ${execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim()}\n\nChannel: ${process.env.DSH_DESKTOP_UPDATE_CHANNEL}\n\nSource: ${process.env.PACKAGE_SOURCE_REF}\n\nPreset: ${process.env.DSH_PACKAGING_PRESET}\n`) diff --git a/apps/desktop/scripts/run-windows-runner-network-process.ps1 b/apps/desktop/scripts/run-windows-runner-network-process.ps1 new file mode 100644 index 0000000000..5129c6c860 --- /dev/null +++ b/apps/desktop/scripts/run-windows-runner-network-process.ps1 @@ -0,0 +1,138 @@ +# Own one operator-configured network process until the registered runner exits. +param([Parameter(Mandatory=$true)][string]$RunnerRoot, [Parameter(Mandatory=$true)][string]$ConfigRoot, [Parameter(Mandatory=$true)][string]$NetworkRoot, [Parameter(Mandatory=$true)][string]$ReadinessScript, [Parameter(Mandatory=$true)][string]$StartScript, [switch]$CheckOnly) +$ErrorActionPreference = 'Stop' +$network = $NetworkRoot +$lock = $null +$process = $null +$started = $false +$runner = $null +$runnerStarted = $false +$restarts = 0 +$recordPath = Join-Path $network 'process.json' +$code = 1 +try { + foreach ($directory in @($RunnerRoot,$ConfigRoot,$NetworkRoot)) { + if ($directory -notmatch '^[A-Za-z]:[\\/]' -or -not (Test-Path -LiteralPath $directory -PathType Container)) { throw 'An existing absolute local directory is required.' } + } + foreach ($script in @($ReadinessScript,$StartScript)) { + if ($script -notmatch '^[A-Za-z]:[\\/]' -or -not (Test-Path -LiteralPath $script -PathType Leaf)) { throw 'An existing absolute local script is required.' } + } + $lock = [IO.File]::Open((Join-Path $network 'supervisor.lock'), 'OpenOrCreate', 'ReadWrite', 'None') + $launch = Get-Content (Join-Path $network 'launch.json') -Raw | ConvertFrom-Json -AsHashtable + if ($launch -isnot [Collections.IDictionary] -or $launch.Count -ne 3 -or @($launch.Keys | Where-Object { $_ -cnotin @('executable','arguments','restartDelaySeconds') }).Count) { throw 'Invalid network launch configuration.' } + if (($launch.restartDelaySeconds -isnot [long] -and $launch.restartDelaySeconds -isnot [int]) -or $launch.restartDelaySeconds -lt 1 -or $launch.restartDelaySeconds -gt 3600) { throw 'Invalid network restart interval.' } + if ($launch.executable -isnot [string] -or $launch.arguments -isnot [array] -or @($launch.arguments | Where-Object { $_ -isnot [string] -or $_.Contains([char]0) }).Count) { throw 'Invalid network executable or arguments.' } + if (-not [IO.Path]::IsPathFullyQualified($launch.executable) -or -not (Test-Path -LiteralPath $launch.executable -PathType Leaf)) { throw 'Network executable unavailable.' } + $launch.executable = [IO.Path]::GetFullPath($launch.executable) + if (Test-Path -LiteralPath $recordPath) { + $record = Get-Content -LiteralPath $recordPath -Raw | ConvertFrom-Json + if ($record.pid -isnot [long] -and $record.pid -isnot [int]) { throw 'Invalid network process record.' } + if ($record.pid -le 0 -or $record.started -isnot [long] -or $record.started -le 0) { throw 'Invalid network process record.' } + $stale = Get-Process -Id $record.pid -ErrorAction SilentlyContinue + if ($stale) { + try { + if (-not $stale.StartTime) { throw 'Owned network process identity unavailable.' } + if ($stale.StartTime.ToUniversalTime().Ticks -eq $record.started) { + if ($stale.Path -ne $launch.executable) { throw 'Owned network process identity unavailable.' } + $stale.Kill($true) + if (-not $stale.WaitForExit(10000)) { throw 'Owned network process did not stop.' } + } + } finally { $stale.Dispose() } + } + Remove-Item -LiteralPath $recordPath + } + $info = [Diagnostics.ProcessStartInfo]::new($launch.executable) + $info.UseShellExecute = $false + $info.CreateNoWindow = $true + $info.WorkingDirectory = $network + foreach ($name in @('HTTP_PROXY','HTTPS_PROXY','ALL_PROXY','http_proxy','https_proxy','all_proxy')) { $null = $info.Environment.Remove($name) } + # Provider output can include private routes; it must never enter runner logs. + $info.RedirectStandardOutput = $true + $info.RedirectStandardError = $true + foreach ($argument in $launch.arguments) { $info.ArgumentList.Add($argument) } + $process = [Diagnostics.Process]::new() + $process.StartInfo = $info + if (-not $process.Start()) { throw 'Network process did not start.' } + $started = $true + $stdout = $process.StandardOutput.BaseStream.CopyToAsync([IO.Stream]::Null) + $stderr = $process.StandardError.BaseStream.CopyToAsync([IO.Stream]::Null) + @{pid=$process.Id;started=$process.StartTime.ToUniversalTime().Ticks} | ConvertTo-Json | Set-Content -LiteralPath $recordPath + & (Join-Path $PSHOME 'pwsh.exe') -NoProfile -NonInteractive -File $ReadinessScript -RunnerRoot $RunnerRoot -ConfigRoot $ConfigRoot -CheckOnly + if ($LASTEXITCODE -ne 0 -or $process.HasExited) { throw 'Network readiness failed; listener was not started.' } + if ($CheckOnly) { $code = 0 } else { + $runnerInfo = [Diagnostics.ProcessStartInfo]::new((Join-Path $PSHOME 'pwsh.exe')) + $runnerInfo.UseShellExecute = $false + $runnerInfo.CreateNoWindow = $true + $runnerInfo.RedirectStandardOutput = $true + $runnerInfo.RedirectStandardError = $true + foreach ($argument in @('-NoProfile','-NonInteractive','-File',$StartScript,'-RunnerRoot',$RunnerRoot,'-ConfigRoot',$ConfigRoot)) { $runnerInfo.ArgumentList.Add($argument) } + $runner = [Diagnostics.Process]::new() + $runner.StartInfo = $runnerInfo + if (-not $runner.Start()) { throw 'Runner process did not start.' } + $runnerStarted = $true + $runnerOut = $runner.StandardOutput.BaseStream.CopyToAsync([Console]::OpenStandardOutput()) + $runnerErr = $runner.StandardError.BaseStream.CopyToAsync([Console]::OpenStandardError()) + while (-not $runner.WaitForExit(1000)) { + if ($started -and -not $process.HasExited) { continue } + if ($started) { + Write-Output "Network process exited (code $($process.ExitCode)); runner retained. Inspect local network configuration if recovery repeats." + $started = $false + Remove-Item -LiteralPath $recordPath + $process.Dispose() + $process = $null + } + # The runner's lifetime owns recovery; waiting on it also cancels the retry delay. + if ($runner.WaitForExit($launch.restartDelaySeconds * 1000)) { break } + $process = [Diagnostics.Process]::new() + $process.StartInfo = $info + try { $started = $process.Start() } + catch { + # Launch errors can contain private arguments or paths. + $started = $false + } + if (-not $started) { + $process.Dispose() + $process = $null + Write-Output 'Network process restart failed; runner retained. Inspect the local executable and configuration; recovery will retry.' + continue + } + $stdout = $process.StandardOutput.BaseStream.CopyToAsync([IO.Stream]::Null) + $stderr = $process.StandardError.BaseStream.CopyToAsync([IO.Stream]::Null) + @{pid=$process.Id;started=$process.StartTime.ToUniversalTime().Ticks} | ConvertTo-Json | Set-Content -LiteralPath $recordPath + $restarts++ + Write-Output "Network process restarted (attempt $restarts); runner retained. Connectivity recovery is handled by the runner." + } + $code = $runner.ExitCode + } +} catch { + # Do not expose provider paths, arguments, configuration or raw error messages. + [Console]::Error.WriteLine('Private network supervision failed; inspect local state. No job was retried.') + if ($runnerStarted -and -not $runner.HasExited) { + [Console]::Error.WriteLine('Network recovery stopped; the existing runner remains running until it exits. Inspect local supervision state before maintenance.') + $runner.WaitForExit() + } +} finally { + if ($runnerStarted) { + try { + if (-not [Threading.Tasks.Task]::WaitAll([Threading.Tasks.Task[]]@($runnerOut,$runnerErr), 5000)) { throw 'Output drain timed out.' } + } catch { + $code = 1 + [Console]::Error.WriteLine('Runner output drain failed or timed out; output may be incomplete.') + } + } + if ($runner) { $runner.Dispose() } + try { + if ($started) { + if (-not $process.HasExited) { $process.Kill($true) } + if (-not $process.WaitForExit(10000)) { throw 'Network cleanup did not complete.' } + if (Test-Path -LiteralPath $recordPath) { Remove-Item -LiteralPath $recordPath } + } + } catch { + $code = 1 + [Console]::Error.WriteLine('Owned network cleanup failed; inspect local process state before restarting.') + } finally { + if ($process) { $process.Dispose() } + if ($lock) { $lock.Dispose() } + } +} +exit $code diff --git a/apps/desktop/scripts/run-windows-runner-task.ps1 b/apps/desktop/scripts/run-windows-runner-task.ps1 index 339350377a..56371e970c 100644 --- a/apps/desktop/scripts/run-windows-runner-task.ps1 +++ b/apps/desktop/scripts/run-windows-runner-task.ps1 @@ -15,7 +15,13 @@ try { exit 1 } Set-Content -LiteralPath $attemptFile -Value ($attempts + 1) - & (Join-Path $PSHOME 'pwsh.exe') -NoProfile -NonInteractive -File (Join-Path $PSScriptRoot 'start.ps1') -RunnerRoot $config.RunnerRoot -ConfigRoot $config.ConfigRoot *> $log + $startup = Join-Path $PSScriptRoot 'start.ps1' + if ($config.NetworkRoot) { + if (-not (Test-Path -LiteralPath (Join-Path $config.ConfigRoot 'runner-network.json') -PathType Leaf)) { throw 'Owned network supervision requires runner-network.json.' } + & (Join-Path $PSHOME 'pwsh.exe') -NoProfile -NonInteractive -File (Join-Path $PSScriptRoot 'run-windows-runner-network-process.ps1') -RunnerRoot $config.RunnerRoot -ConfigRoot $config.ConfigRoot -NetworkRoot $config.NetworkRoot -ReadinessScript $startup -StartScript $startup *> $log + } else { + & (Join-Path $PSHOME 'pwsh.exe') -NoProfile -NonInteractive -File $startup -RunnerRoot $config.RunnerRoot -ConfigRoot $config.ConfigRoot *> $log + } $code = $LASTEXITCODE Add-Content -LiteralPath $log -Value "Runner launcher exited with code $code." # An unexpected exit is a task failure even when run.cmd hides the listener's nonzero status; the log retains its code. diff --git a/apps/desktop/scripts/sign-primary-runtime.ts b/apps/desktop/scripts/sign-primary-runtime.ts index d9a9b36c25..a15e378625 100644 --- a/apps/desktop/scripts/sign-primary-runtime.ts +++ b/apps/desktop/scripts/sign-primary-runtime.ts @@ -11,7 +11,7 @@ import { withWindowsSigningStage } from './windows-signing-stage.mjs' import { failPackagingRun, recordPackagingEvent } from './packaging-run.mjs' import { resolveDesktopBuildTarget, resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs' import { smokePrimaryRuntime } from './prepare-primary-runtime.ts' -import { verifyDesktopRuntime, writeDesktopRuntime, type DesktopRuntimeDescriptor } from '../src/runtime-tree.ts' +import { verifyDesktopRuntime, writeDesktopRuntimeAsync, type DesktopRuntimeDescriptor } from '../src/runtime-tree.ts' import { smokePreparedRuntime } from './smoke-prepared-runtime.ts' /** @@ -39,7 +39,7 @@ export async function signWindowsDesktopRuntime(root: string, version: string, options: WindowsCodeSigningOptions & { smoke: (descriptor: DesktopRuntimeDescriptor) => Promise }): Promise { const descriptor = await verifyDesktopRuntime(root, version) await signWindowsCode(root, options) - writeDesktopRuntime(root, descriptor.release, descriptor.sharedPackages.map(entry => entry.name)) + await writeDesktopRuntimeAsync(root, descriptor.release, descriptor.sharedPackages.map(entry => entry.name)) const signed = await verifyDesktopRuntime(root, version) await options.smoke(signed) await verifyDesktopRuntime(root, version) diff --git a/apps/desktop/scripts/start-windows-packaging-runner.ps1 b/apps/desktop/scripts/start-windows-packaging-runner.ps1 index 13251a110a..a024296024 100644 --- a/apps/desktop/scripts/start-windows-packaging-runner.ps1 +++ b/apps/desktop/scripts/start-windows-packaging-runner.ps1 @@ -16,6 +16,9 @@ if ($drive.DriveType -ne [IO.DriveType]::Fixed) { throw 'ConfigRoot requires a f $env:DSH_PACKAGING_CONFIG_DIR=[IO.Path]::GetFullPath($ConfigRoot) $env:DSH_TELEMETRY_DISABLED='1' $env:POWERSHELL_TELEMETRY_OPTOUT='1' +. (Join-Path $PSScriptRoot 'windows-runner-network.ps1') +$network = Read-RunnerNetwork $ConfigRoot +Set-RunnerNetwork $network foreach($tool in @('pwsh','node','git','tar','python')) { $resolved=Get-Command $tool -CommandType Application -ErrorAction Stop | Select-Object -First 1 Write-Output ('Tool: '+$tool+' -> '+$resolved.Source) @@ -31,6 +34,7 @@ $vswhere=Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio/Installer/v $visualStudio=& $vswhere -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath if($LASTEXITCODE -ne 0 -or -not $visualStudio){throw 'Visual C++ tools unavailable'} Write-Output 'Visual C++ tools located.' +Wait-RunnerNetwork $network if($CheckOnly){Write-Output 'Runner environment check passed.'; exit 0} if(Get-Process -Name Runner.Listener -ErrorAction SilentlyContinue){throw 'A runner listener is already running; inspect before starting another.'} Set-Location $RunnerRoot diff --git a/apps/desktop/scripts/windows-build-workspace.d.mts b/apps/desktop/scripts/windows-build-workspace.d.mts new file mode 100644 index 0000000000..92f3a3c704 --- /dev/null +++ b/apps/desktop/scripts/windows-build-workspace.d.mts @@ -0,0 +1,19 @@ +/** Identity of a Windows packaging run and its independent build root. */ +export interface WindowsBuildWorkspaceOptions { + sourceDirectory: string + buildRoot: string + runId: string + runAttempt: string + sourceSha: string +} +/** + * Clone the clean selected commit into a new run-owned directory. + * @param options - Original checkout and Actions run identity. + * @returns Checkout and temporary directory owned by this run. + */ +export function prepareWindowsBuildWorkspace(options: WindowsBuildWorkspaceOptions): { directory: string; temporaryDirectory: string } +/** + * Remove the directory only when its ownership record matches the run. + * @param options - Original checkout and Actions run identity. + */ +export function removeWindowsBuildWorkspace(options: WindowsBuildWorkspaceOptions): void diff --git a/apps/desktop/scripts/windows-build-workspace.mjs b/apps/desktop/scripts/windows-build-workspace.mjs new file mode 100644 index 0000000000..977dda6618 --- /dev/null +++ b/apps/desktop/scripts/windows-build-workspace.mjs @@ -0,0 +1,96 @@ +/** Create and remove a run-owned checkout for Windows packaging. */ +import { execFileSync } from 'node:child_process' +import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { dirname, isAbsolute, join, parse, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' + +function assertUnlinkedAncestors(directory) { + for (let current = directory; ; current = dirname(current)) { + if (existsSync(current) && lstatSync(current).isSymbolicLink()) { + throw new Error('Packaging workspace ancestors must not be links') + } + if (dirname(current) === current) break + } +} + +function locations(options) { + const { buildRoot, runId, runAttempt, sourceSha } = options + if (!buildRoot || !isAbsolute(buildRoot) || /[\r\n\0]/.test(buildRoot)) { + throw new Error('Packaging build root must be a nonempty absolute directory') + } + const root = resolve(buildRoot) + if (root === parse(root).root) throw new Error('Packaging build root must not be a volume root') + if (!/^[1-9]\d*$/.test(runId) || !/^[1-9]\d*$/.test(runAttempt) || !/^[a-f0-9]{40}$/.test(sourceSha)) { + throw new Error('Packaging workspace requires a run identity and exact commit') + } + assertUnlinkedAncestors(root) + for (let current = root; ; current = dirname(current)) { + if (existsSync(join(current, '.git'))) throw new Error('Packaging build root must be outside existing Git checkouts') + if (dirname(current) === current) break + } + const owner = join(root, `windows-package-${runId}-${runAttempt}`) + assertUnlinkedAncestors(owner) + return { root, owner, directory: join(owner, 'source'), temporaryDirectory: join(owner, 'temp') } +} + +function git(directory, args) { + return execFileSync('git', args, { cwd: directory, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim() +} + +function ownership(options, paths) { + return JSON.stringify({ version: 1, root: paths.root, source: resolve(options.sourceDirectory), runId: options.runId, runAttempt: options.runAttempt, sourceSha: options.sourceSha }) +} + +/** + * Clone the validated commit into a new run-owned checkout; failures retain diagnostics. + * @param {{sourceDirectory: string, buildRoot: string, runId: string, runAttempt: string, sourceSha: string}} options - Source and run identity. + * @returns {{directory: string, temporaryDirectory: string}} Checkout and temporary directory owned by this run. + */ +export function prepareWindowsBuildWorkspace(options) { + const paths = locations(options) + if (git(options.sourceDirectory, ['rev-parse', 'HEAD']) !== options.sourceSha || git(options.sourceDirectory, ['status', '--porcelain'])) { + throw new Error('Packaging source must be clean and match the selected commit') + } + mkdirSync(paths.root, { recursive: true }) + mkdirSync(paths.owner) + writeFileSync(join(paths.owner, 'owner.json'), ownership(options, paths), { flag: 'wx' }) + mkdirSync(paths.temporaryDirectory) + git(paths.owner, ['clone', '--no-hardlinks', '--no-checkout', resolve(options.sourceDirectory), paths.directory]) + git(paths.directory, ['checkout', '--detach', options.sourceSha]) + if (git(paths.directory, ['rev-parse', 'HEAD']) !== options.sourceSha || git(paths.directory, ['status', '--porcelain'])) { + throw new Error('Isolated packaging checkout does not match the selected commit') + } + return { directory: paths.directory, temporaryDirectory: paths.temporaryDirectory } +} + +/** + * Remove only the matching run-owned directory after successful artifact upload. + * Transient filesystem failures retry up to three times; persistent failures propagate. + * @param {{sourceDirectory: string, buildRoot: string, runId: string, runAttempt: string, sourceSha: string}} options - Original source and run identity. + * @returns {void} + */ +export function removeWindowsBuildWorkspace(options) { + const paths = locations(options) + const marker = join(paths.owner, 'owner.json') + const stat = lstatSync(marker) + if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 8192 || readFileSync(marker, 'utf8') !== ownership(options, paths)) { + throw new Error('Packaging workspace ownership does not match this run') + } + rmSync(paths.owner, { recursive: true, maxRetries: 3, retryDelay: 100 }) +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + const options = { + sourceDirectory: process.env.GITHUB_WORKSPACE ?? '', + buildRoot: process.env.PACKAGE_BUILD_ROOT ?? '', + runId: process.env.GITHUB_RUN_ID ?? '', + runAttempt: process.env.GITHUB_RUN_ATTEMPT ?? '', + sourceSha: process.env.PACKAGE_SOURCE_SHA ?? '', + } + if (process.argv[2] === '--remove') removeWindowsBuildWorkspace(options) + else { + if (process.argv.length !== 2 || !process.env.GITHUB_OUTPUT) throw new Error('Expected Actions output file and no arguments') + const result = prepareWindowsBuildWorkspace(options) + appendFileSync(process.env.GITHUB_OUTPUT, `directory=${result.directory}\ntemporaryDirectory=${result.temporaryDirectory}\n`) + } +} diff --git a/apps/desktop/scripts/windows-package-settings.d.mts b/apps/desktop/scripts/windows-package-settings.d.mts index cef8b8aa85..b8eb377952 100644 --- a/apps/desktop/scripts/windows-package-settings.d.mts +++ b/apps/desktop/scripts/windows-package-settings.d.mts @@ -1,6 +1,7 @@ /** - * Validate file-owned Windows packaging and cache worker limits before packaging starts. - * @param environment Windows packaging settings loaded from .env.windows. - * @returns Cache workers from one to eight and a positive integer pack limit; both default to four. Invalid values throw. + * Validate worker limits and compression before packaging starts. + * File-owned compression takes precedence over the existing electron-builder environment override. + * @param environment Loaded packaging settings and inherited build environment. + * @returns Cache workers from one to eight and a positive integer pack limit, both defaulting to four; archive compression from zero to nine, defaulting to three. Invalid values throw. */ -export function resolveWindowsPackageSettings(environment: NodeJS.ProcessEnv): { signatureCacheConcurrency: number, packConcurrency: number } +export function resolveWindowsPackageSettings(environment: NodeJS.ProcessEnv): { signatureCacheConcurrency: number, packConcurrency: number, compressionLevel: number } diff --git a/apps/desktop/scripts/windows-package-settings.mjs b/apps/desktop/scripts/windows-package-settings.mjs index cd78e49756..6fc29d1440 100644 --- a/apps/desktop/scripts/windows-package-settings.mjs +++ b/apps/desktop/scripts/windows-package-settings.mjs @@ -1,9 +1,10 @@ -/** Resolve file-owned Windows packaging and signature-cache concurrency. */ +/** Resolve Windows packaging concurrency and archive compression. */ /** - * Validate packaging and cache worker limits without accessing signing hardware. - * @param {NodeJS.ProcessEnv} environment File-owned Windows packaging settings. - * @returns {{signatureCacheConcurrency: number, packConcurrency: number}} Worker limits, each defaulting to four when omitted. + * Validate worker limits and compression without accessing signing hardware. + * File-owned compression takes precedence over the existing electron-builder environment override. + * @param {NodeJS.ProcessEnv} environment Loaded packaging settings and inherited build environment. + * @returns {{signatureCacheConcurrency: number, packConcurrency: number, compressionLevel: number}} Worker limits defaulting to four and archive compression defaulting to three. */ export function resolveWindowsPackageSettings(environment) { const value = environment.DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_CONCURRENCY ?? '4' @@ -14,5 +15,9 @@ export function resolveWindowsPackageSettings(environment) { if (!/^[1-9]\d*$/u.test(pack) || !Number.isSafeInteger(Number(pack))) { throw new Error('desktop package: DSH_DESKTOP_WINDOWS_PACK_CONCURRENCY must be a positive integer') } - return { signatureCacheConcurrency: Number(value), packConcurrency: Number(pack) } + const compression = environment.DSH_DESKTOP_WINDOWS_COMPRESSION_LEVEL ?? environment.ELECTRON_BUILDER_COMPRESSION_LEVEL ?? '3' + if (!/^[0-9]$/u.test(compression)) { + throw new Error('desktop package: DSH_DESKTOP_WINDOWS_COMPRESSION_LEVEL must be an integer from 0 to 9') + } + return { signatureCacheConcurrency: Number(value), packConcurrency: Number(pack), compressionLevel: Number(compression) } } diff --git a/apps/desktop/scripts/windows-packaging-priority.ps1 b/apps/desktop/scripts/windows-packaging-priority.ps1 new file mode 100644 index 0000000000..2e926f030b --- /dev/null +++ b/apps/desktop/scripts/windows-packaging-priority.ps1 @@ -0,0 +1,59 @@ +# Normalize only this workflow shell and the children it subsequently launches. +[CmdletBinding()] +param([switch]$InspectOnly, [switch]$BestEffort) + +$ErrorActionPreference = 'Stop' +if (-not $IsWindows) { throw 'Packaging process priority requires Windows.' } + +if (-not ('DshPackagingPriority' -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; +public static class DshPackagingPriority { + [DllImport("kernel32.dll")] static extern IntPtr GetCurrentProcess(); + [DllImport("ntdll.dll")] static extern int NtSetInformationProcess(IntPtr process, int kind, ref int value, int size); + [DllImport("ntdll.dll")] static extern int NtQueryInformationProcess(IntPtr process, int kind, out int value, int size, out int length); + public static int Read(int kind) { + int value, length; + int status = NtQueryInformationProcess(GetCurrentProcess(), kind, out value, 4, out length); + if (status != 0 || length != 4) throw new InvalidOperationException("Cannot read packaging priority: " + status); + return value; + } + public static void Set(int kind, int value) { + int status = NtSetInformationProcess(GetCurrentProcess(), kind, ref value, 4); + if (status != 0) throw new InvalidOperationException("Cannot set packaging priority: " + status); + } +} +'@ +} + +$process = [Diagnostics.Process]::GetCurrentProcess() +try { + $before = [ordered]@{ + cpu = $process.PriorityClass.ToString() + io = [DshPackagingPriority]::Read(33) + memory = [DshPackagingPriority]::Read(39) + } + if (-not $InspectOnly) { + $process.PriorityClass = [Diagnostics.ProcessPriorityClass]::Normal + # PROCESSINFOCLASS: ProcessIoPriority (33), ProcessPagePriority (39). + [DshPackagingPriority]::Set(33, 2) + [DshPackagingPriority]::Set(39, 5) + } + $process.Refresh() + $after = [ordered]@{ + cpu = $process.PriorityClass.ToString() + io = [DshPackagingPriority]::Read(33) + memory = [DshPackagingPriority]::Read(39) + } + [ordered]@{ event = 'packaging-process-priority'; before = $before; after = $after } | ConvertTo-Json -Compress + if (-not $InspectOnly -and ($after.cpu -ne 'Normal' -or $after.io -ne 2 -or $after.memory -ne 5)) { + throw 'Packaging process did not reach normal CPU, I/O and memory priority.' + } +} catch { + if (-not $BestEffort) { throw } + Write-Warning "Packaging priority adjustment unavailable; performance comparison is invalid: $($_.Exception.Message)" + [ordered]@{ event = 'packaging-process-priority'; comparable = $false } | ConvertTo-Json -Compress +} finally { + $process.Dispose() +} diff --git a/apps/desktop/scripts/windows-runner-network.ps1 b/apps/desktop/scripts/windows-runner-network.ps1 new file mode 100644 index 0000000000..9ab2491901 --- /dev/null +++ b/apps/desktop/scripts/windows-runner-network.ps1 @@ -0,0 +1,80 @@ +# Load operator-owned network settings without evaluating code or logging their values. +function Read-RunnerNetwork([string]$ConfigRoot) { + $path = Join-Path $ConfigRoot 'runner-network.json' + if (-not (Test-Path -LiteralPath $path)) { return $null } + try { $config = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json -AsHashtable -ErrorAction Stop } + catch { throw 'Cannot read runner-network.json; inspect its JSON locally.' } + $keys = @('proxyUrl','noProxy','serviceName','probeUrl','attempts','timeoutSeconds','retrySeconds') + if ($config -isnot [Collections.IDictionary] -or $config.Count -ne $keys.Count -or @($config.Keys | Where-Object { $_ -cnotin $keys }).Count) { + throw 'runner-network.json requires exactly proxyUrl, noProxy, serviceName, probeUrl, attempts, timeoutSeconds and retrySeconds.' + } + foreach ($key in @('proxyUrl','noProxy','serviceName','probeUrl')) { + if ($config[$key] -isnot [string] -or $config[$key] -match '[\r\n\x00]') { throw 'Invalid network string setting; inspect runner-network.json locally.' } + } + if ([Management.Automation.WildcardPattern]::ContainsWildcardCharacters($config.serviceName)) { throw 'Network service must be an exact name.' } + foreach ($key in @('attempts','timeoutSeconds','retrySeconds')) { + if ($config[$key] -isnot [long] -and $config[$key] -isnot [int]) { throw 'Network budgets must be integers.' } + if ($config[$key] -lt 1 -or $config[$key] -gt 60) { throw 'Network budgets must be between 1 and 60.' } + } + foreach ($key in @('proxyUrl','probeUrl')) { + if ($key -eq 'proxyUrl' -and $config[$key] -eq '') { continue } + $uri = $null + if (-not [Uri]::TryCreate($config[$key], [UriKind]::Absolute, [ref]$uri) -or $uri.Scheme -notin @('http','https') -or $uri.UserInfo -or $uri.Query -or $uri.Fragment) { + throw 'Network URLs must be absolute HTTP(S) URLs without credentials, queries or fragments.' + } + if ($key -eq 'proxyUrl' -and $uri.AbsolutePath -ne '/') { throw 'Proxy URL must not contain a path.' } + } + return $config +} + +# Called after the runner environment is scrubbed; only declared network values reach child jobs. +function Set-RunnerNetwork($Config) { + if ($null -eq $Config) { return } + [Environment]::SetEnvironmentVariable('HTTP_PROXY', $Config.proxyUrl, 'Process') + [Environment]::SetEnvironmentVariable('HTTPS_PROXY', $Config.proxyUrl, 'Process') + [Environment]::SetEnvironmentVariable('NO_PROXY', $Config.noProxy, 'Process') + [Environment]::SetEnvironmentVariable('NODE_USE_ENV_PROXY', '1', 'Process') +} + +# Only probe retries are allowed here. Service recovery belongs to its installed Windows service. +function Wait-RunnerNetwork($Config) { + if ($null -eq $Config) { return } + $info = [Diagnostics.ProcessStartInfo]::new((Get-Command node -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source) + $info.UseShellExecute = $false + $info.CreateNoWindow = $true + $info.RedirectStandardOutput = $true + $info.RedirectStandardError = $true + $info.Environment['DSH_NETWORK_PROBE_URL'] = $Config.probeUrl + $info.Environment['DSH_NETWORK_PROBE_TIMEOUT'] = [string]($Config.timeoutSeconds * 1000) + $info.ArgumentList.Add('--input-type=module') + $info.ArgumentList.Add('-e') + $info.ArgumentList.Add('try { const r = await fetch(process.env.DSH_NETWORK_PROBE_URL, { method: "HEAD", redirect: "error", signal: AbortSignal.timeout(Number(process.env.DSH_NETWORK_PROBE_TIMEOUT)) }); await r.body?.cancel(); process.exit(r.ok ? 0 : 1); } catch { process.exit(1); }') + for ($attempt = 1; $attempt -le $Config.attempts; $attempt++) { + $ready = $true + if ($Config.serviceName) { + try { $service = Get-Service -Name $Config.serviceName -ErrorAction Stop } + catch { throw 'Configured network service is unavailable; inspect its installation locally.' } + $ready = $service.Status -eq 'Running' + } + if ($ready) { + $process = [Diagnostics.Process]::new() + $process.StartInfo = $info + try { + if (-not $process.Start()) { throw 'Cannot launch network probe.' } + $out = $process.StandardOutput.ReadToEndAsync() + $err = $process.StandardError.ReadToEndAsync() + if (-not $process.WaitForExit(($Config.timeoutSeconds + 5) * 1000)) { + $process.Kill($true) + $process.WaitForExit() + $ready = $false + } else { $ready = $process.ExitCode -eq 0 } + $null = $out.GetAwaiter().GetResult() + $null = $err.GetAwaiter().GetResult() + } finally { $process.Dispose() } + } + if ($ready) { Write-Output 'Runner network dependency ready (Node HEAD probe).'; return } + Write-Output "Runner network dependency not ready (probe $attempt/$($Config.attempts))." + if ($attempt -lt $Config.attempts) { Start-Sleep -Seconds $Config.retrySeconds } + } + throw 'Runner network dependency unavailable; runner was not started. Inspect local service and network configuration. No job or signing retry was requested.' +} diff --git a/apps/desktop/scripts/windows-runner-task.ps1 b/apps/desktop/scripts/windows-runner-task.ps1 index 47efba43e0..e940eef988 100644 --- a/apps/desktop/scripts/windows-runner-task.ps1 +++ b/apps/desktop/scripts/windows-runner-task.ps1 @@ -4,13 +4,14 @@ param( [Parameter(Mandatory=$true)][ValidateSet('install','start','stop','status','uninstall')][string]$Action, [Parameter(Mandatory=$true)][string]$RunnerRoot, [string]$ConfigRoot, + [string]$NetworkRoot, [ValidateRange(1,1440)][int]$RestartMinutes = 1, [ValidateRange(1,999)][int]$RestartCount = 10 ) $ErrorActionPreference = 'Stop' if (-not $IsWindows) { throw 'This command requires PowerShell 7 on Windows.' } -if ($Action -ne 'install' -and @('ConfigRoot','RestartMinutes','RestartCount').Where({ $PSBoundParameters.ContainsKey($_) }).Count) { - throw 'ConfigRoot, RestartMinutes and RestartCount apply only to install; reinstall to change them.' +if ($Action -ne 'install' -and @('ConfigRoot','NetworkRoot','RestartMinutes','RestartCount').Where({ $PSBoundParameters.ContainsKey($_) }).Count) { + throw 'ConfigRoot, NetworkRoot, RestartMinutes and RestartCount apply only to install; reinstall to change them.' } if ($RunnerRoot -notmatch '^[A-Za-z]:[\\/]') { throw 'RunnerRoot must be an absolute local directory.' } $RunnerRoot = [IO.Path]::GetFullPath($RunnerRoot).TrimEnd('\','/') @@ -30,7 +31,15 @@ if ($Action -eq 'install') { if (-not $ConfigRoot -or $ConfigRoot -notmatch '^[A-Za-z]:[\\/]') { throw 'Install requires an absolute ConfigRoot.' } $ConfigRoot = [IO.Path]::GetFullPath($ConfigRoot) $pwsh = Join-Path $PSHOME 'pwsh.exe' - & $pwsh -NoProfile -File (Join-Path $PSScriptRoot 'start-windows-packaging-runner.ps1') -RunnerRoot $RunnerRoot -ConfigRoot $ConfigRoot -CheckOnly + $startup = Join-Path $PSScriptRoot 'start-windows-packaging-runner.ps1' + if ($PSBoundParameters.ContainsKey('NetworkRoot')) { + if ($NetworkRoot -notmatch '^[A-Za-z]:[\\/]') { throw 'NetworkRoot must identify an existing absolute local directory.' } + if (-not (Test-Path -LiteralPath (Join-Path $ConfigRoot 'runner-network.json') -PathType Leaf)) { throw 'Owned network supervision requires runner-network.json.' } + $NetworkRoot = [IO.Path]::GetFullPath($NetworkRoot) + & $pwsh -NoProfile -File (Join-Path $PSScriptRoot 'run-windows-runner-network-process.ps1') -RunnerRoot $RunnerRoot -ConfigRoot $ConfigRoot -NetworkRoot $NetworkRoot -ReadinessScript $startup -StartScript $startup -CheckOnly + } else { + & $pwsh -NoProfile -File $startup -RunnerRoot $RunnerRoot -ConfigRoot $ConfigRoot -CheckOnly + } if ($LASTEXITCODE -ne 0) { throw 'Runner preflight failed; no task was installed.' } if (Test-Path -LiteralPath $serviceDir) { if ((Get-Item -LiteralPath $serviceDir).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Task directory cannot be a link.' } @@ -44,7 +53,10 @@ if ($Action -eq 'install') { if ($LASTEXITCODE -ne 0) { throw 'Runner launcher compilation failed; verify .NET Framework 4.5+ is installed. No task was installed.' } Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'start-windows-packaging-runner.ps1') -Destination (Join-Path $serviceDir 'start.ps1') Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'run-windows-runner-task.ps1') -Destination (Join-Path $serviceDir 'run.ps1') - @{ RunnerRoot = $RunnerRoot; ConfigRoot = $ConfigRoot; TaskName = $taskName; RestartCount = $RestartCount } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $serviceDir 'config.json') -Encoding utf8 + foreach ($helper in @('windows-runner-network.ps1','run-windows-runner-network-process.ps1')) { + Copy-Item -LiteralPath (Join-Path $PSScriptRoot $helper) -Destination (Join-Path $serviceDir $helper) + } + @{ RunnerRoot = $RunnerRoot; ConfigRoot = $ConfigRoot; NetworkRoot = $NetworkRoot; TaskName = $taskName; RestartCount = $RestartCount } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $serviceDir 'config.json') -Encoding utf8 Set-Content -LiteralPath (Join-Path $serviceDir 'attempts.txt') -Value '0' $execution = New-ScheduledTaskAction -Execute $launcher -Argument ('"' + $pwsh + '"') -WorkingDirectory $RunnerRoot $principal = New-ScheduledTaskPrincipal -UserId $sid -LogonType Interactive -RunLevel Limited @@ -52,7 +64,7 @@ if ($Action -eq 'install') { (New-ScheduledTaskTrigger -AtLogOn -User $sid), (New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes($RestartMinutes) -RepetitionInterval (New-TimeSpan -Minutes $RestartMinutes)) ) - $settings = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries + $settings = New-ScheduledTaskSettingsSet -Priority 4 -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries $settings.Enabled = $false $null = Register-ScheduledTask -TaskName $taskName -TaskPath '\' -Action $execution -Principal $principal -Trigger $trigger -Settings $settings -Description "DSH packaging runner: $RunnerRoot; owner: $sid" Write-Output "Installed disabled task $taskName. Run start while logged in; reboot requires desktop login. Logs: $serviceDir" diff --git a/apps/desktop/scripts/windows-runtime-signature.d.mts b/apps/desktop/scripts/windows-runtime-signature.d.mts index f47e306885..b5624c2577 100644 --- a/apps/desktop/scripts/windows-runtime-signature.d.mts +++ b/apps/desktop/scripts/windows-runtime-signature.d.mts @@ -41,7 +41,7 @@ export interface WindowsCodeSigningOptions { /** * Enumerate PE files by content without following links. * @param root Materialized directory to scan. - * @returns Sorted PE paths; rejects malformed Windows executables and links. + * @returns Sorted PE paths; eight bounded readers reject links or malformed executables and drain open handles before failure. */ export function windowsRuntimeCode(root: string): Promise @@ -49,7 +49,7 @@ export function windowsRuntimeCode(root: string): Promise * Preserve valid signatures and sign unsigned PE files with a supervised signer. * @param root Materialized directory to sign. * @param options Signer, certificate identity and audit sink. - * @returns Resolves after verified parallel cache restores and sequential signing; stops dispatch and drains active restores on failure, without retries. + * @returns Resolves after parallel cache restores, batched target verification and sequential signing; failures drain active restores or inspections without retries. */ export function signWindowsCode(root: string, options: WindowsCodeSigningOptions): Promise diff --git a/apps/desktop/scripts/windows-runtime-signature.mjs b/apps/desktop/scripts/windows-runtime-signature.mjs index 8780f182ca..9f79547b34 100644 --- a/apps/desktop/scripts/windows-runtime-signature.mjs +++ b/apps/desktop/scripts/windows-runtime-signature.mjs @@ -6,6 +6,7 @@ import { promisify } from 'node:util' import { scrubWindowsSigningEnvironment } from './windows-sign.mjs' import { recordPackagingEvent } from './packaging-run.mjs' import { inspectSignaturesBatched } from './windows-signature-batch.mjs' +import { packagingStep } from './packaging-step.mjs' /** * Read Windows trust, timestamp and signer identity using the engine's bundled modules, without accessing the private key. @@ -52,17 +53,32 @@ export async function preserveWindowsRuntimeSignature(path, options) { /** * Enumerate Windows code without following links or treating foreign .node files as PE binaries. * @param {string} root - Owned, materialized runtime directory. - * @returns {Promise} Sorted real PE files; rejects links and malformed Windows executable files. + * @returns {Promise} Sorted real PE files; eight bounded readers reject links or malformed executables and drain open handles before failure. */ export async function windowsRuntimeCode(root) { - const rootStat = await lstat(root) - if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) throw new Error('Windows code: expected a real directory') + return packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'windows:enumerate-code', async () => { + const candidates = [] + async function collect(directory) { + const rootStat = await lstat(directory) + if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) throw new Error('Windows code: expected a real directory') + for (const entry of await readdir(directory, { withFileTypes: true })) { + const path = join(directory, entry.name) + if (entry.isSymbolicLink()) throw new Error(`Windows code: directory links are not signable: ${path}`) + if (entry.isDirectory()) await collect(path) + else if (entry.isFile()) candidates.push(path) + } + } + await collect(root) + return inspectPortableExecutables(candidates) + }) +} + +/** Close every active file before returning a sorted inventory or the first inspection failure. */ +async function inspectPortableExecutables(candidates) { const files = [] - for (const entry of await readdir(root, { withFileTypes: true })) { - const path = join(root, entry.name) - if (entry.isSymbolicLink()) throw new Error(`Windows code: directory links are not signable: ${path}`) - if (entry.isDirectory()) { files.push(...await windowsRuntimeCode(path)); continue } - if (!entry.isFile()) continue + let next = 0 + let failure + async function inspect(path) { const file = await open(path, 'r') let portableExecutable = false let windowsCandidate = false @@ -80,11 +96,26 @@ export async function windowsRuntimeCode(root) { if (portableExecutable) files.push(path) else if (windowsCandidate || ['.exe', '.dll', '.pyd'].includes(extname(path).toLowerCase())) throw new Error(`Windows code: invalid PE file: ${path}`) } + async function worker() { + while (failure === undefined && next < candidates.length) { + const path = candidates[next++] + try { await inspect(path) } + catch (error) { failure ??= { error } } + } + } + await Promise.all(Array.from({ length: Math.min(8, candidates.length) }, worker)) + if (failure !== undefined) throw failure.error return files.sort() } /** Drain each public-key verification batch before signing or reporting a failure. */ async function inspectWindowsCode(files, inspect) { + return packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'windows:inspect-signatures', + () => inspectWindowsCodeBatch(files, inspect)) +} + +/** Complete bounded inspections without allowing callers to proceed past an active failed batch. */ +async function inspectWindowsCodeBatch(files, inspect) { if (inspect === inspectWindowsRuntimeSignature) return inspectSignaturesBatched(files) const signatures = [] for (let offset = 0; offset < files.length; offset += 4) { @@ -101,7 +132,7 @@ async function inspectWindowsCode(files, inspect) { * Preserve valid signatures and sign unsigned PE files with a supervised signer. * @param {string} root - Owned final runtime directory. * @param {import('./windows-runtime-signature.mjs').WindowsCodeSigningOptions} options - Supervised signer, certificate identity, audit sink. - * @returns {Promise} Resolves after bounded cache restores and sequential hardware signing, each with verification; failures drain active restores before rejecting. + * @returns {Promise} Resolves after bounded cache restores, batched target verification and sequential hardware signing; failures drain active work before rejecting. */ export async function signWindowsCode(root, options) { const inspect = options.inspect ?? inspectWindowsRuntimeSignature @@ -116,12 +147,15 @@ export async function signWindowsCode(root, options) { else if (signature.status !== 'Valid') throw new Error(`Windows code: refusing ${signature.status} signature: ${path}`) } options.record({ type: 'windows-code-signing-plan', files: files.length, unsigned: unsigned.length }) - async function verifySigned(path) { - const signature = await inspect(path) - if (signature.status !== 'Valid' || !signature.timestamped || signature.thumbprint?.toUpperCase() !== options.thumbprint.toUpperCase()) { - throw new Error(`Windows code: signing verification failed: ${path}`) + async function verifySigned(paths) { + const verified = await inspectWindowsCode(paths, inspect) + for (const [index, path] of paths.entries()) { + const signature = verified[index] + if (signature.status !== 'Valid' || !signature.timestamped || signature.thumbprint?.toUpperCase() !== options.thumbprint.toUpperCase()) { + throw new Error(`Windows code: signing verification failed: ${path}`) + } + options.record({ type: 'windows-code-signature-verified', path, ...signature }) } - options.record({ type: 'windows-code-signature-verified', path, ...signature }) } const restored = new Set() if (options.cache) { @@ -132,7 +166,6 @@ export async function signWindowsCode(root, options) { const path = unsigned[next++] try { if (await options.cache.restore({ path, hash: 'sha256', isNest: false })) { - await verifySigned(path) restored.add(path) } } catch (error) { failure ??= { error } } @@ -140,11 +173,12 @@ export async function signWindowsCode(root, options) { } await Promise.all(Array.from({ length: Math.min(options.cache.concurrency, unsigned.length) }, worker)) if (failure !== undefined) throw failure.error + await verifySigned(unsigned.filter(path => restored.has(path))) } for (const path of unsigned) { if (restored.has(path)) continue await options.sign({ path, hash: 'sha256', isNest: false }) - await verifySigned(path) + await verifySigned([path]) } } diff --git a/apps/desktop/scripts/windows-sign.mjs b/apps/desktop/scripts/windows-sign.mjs index 3ebd199615..78459c4c1f 100644 --- a/apps/desktop/scripts/windows-sign.mjs +++ b/apps/desktop/scripts/windows-sign.mjs @@ -135,7 +135,9 @@ export function createRedactedWindowsSigningError(error, path, secrets) { const stderr = record !== undefined && 'stderr' in record ? redactedSigningOutput(record.stderr, secrets).trim() : '' - return new Error(`Windows release signing failed for ${path}${code}${stderr === '' ? '' : `: ${stderr}`}`) + return new Error(`Windows release signing failed for ${path}${code}${stderr === '' ? '' : `: ${stderr}`}. ` + + 'Signing stopped. After replacing the UKey, check the certificate, container, SafeNet provider and user PIN. ' + + 'This error does not establish device lock status or whether PIN retries were consumed; inspect the retained interlock before operator recovery.') } /** diff --git a/apps/desktop/scripts/windows-signing-preflight.ts b/apps/desktop/scripts/windows-signing-preflight.ts index 6076e4cd4e..48d65b7b91 100644 --- a/apps/desktop/scripts/windows-signing-preflight.ts +++ b/apps/desktop/scripts/windows-signing-preflight.ts @@ -8,6 +8,7 @@ import { promisify } from 'node:util' import { createWindowsTokenSigner, scrubWindowsSigningEnvironment } from './windows-sign.mjs' import { inspectWindowsRuntimeSignature, type WindowsRuntimeSignature } from './windows-runtime-signature.mjs' import { failPackagingRun, recordPackagingEvent } from './packaging-run.mjs' +import { inspectWindowsTokenIdentity, windowsTokenIdentityFailure } from './windows-token-identity.ts' const PROBE_SOURCE = 'internal static class SigningProbe { private static int Main() { return 0; } }\n' @@ -18,6 +19,7 @@ interface SigningPreflightOptions { compile?: (compiler: string, source: string, output: string, environment: NodeJS.ProcessEnv) => Promise sign?: ReturnType inspect?: (path: string) => Promise + inspectIdentity?: typeof inspectWindowsTokenIdentity } async function compileProbe(compiler: string, source: string, output: string, environment: NodeJS.ProcessEnv): Promise { @@ -28,7 +30,7 @@ async function compileProbe(compiler: string, source: string, output: string, en } /** - * Sign one newly compiled, never-executed probe and verify its timestamp and configured certificate. + * Match public container keys before signing one never-executed probe and verifying its certificate and timestamp. * @param options Supervised evidence directory, file-owned settings and isolated test adapters. * @returns Resolves after one signature and verification; failures retain evidence; timestamp attempts never repeat hardware signing. */ @@ -71,6 +73,12 @@ export async function preflightWindowsSigning(options: SigningPreflightOptions): compilerSha256: createHash('sha256').update(await readFile(compiler)).digest('hex'), signToolSha256: createHash('sha256').update(await readFile(environment.DSH_DESKTOP_WINDOWS_SIGNTOOL!)).digest('hex'), certificateSha256: createHash('sha256').update(certificate).digest('hex') }) + const identity = await (options.inspectIdentity ?? inspectWindowsTokenIdentity)({ + certificate, container: environment.DSH_DESKTOP_WINDOWS_KEY_CONTAINER!.trim(), + environment: scrubWindowsSigningEnvironment(environment), + }) + record({ type: 'signing-preflight-public-identity', result: identity, pinSupplied: false }) + if (identity !== 'matched') throw new Error(windowsTokenIdentityFailure(identity)) await (options.compile ?? compileProbe)(compiler, source, output, environment) const inspect = options.inspect ?? inspectWindowsRuntimeSignature if ((await inspect(output)).status !== 'NotSigned') throw new Error('Windows signing preflight requires a new unsigned probe') diff --git a/apps/desktop/scripts/windows-token-identity.ts b/apps/desktop/scripts/windows-token-identity.ts new file mode 100644 index 0000000000..a36ddf1d72 --- /dev/null +++ b/apps/desktop/scripts/windows-token-identity.ts @@ -0,0 +1,87 @@ +/** Compare CSP public material without supplying a PIN or invoking a signing operation. */ +import { execFile } from 'node:child_process' +import { createPublicKey, X509Certificate } from 'node:crypto' +import { promisify } from 'node:util' +import { fileURLToPath } from 'node:url' +import { scrubWindowsSigningEnvironment } from './windows-sign.mjs' + +/** Public-data results do not attest physical device presence, authentication or remaining PIN attempts. */ +export type WindowsTokenIdentity = 'matched' | 'certificate-mismatch' | 'provider-unavailable' | 'container-unavailable' | 'unknown' + +interface PublicKeyQuery { + container: string + environment: NodeJS.ProcessEnv +} + +async function queryPublicKeys({ container, environment }: PublicKeyQuery): Promise { + const { NODE_OPTIONS: _options, NODE_PATH: _path, ...safeEnvironment } = scrubWindowsSigningEnvironment(environment) + const { stdout, stderr } = await promisify(execFile)('pwsh', ['-NoProfile', '-NonInteractive', '-File', + fileURLToPath(new URL('./windows-token-public-key.ps1', import.meta.url))], { + env: { ...safeEnvironment, DSH_TOKEN_PUBLIC_CONTAINER: container }, + encoding: 'utf8', windowsHide: true, timeout: 15_000, maxBuffer: 64 * 1024, + }) + if (stderr) throw new Error('Public-key query returned diagnostics') + return stdout +} + +function publicBlobKey(value: string): Buffer { + const bytes = Buffer.from(value, 'base64') + if (bytes.toString('base64') !== value || bytes.length < 20 || bytes[0] !== 6 || bytes[1] !== 2 + || bytes.readUInt16LE(2) !== 0 || ![0x2400, 0xa400].includes(bytes.readUInt32LE(4)) + || bytes.readUInt32LE(8) !== 0x31415352) throw new Error('Invalid RSA public blob') + const bits = bytes.readUInt32LE(12) + const exponent = bytes.readUInt32LE(16) + if (bits < 512 || bits % 8 !== 0 || bytes.length !== 20 + bits / 8 || exponent < 3 || exponent % 2 === 0) { + throw new Error('Invalid RSA public parameters') + } + const exponentBytes = Buffer.alloc(4) + exponentBytes.writeUInt32BE(exponent) + const first = exponentBytes.findIndex(byte => byte !== 0) + return createPublicKey({ format: 'jwk', key: { kty: 'RSA', + n: Buffer.from(bytes.subarray(20)).reverse().toString('base64url'), + e: exponentBytes.subarray(first).toString('base64url') } }).export({ format: 'der', type: 'spki' }) +} + +/** + * Read both CSP public key slots and compare them with the configured certificate; never sign or retry. + * @param options Certificate bytes, container, process environment and optional isolated public-query adapter. + * @returns Matched public information, a specific unavailable/mismatch result, or unknown on incomplete/invalid output. + */ +export async function inspectWindowsTokenIdentity(options: PublicKeyQuery & { + certificate: Uint8Array + query?: (input: PublicKeyQuery) => Promise +}): Promise { + try { + const value: unknown = JSON.parse(await (options.query ?? queryPublicKeys)({ + container: options.container, environment: options.environment, + })) + if (!value || typeof value !== 'object' || !('status' in value)) return 'unknown' + if (value.status === 'provider-unavailable' || value.status === 'container-unavailable') return value.status + if (value.status !== 'public-keys' || !('publicKeys' in value) || !Array.isArray(value.publicKeys) + || value.publicKeys.length < 1 || value.publicKeys.length > 2) return 'unknown' + const keys = value.publicKeys.map((key: unknown) => { + if (typeof key !== 'string') throw new Error('Invalid public key') + return publicBlobKey(key) + }) + const expected = new X509Certificate(options.certificate).publicKey.export({ format: 'der', type: 'spki' }) + return keys.some(key => key.equals(expected)) ? 'matched' : 'certificate-mismatch' + } catch { + // Native failures may include container names or inherited diagnostics; expose only the incomplete result. + return 'unknown' + } +} + +/** + * Explain why public-data validation stopped signing without asserting device lock or authentication status. + * @param result Non-matching public-data result. + * @returns A credential-free operator diagnostic. + */ +export function windowsTokenIdentityFailure(result: Exclude): string { + const reasons = { + 'provider-unavailable': 'The configured eToken provider is unavailable; check the SafeNet driver.', + 'container-unavailable': 'The configured container could not be opened; after replacing the UKey, check its container name and visibility.', + 'certificate-mismatch': 'The returned container public keys do not match the configured certificate; check the certificate and container after replacing the UKey.', + unknown: 'The container public identity could not be confirmed; check that PowerShell 7 (pwsh) can start, then check device visibility and SafeNet public-information support.', + } + return `${reasons[result]} No PIN was supplied and no signing was attempted by this check. Signing stopped; device lock and PIN retry counts are unknown.` +} diff --git a/apps/desktop/scripts/windows-token-public-key.cs b/apps/desktop/scripts/windows-token-public-key.cs new file mode 100644 index 0000000000..2549138c0f --- /dev/null +++ b/apps/desktop/scripts/windows-token-public-key.cs @@ -0,0 +1,94 @@ +// Read only public material through the existing SafeNet CSP. No authentication or key mutation APIs. +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +public static class DshTokenPublicKey +{ + public const string Provider = "eToken Base Cryptographic Provider"; + public const uint PublicContextFlags = 0xF0000040; // CRYPT_VERIFYCONTEXT | CRYPT_SILENT + public const int NoKey = unchecked((int)0x8009000D); + + public interface IApi + { + int Acquire(string container, out IntPtr context); + int GetKey(IntPtr context, uint spec, out IntPtr key); + int Export(IntPtr key, byte[] bytes, ref uint length); + bool Destroy(IntPtr key); + bool Release(IntPtr context); + } + + public sealed class NativeApi : IApi + { + [DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] + static extern bool CryptAcquireContextW(out IntPtr context, string container, string provider, uint type, uint flags); + [DllImport("advapi32.dll", SetLastError = true)] + static extern bool CryptGetUserKey(IntPtr context, uint spec, out IntPtr key); + [DllImport("advapi32.dll", SetLastError = true)] + static extern bool CryptExportKey(IntPtr key, IntPtr exportKey, uint type, uint flags, byte[] bytes, ref uint length); + [DllImport("advapi32.dll", SetLastError = true)] + static extern bool CryptDestroyKey(IntPtr key); + [DllImport("advapi32.dll", SetLastError = true)] + static extern bool CryptReleaseContext(IntPtr context, uint flags); + public int Acquire(string container, out IntPtr context) { + return CryptAcquireContextW(out context, container, Provider, 1, PublicContextFlags) ? 0 : Marshal.GetLastWin32Error(); + } + public int GetKey(IntPtr context, uint spec, out IntPtr key) { + return CryptGetUserKey(context, spec, out key) ? 0 : Marshal.GetLastWin32Error(); + } + public int Export(IntPtr key, byte[] bytes, ref uint length) { + return CryptExportKey(key, IntPtr.Zero, 6, 0, bytes, ref length) ? 0 : Marshal.GetLastWin32Error(); // PUBLICKEYBLOB + } + public bool Destroy(IntPtr key) { return CryptDestroyKey(key); } + public bool Release(IntPtr context) { return CryptReleaseContext(context, 0); } + } + + public sealed class Result + { + public string status = "unknown"; + public string[] publicKeys = new string[0]; + } + + // The adapter seam allows all failure paths to be exercised without loading a hardware provider. + public static Result Read(IApi api, string container) + { + var result = new Result(); + IntPtr context; + int error = api.Acquire(container, out context); + if (error != 0) { + if (error == unchecked((int)0x80090013) || error == unchecked((int)0x80090017) + || error == unchecked((int)0x8009001E)) result.status = "provider-unavailable"; + else if (error == unchecked((int)0x80090016)) result.status = "container-unavailable"; + return result; + } + try { + var keys = new List(); + foreach (uint spec in new uint[] { 2, 1 }) { + IntPtr key; + error = api.GetKey(context, spec, out key); + if (error == NoKey) continue; + if (error != 0) return result; + bool destroyed; + try { + uint length = 0; + if (api.Export(key, null, ref length) != 0 || length < 20 || length > 16384) return result; + var bytes = new byte[length]; + uint capacity = length; + if (api.Export(key, bytes, ref length) != 0 || length < 20 || length > capacity) return result; + keys.Add(Convert.ToBase64String(bytes, 0, (int)length)); + } finally { destroyed = api.Destroy(key); } + if (!destroyed) return result; + } + if (keys.Count > 0) { + result.publicKeys = keys.ToArray(); + result.status = "public-keys"; + } + } finally { + if (!api.Release(context)) { + result.status = "unknown"; + result.publicKeys = new string[0]; + } + } + return result; + } +} diff --git a/apps/desktop/scripts/windows-token-public-key.ps1 b/apps/desktop/scripts/windows-token-public-key.ps1 new file mode 100644 index 0000000000..9adb367c3b --- /dev/null +++ b/apps/desktop/scripts/windows-token-public-key.ps1 @@ -0,0 +1,4 @@ +# Only the container name is needed; the caller removes inherited signing credentials. +$ErrorActionPreference = 'Stop' +Add-Type -Path (Join-Path $PSScriptRoot 'windows-token-public-key.cs') +[DshTokenPublicKey]::Read([DshTokenPublicKey+NativeApi]::new(), $env:DSH_TOKEN_PUBLIC_CONTAINER) | ConvertTo-Json -Compress diff --git a/apps/desktop/src/crash-report.ts b/apps/desktop/src/crash-report.ts index 9c6d9ed793..b4c0140848 100644 --- a/apps/desktop/src/crash-report.ts +++ b/apps/desktop/src/crash-report.ts @@ -29,6 +29,8 @@ export interface CrashReportApp { /** Inputs of {@link renderCrashReport} and {@link writeCrashReport}. */ export interface CrashReportInput { + /** The shell will attempt an independently bounded operation-history append after saving this report. */ + readonly operationHistoryPlanned?: boolean readonly source: CrashReportSource readonly phase: CrashReportPhase readonly error: unknown @@ -125,6 +127,9 @@ export function renderCrashReport(input: CrashReportInput): string { ...(input.hostDiagnostic === undefined ? [] : ['--- host diagnostic (as reported by the Host process) ---', input.hostDiagnostic, '']), '--- renderer console (error level, oldest first) ---', consoleSection, + ...(input.operationHistoryPlanned === true ? ['', '--- auxiliary diagnostics ---', + 'Operation history is best effort. Without its completion marker below, it is unavailable or incomplete.', + 'Recent operations are context only. Missing records do not establish that no changes occurred.'] : []), '', ].join('\n') } diff --git a/apps/desktop/src/fatal-recovery.ts b/apps/desktop/src/fatal-recovery.ts index 5a739b1288..8bfe76ab37 100644 --- a/apps/desktop/src/fatal-recovery.ts +++ b/apps/desktop/src/fatal-recovery.ts @@ -12,10 +12,14 @@ interface RecoveryOperations { disablePlugins(): Promise exit(): void restart(): void + /** Reveal an existing report in the system file manager; reject if it is no longer available. */ + revealReport(path: string): Promise /** Persist the complete diagnostic; resolves with the file path, or `undefined` when nothing was written. */ writeReport(error: unknown, source: CrashReportSource): Promise } +type ReportState = { kind: 'pending' } | { kind: 'failed' } | { kind: 'ready'; path: string } + /** Upper bound on waiting for the crash report before the dialog opens. */ export const CRASH_REPORT_WAIT_MS = 1_000 @@ -25,28 +29,28 @@ const DETAIL_BUDGET = 1200 /** Tail lines of the error kept in the dialog; the report file holds the rest. */ const DETAIL_TAIL_LINES = 8 -/** - * Compose the dialog detail: the error's last lines (prefixed by the - * shortening notice when they are not the whole error), then the report path - * when one was written, then the reinstall advice. The report line does not - * depend on shortening: a short error that was persisted names its file too. +/** At most eight error-tail lines; status, advice and truncation notice share the detail character budget. + * The message heading has its own field. */ -function dialogDetail(error: string, messages: DesktopMessages, reportPath: string | undefined): string { +function dialogDetail(error: string, messages: DesktopMessages, reportState: ReportState): string { const advice = `\n\n${messages.startupReinstallAdvice}` - const report = reportLine(messages, reportPath) + const report = reportLine(messages, reportState) const tail = error.split(/\r\n|[\n\r\u2028\u2029]/u).slice(-DETAIL_TAIL_LINES).join('\n') const budget = DETAIL_BUDGET - advice.length - report.length - messages.diagnosticTruncated.length - 1 const shortened = tail.slice(-budget).replace(/^[\uDC00-\uDFFF]/u, '') return `${shortened === error ? error : `${messages.diagnosticTruncated}\n${shortened}`}${report}${advice}` } -function reportLine(messages: DesktopMessages, reportPath: string | undefined): string { - return reportPath === undefined ? '' : `\n${formatDesktopMessage(messages.reportWrittenTo, { path: reportPath })}` +function reportLine(messages: DesktopMessages, state: ReportState): string { + if (state.kind === 'pending') return `\n${messages.reportPending}` + if (state.kind === 'failed') return `\n${messages.reportUnavailable}` + return `\n${formatDesktopMessage(messages.reportWrittenTo, { path: state.path })}` } /** Deduplicates fatal reports while keeping explicit recovery-operation failures actionable. */ export class DesktopFatalRecovery { private reported = false + private reportState: ReportState = { kind: 'pending' } /** @param operations - Native presentation, report persistence, and application-owned shutdown operations. */ constructor(private readonly operations: RecoveryOperations) {} @@ -57,7 +61,7 @@ export class DesktopFatalRecovery { /** * Show the first fatal error; later reports cannot replace it or open another dialog. * The crash report is written first, bounded by {@link CRASH_REPORT_WAIT_MS}, so the dialog can name it; - * a slow or failed write shows the dialog without a path. + * a slow or failed write shows its status. Retrieving a report rechecks the same write. * @param error - Fatal failure, including nested diagnostic causes. * @param source - Where the failure surfaced, recorded in the report. * @returns Completion of the user's recovery action; duplicate reports resolve immediately. @@ -66,25 +70,42 @@ export class DesktopFatalRecovery { if (this.reported) return this.reported = true const messages = this.operations.messages() - const reportPath = await this.persist(error, source) + const report = this.persist(error, source) + await this.waitForReport(report) let detail = desktopErrorState(error).message let message = messages.fatalSummary for (;;) { const addressInUse = /\blisten EADDRINUSE\b/u.test(detail) + const buttons = addressInUse + ? [messages.exitApplication, messages.restartApplication] + : [messages.exitApplication, messages.restartApplication, messages.disableThirdPartyPlugins] + const reportButton = this.reportState.kind === 'failed' ? undefined : buttons.length + if (reportButton !== undefined) buttons.push(messages.getDiagnosticReport) const { response } = await this.operations.show({ type: 'error', title: messages.startupFailed, message, detail: addressInUse - ? `${messages.startupAddressInUse}${reportLine(messages, reportPath)}` - : dialogDetail(detail, messages, reportPath), - buttons: addressInUse - ? [messages.exitApplication, messages.restartApplication] - : [messages.exitApplication, messages.restartApplication, messages.disableThirdPartyPlugins], + ? `${messages.startupAddressInUse}${reportLine(messages, this.reportState)}` + : dialogDetail(detail, messages, this.reportState), + buttons, defaultId: 1, cancelId: 0, noLink: true, }) + if (response === reportButton) { + await this.waitForReport(report) + if (this.reportState.kind === 'ready') { + try { + await this.operations.revealReport(this.reportState.path) + message = messages.reportShareHint + } catch (failure) { + console.error('dsh desktop: could not reveal crash report', failure) + message = messages.reportRevealFailed + } + } + continue + } if (response === 0) { try { await this.operations.stop() } catch (failure) { console.error(failure) } this.operations.exit() @@ -103,16 +124,23 @@ export class DesktopFatalRecovery { } } - private async persist(error: unknown, source: CrashReportSource): Promise { - let timer: ReturnType | undefined + private async persist(error: unknown, source: CrashReportSource): Promise { try { - return await Promise.race([ - this.operations.writeReport(error, source), - new Promise((resolve) => { timer = setTimeout(() => { resolve(undefined) }, CRASH_REPORT_WAIT_MS) }), - ]) + const path = await this.operations.writeReport(error, source) + this.reportState = path === undefined ? { kind: 'failed' } : { kind: 'ready', path } } catch (failure) { console.error('dsh desktop: crash report failed', failure) - return undefined + this.reportState = { kind: 'failed' } + } + } + + private async waitForReport(report: Promise): Promise { + let timer: ReturnType | undefined + try { + await Promise.race([ + report, + new Promise((resolve) => { timer = setTimeout(resolve, CRASH_REPORT_WAIT_MS) }), + ]) } finally { clearTimeout(timer) } diff --git a/apps/desktop/src/host-process.ts b/apps/desktop/src/host-process.ts index 6dbb908c10..338f93bda4 100644 --- a/apps/desktop/src/host-process.ts +++ b/apps/desktop/src/host-process.ts @@ -2,8 +2,10 @@ import { spawn, type ChildProcess } from 'node:child_process' import { join } from 'node:path' +import { z } from 'zod' import type { PlatformSession } from '@deepseek-ai/dsh-deepseek-account' import { desktopNodeEnvironment } from './node-environment.ts' +import { parsePluginOperationRecord, type PluginOperationRecord, type PluginOperationRunId } from '@deepseek-ai/dsh-plugin-manager/diagnostic' interface ReadyEvent { readonly type: 'ready' @@ -23,7 +25,10 @@ interface PlatformSessionEvent { readonly session: PlatformSession | null } -type DesktopHostEvent = ReadyEvent | FatalEvent | PlatformSessionEvent | { readonly type: 'shutdown-complete' } | { +type DesktopHostEvent = ReadyEvent | FatalEvent | PlatformSessionEvent | { + readonly type: 'starting' + readonly runId: PluginOperationRunId +} | { readonly type: 'shutdown-complete' } | { readonly type: 'file-drag-resource' readonly requestId: number readonly resource: { readonly path: string; readonly sha256: string; readonly size: number } | null @@ -54,11 +59,14 @@ export interface DesktopQuitInspection { export const QUIT_INSPECTION_DEADLINE_MS = 2_000 const MAX_HOST_DIAGNOSTIC_CHARS = 64 * 1024 +const runIdSchema = z.uuid() function isDesktopHostEvent(message: unknown): message is DesktopHostEvent { if (typeof message !== 'object' || message === null || !('type' in message)) return false const candidate = message as Record switch (candidate.type) { + case 'starting': + return runIdSchema.safeParse(candidate.runId).success case 'shutdown-complete': return true case 'ready': @@ -148,6 +156,7 @@ export class DesktopHostFatalError extends Error { /** One Web backend running under the Electron executable in Node mode. */ export class DesktopHostProcess { + private runId: PluginOperationRunId | undefined private child: ChildProcess | undefined private readyResolve!: (ready: DesktopHostReady) => void private readyReject!: (error: Error) => void @@ -177,6 +186,7 @@ export class DesktopHostProcess { * `office-skills` resources fail Host startup. * @param packageManager - Bundled pnpm entry and Node launcher directory, scoped to package operations. * @param onPlatformSession - Private credential updates for embedded Platform views. + * @param onPluginOperation - Optional diagnostic sink; malformed records are ignored without failing the Host. */ constructor( private readonly node: string, @@ -189,6 +199,7 @@ export class DesktopHostProcess { private readonly packageManager?: { readonly pnpm: string; readonly nodeBin: string }, private readonly onPlatformSession?: (session: PlatformSession | null) => void, + private readonly onPluginOperation?: (record: PluginOperationRecord) => void, ) {} /** @@ -216,12 +227,24 @@ export class DesktopHostProcess { child.stderr?.on('data', (chunk: string) => { this.stderr = (this.stderr + chunk).slice(-MAX_HOST_DIAGNOSTIC_CHARS) }) child.stdout?.pipe(process.stdout) child.on('message', (message: unknown) => { + if (typeof message === 'object' && message !== null && 'type' in message && message.type === 'plugin-operation') { + const record = 'record' in message ? parsePluginOperationRecord(message.record) : undefined + if (record !== undefined && record.runId === this.runId) { + try { this.onPluginOperation?.(record) } + catch (_error) { + // Diagnostic persistence cannot invalidate the Host's business IPC channel. + console.error('desktop plugin operation diagnostic sink failed') + } + } + return + } if (!isDesktopHostEvent(message)) { this.fail(new Error('dsh desktop host sent an invalid IPC event')) child.kill('SIGTERM') return } - if (message.type === 'ready') this.readyResolve({ url: message.url, injections: message.injections }) + if (message.type === 'starting') this.runId = message.runId + else if (message.type === 'ready') this.readyResolve({ url: message.url, injections: message.injections }) else if (message.type === 'platform-session') this.onPlatformSession?.(message.session) else if (message.type === 'shutdown-complete') { if (this.stopping) this.shutdownCompleted = true @@ -344,6 +367,7 @@ export class DesktopHostProcess { } private fail(error: Error): void { + if (this.runId !== undefined) Object.assign(error, { hostRunId: this.runId }) this.onPlatformSession?.(null) this.readyReject(error) for (const request of this.controlRequests.values()) request.reject(error) diff --git a/apps/desktop/src/locale-cache.ts b/apps/desktop/src/locale-cache.ts new file mode 100644 index 0000000000..d09ee4da24 --- /dev/null +++ b/apps/desktop/src/locale-cache.ts @@ -0,0 +1,38 @@ +/** Last confirmed shell language, available even when the Host cannot start. */ +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { resolveDesktopLocale, type DesktopLocale } from './locale.ts' + +/** + * Read the last confirmed language without requiring Host settings. + * @param userData - Electron userData directory. + * @returns Cached language, or undefined when missing, invalid or unreadable. + */ +export function readDesktopLocaleCache(userData: string): DesktopLocale['id'] | undefined { + try { + const value = readFileSync(join(userData, 'desktop', 'locale-cache'), 'utf8').trim() + const locale = resolveDesktopLocale(value) + if (locale.id === value) return locale.id + throw new Error('expected a canonical Desktop locale id') + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { + console.warn('desktop locale cache: using system language because the cache could not be read', error) + } + return undefined + } +} + +/** + * Remember a confirmed language; write failure leaves the active language unchanged. + * @param userData - Electron userData directory. + * @param locale - Language confirmed by Host settings or the owned renderer. + */ +export function writeDesktopLocaleCache(userData: string, locale: DesktopLocale['id']): void { + try { + const directory = join(userData, 'desktop') + mkdirSync(directory, { recursive: true, mode: 0o700 }) + writeFileSync(join(directory, 'locale-cache'), `${locale}\n`, { mode: 0o600 }) + } catch (error) { + console.warn('desktop locale cache: language could not be saved for the next startup', error) + } +} diff --git a/apps/desktop/src/locale.ts b/apps/desktop/src/locale.ts index ca6cb30045..74a1f19941 100644 --- a/apps/desktop/src/locale.ts +++ b/apps/desktop/src/locale.ts @@ -1,4 +1,4 @@ -/** Typed English, Chinese, and Japanese copy owned by the Electron shell. */ +/** Typed shell copy for every shipped language owned by the Electron shell. */ export const en = { cliCommandMenu: 'Manage dsh Command…', @@ -61,6 +61,11 @@ export const en = { startupAddressInUse: 'Another DSH instance (such as dsh web or the desktop app) is running. They cannot start at the same time. Quit the other running DSH instance, then restart.', diagnosticTruncated: '… Error details shortened.', reportWrittenTo: 'Diagnostic report: {path}', + getDiagnosticReport: 'Get diagnostic report', + reportPending: 'The diagnostic report is still being saved. Choose Get diagnostic report to check again.', + reportUnavailable: 'The diagnostic report could not be saved. You can provide a screenshot of this dialog when requesting support.', + reportShareHint: 'The report location has been opened. Attach the selected file to your support ticket.', + reportRevealFailed: 'The report location could not be opened. Use the path below to find the file.', startupReinstallAdvice: 'If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately.', exitApplication: 'Exit', restartApplication: 'Restart', @@ -235,6 +240,11 @@ export const zh = { startupAddressInUse: '有其他正在运行的 DSH(如其他 dsh web、桌面端),无法同时启动,请退出其他正在运行的 DSH 后重启。', diagnosticTruncated: '… 错误详情已截短。', reportWrittenTo: '诊断报告:{path}', + getDiagnosticReport: '获取诊断报告', + reportPending: '诊断报告仍在保存,可点击“获取诊断报告”再次检查。', + reportUnavailable: '诊断报告未能保存,反馈问题时可提供此窗口的截图。', + reportShareHint: '已打开报告位置,请将选中的文件附在支持工单中。', + reportRevealFailed: '无法打开报告位置,请通过下方路径查找文件。', startupReinstallAdvice: '如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。', exitApplication: '退出', restartApplication: '重启', @@ -407,6 +417,11 @@ export const ja = { startupAddressInUse: '別の DSH インスタンス (dsh web やデスクトップアプリなど) が実行中です。同時に起動することはできません。実行中の他の DSH インスタンスを終了してから再起動してください。', diagnosticTruncated: '… エラー詳細は省略されています。', reportWrittenTo: '診断レポート: {path}', + getDiagnosticReport: '診断レポートを取得', + reportPending: '診断レポートを保存中です。「診断レポートを取得」を選択して再度確認してください。', + reportUnavailable: '診断レポートを保存できませんでした。サポートへのお問い合わせ時に、このダイアログのスクリーンショットを提供できます。', + reportShareHint: 'レポートの保存場所を開きました。選択されたファイルをサポートチケットに添付してください。', + reportRevealFailed: 'レポートの保存場所を開けませんでした。以下のパスからファイルを探してください。', startupReinstallAdvice: 'アプリケーションファイルが見つからないか破損している場合は、アプリケーションを閉じて再インストールしてください。タスクは別途保存されています。', exitApplication: '終了', restartApplication: '再起動', @@ -517,19 +532,907 @@ export const ja = { mandatoryNotification: 'アプリに戻り、インストールと再起動を確認してください。', } satisfies Record +/** Spanish dictionary, checked against the English keys. */ +export const es = { + cliCommandMenu: 'Administrar el comando dsh…', + cliCommandTitle: 'Administrar el comando dsh', + cliCommandLocation: 'Comando de escritorio: {path}', + cliCommandSelected: 'Comando dsh actual: {path}', + cliCommandTarget: 'Objetivo actual del lanzador: {path}', + cliCommandShadowed: 'Otro dsh tiene prioridad. Elimine o reordene esa instalación para usar el comando Escritorio de forma predeterminada. También puede ejecutar el comando Escritorio por su ruta completa.', + cliCommandSelectionUnknown: 'No se pudo verificar su comando de shell. Un alias u otra instalación de dsh puede tener prioridad.', + cliCommandInstalled: 'El comando Escritorio está instalado.', + cliCommandNotInstalled: 'Agregue el comando Escritorio a su terminal.', + cliCommandBroken: 'El comando de escritorio necesita reparación.', + cliCommandInstall: 'Instalar', + cliCommandRepair: 'Reparación', + cliCommandRemove: 'Quitar', + cliCommandClose: 'Cerrar', + cliCommandSwitch: '¿Continuar con el comando Escritorio?', + cliCommandPreserve: 'Se conservará un comando existente. Otras instalaciones y archivos de inicio del shell no se modificarán.', + cliCommandContinue: 'Continuar', + cliCommandInstallApp: 'Instale Desktop en su carpeta de Aplicaciones antes de administrar el comando dsh.', + cliCommandUpdating: 'Se está instalando una actualización. Administre el comando una vez finalizada la instalación.', + cliCommandNewTerminal: 'Abra una nueva terminal y ejecute dsh --version.', + cliCommandRemoved: 'Se eliminó el registro de comandos de escritorio.', + cliCommandPreviousRestored: 'El lanzador anterior ha sido restaurado.', + cliCommandOtherKept: 'Otras instalaciones de mando se han dejado en su lugar.', + cliCommandBackupKept: 'Se conserva un lanzador anterior en: {path}', + cliCommandChanged: 'El comando o RUTA cambió mientras este cuadro de diálogo estaba abierto. Abra Administrar comando dsh nuevamente para revisar el estado actual.', + cliCommandOwnershipError: 'El registro del comando o la copia de seguridad cambió. No se eliminó ningún comando no relacionado.', + cliCommandFailed: 'El comando no se pudo actualizar. Verifique que la aplicación esté instalada y que se pueda escribir en el destino, luego vuelva a intentarlo.', + application: 'Solicitud', + fileMenu: 'Archivo', + closePage: 'Cerrar página o ventana', + aboutMenu: 'Acerca de DeepSeek Harness', + aboutProduct: 'DeepSeek Harness', + aboutVersion: 'Versión V{version}', + hideApplication: 'Ocultar DeepSeek Harness', + hideOtherApplications: 'Ocultar otros', + showAllApplications: 'Mostrar todo', + quitApplication: 'Salir de DeepSeek Harness', + openApplication: 'Abrir DeepSeek Harness', + quit: 'Salir', + cancel: 'Cancelar', + quitTitle: '¿Salir de DeepSeek Harness?', + quitActiveTasks: 'Las tareas en ejecución se interrumpirán.', + quitScheduledTasks: 'Las tareas programadas no se ejecutarán mientras la aplicación esté cerrada.', + quitActiveAndScheduledTasks: 'Las tareas en ejecución se interrumpirán y las tareas programadas no se ejecutarán mientras la aplicación esté cerrada.', + backgroundNoticeBody: 'Las tareas en ejecución continuarán. Puede volver a abrir la ventana desde la bandeja del sistema.', + backgroundNoticeConfirm: 'Confirmar', + edit: 'Editar', + menuBar: 'Menú de aplicaciones', + delete: 'Eliminar', + undo: 'Deshacer', + redo: 'Rehacer', + cut: 'cortar', + copy: 'Copiar', + paste: 'Pegar', + selectAll: 'Seleccionar todo', + startupFailed: 'DeepSeek Harness no está disponible', + fatalSummary: 'La aplicación no pudo iniciarse o se detuvo inesperadamente.', + startupAddressInUse: 'Se está ejecutando otra instancia de DSH (como la web de dsh o la aplicación de escritorio). No pueden empezar al mismo tiempo. Salga de la otra instancia DSH en ejecución y luego reinicie.', + diagnosticTruncated: '… Detalles del error acortados.', + reportWrittenTo: 'Informe de diagnóstico: {path}', + getDiagnosticReport: 'Obtener informe de diagnóstico', + reportPending: 'El informe de diagnóstico se está guardando. Seleccione Obtener informe de diagnóstico para volver a comprobarlo.', + reportUnavailable: 'No se pudo guardar el informe de diagnóstico. Puede proporcionar una captura de pantalla de este diálogo al solicitar asistencia.', + reportShareHint: 'Se ha abierto la ubicación del informe. Adjunte el archivo seleccionado a su solicitud de asistencia.', + reportRevealFailed: 'No se pudo abrir la ubicación del informe. Use la ruta que aparece a continuación para encontrar el archivo.', + startupReinstallAdvice: 'Si faltan archivos de la aplicación o están dañados, ciérrela y vuelva a instalarla. Sus tareas se almacenan por separado.', + exitApplication: 'Salir', + restartApplication: 'Reiniciar', + recoveryOperationFailed: 'La operación de recuperación falló', + disableThirdPartyPlugins: 'Deshabilite los complementos de terceros, haga una copia de seguridad del parche del perfil y reinicie', + welcomeTitle: 'DeepSeek Harness', + welcomeBrand: 'DeepSeek Harness', + welcomeTaglineBefore: 'Bienvenido a ', + welcomeTaglineBrand: 'DeepSeek Harness', + welcomeTaglineAfter: '', + welcomeDescription: 'Desarrollar potencial. Explora la inteligencia.', + welcomeAuthStarting: 'Abriendo inicio de sesión…', + welcomeAuthWaiting: '¿El navegador no se abrió automáticamente?', + welcomeAuthWaitingDescription: 'Copie el enlace de inicio de sesión y ábralo en su navegador para iniciar sesión.', + welcomeAuthExchanging: 'Completando el inicio de sesión…', + welcomeAuthExpired: 'Se agotó el tiempo de inicio de sesión', + welcomeAuthExpiredDescription: 'Inicia sesión nuevamente para continuar', + welcomeAuthFailed: 'No se pudo completar el inicio de sesión. Inténtelo de nuevo.', + welcomeAuthCopyLink: 'Copiar enlace de inicio de sesión', + welcomeAuthCopied: 'Copiado', + welcomeAuthCopyFailed: 'No se pudo copiar. Intentar otra vez.', + welcomeAuthCancel: 'Cancelar', + welcomeAuthRetry: 'Iniciar sesión nuevamente', + welcomeSignIn: 'Iniciar sesión', + welcomeApiKey: 'Agregar clave API', + welcomeKeyTitle: 'Agregue una clave API para comenzar', + welcomeKeyDescription: 'Configura los modelos oficiales DeepSeek para empezar a utilizar Harness', + welcomeKeyPlaceholder: 'Ingrese la clave API', + welcomeKeySave: 'Guardar y continuar', + welcomeKeyLater: 'Configurar más tarde', + welcomeKeyBack: 'Volver para iniciar sesión', + welcomeSessionExpired: 'Has cerrado sesión en tu cuenta, inicia sesión nuevamente.', + welcomeKeyBlank: 'Ingrese una clave API.', + welcomeKeyInvalid: 'Ingrese la clave API, sin comillas, espacios ni una asignación de variable de entorno.', + welcomeKeyFailed: 'No se pudo guardar la clave API. Por favor inténtalo de nuevo.', + welcomeContinueFailed: 'No se pudo abrir el espacio de trabajo. Por favor inténtalo de nuevo.', + checkUpdatesMenu: 'Buscar actualizaciones...', + reloadPageMenu: 'Recargar página', + restartAppHostMenu: 'Reiniciar la aplicación y el host', + updateCheckFailedTitle: 'Error en la comprobación de actualización', + updateCheckFailed: 'No se pudo buscar actualizaciones. Inténtelo de nuevo más tarde.', + updateDownloadFailed: 'No se pudo descargar la actualización. Por favor inténtalo de nuevo.', + updateInstallFailed: 'No se pudo instalar la actualización. Inténtelo de nuevo más tarde.', + updateCheckNetworkFailed: 'No se pudo buscar actualizaciones. Comprueba tu conexión y vuelve a intentarlo.', + updateDownloadNetworkFailed: 'No se pudo descargar la actualización. Comprueba tu conexión y vuelve a intentarlo.', + updateInstallNetworkFailed: 'No se pudo instalar la actualización. Comprueba tu conexión y vuelve a intentarlo.', + unknownError: 'Error desconocido', + updateCheckTitle: 'Buscar actualizaciones', + updateCurrentDetail: 'Versión actual: {version}', + updateCurrent: '¡Estás al día!', + updateChecking: 'Buscando actualizaciones...', + updateDownload: 'Descargar actualización', + updateDownloadedTitle: 'La versión {version} está lista para instalar.', + updateDownloadedDetail: 'La aplicación se cerrará durante la actualización y se volverá a abrir automáticamente cuando se complete.', + updateDownloadedDetailWindows: 'La aplicación se cerrará temporalmente durante la actualización y se volverá a abrir automáticamente cuando se complete.\n\nLa actualización puede tardar algún tiempo. Espere y no vuelva a iniciar la aplicación durante la instalación.', + updateClose: 'Cerrar', + updateAcknowledge: 'OK', + updateLater: 'Actualizar más tarde', + updateDownloading: 'Descargando {percent}%…', + updateVerifying: 'Verificando archivos de actualización...', + updateInstalling: 'Preparándose para reiniciar…', + updateRetry: 'Reintentar actualización', + updateActiveTasks: 'Las tareas aún están en progreso', + updateActiveTasksDetail: 'La actualización detendrá las tareas en curso y reiniciará la aplicación. ¿Continuar?', + updateStopTasks: 'Detener tareas y actualizar', + updateTasksChanged: 'Han comenzado nuevas tareas. Confirme nuevamente para detener las tareas y actualizar.', + updateTasksUnavailable: 'El estado de la tarea no está disponible. Intente actualizar nuevamente cuando el espacio de trabajo esté listo.', + updateFullscreenTimeout: 'No se pudo salir de la pantalla completa. Salga de la pantalla completa y luego vuelva a intentar la actualización.', + updateStopFailed: 'No se pudieron detener las tareas de forma segura. La actualización no se ha instalado. Inténtelo de nuevo más tarde.', + updateTechnicalDetails: 'Ver detalles técnicos', + updateTitle: 'Actualización DeepSeek Harness', + updateAvailable: 'Nueva versión disponible: {version}', + updateDetail: 'Una vez que se completa la descarga, puede instalar la actualización y reiniciar la aplicación.', + installAndRestart: 'Instalar y reiniciar', + later: 'Más tarde', + updateFailedTitle: 'Actualización fallida', + mandatoryTitle: 'Actualizar para continuar', + mandatoryDetail: 'Esta versión ya no es compatible. Actualiza para continuar. Las tareas en curso seguirán ejecutándose hasta que confirme la instalación y reinicie.', + mandatoryUnavailable: 'No se pudieron verificar los requisitos de actualización. Inténtelo de nuevo más tarde.', + policyLoginTitle: 'Inicie sesión en el entorno de prueba', + policyLoginRequired: 'Inicie sesión con Feishu para verificar los requisitos de actualización para esta versión de prueba. Iniciar sesión no descargará ni instalará una actualización.', + policyLogin: 'Iniciar sesión con Feishu', + policyLoginFailed: 'El inicio de sesión de Feishu no se completó. Por favor inténtalo de nuevo.', + policyLoginLoading: 'Cargando página de inicio de sesión...', + mandatoryNoRelease: 'No se encontró ninguna actualización compatible. Verifique nuevamente o comuníquese con el soporte.', + mandatoryRefresh: 'Comprobar de nuevo', + mandatoryPage: 'Descargar desde el sitio web oficial.', + mandatoryCopy: 'Copiar enlace de descarga', + mandatoryPageFailed: 'No se pudo abrir la página de descarga oficial. Copie el enlace y ábralo en su navegador.', + mandatoryViewDownload: 'Abrir página de descarga', + mandatoryViewPageFailed: 'No se pudo abrir la página de descarga. Por favor inténtalo de nuevo.', + mandatoryActionFailed: 'La acción fracasó. Por favor inténtalo de nuevo. Puede utilizar la aplicación nuevamente una vez completada la actualización.', + mandatoryReady: 'Actualización lista', + mandatoryVersion: 'Nueva versión: {version}', + mandatoryReadyDetail: 'La aplicación se cerrará durante la actualización y se volverá a abrir automáticamente cuando se complete.', + mandatoryDeferred: 'Las tareas en curso seguirán ejecutándose. Complete la actualización antes de volver a utilizar la aplicación.', + mandatoryContinue: 'Continuar actualizando', + mandatoryInspecting: 'Comprobando tareas...', + mandatoryStopping: 'Deteniendo tareas…', + mandatoryRestarting: 'La aplicación se reiniciará en breve. Espere por favor.', + mandatoryDownloadFailed: 'Los archivos de actualización no se pudieron descargar ni preparar. Vuelva a intentarlo.', + mandatoryInstallFailed: 'La actualización no se ha instalado. Verifique las tareas nuevamente y vuelva a intentarlo.', + mandatoryOpenHelp: '¿La página no se abrió?', + mandatoryReopen: 'Abre la página de descarga oficial nuevamente.', + mandatoryCopied: 'Enlace copiado', + mandatoryCopyFailed: 'No se pudo copiar el enlace. Selecciónelo y cópielo a continuación.', + mandatoryAddress: 'Enlace de descarga', + mandatoryNotification: 'Regrese a la aplicación para confirmar la instalación y reiniciar.', +} satisfies DesktopMessages + +/** French dictionary, checked against the English keys. */ +export const fr = { + cliCommandMenu: 'Gérer la commande dsh…', + cliCommandTitle: 'Gérer la commande dsh', + cliCommandLocation: 'Commande de bureau : {path}', + cliCommandSelected: 'Commande dsh actuelle : {path}', + cliCommandTarget: 'Cible actuelle du lanceur : {path}', + cliCommandShadowed: 'Un autre dsh est prioritaire. Supprimez ou réorganisez cette installation pour utiliser la commande Bureau par défaut. Vous pouvez également exécuter la commande Desktop par son chemin complet.', + cliCommandSelectionUnknown: "Votre commande shell n'a pas pu être vérifiée. Un alias ou une autre installation dsh peut être prioritaire.", + cliCommandInstalled: 'La commande Bureau est installée.', + cliCommandNotInstalled: 'Ajoutez la commande Bureau à votre terminal.', + cliCommandBroken: 'La commande Bureau doit être réparée.', + cliCommandInstall: 'Installer', + cliCommandRepair: 'Réparer', + cliCommandRemove: 'Supprimer', + cliCommandClose: 'Fermer', + cliCommandSwitch: 'Continuer avec la commande Bureau ?', + cliCommandPreserve: 'Une commande existante sera conservée. Les autres installations et fichiers de démarrage du shell ne seront pas modifiés.', + cliCommandContinue: 'Continuer', + cliCommandInstallApp: 'Installez Desktop dans votre dossier Applications avant de gérer la commande dsh.', + cliCommandUpdating: "Une mise à jour est en cours d'installation. Gérez la commande une fois l'installation terminée.", + cliCommandNewTerminal: 'Ouvrez un nouveau terminal et exécutez dsh --version.', + cliCommandRemoved: 'Enregistrement des commandes de bureau supprimé.', + cliCommandPreviousRestored: 'Le lanceur précédent a été restauré.', + cliCommandOtherKept: "D'autres installations de commandement ont été laissées en place.", + cliCommandBackupKept: 'Un lanceur précédent est conservé à : {path}', + cliCommandChanged: "La commande ou PATH a changé pendant que cette boîte de dialogue était ouverte. Ouvrez à nouveau la commande Gérer dsh pour vérifier l'état actuel.", + cliCommandOwnershipError: "L'enregistrement ou la sauvegarde de la commande a été modifiée. Aucune commande sans rapport n'a été supprimée.", + cliCommandFailed: "La commande n'a pas pu être mise à jour. Vérifiez que l'application est installée et que la destination est accessible en écriture, puis réessayez.", + application: 'Application', + fileMenu: 'Fichier', + closePage: 'Fermer la page ou la fenêtre', + aboutMenu: 'À propos de DeepSeek Harness', + aboutProduct: 'DeepSeek Harness', + aboutVersion: 'VersionV{version}', + hideApplication: 'Masquer DeepSeek Harness', + hideOtherApplications: 'Masquer les autres', + showAllApplications: 'Afficher tout', + quitApplication: 'Quitter DeepSeek Harness', + openApplication: 'Ouvrir DeepSeek Harness', + quit: 'Quitter', + cancel: 'Annuler', + quitTitle: 'Quitter DeepSeek Harness ?', + quitActiveTasks: 'Les tâches en cours seront interrompues.', + quitScheduledTasks: "Les tâches planifiées ne s'exécuteront pas lorsque l'application est fermée.", + quitActiveAndScheduledTasks: "Les tâches en cours d'exécution seront interrompues et les tâches planifiées ne s'exécuteront pas tant que l'application sera fermée.", + backgroundNoticeBody: "Les tâches en cours continueront. Vous pouvez rouvrir la fenêtre à partir de la barre d'état système.", + backgroundNoticeConfirm: 'Confirmer', + edit: 'Modifier', + menuBar: 'Menu des applications', + delete: 'Supprimer', + undo: 'Annuler', + redo: 'Refaire', + cut: 'Couper', + copy: 'Copier', + paste: 'Coller', + selectAll: 'Sélectionner tout', + startupFailed: "DeepSeek Harness n'est pas disponible", + fatalSummary: "L'application n'a pas pu démarrer ou s'est arrêtée de manière inattendue.", + startupAddressInUse: "Une autre instance DSH (telle que le Web dsh ou l'application de bureau) est en cours d'exécution. Ils ne peuvent pas démarrer en même temps. Quittez l'autre instance DSH en cours d'exécution, puis redémarrez.", + diagnosticTruncated: '… Détails de l’erreur raccourcis.', + reportWrittenTo: 'Rapport de diagnostic : {path}', + getDiagnosticReport: 'Obtenir le rapport de diagnostic', + reportPending: 'Le rapport de diagnostic est en cours d’enregistrement. Sélectionnez Obtenir le rapport de diagnostic pour vérifier à nouveau.', + reportUnavailable: 'Le rapport de diagnostic n’a pas pu être enregistré. Vous pouvez fournir une capture d’écran de cette boîte de dialogue lorsque vous contactez l’assistance.', + reportShareHint: 'L’emplacement du rapport a été ouvert. Joignez le fichier sélectionné à votre demande d’assistance.', + reportRevealFailed: 'L’emplacement du rapport n’a pas pu être ouvert. Utilisez le chemin ci-dessous pour trouver le fichier.', + startupReinstallAdvice: "Si les fichiers de l'application sont manquants ou endommagés, fermez l'application et réinstallez-la. Vos tâches sont stockées séparément.", + exitApplication: 'Quitter', + restartApplication: 'Redémarrer', + recoveryOperationFailed: "L'opération de récupération a échoué", + disableThirdPartyPlugins: 'Désactivez les plugins tiers, sauvegardez le correctif de profil et redémarrez', + welcomeTitle: 'DeepSeek Harness', + welcomeBrand: 'DeepSeek Harness', + welcomeTaglineBefore: 'Bienvenue à ', + welcomeTaglineBrand: 'DeepSeek Harness', + welcomeTaglineAfter: '', + welcomeDescription: "Développer le potentiel. Explorez l'intelligence.", + welcomeAuthStarting: 'Ouverture de la connexion…', + welcomeAuthWaiting: "Le navigateur ne s'est pas ouvert automatiquement ?", + welcomeAuthWaitingDescription: 'Copiez le lien de connexion et ouvrez-le dans votre navigateur pour vous connecter.', + welcomeAuthExchanging: 'Connexion terminée…', + welcomeAuthExpired: 'La connexion a expiré', + welcomeAuthExpiredDescription: 'Connectez-vous à nouveau pour continuer', + welcomeAuthFailed: 'Impossible de terminer la connexion. Veuillez réessayer.', + welcomeAuthCopyLink: 'Copier le lien de connexion', + welcomeAuthCopied: 'Copié', + welcomeAuthCopyFailed: 'Impossible de copier. Essayer à nouveau.', + welcomeAuthCancel: 'Annuler', + welcomeAuthRetry: 'Connectez-vous à nouveau', + welcomeSignIn: 'Connectez-vous', + welcomeApiKey: 'Ajouter une clé API', + welcomeKeyTitle: 'Ajoutez une clé API pour commencer', + welcomeKeyDescription: 'Configurez les modèles DeepSeek officiels pour commencer à utiliser Harness', + welcomeKeyPlaceholder: 'Entrez la clé API', + welcomeKeySave: 'Enregistrer et continuer', + welcomeKeyLater: 'Configurer plus tard', + welcomeKeyBack: 'Retour pour vous connecter', + welcomeSessionExpired: 'Vous vous êtes déconnecté de votre compte, veuillez vous reconnecter.', + welcomeKeyBlank: 'Entrez une clé API.', + welcomeKeyInvalid: "Entrez la clé API elle-même, sans guillemets, espaces ni affectation de variable d'environnement.", + welcomeKeyFailed: "Impossible d'enregistrer la clé API. Veuillez réessayer.", + welcomeContinueFailed: "Impossible d'ouvrir l'espace de travail. Veuillez réessayer.", + checkUpdatesMenu: 'Vérifiez les mises à jour…', + reloadPageMenu: 'Recharger la page', + restartAppHostMenu: "Redémarrez l'application et l'hôte", + updateCheckFailedTitle: 'Échec de la vérification de la mise à jour', + updateCheckFailed: 'Impossible de vérifier les mises à jour. Veuillez réessayer plus tard.', + updateDownloadFailed: 'Impossible de télécharger la mise à jour. Veuillez réessayer.', + updateInstallFailed: "Impossible d'installer la mise à jour. Veuillez réessayer plus tard.", + updateCheckNetworkFailed: 'Impossible de vérifier les mises à jour. Vérifiez votre connexion et réessayez.', + updateDownloadNetworkFailed: 'Impossible de télécharger la mise à jour. Vérifiez votre connexion et réessayez.', + updateInstallNetworkFailed: "Impossible d'installer la mise à jour. Vérifiez votre connexion et réessayez.", + unknownError: 'Erreur inconnue', + updateCheckTitle: 'Vérifier les mises à jour', + updateCurrentDetail: 'Version actuelle : {version}', + updateCurrent: 'Vous êtes à jour !', + updateChecking: 'Vérification des mises à jour…', + updateDownload: 'Télécharger la mise à jour', + updateDownloadedTitle: 'La version {version} est prête à installer', + updateDownloadedDetail: "L'application se fermera pendant la mise à jour et rouvrira automatiquement une fois celle-ci terminée.", + updateDownloadedDetailWindows: "L'application se fermera temporairement pendant la mise à jour et rouvrira automatiquement une fois celle-ci terminée.\n\nLa mise à jour peut prendre un certain temps. Veuillez patienter et ne pas relancer l'application pendant l'installation.", + updateClose: 'Fermer', + updateAcknowledge: 'OK', + updateLater: 'Mettre à jour plus tard', + updateDownloading: 'Téléchargement de {percent}%…', + updateVerifying: 'Vérification des fichiers de mise à jour…', + updateInstalling: 'Préparation du redémarrage…', + updateRetry: 'Réessayez la mise à jour', + updateActiveTasks: 'Les tâches sont toujours en cours', + updateActiveTasksDetail: "La mise à jour arrêtera les tâches en cours et redémarrera l'application. Continuer?", + updateStopTasks: 'Arrêter les tâches et mettre à jour', + updateTasksChanged: 'De nouvelles tâches ont commencé. Confirmez à nouveau pour arrêter les tâches et mettre à jour.', + updateTasksUnavailable: "L'état de la tâche n'est pas disponible. Essayez à nouveau de mettre à jour lorsque l'espace de travail est prêt.", + updateFullscreenTimeout: 'Impossible de quitter le mode plein écran. Quittez le mode plein écran, puis réessayez la mise à jour.', + updateStopFailed: "Impossible d'arrêter les tâches en toute sécurité. La mise à jour n'a pas été installée. Veuillez réessayer plus tard.", + updateTechnicalDetails: 'Voir les détails techniques', + updateTitle: 'Mise à jour DeepSeek Harness', + updateAvailable: 'Nouvelle version disponible : {version}', + updateDetail: "Une fois le téléchargement terminé, vous pouvez installer la mise à jour et redémarrer l'application.", + installAndRestart: 'Installer et redémarrer', + later: 'Plus tard', + updateFailedTitle: 'Échec de la mise à jour', + mandatoryTitle: 'Mettre à jour pour continuer', + mandatoryDetail: "Cette version n'est plus prise en charge. Mettez à jour pour continuer. Les tâches en cours continueront à s'exécuter jusqu'à ce que vous confirmiez l'installation et redémarriez.", + mandatoryUnavailable: 'Impossible de vérifier les exigences de mise à jour. Veuillez réessayer plus tard.', + policyLoginTitle: "Connectez-vous à l'environnement de test", + policyLoginRequired: 'Connectez-vous avec Feishu pour vérifier les exigences de mise à jour pour cette version de test. La connexion ne téléchargera ni n’installera de mise à jour.', + policyLogin: 'Connectez-vous avec Feishu', + policyLoginFailed: 'La connexion à Feishu n’a pas abouti. Veuillez réessayer.', + policyLoginLoading: 'Chargement de la page de connexion…', + mandatoryNoRelease: "Aucune mise à jour compatible n'a été trouvée. Vérifiez à nouveau ou contactez l'assistance.", + mandatoryRefresh: 'Vérifiez à nouveau', + mandatoryPage: 'Télécharger depuis le site officiel', + mandatoryCopy: 'Copier le lien de téléchargement', + mandatoryPageFailed: "Impossible d'ouvrir la page de téléchargement officielle. Copiez le lien et ouvrez-le dans votre navigateur.", + mandatoryViewDownload: 'Ouvrir la page de téléchargement', + mandatoryViewPageFailed: "Impossible d'ouvrir la page de téléchargement. Veuillez réessayer.", + mandatoryActionFailed: "L'action a échoué. Veuillez réessayer. Vous pourrez réutiliser l'application une fois la mise à jour terminée.", + mandatoryReady: 'Mise à jour prête', + mandatoryVersion: 'Nouvelle version : {version}', + mandatoryReadyDetail: "L'application se fermera pendant la mise à jour et rouvrira automatiquement une fois celle-ci terminée.", + mandatoryDeferred: "Les tâches en cours continueront à s'exécuter. Terminez la mise à jour avant d'utiliser à nouveau l'application.", + mandatoryContinue: 'Continuer la mise à jour', + mandatoryInspecting: 'Vérification des tâches…', + mandatoryStopping: 'Arrêt des tâches…', + mandatoryRestarting: "L'application redémarrera sous peu. S'il vous plaît, attendez.", + mandatoryDownloadFailed: "Les fichiers de mise à jour n'ont pas pu être téléchargés ou préparés. Veuillez réessayer.", + mandatoryInstallFailed: "La mise à jour n'a pas été installée. Vérifiez à nouveau les tâches et réessayez.", + mandatoryOpenHelp: "La page ne s'est pas ouverte ?", + mandatoryReopen: 'Ouvrez à nouveau la page de téléchargement officielle', + mandatoryCopied: 'Lien copié', + mandatoryCopyFailed: 'Impossible de copier le lien. Sélectionnez-le et copiez-le ci-dessous.', + mandatoryAddress: 'Lien de téléchargement', + mandatoryNotification: "Revenez à l'application pour confirmer l'installation et redémarrer.", +} satisfies DesktopMessages + +/** German dictionary, checked against the English keys. */ +export const de = { + cliCommandMenu: 'dsh-Befehl verwalten…', + cliCommandTitle: 'dsh-Befehl verwalten', + cliCommandLocation: 'Desktop-Befehl: {path}', + cliCommandSelected: 'Aktueller dsh-Befehl: {path}', + cliCommandTarget: 'Aktuelles Launcher-Ziel: {path}', + cliCommandShadowed: 'Ein anderer dsh hat Vorrang. Entfernen Sie diese Installation oder ordnen Sie sie neu an, um standardmäßig den Desktop-Befehl zu verwenden. Sie können den Desktop-Befehl auch über seinen vollständigen Pfad ausführen.', + cliCommandSelectionUnknown: 'Ihr Shell-Befehl konnte nicht überprüft werden. Ein Alias oder eine andere dsh-Installation kann Vorrang haben.', + cliCommandInstalled: 'Der Desktop-Befehl ist installiert.', + cliCommandNotInstalled: 'Fügen Sie den Desktop-Befehl zu Ihrem Terminal hinzu.', + cliCommandBroken: 'Der Desktop-Befehl muss repariert werden.', + cliCommandInstall: 'Installieren', + cliCommandRepair: 'Reparieren', + cliCommandRemove: 'Entfernen', + cliCommandClose: 'Schließen', + cliCommandSwitch: 'Mit dem Desktop-Befehl fortfahren?', + cliCommandPreserve: 'Ein vorhandener Befehl bleibt erhalten. Andere Installationen und Shell-Startdateien werden nicht geändert.', + cliCommandContinue: 'Weiter', + cliCommandInstallApp: 'Installieren Sie Desktop in Ihrem Anwendungsordner, bevor Sie den Befehl dsh verwalten.', + cliCommandUpdating: 'Ein Update wird installiert. Verwalten Sie den Befehl nach Abschluss der Installation.', + cliCommandNewTerminal: 'Öffnen Sie ein neues Terminal und führen Sie dsh --version aus.', + cliCommandRemoved: 'Desktop-Befehlsregistrierung entfernt.', + cliCommandPreviousRestored: 'Der vorherige Launcher wurde wiederhergestellt.', + cliCommandOtherKept: 'Andere Befehlsinstallationen wurden beibehalten.', + cliCommandBackupKept: 'Ein früherer Launcher ist unter folgender Adresse erhalten: {path}', + cliCommandChanged: 'Der Befehl oder PATH hat sich geändert, während dieses Dialogfeld geöffnet war. Öffnen Sie den Befehl „dsh verwalten“ erneut, um den aktuellen Status zu überprüfen.', + cliCommandOwnershipError: 'Die Befehlsregistrierung oder Sicherung wurde geändert. Es wurde kein nicht verwandter Befehl entfernt.', + cliCommandFailed: 'Der Befehl konnte nicht aktualisiert werden. Überprüfen Sie, ob die Anwendung installiert ist und das Ziel beschreibbar ist, und versuchen Sie es dann erneut.', + application: 'Anwendung', + fileMenu: 'Datei', + closePage: 'Seite oder Fenster schließen', + aboutMenu: 'Über DeepSeek Harness', + aboutProduct: 'DeepSeek Harness', + aboutVersion: 'Version V{version}', + hideApplication: 'DeepSeek Harness ausblenden', + hideOtherApplications: 'Andere ausblenden', + showAllApplications: 'Alle einblenden', + quitApplication: 'DeepSeek Harness beenden', + openApplication: 'DeepSeek Harness öffnen', + quit: 'Beenden', + cancel: 'Abbrechen', + quitTitle: 'DeepSeek Harness beenden?', + quitActiveTasks: 'Laufende Aufgaben werden unterbrochen.', + quitScheduledTasks: 'Geplante Aufgaben werden nicht ausgeführt, während die App geschlossen ist.', + quitActiveAndScheduledTasks: 'Laufende Aufgaben werden unterbrochen und geplante Aufgaben werden nicht ausgeführt, während die App geschlossen ist.', + backgroundNoticeBody: 'Laufende Aufgaben werden fortgesetzt. Sie können das Fenster über die Taskleiste erneut öffnen.', + backgroundNoticeConfirm: 'Bestätigen', + edit: 'Bearbeiten', + menuBar: 'Anwendungsmenü', + delete: 'Löschen', + undo: 'Rückgängig machen', + redo: 'Wiederholen', + cut: 'Ausschneiden', + copy: 'Kopieren', + paste: 'Einfügen', + selectAll: 'Alles auswählen', + startupFailed: 'DeepSeek Harness ist nicht verfügbar', + fatalSummary: 'Die Anwendung konnte nicht gestartet werden oder wurde unerwartet gestoppt.', + startupAddressInUse: 'Eine andere DSH-Instanz (z. B. dsh Web oder die Desktop-App) wird ausgeführt. Sie können nicht gleichzeitig starten. Beenden Sie die andere laufende DSH-Instanz und starten Sie sie neu.', + diagnosticTruncated: '… Fehlerdetails gekürzt.', + reportWrittenTo: 'Diagnosebericht: {path}', + getDiagnosticReport: 'Diagnosebericht abrufen', + reportPending: 'Der Diagnosebericht wird noch gespeichert. Wählen Sie „Diagnosebericht abrufen“, um ihn erneut zu prüfen.', + reportUnavailable: 'Der Diagnosebericht konnte nicht gespeichert werden. Sie können bei einer Supportanfrage einen Screenshot dieses Dialogs bereitstellen.', + reportShareHint: 'Der Speicherort des Berichts wurde geöffnet. Fügen Sie die ausgewählte Datei Ihrer Supportanfrage bei.', + reportRevealFailed: 'Der Speicherort des Berichts konnte nicht geöffnet werden. Verwenden Sie den folgenden Pfad, um die Datei zu finden.', + startupReinstallAdvice: 'Wenn Anwendungsdateien fehlen oder beschädigt sind, schließen Sie die Anwendung und installieren Sie sie erneut. Ihre Aufgaben werden separat gespeichert.', + exitApplication: 'Beenden', + restartApplication: 'Neustart', + recoveryOperationFailed: 'Der Wiederherstellungsvorgang ist fehlgeschlagen', + disableThirdPartyPlugins: 'Deaktivieren Sie Plugins von Drittanbietern, sichern Sie den Profil-Patch und starten Sie neu', + welcomeTitle: 'DeepSeek Harness', + welcomeBrand: 'DeepSeek Harness', + welcomeTaglineBefore: 'Willkommen bei ', + welcomeTaglineBrand: 'DeepSeek Harness', + welcomeTaglineAfter: '', + welcomeDescription: 'Potenzial aufbauen. Entdecken Sie Intelligenz.', + welcomeAuthStarting: 'Anmeldung wird geöffnet…', + welcomeAuthWaiting: 'Browser wurde nicht automatisch geöffnet?', + welcomeAuthWaitingDescription: 'Kopieren Sie den Anmeldelink und öffnen Sie ihn in Ihrem Browser, um sich anzumelden.', + welcomeAuthExchanging: 'Anmeldung wird abgeschlossen…', + welcomeAuthExpired: 'Zeitüberschreitung bei der Anmeldung', + welcomeAuthExpiredDescription: 'Melden Sie sich erneut an, um fortzufahren', + welcomeAuthFailed: 'Die Anmeldung konnte nicht abgeschlossen werden. Bitte versuchen Sie es erneut.', + welcomeAuthCopyLink: 'Anmeldelink kopieren', + welcomeAuthCopied: 'Kopiert', + welcomeAuthCopyFailed: 'Konnte nicht kopiert werden. Versuchen Sie es erneut.', + welcomeAuthCancel: 'Abbrechen', + welcomeAuthRetry: 'Erneut anmelden', + welcomeSignIn: 'Anmelden', + welcomeApiKey: 'API-Schlüssel hinzufügen', + welcomeKeyTitle: 'Fügen Sie einen API-Schlüssel hinzu, um loszulegen', + welcomeKeyDescription: 'Konfigurieren Sie offizielle DeepSeek-Modelle für die Verwendung von Harness', + welcomeKeyPlaceholder: 'API-Schlüssel eingeben', + welcomeKeySave: 'Speichern und fortfahren', + welcomeKeyLater: 'Später einrichten', + welcomeKeyBack: 'Zurück zur Anmeldung', + welcomeSessionExpired: 'Sie haben sich von Ihrem Konto abgemeldet. Bitte melden Sie sich erneut an.', + welcomeKeyBlank: 'Geben Sie einen API-Schlüssel ein.', + welcomeKeyInvalid: 'Geben Sie den API-Schlüssel selbst ein, ohne Anführungszeichen, Leerzeichen oder eine Umgebungsvariablenzuweisung.', + welcomeKeyFailed: 'Der API-Schlüssel konnte nicht gespeichert werden. Bitte versuchen Sie es erneut.', + welcomeContinueFailed: 'Der Arbeitsbereich konnte nicht geöffnet werden. Bitte versuchen Sie es erneut.', + checkUpdatesMenu: 'Nach Updates suchen…', + reloadPageMenu: 'Seite neu laden', + restartAppHostMenu: 'Anwendung und Host neu starten', + updateCheckFailedTitle: 'Update-Überprüfung fehlgeschlagen', + updateCheckFailed: 'Es konnte nicht nach Updates gesucht werden. Bitte versuchen Sie es später noch einmal.', + updateDownloadFailed: 'Das Update konnte nicht heruntergeladen werden. Bitte versuchen Sie es erneut.', + updateInstallFailed: 'Das Update konnte nicht installiert werden. Bitte versuchen Sie es später noch einmal.', + updateCheckNetworkFailed: 'Es konnte nicht nach Updates gesucht werden. Überprüfen Sie Ihre Verbindung und versuchen Sie es erneut.', + updateDownloadNetworkFailed: 'Das Update konnte nicht heruntergeladen werden. Überprüfen Sie Ihre Verbindung und versuchen Sie es erneut.', + updateInstallNetworkFailed: 'Das Update konnte nicht installiert werden. Überprüfen Sie Ihre Verbindung und versuchen Sie es erneut.', + unknownError: 'Unbekannter Fehler', + updateCheckTitle: 'Nach Updates suchen', + updateCurrentDetail: 'Aktuelle Version: {version}', + updateCurrent: 'Sie verwenden die neueste Version.', + updateChecking: 'Suche nach Updates…', + updateDownload: 'Update herunterladen', + updateDownloadedTitle: 'Die Version {version} ist zur Installation bereit', + updateDownloadedDetail: 'Die App wird während des Updates geschlossen und nach Abschluss automatisch wieder geöffnet.', + updateDownloadedDetailWindows: 'Die App wird während des Updates vorübergehend geschlossen und nach Abschluss automatisch wieder geöffnet.\n\nDas Update kann einige Zeit dauern. Bitte warten Sie und starten Sie die App während der Installation nicht erneut.', + updateClose: 'Schließen', + updateAcknowledge: 'OK', + updateLater: 'Später aktualisieren', + updateDownloading: '{percent}% wird heruntergeladen…', + updateVerifying: 'Aktualisierungsdateien werden überprüft…', + updateInstalling: 'Neustart wird vorbereitet…', + updateRetry: 'Update erneut versuchen', + updateActiveTasks: 'Aufgaben sind noch in Bearbeitung', + updateActiveTasksDetail: 'Durch die Aktualisierung werden die laufenden Aufgaben gestoppt und die App neu gestartet. Weitermachen?', + updateStopTasks: 'Aufgaben beenden und Update installieren', + updateTasksChanged: 'Neue Aufgaben haben begonnen. Bestätigen Sie erneut, um die Aufgaben zu stoppen und zu aktualisieren.', + updateTasksUnavailable: 'Der Aufgabenstatus ist nicht verfügbar. Versuchen Sie erneut, die Aktualisierung durchzuführen, wenn der Arbeitsbereich bereit ist.', + updateFullscreenTimeout: 'Der Vollbildmodus konnte nicht beendet werden. Beenden Sie den Vollbildmodus und versuchen Sie dann erneut, das Update durchzuführen.', + updateStopFailed: 'Die Aufgaben konnten nicht sicher gestoppt werden. Das Update wurde nicht installiert. Bitte versuchen Sie es später noch einmal.', + updateTechnicalDetails: 'Technische Details anzeigen', + updateTitle: 'DeepSeek Harness-Update', + updateAvailable: 'Neue Version verfügbar: {version}', + updateDetail: 'Sobald der Download abgeschlossen ist, können Sie das Update installieren und die App neu starten.', + installAndRestart: 'Installieren und neu starten', + later: 'Später', + updateFailedTitle: 'Aktualisierung fehlgeschlagen', + mandatoryTitle: 'Aktualisieren, um fortzufahren', + mandatoryDetail: 'Diese Version wird nicht mehr unterstützt. Aktualisieren, um fortzufahren. Laufende Aufgaben werden so lange ausgeführt, bis Sie die Installation bestätigen und neu starten.', + mandatoryUnavailable: 'Update-Anforderungen konnten nicht überprüft werden. Bitte versuchen Sie es später noch einmal.', + policyLoginTitle: 'Melden Sie sich bei der Testumgebung an', + policyLoginRequired: 'Melden Sie sich bei Feishu an, um die Update-Anforderungen für diesen Test-Build zu prüfen. Durch die Anmeldung wird kein Update heruntergeladen oder installiert.', + policyLogin: 'Melden Sie sich mit Feishu an', + policyLoginFailed: 'Die Feishu-Anmeldung wurde nicht abgeschlossen. Bitte versuchen Sie es erneut.', + policyLoginLoading: 'Anmeldeseite wird geladen…', + mandatoryNoRelease: 'Es wurde kein kompatibles Update gefunden. Überprüfen Sie es erneut oder wenden Sie sich an den Support.', + mandatoryRefresh: 'Erneut prüfen', + mandatoryPage: 'Von der offiziellen Website herunterladen', + mandatoryCopy: 'Download-Link kopieren', + mandatoryPageFailed: 'Die offizielle Download-Seite konnte nicht geöffnet werden. Kopieren Sie den Link und öffnen Sie ihn in Ihrem Browser.', + mandatoryViewDownload: 'Download-Seite öffnen', + mandatoryViewPageFailed: 'Die Download-Seite konnte nicht geöffnet werden. Bitte versuchen Sie es erneut.', + mandatoryActionFailed: 'Die Aktion ist fehlgeschlagen. Bitte versuchen Sie es erneut. Nach Abschluss des Updates können Sie die App wieder verwenden.', + mandatoryReady: 'Update bereit', + mandatoryVersion: 'Neue Version: {version}', + mandatoryReadyDetail: 'Die App wird während des Updates geschlossen und nach Abschluss automatisch wieder geöffnet.', + mandatoryDeferred: 'Laufende Aufgaben werden weiterhin ausgeführt. Schließen Sie das Update ab, bevor Sie die App erneut verwenden.', + mandatoryContinue: 'Update fortsetzen', + mandatoryInspecting: 'Aufgaben prüfen…', + mandatoryStopping: 'Aufgaben stoppen…', + mandatoryRestarting: 'Die App wird in Kürze neu gestartet. Bitte warten.', + mandatoryDownloadFailed: 'Die Update-Dateien konnten nicht heruntergeladen oder vorbereitet werden. Bitte versuchen Sie es erneut.', + mandatoryInstallFailed: 'Das Update wurde nicht installiert. Überprüfen Sie die Aufgaben erneut und versuchen Sie es erneut.', + mandatoryOpenHelp: 'Seite wurde nicht geöffnet?', + mandatoryReopen: 'Offizielle Downloadseite erneut öffnen', + mandatoryCopied: 'Link kopiert', + mandatoryCopyFailed: 'Der Link konnte nicht kopiert werden. Wählen Sie es aus und kopieren Sie es unten.', + mandatoryAddress: 'Download-Link', + mandatoryNotification: 'Kehren Sie zur Anwendung zurück, um die Installation zu bestätigen und neu zu starten.', +} satisfies DesktopMessages + +/** Russian dictionary, checked against the English keys. */ +export const ru = { + cliCommandMenu: 'Управление командой dsh…', + cliCommandTitle: 'Управление командой dsh', + cliCommandLocation: 'Команда Desktop: {path}', + cliCommandSelected: 'Текущая команда dsh: {path}.', + cliCommandTarget: 'Текущая цель лаунчера: {path}', + cliCommandShadowed: 'Другой dsh имеет приоритет. Удалите или измените порядок установки, чтобы использовать команду «Desktop» по умолчанию. Вы также можете запустить команду «Desktop» по ее полному пути.', + cliCommandSelectionUnknown: 'Не удалось проверить вашу команду оболочки. Псевдоним или другая установка dsh может иметь приоритет.', + cliCommandInstalled: 'Команда «Desktop» установлена.', + cliCommandNotInstalled: 'Добавьте команду «Desktop» в свой терминал.', + cliCommandBroken: 'Команда Desktop требует ремонта.', + cliCommandInstall: 'Установить', + cliCommandRepair: 'Исправить', + cliCommandRemove: 'Удалить', + cliCommandClose: 'Закрыть', + cliCommandSwitch: 'Продолжить команду «Desktop»?', + cliCommandPreserve: 'Существующая команда будет сохранена. Другие установки и файлы запуска оболочки не будут изменены.', + cliCommandContinue: 'Продолжить', + cliCommandInstallApp: 'Установите Desktop в папку «Приложения», прежде чем управлять командой dsh.', + cliCommandUpdating: 'Идет установка обновления. Управляйте командой после завершения установки.', + cliCommandNewTerminal: 'Откройте новый терминал и запустите dsh --version.', + cliCommandRemoved: 'Регистрация команд Desktop удалена.', + cliCommandPreviousRestored: 'Предыдущий лаунчер восстановлен.', + cliCommandOtherKept: 'Остальные командные установки остались на месте.', + cliCommandBackupKept: 'Предыдущий лаунчер сохранился по адресу: {path}.', + cliCommandChanged: 'Команда или PATH изменилась, пока это диалоговое окно было открыто. Откройте команду «Управление dsh» еще раз, чтобы просмотреть текущее состояние.', + cliCommandOwnershipError: 'Регистрация команд или резервное копирование изменены. Ни одна несвязанная команда не была удалена.', + cliCommandFailed: 'Не удалось обновить команду. Убедитесь, что приложение установлено и место назначения доступно для записи, затем повторите попытку.', + application: 'Приложение', + fileMenu: 'Файл', + closePage: 'Закрыть страницу или окно', + aboutMenu: 'О DeepSeek Harness', + aboutProduct: 'DeepSeek Harness', + aboutVersion: 'Версия V{version}', + hideApplication: 'Скрыть DeepSeek Harness', + hideOtherApplications: 'Скрыть других', + showAllApplications: 'Показать все', + quitApplication: 'Выйти из DeepSeek Harness', + openApplication: 'Открыть DeepSeek Harness', + quit: 'Выйти', + cancel: 'Отмена', + quitTitle: 'Выйти из DeepSeek Harness?', + quitActiveTasks: 'Выполнение задач будет прервано.', + quitScheduledTasks: 'Запланированные задачи не будут выполняться, пока приложение закрыто.', + quitActiveAndScheduledTasks: 'Выполнение задач будет прервано, а запланированные задачи не будут выполняться, пока приложение закрыто.', + backgroundNoticeBody: 'Выполнение задач продолжится. Вы можете снова открыть окно из системного трея.', + backgroundNoticeConfirm: 'Подтвердить', + edit: 'Редактировать', + menuBar: 'Меню приложения', + delete: 'Удалить', + undo: 'Отменить', + redo: 'Повторить', + cut: 'Вырезать', + copy: 'Копировать', + paste: 'Вставить', + selectAll: 'Выбрать все', + startupFailed: 'DeepSeek Harness недоступен.', + fatalSummary: 'Приложение не могло запуститься или неожиданно остановилось.', + startupAddressInUse: 'Другой экземпляр DSH (например, веб-приложение dsh или настольное приложение) запущен. Они не могут начаться одновременно. Закройте другой работающий экземпляр DSH, а затем перезапустите.', + diagnosticTruncated: '… Подробности об ошибках сокращены.', + reportWrittenTo: 'Диагностический отчет: {path}', + getDiagnosticReport: 'Получить диагностический отчет', + reportPending: 'Диагностический отчет еще сохраняется. Выберите «Получить диагностический отчет», чтобы проверить еще раз.', + reportUnavailable: 'Не удалось сохранить диагностический отчет. При обращении в службу поддержки можно приложить снимок экрана этого диалогового окна.', + reportShareHint: 'Открыта папка с отчетом. Прикрепите выбранный файл к обращению в службу поддержки.', + reportRevealFailed: 'Не удалось открыть папку с отчетом. Найдите файл по указанному ниже пути.', + startupReinstallAdvice: 'Если файлы приложения отсутствуют или повреждены, закройте приложение и переустановите его. Ваши задачи хранятся отдельно.', + exitApplication: 'Выход', + restartApplication: 'Перезапустить', + recoveryOperationFailed: 'Операция восстановления не удалась', + disableThirdPartyPlugins: 'Отключите сторонние плагины, создайте резервную копию патча профиля и перезапустите.', + welcomeTitle: 'DeepSeek Harness', + welcomeBrand: 'DeepSeek Harness', + welcomeTaglineBefore: 'Добро пожаловать в ', + welcomeTaglineBrand: 'DeepSeek Harness', + welcomeTaglineAfter: '', + welcomeDescription: 'Развивайте потенциал. Исследуйте интеллект.', + welcomeAuthStarting: 'Открытие входа в систему…', + welcomeAuthWaiting: 'Браузер не открылся автоматически?', + welcomeAuthWaitingDescription: 'Скопируйте ссылку для входа и откройте ее в браузере, чтобы войти.', + welcomeAuthExchanging: 'Завершение входа…', + welcomeAuthExpired: 'Время входа в систему истекло', + welcomeAuthExpiredDescription: 'Войдите еще раз, чтобы продолжить', + welcomeAuthFailed: 'Не удалось завершить вход. Повторите попытку.', + welcomeAuthCopyLink: 'Скопировать ссылку для входа', + welcomeAuthCopied: 'Скопировано', + welcomeAuthCopyFailed: 'Не удалось скопировать. Попробуйте еще раз.', + welcomeAuthCancel: 'Отмена', + welcomeAuthRetry: 'Войдите снова', + welcomeSignIn: 'Войти', + welcomeApiKey: 'Добавить ключ API', + welcomeKeyTitle: 'Добавьте ключ API, чтобы начать работу.', + welcomeKeyDescription: 'Настройте официальные модели DeepSeek, чтобы начать использовать Harness.', + welcomeKeyPlaceholder: 'Введите ключ API', + welcomeKeySave: 'Сохранить и продолжить', + welcomeKeyLater: 'Настроить позже', + welcomeKeyBack: 'Вернуться для входа в систему', + welcomeSessionExpired: 'Вы вышли из своей учетной записи, пожалуйста, войдите снова.', + welcomeKeyBlank: 'Введите ключ API.', + welcomeKeyInvalid: 'Введите сам ключ API без кавычек, пробелов и присвоения переменной среды.', + welcomeKeyFailed: 'Не удалось сохранить ключ API. Пожалуйста, попробуйте еще раз.', + welcomeContinueFailed: 'Не удалось открыть рабочую область. Пожалуйста, попробуйте еще раз.', + checkUpdatesMenu: 'Проверить наличие обновлений…', + reloadPageMenu: 'Обновить страницу', + restartAppHostMenu: 'Перезапустите приложение и хост.', + updateCheckFailedTitle: 'Проверка обновления не удалась', + updateCheckFailed: 'Не удалось проверить наличие обновлений. Пожалуйста, повторите попытку позже.', + updateDownloadFailed: 'Не удалось загрузить обновление. Пожалуйста, попробуйте еще раз.', + updateInstallFailed: 'Не удалось установить обновление. Пожалуйста, повторите попытку позже.', + updateCheckNetworkFailed: 'Не удалось проверить наличие обновлений. Проверьте подключение и повторите попытку.', + updateDownloadNetworkFailed: 'Не удалось загрузить обновление. Проверьте подключение и повторите попытку.', + updateInstallNetworkFailed: 'Не удалось установить обновление. Проверьте подключение и повторите попытку.', + unknownError: 'Неизвестная ошибка', + updateCheckTitle: 'Проверьте наличие обновлений', + updateCurrentDetail: 'Текущая версия: {version}.', + updateCurrent: 'У вас последняя версия.', + updateChecking: 'Проверка обновлений…', + updateDownload: 'Скачать обновление', + updateDownloadedTitle: 'Версия {version} готова к установке.', + updateDownloadedDetail: 'Приложение закроется во время обновления и автоматически откроется после его завершения.', + updateDownloadedDetailWindows: 'Приложение временно закроется во время обновления и автоматически откроется после его завершения.\n\nОбновление может занять некоторое время. Пожалуйста, подождите и не запускайте приложение снова во время установки.', + updateClose: 'Закрыть', + updateAcknowledge: 'OK', + updateLater: 'Обновить позже', + updateDownloading: 'Загрузка {percent}%…', + updateVerifying: 'Проверка файлов обновлений…', + updateInstalling: 'Подготовка к перезапуску…', + updateRetry: 'Повторить обновление', + updateActiveTasks: 'Задачи еще выполняются', + updateActiveTasksDetail: 'Обновление остановит выполняемые задачи и перезапустит приложение. Продолжать?', + updateStopTasks: 'Остановить задачи и обновить', + updateTasksChanged: 'Начались новые задачи. Подтвердите еще раз, чтобы остановить выполнение задач и выполнить обновление.', + updateTasksUnavailable: 'Статус задачи недоступен. Попробуйте обновить еще раз, когда рабочая область будет готова.', + updateFullscreenTimeout: 'Не удалось выйти из полноэкранного режима. Выйдите из полноэкранного режима и повторите попытку обновления.', + updateStopFailed: 'Не удалось безопасно остановить задачи. Обновление не установлено. Пожалуйста, повторите попытку позже.', + updateTechnicalDetails: 'Посмотреть технические подробности', + updateTitle: 'DeepSeek Harness Обновление', + updateAvailable: 'Доступна новая версия: {version}.', + updateDetail: 'После завершения загрузки вы можете установить обновление и перезапустить приложение.', + installAndRestart: 'Установить и перезапустить', + later: 'Позже', + updateFailedTitle: 'Обновление не выполнено', + mandatoryTitle: 'Обновите, чтобы продолжить', + mandatoryDetail: 'Эта версия больше не поддерживается. Обновите, чтобы продолжить. Выполняемые задачи будут продолжать выполняться до тех пор, пока вы не подтвердите установку и не перезапустите.', + mandatoryUnavailable: 'Не удалось проверить требования к обновлению. Пожалуйста, повторите попытку позже.', + policyLoginTitle: 'Войдите в тестовую среду', + policyLoginRequired: 'Войдите в систему с помощью Feishu, чтобы проверить требования к обновлению для этой тестовой сборки. При входе в систему обновление не загружается и не устанавливается.', + policyLogin: 'Войти через Feishu', + policyLoginFailed: 'Вход в Feishu не завершен. Пожалуйста, попробуйте еще раз.', + policyLoginLoading: 'Загрузка страницы входа…', + mandatoryNoRelease: 'Совместимое обновление не найдено. Проверьте еще раз или обратитесь в службу поддержки.', + mandatoryRefresh: 'Проверьте еще раз', + mandatoryPage: 'Скачать с официального сайта', + mandatoryCopy: 'Скопировать ссылку для скачивания', + mandatoryPageFailed: 'Не удалось открыть официальную страницу загрузки. Скопируйте ссылку и откройте ее в браузере.', + mandatoryViewDownload: 'Открыть страницу загрузки', + mandatoryViewPageFailed: 'Не удалось открыть страницу загрузки. Пожалуйста, попробуйте еще раз.', + mandatoryActionFailed: 'Не удалось выполнить действие. Повторите попытку. Вы сможете снова использовать приложение после завершения обновления.', + mandatoryReady: 'Обновление готово', + mandatoryVersion: 'Новая версия: {version}', + mandatoryReadyDetail: 'Приложение закроется во время обновления и автоматически откроется после его завершения.', + mandatoryDeferred: 'Выполняемые задачи будут продолжать выполняться. Завершите обновление, прежде чем снова использовать приложение.', + mandatoryContinue: 'Продолжить обновление', + mandatoryInspecting: 'Проверка задач…', + mandatoryStopping: 'Остановка задач…', + mandatoryRestarting: 'Приложение вскоре перезапустится. Пожалуйста, подождите.', + mandatoryDownloadFailed: 'Файлы обновления не удалось загрузить или подготовить. Пожалуйста, повторите попытку.', + mandatoryInstallFailed: 'Обновление не установлено. Проверьте задачи еще раз и повторите попытку.', + mandatoryOpenHelp: 'Страница не открылась?', + mandatoryReopen: 'Откройте официальную страницу загрузки еще раз.', + mandatoryCopied: 'Ссылка скопирована', + mandatoryCopyFailed: 'Не удалось скопировать ссылку. Выделите и скопируйте его ниже.', + mandatoryAddress: 'Ссылка для скачивания', + mandatoryNotification: 'Вернитесь в приложение, чтобы подтвердить установку и перезапустить.', +} satisfies DesktopMessages + +/** Portuguese dictionary, checked against the English keys. */ +export const pt = { + cliCommandMenu: 'Gerenciar comando dsh…', + cliCommandTitle: 'Gerenciar comando dsh', + cliCommandLocation: 'Comando da área de trabalho: {path}', + cliCommandSelected: 'Comando dsh atual: {path}', + cliCommandTarget: 'Alvo atual do iniciador: {path}', + cliCommandShadowed: 'Outro dsh tem precedência. Remova ou reordene essa instalação para usar o comando Desktop por padrão. Você também pode executar o comando Desktop pelo caminho completo.', + cliCommandSelectionUnknown: 'Seu comando shell não pôde ser verificado. Um alias ou outra instalação do dsh pode ter precedência.', + cliCommandInstalled: 'O comando Desktop está instalado.', + cliCommandNotInstalled: 'Adicione o comando Desktop ao seu terminal.', + cliCommandBroken: 'O comando Desktop precisa de reparo.', + cliCommandInstall: 'Instalar', + cliCommandRepair: 'Reparar', + cliCommandRemove: 'Remover', + cliCommandClose: 'Fechar', + cliCommandSwitch: 'Continuar com o comando Desktop?', + cliCommandPreserve: 'Um comando existente será preservado. Outras instalações e arquivos de inicialização do shell não serão alterados.', + cliCommandContinue: 'Continuar', + cliCommandInstallApp: 'Instale o Desktop na pasta Aplicativos antes de gerenciar o comando dsh.', + cliCommandUpdating: 'Uma atualização está sendo instalada. Gerencie o comando após a conclusão da instalação.', + cliCommandNewTerminal: 'Abra um novo terminal e execute dsh --version.', + cliCommandRemoved: 'Registro de comando da área de trabalho removido.', + cliCommandPreviousRestored: 'O inicializador anterior foi restaurado.', + cliCommandOtherKept: 'Outras instalações de comando foram mantidas.', + cliCommandBackupKept: 'Um inicializador anterior é preservado em: {path}', + cliCommandChanged: 'O comando ou PATH foi alterado enquanto esta caixa de diálogo estava aberta. Abra o comando Gerenciar dsh novamente para revisar o estado atual.', + cliCommandOwnershipError: 'O registro ou backup do comando foi alterado. Nenhum comando não relacionado foi removido.', + cliCommandFailed: 'O comando não pôde ser atualizado. Verifique se o aplicativo está instalado e se o destino é gravável e tente novamente.', + application: 'Aplicativo', + fileMenu: 'Arquivo', + closePage: 'Fechar página ou janela', + aboutMenu: 'Sobre DeepSeek Harness', + aboutProduct: 'DeepSeek Harness', + aboutVersion: 'Versão V{version}', + hideApplication: 'Ocultar DeepSeek Harness', + hideOtherApplications: 'Ocultar outros', + showAllApplications: 'Mostrar tudo', + quitApplication: 'Sair de DeepSeek Harness', + openApplication: 'Abra DeepSeek Harness', + quit: 'Sair', + cancel: 'Cancelar', + quitTitle: 'Sair de DeepSeek Harness?', + quitActiveTasks: 'As tarefas em execução serão interrompidas.', + quitScheduledTasks: 'As tarefas agendadas não serão executadas enquanto o aplicativo estiver fechado.', + quitActiveAndScheduledTasks: 'As tarefas em execução serão interrompidas e as tarefas agendadas não serão executadas enquanto o aplicativo estiver fechado.', + backgroundNoticeBody: 'As tarefas em execução continuarão. Você pode reabrir a janela na bandeja do sistema.', + backgroundNoticeConfirm: 'Confirmar', + edit: 'Editar', + menuBar: 'Menu de aplicativos', + delete: 'Excluir', + undo: 'Desfazer', + redo: 'Refazer', + cut: 'Cortar', + copy: 'Copiar', + paste: 'Colar', + selectAll: 'Selecionar tudo', + startupFailed: 'DeepSeek Harness não está disponível', + fatalSummary: 'O aplicativo não pôde ser iniciado ou parou inesperadamente.', + startupAddressInUse: 'Outra instância DSH (como dsh web ou aplicativo de desktop) está em execução. Eles não podem começar ao mesmo tempo. Saia da outra instância DSH em execução e reinicie.', + diagnosticTruncated: '… Detalhes do erro reduzidos.', + reportWrittenTo: 'Relatório de diagnóstico: {path}', + getDiagnosticReport: 'Obter relatório de diagnóstico', + reportPending: 'O relatório de diagnóstico ainda está sendo salvo. Selecione Obter relatório de diagnóstico para verificar novamente.', + reportUnavailable: 'Não foi possível salvar o relatório de diagnóstico. Você pode fornecer uma captura de tela desta caixa de diálogo ao solicitar suporte.', + reportShareHint: 'O local do relatório foi aberto. Anexe o arquivo selecionado à sua solicitação de suporte.', + reportRevealFailed: 'Não foi possível abrir o local do relatório. Use o caminho abaixo para encontrar o arquivo.', + startupReinstallAdvice: 'Se os arquivos do aplicativo estiverem ausentes ou danificados, feche o aplicativo e reinstale-o. Suas tarefas são armazenadas separadamente.', + exitApplication: 'Sair', + restartApplication: 'Reiniciar', + recoveryOperationFailed: 'A operação de recuperação falhou', + disableThirdPartyPlugins: 'Desative plug-ins de terceiros, faça backup do patch do perfil e reinicie', + welcomeTitle: 'DeepSeek Harness', + welcomeBrand: 'DeepSeek Harness', + welcomeTaglineBefore: 'Bem-vindo ao ', + welcomeTaglineBrand: 'DeepSeek Harness', + welcomeTaglineAfter: '', + welcomeDescription: 'Construir potencial. Explore a inteligência.', + welcomeAuthStarting: 'Abrindo login…', + welcomeAuthWaiting: 'O navegador não abriu automaticamente?', + welcomeAuthWaitingDescription: 'Copie o link de login e abra-o em seu navegador para fazer login.', + welcomeAuthExchanging: 'Concluindo login…', + welcomeAuthExpired: 'O tempo limite de login expirou', + welcomeAuthExpiredDescription: 'Faça login novamente para continuar', + welcomeAuthFailed: 'Não foi possível concluir o login. Tente novamente.', + welcomeAuthCopyLink: 'Copiar link de login', + welcomeAuthCopied: 'Copiado', + welcomeAuthCopyFailed: 'Não foi possível copiar. Tente novamente.', + welcomeAuthCancel: 'Cancelar', + welcomeAuthRetry: 'Faça login novamente', + welcomeSignIn: 'Faça login', + welcomeApiKey: 'Adicionar chave API', + welcomeKeyTitle: 'Adicione uma chave API para começar', + welcomeKeyDescription: 'Configure modelos DeepSeek oficiais para começar a usar o Harness', + welcomeKeyPlaceholder: 'Insira a chave de API', + welcomeKeySave: 'Salvar e continuar', + welcomeKeyLater: 'Configurar mais tarde', + welcomeKeyBack: 'Voltar para fazer login', + welcomeSessionExpired: 'Você saiu da sua conta, faça login novamente.', + welcomeKeyBlank: 'Insira uma chave API.', + welcomeKeyInvalid: 'Insira a própria chave API, sem aspas, espaços ou atribuição de variável de ambiente.', + welcomeKeyFailed: 'Não foi possível salvar a chave API. Por favor, tente novamente.', + welcomeContinueFailed: 'Não foi possível abrir o espaço de trabalho. Por favor, tente novamente.', + checkUpdatesMenu: 'Verifique se há atualizações…', + reloadPageMenu: 'Recarregar página', + restartAppHostMenu: 'Reinicie o aplicativo e o host', + updateCheckFailedTitle: 'Falha na verificação de atualização', + updateCheckFailed: 'Não foi possível verificar se há atualizações. Por favor, tente novamente mais tarde.', + updateDownloadFailed: 'Não foi possível baixar a atualização. Por favor, tente novamente.', + updateInstallFailed: 'Não foi possível instalar a atualização. Por favor, tente novamente mais tarde.', + updateCheckNetworkFailed: 'Não foi possível verificar se há atualizações. Verifique sua conexão e tente novamente.', + updateDownloadNetworkFailed: 'Não foi possível baixar a atualização. Verifique sua conexão e tente novamente.', + updateInstallNetworkFailed: 'Não foi possível instalar a atualização. Verifique sua conexão e tente novamente.', + unknownError: 'Erro desconhecido', + updateCheckTitle: 'Verifique se há atualizações', + updateCurrentDetail: 'Versão atual: {version}', + updateCurrent: 'Você está atualizado!', + updateChecking: 'Verificando atualizações…', + updateDownload: 'Baixar atualização', + updateDownloadedTitle: 'A versão {version} está pronta para instalação', + updateDownloadedDetail: 'O aplicativo será fechado durante a atualização e reaberto automaticamente quando for concluída.', + updateDownloadedDetailWindows: 'O aplicativo será fechado temporariamente durante a atualização e reaberto automaticamente quando for concluída.\n\nA atualização pode levar algum tempo. Aguarde e não inicie o aplicativo novamente durante a instalação.', + updateClose: 'Fechar', + updateAcknowledge: 'OK', + updateLater: 'Atualizar mais tarde', + updateDownloading: 'Baixando {percent}%…', + updateVerifying: 'Verificando arquivos de atualização…', + updateInstalling: 'Preparando para reiniciar…', + updateRetry: 'Tentar atualizar novamente', + updateActiveTasks: 'As tarefas ainda estão em andamento', + updateActiveTasksDetail: 'A atualização interromperá as tarefas em andamento e reiniciará o aplicativo. Continuar?', + updateStopTasks: 'Pare tarefas e atualize', + updateTasksChanged: 'Novas tarefas foram iniciadas. Confirme novamente para interromper as tarefas e atualizar.', + updateTasksUnavailable: 'O status da tarefa não está disponível. Tente atualizar novamente quando o espaço de trabalho estiver pronto.', + updateFullscreenTimeout: 'Não foi possível sair da tela cheia. Saia da tela inteira e tente atualizar novamente.', + updateStopFailed: 'Não foi possível interromper as tarefas com segurança. A atualização não foi instalada. Por favor, tente novamente mais tarde.', + updateTechnicalDetails: 'Ver detalhes técnicos', + updateTitle: 'DeepSeek Harness Atualização', + updateAvailable: 'Nova versão disponível: {version}', + updateDetail: 'Assim que o download for concluído, você pode instalar a atualização e reiniciar o aplicativo.', + installAndRestart: 'Instalar e reiniciar', + later: 'Mais tarde', + updateFailedTitle: 'Falha na atualização', + mandatoryTitle: 'Atualizar para continuar', + mandatoryDetail: 'Esta versão não é mais suportada. Atualize para continuar. As tarefas em andamento continuarão em execução até você confirmar a instalação e reiniciar.', + mandatoryUnavailable: 'Não foi possível verificar os requisitos de atualização. Por favor, tente novamente mais tarde.', + policyLoginTitle: 'Faça login no ambiente de teste', + policyLoginRequired: 'Faça login com Feishu para verificar os requisitos de atualização para esta versão de teste. O login não baixará nem instalará uma atualização.', + policyLogin: 'Faça login com Feishu', + policyLoginFailed: 'O login do Feishu não foi concluído. Por favor, tente novamente.', + policyLoginLoading: 'Carregando página de login…', + mandatoryNoRelease: 'Nenhuma atualização compatível foi encontrada. Verifique novamente ou entre em contato com o suporte.', + mandatoryRefresh: 'Verifique novamente', + mandatoryPage: 'Baixe do site oficial', + mandatoryCopy: 'Copiar link de download', + mandatoryPageFailed: 'Não foi possível abrir a página oficial de download. Copie o link e abra-o no seu navegador.', + mandatoryViewDownload: 'Abrir página de download', + mandatoryViewPageFailed: 'Não foi possível abrir a página de download. Por favor, tente novamente.', + mandatoryActionFailed: 'A ação falhou. Por favor, tente novamente. Você poderá usar o aplicativo novamente após a conclusão da atualização.', + mandatoryReady: 'Atualização pronta', + mandatoryVersion: 'Nova versão: {version}', + mandatoryReadyDetail: 'O aplicativo será fechado durante a atualização e reaberto automaticamente quando for concluída.', + mandatoryDeferred: 'As tarefas em andamento continuarão em execução. Conclua a atualização antes de usar o aplicativo novamente.', + mandatoryContinue: 'Continuar atualização', + mandatoryInspecting: 'Verificando tarefas…', + mandatoryStopping: 'Parando tarefas…', + mandatoryRestarting: 'O aplicativo será reiniciado em breve. Por favor, aguarde.', + mandatoryDownloadFailed: 'Os arquivos de atualização não puderam ser baixados ou preparados. Por favor, tente novamente.', + mandatoryInstallFailed: 'A atualização não foi instalada. Verifique as tarefas novamente e tente novamente.', + mandatoryOpenHelp: 'A página não abriu?', + mandatoryReopen: 'Abra a página oficial de download novamente', + mandatoryCopied: 'Link copiado', + mandatoryCopyFailed: 'Não foi possível copiar o link. Selecione e copie abaixo.', + mandatoryAddress: 'Link de download', + mandatoryNotification: 'Retorne ao aplicativo para confirmar a instalação e reinicie.', +} satisfies DesktopMessages + +const dictionaries = { en, zh, ja, es, fr, de, ru, pt } + /** Locale payload exposed to the Desktop-owned renderer. */ export interface DesktopLocale { - readonly id: 'en' | 'zh-CN' | 'ja' + readonly id: 'en' | 'zh-CN' | 'ja' | 'es' | 'fr' | 'de' | 'ru' | 'pt' readonly messages: DesktopMessages } /** Resolve Electron's locale to one shipped Desktop dictionary. */ export function resolveDesktopLocale(locale: string): DesktopLocale { const primary = locale.toLowerCase().split('-')[0] - if (primary === 'ja') return { id: 'ja', messages: ja } - return primary === 'zh' - ? { id: 'zh-CN', messages: zh } - : { id: 'en', messages: en } + if (primary !== undefined && Object.hasOwn(dictionaries, primary)) { + const id = primary as keyof typeof dictionaries + return { id: id === 'zh' ? 'zh-CN' : id, messages: dictionaries[id] } + } + return { id: 'en', messages: en } } /** @@ -540,10 +1443,10 @@ export function resolveDesktopLocale(locale: string): DesktopLocale { */ export function resolveDesktopStartupLocale(preference: string | null, languages: readonly string[]): DesktopLocale { const selected = preference?.toLowerCase() - if (selected === 'zh' || selected === 'en' || selected === 'ja') return resolveDesktopLocale(selected) + if (selected !== undefined && Object.hasOwn(dictionaries, selected)) return resolveDesktopLocale(selected) for (const language of languages) { const primary = language.toLowerCase().split('-')[0] - if (primary === 'zh' || primary === 'en' || primary === 'ja') return resolveDesktopLocale(primary) + if (primary !== undefined && Object.hasOwn(dictionaries, primary)) return resolveDesktopLocale(primary) } return resolveDesktopLocale('en') } diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index fb938dec84..4770fe83bf 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -2,7 +2,7 @@ import type { ProductEventMap, ProductEvent } from '@deepseek-ai/dsh-client-prod import { WINDOWS_TITLEBAR_HEIGHT } from './windows-layout.ts' /** Electron shell: desktop project ownership, custom protocol, windows, and lifecycle. */ -import { readFile, writeFile } from 'node:fs/promises' +import { access, readFile, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { @@ -41,6 +41,8 @@ import { DesktopCommandManager } from './command-management.ts' import { serveWebDocument, authenticateWebHost, forwardWebRequest } from './web-document.ts' import { DesktopFatalRecovery } from './fatal-recovery.ts' import { pruneCrashReports, RendererConsoleTail, writeCrashReport, type CrashReportSource } from './crash-report.ts' +import { OperationJournal } from './operation-journal.ts' +import { runOperationReportJob, type OperationReportJobResult } from './operation-report-job.ts' import { openWelcomeWindow } from './welcome-window.ts' import { WELCOME_IPC, needsWelcome, type WelcomeNotice } from './welcome-api.ts' import { connectDesktopWelcome, type DesktopWelcomeBackend } from './welcome-backend.ts' @@ -55,6 +57,7 @@ import { desktopClientMetadata, desktopClientVersion } from './client-metadata.t import { DesktopMandatoryUpdateWindow } from './mandatory-update-window.ts' import { DesktopPolicyTestAuth } from './policy-test-auth.ts' import { readDesktopSettings } from './settings.ts' +import { readDesktopLocaleCache, writeDesktopLocaleCache } from './locale-cache.ts' import { DesktopUpdateDialog, type UpdateDialogOptions } from './update-dialog.ts' import { readDesktopRuntime } from './runtime-tree.ts' import { DesktopBrowserGuests } from './browser-guests.ts' @@ -65,14 +68,14 @@ import { DesktopTray } from './tray.ts' import { DesktopBackgroundNotice } from './background-notice.ts' let focusPrimaryWindow = (): void => {} -let stopForRecovery = async (): Promise => {} +let stopForRecovery = async (): Promise => { await stopOperationReports() } let shuttingDown = false /** * Set by quit entries that must not ask: crash recovery exit and restart, and the * development restart command. The installer handoff has its own before-quit branch. */ let skipQuitConfirmation = false -let windowsLanguage: string | undefined +let windowsLanguage: string | undefined = readDesktopLocaleCache(app.getPath('userData')) /** * Whether the backend has reached ready: false until the first ready, back to * false when a restart returns it to starting, frozen during shutdown so a @@ -106,10 +109,39 @@ const recovery = new DesktopFatalRecovery({ exit: () => { quitWithoutConfirmation() }, restart: () => { app.relaunch(); quitWithoutConfirmation() }, writeReport: (error, source) => persistCrashReport(error, source), + revealReport: async (path) => { await access(path); shell.showItemInFolder(path) }, }) +let operationJournal: OperationJournal | undefined +let operationReportJob: Promise | undefined +let operationReportAbort: AbortController | undefined +let operationReportsStopping = false +let operationReportStop: Promise | undefined + +/** Bound application shutdown waiting without claiming that an unresponsive Worker has exited. */ +function stopOperationReports(): Promise { + operationReportStop ??= waitForOperationReports() + return operationReportStop +} + +async function waitForOperationReports(): Promise { + operationReportsStopping = true + operationReportAbort?.abort() + const job = operationReportJob + if (job === undefined) return + let timer: ReturnType | undefined + try { + const exited = await Promise.race([job.then(() => true), new Promise((resolve) => { + timer = setTimeout(() => { resolve(false) }, 500) + })]) + if (!exited) console.error('dsh desktop: operation report Worker has not exited; continuing shutdown') + } finally { clearTimeout(timer) } +} + function persistCrashReport(error: unknown, source: CrashReportSource): Promise { - return writeCrashReport(app.getPath('logs'), { + const directory = app.getPath('logs') + const report = writeCrashReport(directory, { + operationHistoryPlanned: !shuttingDown && !operationReportsStopping, source, phase: backendReady ? 'running' : 'startup', error, @@ -121,6 +153,17 @@ function persistCrashReport(error: unknown, source: CrashReportSource): Promise< }, time: new Date(), }) + void report.then((path) => { + if (path !== undefined && operationReportJob === undefined && !shuttingDown && !operationReportsStopping) { + operationReportAbort = new AbortController() + operationReportJob = runOperationReportJob({ reportPath: path, directory: join(app.getPath('userData'), 'plugin-operations'), + limits: { bytes: 64 * 1024, recordBytes: 4096, records: 100, outputBytes: 64 * 1024 }, + journal: operationJournal?.status() ?? null, + }, { timeoutMs: 500, cancellationGraceMs: 100 }, operationReportAbort.signal) + void operationReportJob.finally(() => { operationReportJob = undefined; operationReportAbort = undefined }) + } + }).catch((_error: unknown) => { /* Basic persistence failure is owned by fatal recovery. */ }) + return report } function reportFatal(error: unknown, source: CrashReportSource): void { @@ -130,7 +173,12 @@ function reportFatal(error: unknown, source: CrashReportSource): void { void persistCrashReport(error, source) return } - void recovery.report(error, source).catch((failure: unknown) => { console.error(failure); app.exit(1) }) + void recovery.report(error, source).catch(async (failure: unknown) => { + console.error(failure) + shuttingDown = true + await stopOperationReports() + app.exit(1) + }) } protocol.registerSchemesAsPrivileged([{ @@ -374,7 +422,8 @@ async function main(): Promise { let updateStopFailure: DesktopHostUncleanExitError | undefined let updateState: DesktopUpdateState = { phase: 'idle' } const systemLanguages = app.getPreferredSystemLanguages() - let locale = resolveDesktopStartupLocale(null, systemLanguages) + let locale = windowsLanguage === undefined + ? resolveDesktopStartupLocale(null, systemLanguages) : resolveDesktopLocale(windowsLanguage) windowsLanguage = locale.id let mandatoryPolicy: DesktopMandatoryUpdatePolicy | undefined let mandatoryUI: DesktopMandatoryUpdateWindow | undefined @@ -470,7 +519,12 @@ async function main(): Promise { const host = new DesktopHostProcess(resources.node, resources.dsh, activeProject, hostInspectPort, { ...hostEnvironment, DSH_CLIENT_VERSION: desktopClientVersion() }, onFailure, primaryRuntime, - resources, (next) => { platformView.setSession(next) }) + resources, (next) => { platformView.setSession(next) }, (record) => { + operationJournal ??= new OperationJournal(join(app.getPath('userData'), 'plugin-operations'), { + segmentBytes: 256 * 1024, recordBytes: 4096, queuedBytes: 64 * 1024, + }) + operationJournal.enqueue(JSON.stringify(record)) + }) return { start: async () => { const ready = await host.start() @@ -565,6 +619,10 @@ async function main(): Promise { fileDragStopped = false } const restoreHost = state.failedOperation === 'install' && updateStoppedHost && !quitting + if (state.failedOperation === 'install' && !quitting) { + operationReportsStopping = shuttingDown + operationReportStop = undefined + } shellInstallerOwnsQuit = false updateStoppedHost = false if (restoreHost) { @@ -593,7 +651,11 @@ async function main(): Promise { if (backend.host === undefined || welcomeBackend === undefined) throw new Error('desktop welcome: backend unavailable') return welcomeBackend.read() } - stopForRecovery = () => backend.close() + stopForRecovery = async () => { + const reports = stopOperationReports() + try { await backend.close() } + finally { await Promise.all([operationJournal?.drain(500), reports]) } + } const reconcileBackend = (): Promise => { startup ??= (async () => { @@ -651,14 +713,17 @@ async function main(): Promise { await disposeFileDrag().catch((error: unknown) => { console.error(error) }) requireCleanStop = true updateStopFailure = undefined - await backend.stop() + await Promise.all([backend.stop(), stopOperationReports()]) updateStoppedHost = true // The backend's async cleanup callback can assign this after the reset above. const stopFailure = updateStopFailure as DesktopHostUncleanExitError | undefined if (stopFailure !== undefined) throw new DesktopUpdatePreparationError('stop-failed', locale.messages.updateStopFailed, stopFailure.message) + await operationJournal?.drain(500) updateJournal?.action('install-confirmed') shellInstallerOwnsQuit = true } catch (error) { + operationReportsStopping = shuttingDown + operationReportStop = undefined if (!updateStoppedHost) await host.updateTasks('unlock').catch((unlockError: unknown) => { console.error(unlockError) }) throw error } finally { @@ -793,6 +858,7 @@ async function main(): Promise { if (window === undefined || event.sender !== window.webContents || event.senderFrame !== window.webContents.mainFrame || typeof next !== 'string') return const current = resolveDesktopStartupLocale(next, systemLanguages) + writeDesktopLocaleCache(app.getPath('userData'), current.id) if (current.id === locale.id) return locale = current platformView.notifyLocaleChanged() @@ -1076,13 +1142,11 @@ async function main(): Promise { Menu.buildFromTemplate(items).popup({ window, x: Math.round(x * zoom), y: Math.round(y * zoom), callback: resolve }) }) }) - ipcMain.on(DESKTOP_IPC.windowsAppearance, (event, language: unknown, color: unknown, symbolColor: unknown) => { + ipcMain.on(DESKTOP_IPC.windowsAppearance, (event, _language: unknown, color: unknown, symbolColor: unknown) => { if (mainWindow === undefined || event.sender !== mainWindow.webContents || event.senderFrame !== mainWindow.webContents.mainFrame) return if (!event.senderFrame.url.startsWith(`${SCHEME}://app/`)) return - if (typeof language === 'string' && /^[a-zA-Z]+(?:-[a-zA-Z0-9]+)*$/u.test(language)) { - windowsLanguage = language - } + // Document lang starts as English before Host locale bootstrap; only localeChanged owns shell language. // Empty colors precede client stylesheet installation; only CSS color values cross IPC. const validColor = (value: unknown): value is string => typeof value === 'string' && /^(?:#[\da-f]{3,8}|rgba?\([\d.,%\s]+\))$/iu.test(value) @@ -1236,6 +1300,7 @@ async function main(): Promise { const state = await readWelcomeState() if (isQuitting() || backend.state.phase !== 'ready') return locale = resolveDesktopStartupLocale(state.localePreference, systemLanguages) + writeDesktopLocaleCache(app.getPath('userData'), locale.id) windowsLanguage = locale.id refreshApplicationMenu() if (!enteredWorkspace && needsWelcome({ loggedIn: state.loggedIn, hasApiKey: state.hasApiKey })) { @@ -1288,11 +1353,15 @@ async function main(): Promise { updateSchedule.dispose() updateDialog.dispose() mandatoryUI?.dispose() - void Promise.all([Promise.resolve(mandatoryPolicy?.dispose()).then(() => policyAuth?.dispose()), backend.close(), - // A Platform cleanup failure is logged without cutting the remaining Host shutdown short. - platformView.dispose().catch((error: unknown) => { console.error(error) }), - disposeFileDrag().catch((error: unknown) => { console.error(error) })]) - .catch((error: unknown) => { console.error(error) }).finally(() => { app.quit() }) + void Promise.all([stopOperationReports(), Promise.resolve(mandatoryPolicy?.dispose()).then(() => policyAuth?.dispose()), + backend.close().then(async () => { await operationJournal?.drain(500) }, async (error: unknown) => { + await operationJournal?.drain(500) + throw error + }), + platformView.dispose(), + disposeFileDrag(), + ].map(cleanup => cleanup.catch((error: unknown) => { console.error(error) }))) + .then(() => { app.quit() }) } app.on('before-quit', (event) => { if (shellInstallerOwnsQuit) { @@ -1381,7 +1450,9 @@ if (ownsDesktopInstance) void app.whenReady().then(main).catch(async (error: unk await writeFile(diagnosticFile, `${error instanceof Error ? error.stack ?? message : message}\n`).catch(() => undefined) } reportFatal(error, 'main') -}).catch((error: unknown) => { +}).catch(async (error: unknown) => { console.error(error) + shuttingDown = true + await stopOperationReports() app.exit(1) }) diff --git a/apps/desktop/src/operation-history.ts b/apps/desktop/src/operation-history.ts new file mode 100644 index 0000000000..ca9584f79f --- /dev/null +++ b/apps/desktop/src/operation-history.ts @@ -0,0 +1,120 @@ +/** Bounded, cancellable reads of Desktop-owned plugin operation history. */ +import { open } from 'node:fs/promises' +import { join } from 'node:path' +import { setImmediate } from 'node:timers/promises' +import { parsePluginOperationRecord, type PluginOperationRecord } from '@deepseek-ai/dsh-plugin-manager/diagnostic' + +/** Resource budgets for auxiliary history collection, independent of basic crash report writing. */ +export interface OperationHistoryReadLimits { + readonly bytes: number + readonly recordBytes: number + readonly records: number +} + +/** Collection facts; incomplete history must not be interpreted as absence of plugin changes. */ +export interface OperationHistoryReadResult { + readonly records: readonly PluginOperationRecord[] + readonly bytesRead: number + /** Distinct files from which at least one byte was read. */ + readonly filesRead: number + readonly truncated: boolean + readonly invalidRecords: number + readonly unavailableFiles: number + readonly cancelled: boolean +} + +/** + * Read only the bounded tails of the two owned history files, newest segment first. + * Cancellation is observed between bounded records after yielding to Worker messages and stops subsequent I/O and parsing. + * An already-issued OS read must settle before its handle closes. + * @param directory - Desktop's operation history directory; unrelated files are never enumerated. + * @param limits - Positive byte, record-size and record-count budgets. + * @param signal - Caller-owned collection deadline or shutdown cancellation. + * @returns Partial records and explicit omissions; filesystem failures never reject the collection. + */ +export async function readOperationHistory( + directory: string, + limits: OperationHistoryReadLimits, + signal: AbortSignal, +): Promise { + if (![limits.bytes, limits.recordBytes, limits.records].every(value => Number.isSafeInteger(value) && value > 0)) { + throw new RangeError('Operation history budgets must be positive safe integers') + } + await setImmediate() + const cancelled = (): boolean => signal.aborted + const records: PluginOperationRecord[] = [] + let bytesRead = 0 + const seenFiles = new Set() + let truncated = false + let invalidRecords = 0 + let unavailableFiles = 0 + for (const name of ['operations.jsonl', 'operations.previous.jsonl']) { + if (cancelled()) break + try { + await using handle = await open(join(directory, name), 'r') + if (cancelled()) break + const fileStat = await handle.stat() + if (cancelled()) break + if (!fileStat.isFile()) { + unavailableFiles++ + continue + } + const identity = `${String(fileStat.dev)}:${String(fileStat.ino)}` + if (seenFiles.has(identity)) { + truncated = true + continue + } + if (fileStat.size > 0 && (bytesRead >= limits.bytes || records.length >= limits.records)) { + truncated = true + break + } + + const readLength = Math.min(fileStat.size, limits.bytes - bytesRead) + const readStart = fileStat.size - readLength + const buffer = Buffer.alloc(readLength) + let readOffset = 0 + while (readOffset < readLength && !cancelled()) { + const read = await handle.read(buffer, readOffset, Math.min(16 * 1024, readLength - readOffset), readStart + readOffset) + bytesRead += read.bytesRead + if (read.bytesRead === 0) break + readOffset += read.bytesRead + } + if (readOffset > 0) seenFiles.add(identity) + if (cancelled()) break + truncated ||= readStart > 0 || readOffset < readLength + + // An unterminated last record can still be in flight; never parse it as a committed record. + if (readOffset === 0) continue + let lineEnd = buffer.lastIndexOf(10, readOffset - 1) + if (lineEnd !== readOffset - 1) truncated = true + while (lineEnd >= 0 && records.length < limits.records && !cancelled()) { + await setImmediate() + if (cancelled()) break + const previousLineEnd = lineEnd === 0 ? -1 : buffer.lastIndexOf(10, lineEnd - 1) + if (previousLineEnd < 0 && readStart > 0) { + truncated = true + break + } + const recordBytes = lineEnd - previousLineEnd - 1 + if (recordBytes > limits.recordBytes) { + invalidRecords++ + } else if (recordBytes > 0) { + try { + const value: unknown = JSON.parse(buffer.subarray(previousLineEnd + 1, lineEnd).toString('utf8')) + const record = parsePluginOperationRecord(value) + if (record === undefined) invalidRecords++ + else records.push(record) + } catch (_error) { + // A corrupt record does not invalidate independently delimited older records. + invalidRecords++ + } + } + lineEnd = previousLineEnd + } + if (lineEnd >= 0) truncated = true + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') unavailableFiles++ + } + } + return { records, bytesRead, filesRead: seenFiles.size, truncated, invalidRecords, unavailableFiles, cancelled: cancelled() } +} diff --git a/apps/desktop/src/operation-journal.ts b/apps/desktop/src/operation-journal.ts new file mode 100644 index 0000000000..b72cc6baac --- /dev/null +++ b/apps/desktop/src/operation-journal.ts @@ -0,0 +1,208 @@ +/** Single-shell, bounded persistence for already-projected operation diagnostics. */ +import { mkdir, open, rename, stat, writeFile } from 'node:fs/promises' +import { join } from 'node:path' + +/** Budgets include serialized JSON and its line delimiter. */ +export interface OperationJournalLimits { + readonly segmentBytes: number + readonly recordBytes: number + readonly queuedBytes: number +} + +/** In-memory omissions for the current shell lifetime; missing records never imply no operations occurred. */ +export interface OperationJournalStatus { + readonly dropped: number + readonly failed: number + readonly queuedBytes: number + readonly disabled: boolean + /** Damaged or oversized segments repaired; their lost record count is unknown. */ + readonly repairedSegments: number +} + +/** Owns two known files and one serial writer; the owning shell must exclude other writers. */ +export class OperationJournal { + private readonly queue: string[] = [] + private queuedBytes = 0 + private dropped = 0 + private failed = 0 + private repairedSegments = 0 + private disabled = false + private closed = false + private writing: Promise | undefined + private initialized = false + private readonly abort = new AbortController() + + /** + * @param directory - Directory reserved for the shell's operation journal. + * @param limits - Positive byte budgets, with recordBytes no greater than either other budget. + */ + constructor( + private readonly directory: string, + private readonly limits: OperationJournalLimits, + ) { + if (![limits.segmentBytes, limits.recordBytes, limits.queuedBytes].every(value => Number.isSafeInteger(value) && value > 0) + || limits.recordBytes > limits.segmentBytes || limits.recordBytes > limits.queuedBytes) { + throw new RangeError('Invalid operation journal budgets') + } + } + + /** + * Queue one prevalidated, whitelisted JSON record without awaiting disk I/O. + * @param record - An already serialized JSON object without literal line delimiters. + * @returns Whether the record was accepted; disk failures are reported separately by status(). + */ + enqueue(record: string): boolean { + const line = record + '\n' + const bytes = Buffer.byteLength(line) + if (this.closed || this.disabled || bytes > this.limits.recordBytes + || bytes + this.queuedBytes > this.limits.queuedBytes || /[\r\n]/u.test(record)) { + this.dropped++ + return false + } + this.queue.push(line) + this.queuedBytes += bytes + this.startWriter() + return true + } + + /** @returns Current queue occupancy and omission counters. */ + status(): OperationJournalStatus { + return { + dropped: this.dropped, + failed: this.failed, + queuedBytes: this.queuedBytes, + disabled: this.disabled, + repairedSegments: this.repairedSegments, + } + } + + /** Stop accepting records and await completion of the owned writer. */ + async close(): Promise { + this.closed = true + while (this.writing !== undefined) await this.writing + } + + /** + * Wait for queued records during shutdown or installer handoff without holding the application indefinitely. + * @param timeoutMs - Waiting budget before disabling the writer and cancelling subsequent I/O. + * @returns True after the queue settles successfully; false immediately when disabled, or on failure or deadline. + * False does not confirm that an issued OS request has settled. + */ + async drain(timeoutMs: number): Promise { + if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1) throw new RangeError('Invalid journal drain deadline') + if (this.disabled) return false + let timer: ReturnType | undefined + try { + return await Promise.race([ + (async () => { + while (this.writing !== undefined) await this.writing + return !this.disabled + })(), + new Promise((resolve) => { + timer = setTimeout(() => { + this.disabled = true + this.abort.abort() + resolve(false) + }, timeoutMs) + }), + ]) + } finally { + clearTimeout(timer) + } + } + + private startWriter(): void { + this.writing ??= this.writeQueue().finally(() => { + this.writing = undefined + if (this.queue.length > 0) this.startWriter() + }) + } + + private async writeQueue(): Promise { + try { + await mkdir(this.directory, { recursive: true, mode: 0o700 }) + this.abort.signal.throwIfAborted() + const current = join(this.directory, 'operations.jsonl') + const previous = join(this.directory, 'operations.previous.jsonl') + if (!this.initialized) { + await this.prepareSegments(current, previous) + this.initialized = true + } + for (let line = this.queue[0]; line !== undefined; line = this.queue[0]) { + this.abort.signal.throwIfAborted() + const bytes = Buffer.byteLength(line) + let size = 0 + try { + size = (await stat(current)).size + } + catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error + } + this.abort.signal.throwIfAborted() + if (size > this.limits.segmentBytes) { + // An oversized pre-existing segment is not copied into the bounded retained history. + await writeFile(current, '', { mode: 0o600 }) + this.repairedSegments++ + } else if (size + bytes > this.limits.segmentBytes) { + await rename(current, previous) + } + this.abort.signal.throwIfAborted() + await writeFile(current, line, { flag: 'a', mode: 0o600, signal: this.abort.signal }) + this.queue.shift() + this.queuedBytes -= bytes + } + } catch (_error) { + // A failed append may have written a partial line; disable this writer rather than concatenate another record. + this.disabled = true + this.failed += this.queue.length + this.queue.length = 0 + this.queuedBytes = 0 + } + } + + private async prepareSegments(current: string, previous: string): Promise { + try { + const size = (await stat(previous)).size + this.abort.signal.throwIfAborted() + if (size > this.limits.segmentBytes) { + await writeFile(previous, '', { mode: 0o600 }) + this.repairedSegments++ + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error + } + this.abort.signal.throwIfAborted() + { + await using handle = await open(current, 'r+').catch((error: unknown) => { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error + this.abort.signal.throwIfAborted() + return open(current, 'wx+', 0o600) + }) + this.abort.signal.throwIfAborted() + const size = (await handle.stat()).size + this.abort.signal.throwIfAborted() + if (size > this.limits.segmentBytes) { + await handle.truncate(0) + this.repairedSegments++ + } else if (size > 0) { + const byte = Buffer.alloc(1) + const read = await handle.read(byte, 0, 1, size - 1) + if (read.bytesRead !== 1 || byte[0] !== 10) { + const buffer = Buffer.alloc(size) + let offset = 0 + while (offset < size) { + this.abort.signal.throwIfAborted() + const chunk = await handle.read(buffer, offset, size - offset, offset) + if (chunk.bytesRead === 0) break + offset += chunk.bytesRead + } + this.abort.signal.throwIfAborted() + // Keep committed lines in both segments; only the unfinished append is discarded. + await handle.truncate(buffer.subarray(0, offset).lastIndexOf(10) + 1) + this.repairedSegments++ + } + } + } + this.abort.signal.throwIfAborted() + } +} diff --git a/apps/desktop/src/operation-report-job.ts b/apps/desktop/src/operation-report-job.ts new file mode 100644 index 0000000000..b78259df78 --- /dev/null +++ b/apps/desktop/src/operation-report-job.ts @@ -0,0 +1,106 @@ +/** Worker lifetime for an auxiliary report; completion includes worker exit. */ +import { Worker } from 'node:worker_threads' +import type { OperationReportLimits } from './operation-report.ts' +import type { OperationJournalStatus } from './operation-journal.ts' + +/** Facts passed to the isolated collector after the basic report is saved. */ +export interface OperationReportJobInput { + readonly reportPath: string + readonly directory: string + readonly limits: OperationReportLimits + readonly journal: OperationJournalStatus | null +} + +/** Collection and cooperative shutdown share one total budget. */ +export interface OperationReportJobOptions { + /** Deadline for requesting forced termination, including Worker startup. */ + readonly timeoutMs: number + /** Reserved part of timeoutMs for cancellation and resource cleanup. */ + readonly cancellationGraceMs: number +} + +/** Cancellation can leave a partial append; the independently saved basic report remains valid. */ +export interface OperationReportJobResult { + readonly appended: boolean + readonly timedOut: boolean + readonly cancelled: boolean +} + +/** + * Collect history, request cooperative cancellation, then force termination if cleanup exceeds its budget. + * @param input - Bounded collection request for an existing basic report. + * @param options - Total deadline and the cleanup window reserved within it. + * @param signal - Application shutdown or recovery cancellation; an already-aborted signal prevents startup. + * @returns Append outcome only after Worker exit; cancellation or termination requests alone do not confirm exit. + */ +export async function runOperationReportJob( + input: OperationReportJobInput, + options: OperationReportJobOptions, + signal: AbortSignal, +): Promise { + const { timeoutMs, cancellationGraceMs } = options + if (!Number.isSafeInteger(timeoutMs) || !Number.isSafeInteger(cancellationGraceMs) + || cancellationGraceMs < 1 || timeoutMs <= cancellationGraceMs) throw new RangeError('Invalid operation report deadlines') + if (signal.aborted) return { appended: false, timedOut: false, cancelled: true } + const terminationDeadline = performance.now() + timeoutMs + let worker: Worker + try { + worker = new Worker(new URL('./operation-report-worker.js', import.meta.url), { + workerData: input, + resourceLimits: { + maxOldGenerationSizeMb: 32, + maxYoungGenerationSizeMb: 8, + stackSizeMb: 2, + }, + }) + } + catch (_error) { + return { appended: false, timedOut: false, cancelled: false } + } + return new Promise((resolve) => { + let appended = false + let failed = false + let timedOut = false + let cancelled = false + let terminationTimer: ReturnType | undefined + + const terminateWorker = (): void => { + void worker.terminate().catch(() => { + failed = true + }) + } + + const requestCancellation = (): void => { + if (cancelled) return + cancelled = true + clearTimeout(collectionTimer) + try { + worker.postMessage('cancel') + } + catch (_error) { + failed = true + } + terminationTimer = setTimeout(terminateWorker, Math.max(0, Math.min(cancellationGraceMs, terminationDeadline - performance.now()))) + } + + const collectionTimer = setTimeout(() => { + timedOut = true + requestCancellation() + }, Math.max(0, terminationDeadline - performance.now() - cancellationGraceMs)) + + signal.addEventListener('abort', requestCancellation, { once: true }) + worker.on('message', (message: unknown) => { + appended = message === true + }) + worker.once('error', () => { + failed = true + }) + worker.once('exit', (code) => { + clearTimeout(collectionTimer) + clearTimeout(terminationTimer) + signal.removeEventListener('abort', requestCancellation) + resolve({ appended: appended && code === 0 && !failed && !cancelled, timedOut, cancelled }) + }) + if (signal.aborted) requestCancellation() + }) +} diff --git a/apps/desktop/src/operation-report-worker.ts b/apps/desktop/src/operation-report-worker.ts new file mode 100644 index 0000000000..c7ee527b77 --- /dev/null +++ b/apps/desktop/src/operation-report-worker.ts @@ -0,0 +1,36 @@ +/** Isolated auxiliary-report I/O; the shell owns termination and observes worker exit. */ +import { parentPort, workerData } from 'node:worker_threads' +import { z } from 'zod' +import { appendOperationReport } from './operation-report.ts' + +const positive = z.number().int().positive().max(Number.MAX_SAFE_INTEGER) +const input = z.object({ + reportPath: z.string(), + directory: z.string(), + limits: z.object({ + bytes: positive, + recordBytes: positive, + records: positive, + outputBytes: positive, + }), + journal: z.object({ + dropped: z.number().int().nonnegative(), + failed: z.number().int().nonnegative(), + repairedSegments: z.number().int().nonnegative(), + queuedBytes: z.number().int().nonnegative(), + disabled: z.boolean(), + }).nullable(), +}).parse(workerData) + +const cancellation = new AbortController() +const cancel = (message: unknown): void => { + if (message === 'cancel') cancellation.abort() +} +parentPort?.on('message', cancel) +try { + const appended = await appendOperationReport(input.reportPath, input.directory, input.limits, cancellation.signal, input.journal) + parentPort?.postMessage(appended) +} finally { + parentPort?.off('message', cancel) + parentPort?.close() +} diff --git a/apps/desktop/src/operation-report.ts b/apps/desktop/src/operation-report.ts new file mode 100644 index 0000000000..2c023abf82 --- /dev/null +++ b/apps/desktop/src/operation-report.ts @@ -0,0 +1,62 @@ +/** Best-effort operation history appended only after the independent basic report exists. */ +import { writeFile } from 'node:fs/promises' +import { setImmediate } from 'node:timers/promises' +import { readOperationHistory, type OperationHistoryReadLimits } from './operation-history.ts' +import type { OperationJournalStatus } from './operation-journal.ts' + +/** Read budgets and the complete appended section's UTF-8 byte budget. */ +export interface OperationReportLimits extends OperationHistoryReadLimits { + readonly outputBytes: number +} + +/** + * Append a bounded summary without rewriting the basic report's bytes. + * A missing completion marker means the auxiliary section is unavailable or incomplete. + * @param reportPath - Successfully saved basic report. + * @param directory - Owned operation history directory. + * @param limits - Read and parse budgets. + * @param signal - Collection deadline or shutdown cancellation; already-issued OS I/O must settle. + * @param journal - Current writer status, or null when this shell has not received operation records. + * @returns Whether the complete auxiliary section was appended. + */ +export async function appendOperationReport( + reportPath: string, + directory: string, + limits: OperationReportLimits, + signal: AbortSignal, + journal: OperationJournalStatus | null, +): Promise { + try { + if (!Number.isSafeInteger(limits.outputBytes) || limits.outputBytes < 1) return false + const cancelled = (): boolean => signal.aborted + const history = await readOperationHistory(directory, limits, signal) + if (cancelled()) return false + + const { records, ...facts } = history + const renderHeader = (omitted: number): string => '\n--- recent plugin operations (context, not proof of cause) ---\n' + + JSON.stringify({ journal, ...facts, outputRecordsOmitted: omitted }).slice(0, -1) + ',"records":[' + const completionFooter = ']}\n--- operation history collection complete; consult omission counters above ---\n' + let outputBytes = Buffer.byteLength(renderHeader(records.length) + completionFooter) + if (outputBytes > limits.outputBytes) return false + + const encodedRecords: string[] = [] + for (const record of records) { + await setImmediate() + if (cancelled()) return false + const encodedRecord = JSON.stringify(record) + const additionalBytes = Buffer.byteLength(encodedRecord) + (encodedRecords.length === 0 ? 0 : 1) + if (outputBytes + additionalBytes > limits.outputBytes) break + encodedRecords.push(encodedRecord) + outputBytes += additionalBytes + } + + const reportSection = renderHeader(records.length - encodedRecords.length) + encodedRecords.join(',') + completionFooter + await setImmediate() + if (cancelled()) return false + await writeFile(reportPath, reportSection, { flag: 'a', signal }) + return true + } catch (_error) { + // The independently written basic report remains usable, including after a partial append. + return false + } +} diff --git a/apps/desktop/src/runtime-tree.ts b/apps/desktop/src/runtime-tree.ts index dd7941d8e8..5bc8b758cf 100644 --- a/apps/desktop/src/runtime-tree.ts +++ b/apps/desktop/src/runtime-tree.ts @@ -89,7 +89,7 @@ export function inventoryDesktopRuntime(root: string): DesktopRuntimeFile[] { .sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0) } -async function inventoryRuntimeForVerification(root: string): Promise { +async function inventoryRuntimeConcurrently(root: string): Promise { const entries = runtimeFiles(root) const files: DesktopRuntimeFile[] = [] const remaining = entries.values() @@ -125,6 +125,31 @@ export function writeDesktopRuntime( root: string, release: DesktopRelease, sharedNames: readonly string[], target: { platform: NodeJS.Platform; arch: string } = process, ): DesktopRuntimeDescriptor { + return writeRuntimeDescriptor(root, { + ...runtimeMetadata(root, release, sharedNames, target), files: inventoryDesktopRuntime(root), + }) +} + +/** + * Seal a materialized runtime with bounded concurrent reads, draining readers before failure returns. + * @param root - Runtime output directory. + * @param release - Matching shell, dsh, Host, and executable versions. + * @param sharedNames - Release-owned packages supplied to plugins. + * @param target - Platform and architecture selected by runtime preparation. + * @returns Descriptor written after every final file has been inventoried. + */ +export async function writeDesktopRuntimeAsync( + root: string, release: DesktopRelease, sharedNames: readonly string[], + target: { platform: NodeJS.Platform; arch: string } = process, +): Promise { + const metadata = runtimeMetadata(root, release, sharedNames, target) + return writeRuntimeDescriptor(root, { ...metadata, files: await inventoryRuntimeConcurrently(root) }) +} + +function runtimeMetadata( + root: string, release: DesktopRelease, sharedNames: readonly string[], + target: { platform: NodeJS.Platform; arch: string }, +): Omit { const sharedPackages = [...new Set(sharedNames)].sort().map((name) => { if (!PACKAGE_NAME.test(name)) throw new Error(`desktop runtime: invalid shared package ${name}`) const path = `node_modules/${name}` @@ -134,10 +159,10 @@ export function writeDesktopRuntime( } return { name, version: manifest.version, path } }) - const descriptor: DesktopRuntimeDescriptor = { - schemaVersion: 1, release, platform: target.platform, arch: target.arch, - sharedPackages, files: inventoryDesktopRuntime(root), - } + return { schemaVersion: 1, release, platform: target.platform, arch: target.arch, sharedPackages } +} + +function writeRuntimeDescriptor(root: string, descriptor: DesktopRuntimeDescriptor): DesktopRuntimeDescriptor { writeFileSync(join(root, DESKTOP_RUNTIME_FILE), `${JSON.stringify(descriptor, undefined, 2)}\n`) return descriptor } @@ -203,7 +228,7 @@ export async function verifyDesktopRuntime( throw new Error(`desktop runtime: shared package metadata mismatch for ${entry.name}`) } } - const actual = await inventoryRuntimeForVerification(root) + const actual = await inventoryRuntimeConcurrently(root) // Windows has no portable Unix executable permission bits. const comparable = (items: readonly DesktopRuntimeFile[]): unknown => process.platform === 'win32' ? items.map(({ executable: _executable, ...item }) => item) : items diff --git a/apps/desktop/tests/README.i18n.yaml b/apps/desktop/tests/README.i18n.yaml index fbb1c7d3e9..97e9812489 100644 --- a/apps/desktop/tests/README.i18n.yaml +++ b/apps/desktop/tests/README.i18n.yaml @@ -2,27 +2,30 @@ # 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 apps/desktop/tests/README.md -/desktop-local-update-verification: - en: 194f1f0f1ca90743 - zh: 773ca28e04c8911f -/desktop-local-update-verification/summary: +/desktop-local-verification: + en: 5056a9b4d24c1880 + zh: 4d0c9d8e5f69d153 +/desktop-local-verification/summary: en: 94559f431b0b2151 zh: 1a22166a2bc59686 -/desktop-local-update-verification/table-of-contents: - en: 86afdf78fa613876 - zh: 66fad143d99e999f -/desktop-local-update-verification/update-dialog-themes: +/desktop-local-verification/table-of-contents: + en: fa9e3048995c0e3c + zh: ef30232afa4ba125 +/desktop-local-verification/fault-report-verification: + en: a418eb04ce93b1ee + zh: 1ec04872a66ce1b7 +/desktop-local-verification/update-dialog-themes: en: d086c3b38ce623f1 zh: 8327c31092f5f174 -/desktop-local-update-verification/native-overlay-visibility: +/desktop-local-verification/native-overlay-visibility: en: 6f4de4503748f3e2 zh: 648370375f16e463 -/desktop-local-update-verification/manual-walkthrough: +/desktop-local-verification/manual-walkthrough: en: c4b4ee8763d8464a zh: ee2159bc08966592 -/desktop-local-update-verification/evidence: +/desktop-local-verification/evidence: en: dcb2473264c825d4 zh: cebb2832efa15974 -/desktop-local-update-verification/open-verification: +/desktop-local-verification/open-verification: en: 20e9ea47acb1ff50 zh: acce24b56d57e12c diff --git a/apps/desktop/tests/README.md b/apps/desktop/tests/README.md index 400bfb0c00..cda4533699 100644 --- a/apps/desktop/tests/README.md +++ b/apps/desktop/tests/README.md @@ -1,4 +1,4 @@ -# Desktop local update verification +# Desktop local verification English | [中文](README.zh.md) @@ -10,12 +10,26 @@ Installed qualification can opt into `DSH_DESKTOP_UPDATE_JOURNAL_DIR`, an absolu ## Table of Contents +- [Fault-report verification](#verification-diagnostics) - [Update dialog themes](#verification-theme) - [Native overlay visibility](#verification-overlay) - [Evidence](#verification-evidence) - [Manual walkthrough](#verification-interactive) - [Open verification](#verification-open) + + +## Fault-report verification + +See [recovery and diagnostics](../docs/diagnostics/README.md) for product behavior and limitations. + +Use a disposable profile and separate Electron `userData` with the actual packaged client. Construct a minimal local bundle with `package.json`, `dsh.bundle.patch` pointing to `cordis.patch.yml`, and an optional plugin module; archive it as a local `.tgz`. These packages deliberately break the application and must not be published or installed in a daily profile. + +Exercise import and plugin-initialization exceptions, an asynchronous exception after `appReady`, and a nonzero Host exit. A patch disabling the `agent`, `session`, `llm`, and `tools` providers exercises missing-service diagnostics. To check cross-restart history, select that bundle through `pluginManager`, then restart the same profile. Runtime scenarios require observing actual client readiness; `appReady` alone does not establish that the window is visible. + +Check the original error and cause or exit code, operation and Host run IDs across restart, report-collection completion and omissions, file retrieval from the native dialog, and startup after plugin recovery. Record the package version and source commit; successful package generation or a management result alone does not establish client functionality. Restore protocol associations and stop test processes afterward. + +For resource checks, use large sparse history files, unrelated files, dense records, and malformed or unfinished lines. Measure setup separately from collection in fresh processes, recording actual bytes read, output size, time, and peak memory. To check Worker cancellation, a test-only module hook can hold an asynchronous file open after writing an entry marker. Confirm that marker, observe Worker exit after the deadline, and compare the basic report bytes. This does not reproduce a kernel-hung system call or establish packaged-client behavior. ## Update dialog themes diff --git a/apps/desktop/tests/README.zh.md b/apps/desktop/tests/README.zh.md index b52cf6309e..6cca69e8ac 100644 --- a/apps/desktop/tests/README.zh.md +++ b/apps/desktop/tests/README.zh.md @@ -1,4 +1,4 @@ -# Desktop 本地更新验证 +# Desktop 本地验证 [English](README.md) | 中文 @@ -10,12 +10,26 @@ ## 目录 +- [故障报告验证](#verification-diagnostics) - [更新弹窗主题](#verification-theme) - [原生浮层可见性](#verification-overlay) - [验证证据](#verification-evidence) - [手动演练](#verification-interactive) - [待验证事项](#verification-open) + + +## 故障报告验证 + +产品行为与限制见[故障恢复与诊断](../docs/diagnostics/README.zh.md)。 + +使用可丢弃的 profile、独立的 Electron `userData` 和实际打包客户端。构造最小本地组合包:`package.json` 的 `dsh.bundle.patch` 指向 `cordis.patch.yml`,需要执行代码时再加入插件模块,然后打成可本地安装的 `.tgz`。这些包会故意使应用出错,不得发布或安装到日常 profile。 + +分别构造模块导入异常、插件初始化异常、`appReady` 后的异步异常,以及 Host 非零退出。用 patch 禁用 `agent`、`session`、`llm`、`tools` 提供者,检查服务缺失诊断。跨重启场景通过 `pluginManager` 选入该组合包,再重启同一 profile。运行期场景须实际观察客户端就绪;`appReady` 不代表窗口已经显示。 + +检查原始错误与 cause 或退出码、跨重启的操作 ID 和 Host 运行 ID、报告收集完成标记与遗漏信息、原生弹窗中的文件获取,以及禁用插件恢复后的启动。记录安装包版本和源码提交;生成测试包成功或管理操作返回成功,都不能代替客户端功能验证。测试后恢复协议关联并退出测试进程。 + +资源验证可构造大型稀疏历史文件、大量无关文件、密集记录,以及损坏行和未完成行。在独立新进程中测量,分开记录数据构造与收集开销,并核对实际读取量、输出大小、耗时和峰值内存。验证 Worker 取消时,可用仅测试加载的模块钩子在写入进入标记后挂起异步文件打开操作;先确认标记,再观察期限到达后的 Worker 退出,并逐字节核对基本报告。该方法不模拟内核系统调用卡死,也不代替打包客户端验证。 ## 更新弹窗主题 diff --git a/apps/desktop/tests/desktop-build-paths.spec.ts b/apps/desktop/tests/desktop-build-paths.spec.ts index ede5c5e3d3..f9891ebb9c 100644 --- a/apps/desktop/tests/desktop-build-paths.spec.ts +++ b/apps/desktop/tests/desktop-build-paths.spec.ts @@ -1,10 +1,11 @@ -import { join, sep } from 'node:path' +import { join, resolve, sep } from 'node:path' import { describe, expect, it } from 'vitest' import { desktopTargetBuildPaths, desktopTargetPlatform, developmentRuntimeDirectory, resolveDesktopBuildTarget, + resolveDesktopTargetBuildPaths, } from '../scripts/desktop-build-paths.mjs' describe('desktop build paths', () => { @@ -35,11 +36,34 @@ describe('desktop build paths', () => { expect(windows.runtime).toContain(join('targets', 'win-x64', 'runtime')) }) - it('shares only the immutable upstream download cache', () => { + it('shares download and package caches outside target output directories', () => { const arm64 = desktopTargetBuildPaths('mac-arm64') const x64 = desktopTargetBuildPaths('mac-x64') expect(arm64.downloads).toBe(x64.downloads) expect(arm64.downloads).not.toContain(`${sep}targets${sep}`) + expect(arm64.pnpmStore).toBe(x64.pnpmStore) + expect(arm64.pnpmStore).not.toContain(`${sep}targets${sep}`) + }) + + it('retains target outputs while relocating caches through the supplied environment', () => { + const cache = resolve('external-package-cache') + const environment = { DSH_DESKTOP_PACKAGE_CACHE_DIR: cache } + const defaults = desktopTargetBuildPaths('win-x64', {}) + const paths = resolveDesktopTargetBuildPaths(environment, 'win32', 'x64') + expect(paths).toEqual({ ...defaults, downloads: join(cache, 'downloads'), pnpmStore: join(cache, 'pnpm-store') }) + expect(desktopTargetBuildPaths('mac-arm64', environment).pnpmStore).toBe(paths.pnpmStore) + for (const target of ['mac-arm64', 'mac-x64', 'win-x64'] as const) { + const configured = desktopTargetBuildPaths(target, environment) + expect(configured.downloads).toBe(join(cache, 'downloads')) + expect(configured.pnpmStore).toBe(join(cache, 'pnpm-store')) + expect(configured.root).not.toContain(cache) + } + expect(defaults.pnpmStore).toBe(resolve(defaults.root, '../..', 'pnpm-store')) + }) + + it.each(['', ' ', 'relative/cache', './cache', 'cache\0invalid'])('rejects invalid cache directory %j', (directory) => { + expect(() => desktopTargetBuildPaths('win-x64', { DSH_DESKTOP_PACKAGE_CACHE_DIR: directory })) + .toThrow('DSH_DESKTOP_PACKAGE_CACHE_DIR') }) it('resolves the development primary runtime from the build target rather than the host architecture', () => { diff --git a/apps/desktop/tests/desktop-package-environment.spec.ts b/apps/desktop/tests/desktop-package-environment.spec.ts index 6116cb718a..a8d79a2c96 100644 --- a/apps/desktop/tests/desktop-package-environment.spec.ts +++ b/apps/desktop/tests/desktop-package-environment.spec.ts @@ -1,4 +1,4 @@ -import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it } from 'vitest' @@ -23,6 +23,85 @@ async function withDirectory(action: (directory: string) => Promise): Prom } describe('Desktop local packaging configuration', () => { + it('loads file-owned compression and defaults to fast Windows archive compression', async () => { + expect(resolveWindowsPackageSettings({}).compressionLevel).toBe(3) + await withDirectory(async (directory) => { + await writeFile(join(directory, '.env.windows'), 'DSH_DESKTOP_WINDOWS_COMPRESSION_LEVEL=3\n') + const selected = loadDesktopPackageEnvironment('win32', { DSH_DESKTOP_WINDOWS_COMPRESSION_LEVEL: '0' }, directory) + expect(resolveWindowsPackageSettings(selected).compressionLevel).toBe(3) + }) + }) + + it.each(['3', '7'])('applies an explicit Windows workflow compression override %s', async (value) => { + await withDirectory(async (directory) => { + await writeFile(join(directory, '.env.windows'), 'DSH_DESKTOP_WINDOWS_COMPRESSION_LEVEL=5\n') + const selected = loadDesktopPackageEnvironment('win32', { PACKAGE_WINDOWS_COMPRESSION_LEVEL: value }, directory) + expect(resolveWindowsPackageSettings(selected).compressionLevel).toBe(Number(value)) + const unchanged = loadDesktopPackageEnvironment('win32', { PACKAGE_WINDOWS_COMPRESSION_LEVEL: '' }, directory) + expect(resolveWindowsPackageSettings(unchanged).compressionLevel).toBe(5) + }) + }) + + it.each(['0', '5', '7', '9'])('retains explicit Windows file compression %s outside the workflow', async (value) => { + await withDirectory(async (directory) => { + await writeFile(join(directory, '.env.windows'), `DSH_DESKTOP_WINDOWS_COMPRESSION_LEVEL=${value}\n`) + expect(resolveWindowsPackageSettings(loadDesktopPackageEnvironment('win32', {}, directory)).compressionLevel).toBe(Number(value)) + }) + }) + + it('keeps the legacy builder override below the file-owned Windows setting', () => { + expect(resolveWindowsPackageSettings({ ELECTRON_BUILDER_COMPRESSION_LEVEL: '7' }).compressionLevel).toBe(7) + expect(resolveWindowsPackageSettings({ ELECTRON_BUILDER_COMPRESSION_LEVEL: '7', DSH_DESKTOP_WINDOWS_COMPRESSION_LEVEL: '3' }).compressionLevel).toBe(3) + }) + + it.each(['test', 'production'])('uses the same Windows compression defaults and overrides for %s', async (preset) => { + await withDirectory(async (directory) => { + await mkdir(join(directory, 'presets')) + const path = join(directory, 'presets', `${preset}.env`) + const parent = { DSH_PACKAGING_CONFIG_DIR: directory, DSH_PACKAGING_PRESET: preset } + await writeFile(path, `DSH_DESKTOP_AUTO_UPDATE_ENV=${preset}\n`) + const load = (environment: NodeJS.ProcessEnv) => resolveWindowsPackageSettings( + loadDesktopPackageEnvironment('win32', environment, directory, { unsigned: true }), + ).compressionLevel + expect(load(parent)).toBe(3) + await writeFile(path, `DSH_DESKTOP_AUTO_UPDATE_ENV=${preset}\nDSH_DESKTOP_WINDOWS_COMPRESSION_LEVEL=9\n`) + expect(load(parent)).toBe(9) + expect(load({ ...parent, PACKAGE_WINDOWS_COMPRESSION_LEVEL: '3' })).toBe(3) + expect(load({ ...parent, PACKAGE_WINDOWS_COMPRESSION_LEVEL: '7' })).toBe(7) + }) + }) + + it.each([' ', '0', '5', '9', '-1', '10', '3.5', '03', 'fast'])('rejects invalid workflow compression %j before reading settings', (value) => { + expect(() => loadDesktopPackageEnvironment('win32', { PACKAGE_WINDOWS_COMPRESSION_LEVEL: value }, 'missing-settings')) + .toThrow('PACKAGE_WINDOWS_COMPRESSION_LEVEL') + }) + + it('rejects a Windows compression override for macOS before reading settings', () => { + expect(() => loadDesktopPackageEnvironment('darwin', { PACKAGE_WINDOWS_COMPRESSION_LEVEL: '3' }, 'missing-settings')) + .toThrow('PACKAGE_WINDOWS_COMPRESSION_LEVEL') + }) + it.each(['', '-1', '10', '3.5', '03', 'fast'])('rejects invalid compression %j before preparation', (value) => { + const selected = { ...RELEASE, DSH_DESKTOP_WINDOWS_COMPRESSION_LEVEL: value } + expect(() => { validateDesktopPackageEnvironment(selected, WINDOWS, { unsigned: true }) }) + .toThrow('COMPRESSION_LEVEL') + }) + + it.each(['', ' ', 'relative/cache'])('rejects invalid package caches before any signing mode %j', (directory) => { + for (const target of [WINDOWS, MACOS]) { + for (const options of [{ unsigned: true }, { prepareOnly: true }, {}]) { + expect(() => { validateDesktopPackageEnvironment({ DSH_DESKTOP_PACKAGE_CACHE_DIR: directory }, target, options) }) + .toThrow('DSH_DESKTOP_PACKAGE_CACHE_DIR') + } + } + }) + + it('preserves the machine package cache when loading a release file', async () => { + await withDirectory(async (directory) => { + await writeFile(join(directory, '.env.windows'), '') + expect(loadDesktopPackageEnvironment('win32', { DSH_DESKTOP_PACKAGE_CACHE_DIR: directory }, directory)) + .toEqual({ DSH_DESKTOP_PACKAGE_CACHE_DIR: directory }) + }) + }) it('selects macOS local defaults while excluding inherited release settings and retaining build networking', () => { const parent = { PATH: 'build-tools', HTTPS_PROXY: 'http://proxy.example:8080', DSH_DESKTOP_NPM_REGISTRY: 'https://registry.npmmirror.com', @@ -272,3 +351,40 @@ it('skips Apple credentials but still requires signing credentials for unnotariz }).toThrow(/CSC_KEY_PASSWORD/u) }) }) + +it('takes ZIP compression from the Mac file instead of ambient release settings', async () => { + await withDirectory(async (directory) => { + await writeFile(join(directory, '.env.macos'), 'DSH_DESKTOP_MACOS_ZIP_COMPRESSION_LEVEL=5\n') + const loaded = loadDesktopPackageEnvironment('darwin', { DSH_DESKTOP_MACOS_ZIP_COMPRESSION_LEVEL: '9' }, directory) + expect(loaded.DSH_DESKTOP_MACOS_ZIP_COMPRESSION_LEVEL).toBe('5') + await writeFile(join(directory, '.env.macos'), '') + expect(loadDesktopPackageEnvironment('darwin', { DSH_DESKTOP_MACOS_ZIP_COMPRESSION_LEVEL: '9' }, directory)) + .not.toHaveProperty('DSH_DESKTOP_MACOS_ZIP_COMPRESSION_LEVEL') + }) +}) + +it.each(['', 'relative-cache'])('rejects invalid build cache paths during preflight (%s)', (cache) => { + expect(() => { validateDesktopPackageEnvironment({ ...RELEASE, DSH_DESKTOP_PACKAGE_CACHE_DIR: cache }, MACOS, { unsigned: true }) }) + .toThrow('DSH_DESKTOP_PACKAGE_CACHE_DIR must be a nonempty absolute directory') +}) + +it.each(['3', '7'])('applies the workflow ZIP choice %s over the Mac file setting', async (level) => { + await withDirectory(async (directory) => { + await writeFile(join(directory, '.env.macos'), 'DSH_DESKTOP_MACOS_ZIP_COMPRESSION_LEVEL=5\n') + const loaded = loadDesktopPackageEnvironment('darwin', { PACKAGE_MACOS_ZIP_COMPRESSION_LEVEL: level }, directory) + expect(loaded.DSH_DESKTOP_MACOS_ZIP_COMPRESSION_LEVEL).toBe(level) + }) +}) + +it.each(['', '3', '7'])('rejects Mac workflow ZIP choice %j on Windows before reading settings', (level) => { + expect(() => loadDesktopPackageEnvironment('win32', { PACKAGE_MACOS_ZIP_COMPRESSION_LEVEL: level }, 'missing-settings')) + .toThrow('PACKAGE_MACOS_ZIP_COMPRESSION_LEVEL requires macOS') +}) + +it.each(['', '0', '9', 'invalid'])('rejects unsupported workflow ZIP choice %j', async (level) => { + await withDirectory(async (directory) => { + await writeFile(join(directory, '.env.macos'), '') + expect(() => loadDesktopPackageEnvironment('darwin', { PACKAGE_MACOS_ZIP_COMPRESSION_LEVEL: level }, directory)) + .toThrow('workflow ZIP compression must be 3 or 7') + }) +}) diff --git a/apps/desktop/tests/expected/fatal-address-in-use-en.txt b/apps/desktop/tests/expected/fatal-address-in-use-en.txt index 1e9a9b62d0..fff3b98aec 100644 --- a/apps/desktop/tests/expected/fatal-address-in-use-en.txt +++ b/apps/desktop/tests/expected/fatal-address-in-use-en.txt @@ -1,5 +1,6 @@ DeepSeek Harness is unavailable The application could not start or stopped unexpectedly. Another DSH instance (such as dsh web or the desktop app) is running. They cannot start at the same time. Quit the other running DSH instance, then restart. +The diagnostic report could not be saved. You can provide a screenshot of this dialog when requesting support. Exit Restart diff --git a/apps/desktop/tests/expected/fatal-address-in-use-zh-CN.txt b/apps/desktop/tests/expected/fatal-address-in-use-zh-CN.txt index 30cad3d061..7c6e3dbc61 100644 --- a/apps/desktop/tests/expected/fatal-address-in-use-zh-CN.txt +++ b/apps/desktop/tests/expected/fatal-address-in-use-zh-CN.txt @@ -1,5 +1,6 @@ DeepSeek Harness 无法使用 应用无法启动或已意外停止。 有其他正在运行的 DSH(如其他 dsh web、桌面端),无法同时启动,请退出其他正在运行的 DSH 后重启。 +诊断报告未能保存,反馈问题时可提供此窗口的截图。 退出 重启 diff --git a/apps/desktop/tests/expected/fatal-dialog-en.txt b/apps/desktop/tests/expected/fatal-dialog-en.txt index 0dd0a62eb3..72cc858a1c 100644 --- a/apps/desktop/tests/expected/fatal-dialog-en.txt +++ b/apps/desktop/tests/expected/fatal-dialog-en.txt @@ -2,6 +2,7 @@ DeepSeek Harness is unavailable The application could not start or stopped unexpectedly. Desktop Host failed Plugin initialization failed +The diagnostic report could not be saved. You can provide a screenshot of this dialog when requesting support. If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately. Exit diff --git a/apps/desktop/tests/expected/fatal-dialog-with-report-en.txt b/apps/desktop/tests/expected/fatal-dialog-with-report-en.txt index aaa637ca1a..89745ea803 100644 --- a/apps/desktop/tests/expected/fatal-dialog-with-report-en.txt +++ b/apps/desktop/tests/expected/fatal-dialog-with-report-en.txt @@ -8,3 +8,4 @@ If application files are missing or damaged, close the application and reinstall Exit Restart Disable third-party plugins, back up profile patch, and restart +Get diagnostic report diff --git a/apps/desktop/tests/expected/fatal-dialog-with-report-zh-CN.txt b/apps/desktop/tests/expected/fatal-dialog-with-report-zh-CN.txt index 353b59f4a4..610b96c509 100644 --- a/apps/desktop/tests/expected/fatal-dialog-with-report-zh-CN.txt +++ b/apps/desktop/tests/expected/fatal-dialog-with-report-zh-CN.txt @@ -8,3 +8,4 @@ Plugin initialization failed 退出 重启 禁用第三方插件、备份 profile patch 并重启 +获取诊断报告 diff --git a/apps/desktop/tests/expected/fatal-dialog-zh-CN.txt b/apps/desktop/tests/expected/fatal-dialog-zh-CN.txt index 6c40644c09..c8db153ae1 100644 --- a/apps/desktop/tests/expected/fatal-dialog-zh-CN.txt +++ b/apps/desktop/tests/expected/fatal-dialog-zh-CN.txt @@ -2,6 +2,7 @@ DeepSeek Harness 无法使用 应用无法启动或已意外停止。 Desktop Host failed Plugin initialization failed +诊断报告未能保存,反馈问题时可提供此窗口的截图。 如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。 退出 diff --git a/apps/desktop/tests/expected/operation-history.txt b/apps/desktop/tests/expected/operation-history.txt new file mode 100644 index 0000000000..7ce5170211 --- /dev/null +++ b/apps/desktop/tests/expected/operation-history.txt @@ -0,0 +1,4 @@ + +--- recent plugin operations (context, not proof of cause) --- +{"journal":null,"bytesRead":260,"filesRead":1,"truncated":false,"invalidRecords":0,"unavailableFiles":0,"cancelled":false,"outputRecordsOmitted":0,"records":[{"runId":"c254ab28-97c9-4382-95e6-2db9c66f98c8","operation":{"id":"c254ab28-97c9-4382-95e6-2db9c66f98c9","time":"2026-10-19T00:00:00.000Z","reason":"bundle","target":"test-bundle","stage":"enable","phase":"started"},"transportDropped":0}]} +--- operation history collection complete; consult omission counters above --- diff --git a/apps/desktop/tests/fatal-recovery.spec.ts b/apps/desktop/tests/fatal-recovery.spec.ts index 7ab4efd68a..80f75c2cef 100644 --- a/apps/desktop/tests/fatal-recovery.spec.ts +++ b/apps/desktop/tests/fatal-recovery.spec.ts @@ -17,6 +17,7 @@ function fixture( disablePlugins: vi.fn(async () => {}), exit: vi.fn(), restart: vi.fn(), + revealReport: vi.fn(async (_path: string) => {}), writeReport: vi.fn(writeReport), } return { operations, choice, stopped, recovery: new DesktopFatalRecovery(operations) } @@ -31,14 +32,16 @@ const REPORT_PATH = 'C:\\Users\\someone\\AppData\\Roaming\\DeepSeek Harness\\log afterEach(() => { vi.restoreAllMocks() }) -it.each(['en', 'zh-CN'])('offers only exit and restart for a listener conflict in %s', async (locale) => { +it.each(['en', 'zh-CN'])('offers exit and restart for a listener conflict without a saved report in %s', async (locale) => { const { operations, choice, stopped, recovery } = fixture(locale) const pending = recovery.report(new AggregateError([ new Error('webserver (@deepseek-ai/dsh-host-webserver): Error: listen EADDRINUSE: address already in use 127.0.0.1:19387'), ], 'required startup failure'), 'host') await shown(operations) const options = operations.show.mock.calls[0]![0] - expect(options.buttons).toEqual([operations.messages().exitApplication, operations.messages().restartApplication]) + expect(options.buttons).toEqual([ + operations.messages().exitApplication, operations.messages().restartApplication, + ]) await expect([options.title, options.message, options.detail, ...options.buttons!].join('\n') + '\n') .toMatchFileSnapshot(`expected/fatal-address-in-use-${locale}.txt`) choice.resolve({ response: 1, checkboxChecked: false }) @@ -56,7 +59,7 @@ it.each(['win32', 'darwin', 'linux'] as const)('offers the same listener conflic expect(operations.show.mock.calls[0]![0].buttons).toEqual([ operations.messages().exitApplication, operations.messages().restartApplication, ]) - expect(operations.show.mock.calls[0]![0].detail).toBe(operations.messages().startupAddressInUse) + expect(operations.show.mock.calls[0]![0].detail).toBe(`${operations.messages().startupAddressInUse}\n${operations.messages().reportUnavailable}`) choice.resolve({ response: 0, checkboxChecked: false }) stopped.resolve(undefined) await pending @@ -188,7 +191,7 @@ it('names the report file in the listener-conflict dialog too', async () => { await shown(operations) await vi.waitFor(() => { expect(operations.show).toHaveBeenCalledOnce() }) const options = operations.show.mock.calls[0]![0] - expect(options.buttons).toHaveLength(2) + expect(options.buttons).toHaveLength(3) expect(options.detail).toBe(`${operations.messages().startupAddressInUse}\n${operations.messages().reportWrittenTo.replace('{path}', REPORT_PATH)}`) choice.resolve({ response: 0, checkboxChecked: false }) stopped.resolve(undefined) @@ -202,7 +205,7 @@ it('shows the dialog without a path when the report write fails or returns nothi const pending = recovery.report(new Error('fatal'), 'main') await shown(operations) await vi.waitFor(() => { expect(operations.show).toHaveBeenCalledOnce() }) - expect(operations.show.mock.calls[0]![0].detail).toBe(`fatal\n\n${operations.messages().startupReinstallAdvice}`) + expect(operations.show.mock.calls[0]![0].detail).toBe(`fatal\n${operations.messages().reportUnavailable}\n\n${operations.messages().startupReinstallAdvice}`) choice.resolve({ response: 0, checkboxChecked: false }) stopped.resolve(undefined) await pending @@ -239,3 +242,110 @@ it('writes the report once for the first fatal failure and not for the recovery- expect(operations.writeReport).toHaveBeenCalledOnce() expect(operations.show.mock.calls[1]![0].detail).toContain(REPORT_PATH) }) + +it('reveals the saved report without stopping the Host or restarting', async () => { + const { operations, stopped, recovery } = fixture('en', async () => REPORT_PATH) + operations.show.mockResolvedValueOnce({ response: 3, checkboxChecked: false }) + .mockImplementationOnce(async () => { + expect(operations.revealReport).toHaveBeenCalledWith(REPORT_PATH) + expect(operations.stop).not.toHaveBeenCalled() + expect(operations.restart).not.toHaveBeenCalled() + return { response: 0, checkboxChecked: false } + }) + stopped.resolve(undefined) + await recovery.report(new Error('fatal'), 'host') + expect(operations.writeReport).toHaveBeenCalledOnce() + expect(operations.show.mock.calls[1]![0].message).toBe(operations.messages().reportShareHint) +}) + +it('keeps the original failure and report path when revealing the file fails', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const { operations, stopped, recovery } = fixture('en', async () => REPORT_PATH) + operations.revealReport.mockRejectedValueOnce(new Error('file removed')) + operations.show.mockResolvedValueOnce({ response: 3, checkboxChecked: false }) + .mockResolvedValueOnce({ response: 0, checkboxChecked: false }) + stopped.resolve(undefined) + await recovery.report(new Error('original startup failure'), 'host') + expect(operations.show.mock.calls[1]![0]).toMatchObject({ message: operations.messages().reportRevealFailed }) + expect(operations.show.mock.calls[1]![0].detail).toContain('original startup failure') + expect(operations.show.mock.calls[1]![0].detail).toContain(REPORT_PATH) +}) + +it('makes a report that finishes after the initial deadline available without rewriting it', async () => { + vi.useFakeTimers() + try { + const write = Promise.withResolvers() + const { operations, choice, stopped, recovery } = fixture('en', () => write.promise) + const pending = recovery.report(new Error('fatal'), 'host') + await vi.advanceTimersByTimeAsync(CRASH_REPORT_WAIT_MS) + expect(operations.show.mock.calls[0]![0].detail).toContain(operations.messages().reportPending) + operations.show.mockResolvedValueOnce({ response: 0, checkboxChecked: false }) + write.resolve(REPORT_PATH) + choice.resolve({ response: 3, checkboxChecked: false }) + stopped.resolve(undefined) + await pending + expect(operations.revealReport).toHaveBeenCalledWith(REPORT_PATH) + expect(operations.writeReport).toHaveBeenCalledOnce() + } finally { + vi.useRealTimers() + } +}) + +it('does not attempt to reveal an unavailable report', async () => { + const { operations, stopped, recovery } = fixture() + operations.show.mockResolvedValueOnce({ response: 0, checkboxChecked: false }) + stopped.resolve(undefined) + await recovery.report(new Error('fatal'), 'host') + expect(operations.revealReport).not.toHaveBeenCalled() + expect(operations.show.mock.calls[0]![0].buttons).not.toContain(operations.messages().getDiagnosticReport) + expect(operations.show.mock.calls[0]![0].detail).toContain(operations.messages().reportUnavailable) +}) + +it.each(['pending', 'failed'] as const)('keeps the recovery failure visible when fetching a %s report', async (state) => { + vi.useFakeTimers() + vi.spyOn(console, 'error').mockImplementation(() => {}) + const write = Promise.withResolvers() + try { + const { operations, stopped, recovery } = fixture('en', () => write.promise) + stopped.resolve(undefined) + operations.disablePlugins.mockRejectedValueOnce(new Error('profile is read-only')) + operations.show.mockResolvedValueOnce({ response: 2, checkboxChecked: false }) + .mockImplementationOnce(async () => { + if (state === 'failed') write.resolve(undefined) + return { response: 3, checkboxChecked: false } + }) + .mockResolvedValueOnce({ response: 0, checkboxChecked: false }) + const pending = recovery.report(new Error('original startup failure'), 'host') + await vi.runAllTimersAsync() + await pending + expect(operations.show).toHaveBeenCalledTimes(3) + const last = operations.show.mock.calls[2]![0] + expect(last.message).toBe(operations.messages().recoveryOperationFailed) + expect(last.detail).toContain('profile is read-only') + if (state === 'failed') expect(last.buttons).not.toContain(operations.messages().getDiagnosticReport) + expect(last.detail).toContain(state === 'pending' ? operations.messages().reportPending : operations.messages().reportUnavailable) + expect(operations.revealReport).not.toHaveBeenCalled() + expect(operations.writeReport).toHaveBeenCalledOnce() + } finally { + write.resolve(undefined) + vi.useRealTimers() + } +}) + +it.each([false, true])('keeps the original attachment when revealing after a recovery failure (reveal fails=%s)', async (revealFails) => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const { operations, stopped, recovery } = fixture('en', async () => REPORT_PATH) + const original = new Error('original startup failure') + stopped.resolve(undefined) + operations.disablePlugins.mockRejectedValueOnce(new Error('profile is read-only')) + if (revealFails) operations.revealReport.mockRejectedValueOnce(new Error('file manager unavailable')) + operations.show.mockResolvedValueOnce({ response: 2, checkboxChecked: false }) + .mockResolvedValueOnce({ response: 3, checkboxChecked: false }) + .mockResolvedValueOnce({ response: 0, checkboxChecked: false }) + await recovery.report(original, 'host') + const last = operations.show.mock.calls[2]![0] + expect(last.message).toBe(revealFails ? operations.messages().reportRevealFailed : operations.messages().reportShareHint) + expect(last.detail).toContain('profile is read-only') + expect(operations.writeReport).toHaveBeenCalledExactlyOnceWith(original, 'host') + expect(operations.revealReport).toHaveBeenCalledExactlyOnceWith(REPORT_PATH) +}) diff --git a/apps/desktop/tests/fixtures/windows-token-public-key-fake.cs b/apps/desktop/tests/fixtures/windows-token-public-key-fake.cs new file mode 100644 index 0000000000..9d2c1342f9 --- /dev/null +++ b/apps/desktop/tests/fixtures/windows-token-public-key-fake.cs @@ -0,0 +1,49 @@ + +public sealed class FakeTokenPublicKey : DshTokenPublicKey.IApi +{ + string scenario; + int releases, destroys, exports, keys; + public FakeTokenPublicKey(string value) { scenario = value; } + public int Acquire(string container, out System.IntPtr context) { + if (container != "fake-container") throw new System.Exception("unexpected container"); + context = new System.IntPtr(1); + if (scenario == "provider") return unchecked((int)0x80090013); + if (scenario == "container") return unchecked((int)0x80090016); + if (scenario == "auth") return unchecked((int)0x80090022); + return 0; + } + public int GetKey(System.IntPtr context, uint spec, out System.IntPtr key) { + keys++; + key = new System.IntPtr(2); + if (scenario == "no-key" || spec == 1) return DshTokenPublicKey.NoKey; + if (scenario == "get-key") return 5; + return 0; + } + public int Export(System.IntPtr key, byte[] bytes, ref uint length) { + exports++; + if (scenario == "export") return 5; + if (scenario == "size") { length = 1000000; return 0; } + length = 24; + return 0; + } + public bool Destroy(System.IntPtr key) { destroys++; return scenario != "destroy"; } + public bool Release(System.IntPtr context) { releases++; return scenario != "release"; } + public static string Test() { + if (DshTokenPublicKey.PublicContextFlags != 0xF0000040) throw new System.Exception("unsafe flags"); + foreach (string scenario in new [] { "ok", "provider", "container", "auth", "no-key", "get-key", "export", "size", "destroy", "release" }) { + var fake = new FakeTokenPublicKey(scenario); + var result = DshTokenPublicKey.Read(fake, "fake-container"); + string expected = scenario == "ok" ? "public-keys" : scenario == "provider" ? "provider-unavailable" + : scenario == "container" ? "container-unavailable" : "unknown"; + if (result.status != expected) throw new System.Exception("wrong outcome: " + scenario); + bool acquired = scenario != "provider" && scenario != "container" && scenario != "auth"; + if (fake.releases != (acquired ? 1 : 0)) throw new System.Exception("context leak: " + scenario); + bool hasKey = acquired && scenario != "no-key" && scenario != "get-key"; + if (fake.destroys != (hasKey ? 1 : 0)) throw new System.Exception("key leak: " + scenario); + if (!acquired && fake.keys != 0) throw new System.Exception("read after failed acquire"); + if (scenario == "ok" && (fake.exports != 2 || fake.keys != 2)) throw new System.Exception("incomplete read"); + if (result.status != "public-keys" && result.publicKeys.Length != 0) throw new System.Exception("partial result escaped"); + } + return "fake CSP cases passed"; + } +} diff --git a/apps/desktop/tests/helpers/windows-signing-corpus.ts b/apps/desktop/tests/helpers/windows-signing-corpus.ts new file mode 100644 index 0000000000..c12b936422 --- /dev/null +++ b/apps/desktop/tests/helpers/windows-signing-corpus.ts @@ -0,0 +1,52 @@ +/** Snapshot operator-selected release files into unsigned, hash-pinned experiment inputs. */ +import { createHash } from 'node:crypto' +import { copyFile, lstat, mkdir, readFile } from 'node:fs/promises' +import { extname, isAbsolute, join } from 'node:path' +import { inspectWindowsRuntimeSignature } from '../../scripts/windows-runtime-signature.mjs' + +/** One immutable unsigned input; its source is never modified or executed. */ +export interface SigningCorpusFile { + readonly path: string + readonly sha256: string + readonly bytes: number +} + +/** + * Copy a nonempty JSON array of absolute paths and SHA-256 digests, then strip signatures only on copies. + * @param manifestPath Operator-owned JSON manifest; every source must be a regular file with the pinned digest. + * @param directory New private directory for retained unsigned templates. + * @param removeSignature Public SignTool removal operation; never receives an original source path. + * @param signal Stops preparation before the next file when aborted. + * @returns Unsigned template digests and sizes in manifest order; rejects invalid signatures or changed inputs. + */ +export async function prepareSigningCorpus( + manifestPath: string, directory: string, removeSignature: (path: string) => Promise, signal: AbortSignal, +): Promise { + const manifest: unknown = JSON.parse(await readFile(manifestPath, 'utf8')) + if (!Array.isArray(manifest) || manifest.length === 0) throw new Error('Signing corpus must be a nonempty JSON array') + const inputs = manifest.map((entry: unknown) => { + if (typeof entry !== 'object' || entry === null || !('path' in entry) || typeof entry.path !== 'string' + || !isAbsolute(entry.path) || !('sha256' in entry) || typeof entry.sha256 !== 'string' + || !/^[a-f0-9]{64}$/u.test(entry.sha256)) throw new Error('Signing corpus requires absolute paths and lowercase SHA-256 digests') + return { path: entry.path, sha256: entry.sha256 } + }) + await mkdir(directory) + const result: SigningCorpusFile[] = [] + for (const [index, input] of inputs.entries()) { + signal.throwIfAborted() + const stat = await lstat(input.path) + if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('Signing corpus source must be a regular file') + const path = join(directory, `${index}${extname(input.path) || '.exe'}`) + await copyFile(input.path, path) + if (createHash('sha256').update(await readFile(path)).digest('hex') !== input.sha256) { + throw new Error('Signing corpus source differs from its pinned digest') + } + const before = await inspectWindowsRuntimeSignature(path) + if (before.status === 'Valid') await removeSignature(path) + else if (before.status !== 'NotSigned') throw new Error('Signing corpus source has an invalid signature') + if ((await inspectWindowsRuntimeSignature(path)).status !== 'NotSigned') throw new Error('Signing corpus copy must be unsigned') + const content = await readFile(path) + result.push({ path, sha256: createHash('sha256').update(content).digest('hex'), bytes: content.length }) + } + return result +} diff --git a/apps/desktop/tests/helpers/windows-signing-experiment.ts b/apps/desktop/tests/helpers/windows-signing-experiment.ts new file mode 100644 index 0000000000..f9ccac9eda --- /dev/null +++ b/apps/desktop/tests/helpers/windows-signing-experiment.ts @@ -0,0 +1,70 @@ +/** Bounded scheduling for the opt-in signing experiment; production signing does not use this helper. */ + +/** Operations owned by one experiment, with independently bounded completion and hardware work. */ +export interface SigningExperimentOptions { + readonly jobs: 1 | 2 | 4 + readonly hardwareConcurrency: 1 | 2 | 4 + readonly signal?: AbortSignal + /** Complete one item, awaiting the supplied signing operation and all subsequent work before returning. */ + readonly complete: (item: T, sign: (path: string) => Promise) => Promise + /** Perform one hardware request without retrying it. */ + readonly sign: (item: T, path: string) => Promise +} + +/** + * Schedule independent experiment items and stop dispatch on the first failure or cancellation. + * @param items Ordered inputs owned by this batch. + * @param options Completion workers, hardware limit, cancellation and experiment operations. + * @returns Resolves after every item completes; otherwise drains issued work before rejecting with the first reason. + * Cancellation prevents new items and hardware requests but does not terminate an issued native operation. + */ +export async function runSigningExperimentBatch(items: readonly T[], options: SigningExperimentOptions): Promise { + let failure: { reason: unknown } | undefined + let next = 0 + let signing = 0 + const requests = new Set>() + const waiting = new Set<() => void>() + const wake = (): void => { + for (const resume of waiting) resume() + waiting.clear() + } + const stop = (reason: unknown): void => { + failure ??= { reason } + wake() + } + const aborted = (): void => { stop(options.signal?.reason) } + const signItem = async (item: T, path: string): Promise => { + while (failure === undefined && signing >= options.hardwareConcurrency) { + await new Promise((resume) => { waiting.add(resume) }) + } + if (failure !== undefined) throw failure.reason + signing++ + try { await options.sign(item, path) } + catch (error) { stop(error); throw error } + finally { signing--; wake() } + } + const worker = async (): Promise => { + while (failure === undefined && next < items.length) { + const item = items[next++]! + try { + await options.complete(item, (path) => { + const request = signItem(item, path) + requests.add(request) + void request.then(() => requests.delete(request), () => requests.delete(request)) + return request + }) + } + catch (error) { stop(error) } + } + } + options.signal?.addEventListener('abort', aborted, { once: true }) + try { + if (options.signal?.aborted) aborted() + await Promise.all(Array.from({ length: Math.min(options.jobs, items.length) }, worker)) + // A completion failure can leave a previously issued request awaiting its native result. + await Promise.allSettled(requests) + if (failure !== undefined) throw failure.reason + } finally { + options.signal?.removeEventListener('abort', aborted) + } +} diff --git a/apps/desktop/tests/host-process.spec.ts b/apps/desktop/tests/host-process.spec.ts index 93b5f9bce2..9a72fd2925 100644 --- a/apps/desktop/tests/host-process.spec.ts +++ b/apps/desktop/tests/host-process.spec.ts @@ -1,8 +1,11 @@ import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { DesktopHostFatalError, DesktopHostProcess, DesktopHostUncleanExitError, QUIT_INSPECTION_DEADLINE_MS } from '../src/host-process.ts' +import { OperationJournal } from '../src/operation-journal.ts' +import { readOperationHistory } from '../src/operation-history.ts' +import { renderCrashReport } from '../src/crash-report.ts' const roots: string[] = [] const hosts: DesktopHostProcess[] = [] @@ -88,6 +91,85 @@ afterEach(async () => { }) describe('desktop host process', () => { + it('retains the announced run identity when startup fails before readiness', async () => { + const runtime = projectWithHost(` +process.send({ type: 'starting', runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8' }) +process.send({ type: 'fatal', message: 'profile startup failed', diagnostic: 'required plugin failed' }, () => process.disconnect()) +`) + const host = hostProcess(runtime) + const failure: unknown = await host.start().catch((error: unknown) => error) + await host.stop() + expect(failure).toBeInstanceOf(DesktopHostFatalError) + expect(failure).toHaveProperty('hostRunId', 'c254ab28-97c9-4382-95e6-2db9c66f98c8') + }) + + it.each([ + ['exception', 'queueMicrotask(() => { throw new Error("qualification-exception", { cause: new Error("qualification-runtime-cause") }) })'], + ['rejection', 'Promise.reject(new Error("qualification-rejection"))'], + ['exit', 'process.stderr.write("qualification-exit", () => process.exit(7))'], + ])('retains real child %s evidence in the final report after readiness', async (kind, trigger) => { + const failed = Promise.withResolvers() + const runtime = projectWithHost(` +process.send({ type: 'starting', runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8' }) +process.send({ type: 'ready', url: 'http://127.0.0.1:3080/' }, () => { ${trigger} }) +`) + const host = hostProcess(runtime, runtime, failed.resolve) + await host.start() + const failure = await failed.promise + await host.stop() + const report = renderCrashReport({ source: 'host', phase: 'running', error: failure, + rendererConsole: [], operationHistoryPlanned: true, time: new Date('2026-10-19T00:00:00Z'), + app: { name: 'qualification', version: 'test', platform: process.platform, arch: process.arch, + electron: 'not-running', node: process.version, locale: 'zh-CN' }, + }) + expect(report).toContain(`qualification-${kind}`) + expect(report).toContain('phase: running') + expect(report).toContain("hostRunId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8'") + if (kind === 'exception') expect(report).toContain('qualification-runtime-cause') + if (kind === 'exit') expect(report).toContain('7') + }) + + it('persists validated operation IPC across Host lifetimes and isolates a failing diagnostic sink', async () => { + const record = { + runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8', transportDropped: 0, + operation: { id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9', time: '2026-10-19T00:00:00.000Z', + reason: 'bundle', phase: 'started', target: 'test-bundle', stage: 'enable' }, + secret: 'not-persisted', + } + const runtime = projectWithHost(` +process.send({ type: 'starting', runId: ${JSON.stringify(record.runId)} }) +process.send({ type: 'plugin-operation', record: { invalid: true } }) +process.send({ type: 'plugin-operation', record: { ...${JSON.stringify(record)}, runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c0' } }) +process.send({ type: 'plugin-operation', record: ${JSON.stringify(record)} }) +${HTTP_HOST}`) + const directory = join(runtime, 'operation-history') + const journal = new OperationJournal(directory, { recordBytes: 4096, segmentBytes: 8192, queuedBytes: 8192 }) + onTestFinished(async () => { await journal.close() }) + const sink = vi.fn(value => journal.enqueue(JSON.stringify(value))) + const first = new DesktopHostProcess(process.execPath, runtime, runtime, undefined, process.env, + undefined, undefined, undefined, undefined, sink) + hosts.push(first) + await first.start() + await first.stop() + await journal.close() + expect(sink).toHaveBeenCalledTimes(1) + const saved = await readOperationHistory(directory, { bytes: 8192, recordBytes: 4096, records: 10 }, new AbortController().signal) + expect(saved.records).toEqual([{ runId: record.runId, transportDropped: 0, operation: record.operation }]) + + const warning = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + const failure = vi.fn() + const second = new DesktopHostProcess(process.execPath, runtime, runtime, undefined, process.env, + failure, undefined, undefined, undefined, () => { throw new Error('sink unavailable') }) + hosts.push(second) + await second.start() + expect(await second.updateTasks('inspect')).toBe(false) + await second.stop() + expect(failure).not.toHaveBeenCalled() + expect(warning).toHaveBeenCalledWith('desktop plugin operation diagnostic sink failed') + } finally { warning.mockRestore() } + }) + it('correlates authorized file resources and rejects Host denial over private IPC', async () => { const host = hostProcess(projectWithHost()) await host.start() diff --git a/apps/desktop/tests/installer-locales.spec.ts b/apps/desktop/tests/installer-locales.spec.ts index 4dea51a414..ba842d8e18 100644 --- a/apps/desktop/tests/installer-locales.spec.ts +++ b/apps/desktop/tests/installer-locales.spec.ts @@ -1,3 +1,5 @@ +import { SHIPPED_LOCALE_IDS } from '../../../scripts/shipped-locales.ts' +import { createRequire } from 'node:module' /** Per-language installer resources feed both the packaging language list and the NSIS compiler. */ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' @@ -8,7 +10,7 @@ import { readInstallerLocales, renderInstallerStrings } from '../scripts/install function fixture(): string { const directory = mkdtempSync(join(tmpdir(), 'dsh-installer-locales-')) onTestFinished(() => { rmSync(directory, { recursive: true, force: true }) }) - for (const id of ['en_US', 'zh_CN', 'ja_JP']) { + for (const id of ['en_US', 'zh_CN', 'ja_JP', 'es_ES', 'fr_FR', 'de_DE', 'ru_RU', 'pt_BR']) { writeFileSync(join(directory, `${id}.json`), readFileSync(new URL(`../installer/locales/${id}.json`, import.meta.url))) } return directory @@ -16,17 +18,17 @@ function fixture(): string { it('generates Japanese NSIS strings from the same files that select packaged languages', () => { const locales = readInstallerLocales() - expect(locales.map(locale => locale.id)).toEqual(['en_US', 'ja_JP', 'zh_CN']) + expect(locales.map(locale => locale.id)).toEqual(['en_US', 'de_DE', 'es_ES', 'fr_FR', 'ja_JP', 'pt_BR', 'ru_RU', 'zh_CN']) const source = renderInstallerStrings(locales) expect(source).toContain('LangString INSTALLER_INSTALL ${LANG_JAPANESE} "今すぐインストール"') expect(source).toContain('LangString INSTALLER_NATIVE_PROGRESS ${LANG_JAPANESE} "インストールを準備しています… %d%%"') expect(source).toContain('!ifdef LANG_JAPANESE\n') - expect(source.match(/^LangString /gmu)).toHaveLength(93) + expect(source.match(/^LangString /gmu)).toHaveLength(248) const japanese = locales.filter(locale => locale.id === 'ja_JP') expect(renderInstallerStrings(japanese)).not.toContain('${LANG_ENGLISH}') }) -it.each(['en_US', 'zh_CN', 'ja_JP'])('rejects a missing %s configuration', (id) => { +it.each(['en_US', 'zh_CN', 'ja_JP', 'es_ES', 'fr_FR', 'de_DE', 'ru_RU', 'pt_BR'])('rejects a missing %s configuration', (id) => { const directory = fixture() rmSync(join(directory, `${id}.json`)) expect(() => readInstallerLocales(directory)).toThrow(`missing ${id}.json`) @@ -39,7 +41,10 @@ it.each([ ['changed placeholder', (resource: ReturnType[number]) => { resource.strings.INSTALLER_NATIVE_PROGRESS = '%s%%' }, 'format placeholders'], ['missing percent escape', (resource: ReturnType[number]) => { resource.strings.INSTALLER_NATIVE_PROGRESS = '%d%' }, 'format placeholders'], ['extra format specifier', (resource: ReturnType[number]) => { resource.strings.INSTALLER_NATIVE_PROGRESS = '%d%% %q' }, 'format placeholders'], + ['translated command', (resource: ReturnType[number]) => { resource.strings.INSTALLER_THEME_ERROR = 'Use /THEME=claro.' }, 'format placeholders'], ['duplicate language', (resource: ReturnType[number]) => { resource.nsisLanguage = 'ENGLISH' }, 'duplicate NSIS language'], + ['invisible character', (resource: ReturnType[number]) => { resource.strings.INSTALLER_INSTALL = 'Install\u200b' }, 'invisible'], + ['byte-order mark', (resource: ReturnType[number]) => { resource.strings.INSTALLER_INSTALL = 'Install\ufeff' }, 'invisible'], ['invalid compiler token', (resource: ReturnType[number]) => { resource.nsisLanguage = 'JA\n!error' }, 'invalid NSIS language'], ])('rejects %s', (_name, mutate, diagnostic) => { const directory = fixture() @@ -54,3 +59,18 @@ it('escapes literal NSIS syntax without changing translated text', () => { expect(renderInstallerStrings([{ ...locale, strings: { INSTALLER_INSTALL: '"$name"\nnext\rline' } }])) .toContain('"$\\"$$name$\\"$\\nnext$\\rline"') }) + +it('uses the real electron-builder language identifiers and English fallback', () => { + const require = createRequire(import.meta.url) + const { LangConfigurator, createAddLangsMacro } = require('app-builder-lib/out/targets/nsis/nsisLang.js') as { + LangConfigurator: new (options: { installerLanguages: string[] }) => object + createAddLangsMacro: (generator: { macro: (name: string, lines: string[]) => void }, languages: object) => void + } + const locales = readInstallerLocales() + expect(locales[0]?.id).toBe('en_US') + expect(locales.map(locale => locale.id.split('_')[0]).sort()).toEqual([...SHIPPED_LOCALE_IDS].sort()) + createAddLangsMacro({ macro: (_name, lines) => { + expect(lines.map(line => /MUI_LANGUAGE "([^" ]+)"/u.exec(line)?.[1]?.toUpperCase())) + .toEqual(locales.map(locale => locale.nsisLanguage)) + } }, new LangConfigurator({ installerLanguages: locales.map(locale => locale.id) })) +}) diff --git a/apps/desktop/tests/installer-packaging.spec.ts b/apps/desktop/tests/installer-packaging.spec.ts index 57da6058df..1e438dedf4 100644 --- a/apps/desktop/tests/installer-packaging.spec.ts +++ b/apps/desktop/tests/installer-packaging.spec.ts @@ -1,3 +1,4 @@ +import { readInstallerLocales } from '../scripts/installer-locales.mjs' import { tmpdir } from 'node:os' import { readFileSync } from 'node:fs' import { Arch, Platform } from 'electron-builder' @@ -54,7 +55,7 @@ describe('installer preparation preserves application dependencies', () => { expect(appInfo.copyright).toBe(`Copyright © ${new Date().getFullYear()} DeepSeek Harness`) if (platform === 'win32') { expect(expandMacro(config.nsis.uninstallDisplayName, null, appInfo, {}, false)).toBe('DeepSeek Harness') - expect(config.nsis.installerLanguages).toEqual(['en_US', 'ja_JP', 'zh_CN']) + expect(config.nsis.installerLanguages).toEqual(readInstallerLocales().map(locale => locale.id)) } const aboutIcon = config.extraResources.find(resource => resource.to === 'icon.png') expect(aboutIcon).toBeDefined() diff --git a/apps/desktop/tests/locale-cache.spec.ts b/apps/desktop/tests/locale-cache.spec.ts new file mode 100644 index 0000000000..fdfeb4d557 --- /dev/null +++ b/apps/desktop/tests/locale-cache.spec.ts @@ -0,0 +1,62 @@ +import { SHIPPED_LOCALE_IDS } from '../../../scripts/shipped-locales.ts' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import { readDesktopLocaleCache, writeDesktopLocaleCache } from '../src/locale-cache.ts' +import { resolveDesktopLocale, resolveDesktopStartupLocale } from '../src/locale.ts' + +function fixture() { + const directory = mkdtempSync(join(tmpdir(), 'desktop-locale-')) + onTestFinished(() => { rmSync(directory, { recursive: true, force: true }) }) + return directory +} + +it('uses the confirmed Chinese language for recovery before Host settings are available', () => { + const directory = fixture() + expect(readDesktopLocaleCache(directory)).toBeUndefined() + writeDesktopLocaleCache(directory, 'zh-CN') + const cached = readDesktopLocaleCache(directory) + const locale = cached === undefined ? resolveDesktopStartupLocale(null, ['en-US']) : resolveDesktopLocale(cached) + expect(locale.messages.fatalSummary).toBe('应用无法启动或已意外停止。') + writeDesktopLocaleCache(directory, 'en') + expect(readDesktopLocaleCache(directory)).toBe('en') +}) + +it('uses the confirmed Japanese language for recovery before Host settings are available', () => { + const directory = fixture() + writeDesktopLocaleCache(directory, 'ja') + const cached = readDesktopLocaleCache(directory) + const locale = cached === undefined ? resolveDesktopStartupLocale(null, ['en-US']) : resolveDesktopLocale(cached) + expect(locale.id).toBe('ja') + expect(locale.messages.getDiagnosticReport).toBe('診断レポートを取得') +}) + +it.each(SHIPPED_LOCALE_IDS)('restores the confirmed shipped language %s before Host settings are available', (id) => { + const directory = fixture() + const selected = resolveDesktopLocale(id) + writeDesktopLocaleCache(directory, selected.id) + const cached = readDesktopLocaleCache(directory) + expect(cached).toBe(selected.id) + expect(resolveDesktopLocale(cached!).messages.getDiagnosticReport).toBe(selected.messages.getDiagnosticReport) +}) + +it.each(['', 'it', '{invalid'])('falls back to system language for an invalid cache: %s', (value) => { + const directory = fixture() + writeDesktopLocaleCache(directory, 'en') + writeFileSync(join(directory, 'desktop', 'locale-cache'), value) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warn.mockRestore() }) + expect(readDesktopLocaleCache(directory)).toBeUndefined() + expect(warn).toHaveBeenCalled() +}) + +it('keeps read and write failures from blocking recovery', () => { + const directory = fixture() + writeFileSync(join(directory, 'desktop'), 'not a directory') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warn.mockRestore() }) + expect(() => { writeDesktopLocaleCache(directory, 'zh-CN') }).not.toThrow() + expect(readDesktopLocaleCache(directory)).toBeUndefined() + expect(warn).toHaveBeenCalled() +}) diff --git a/apps/desktop/tests/locale.spec.ts b/apps/desktop/tests/locale.spec.ts index eb9f2ccb81..b53a02e8fb 100644 --- a/apps/desktop/tests/locale.spec.ts +++ b/apps/desktop/tests/locale.spec.ts @@ -1,14 +1,34 @@ +import { SHIPPED_LOCALE_IDS } from '../../../scripts/shipped-locales.ts' import { describe, expect, it } from 'vitest' -import { en, formatDesktopMessage, resolveDesktopLocale, resolveDesktopStartupLocale, ja, zh } from '../src/locale.ts' +import { en, formatDesktopMessage, resolveDesktopLocale, resolveDesktopStartupLocale, ja, zh, es, fr, de, ru, pt } from '../src/locale.ts' describe('desktop locale dictionaries', () => { - it('ships the same key set in English, Chinese, and Japanese', () => { + it('ships baseline and Japanese keys and falls back for unsupported languages', () => { expect(Object.keys(zh)).toEqual(Object.keys(en)) expect(Object.keys(ja)).toEqual(Object.keys(en)) expect(resolveDesktopLocale('JA-jp')).toEqual({ id: 'ja', messages: ja }) expect(resolveDesktopLocale('zh-Hans-CN').messages).toEqual(zh) expect(resolveDesktopLocale('en-US').messages).toEqual(en) - expect(resolveDesktopLocale('fr-FR').messages).toEqual(en) + expect(resolveDesktopLocale('it-IT').messages).toEqual(en) + }) + + it.each([ + ['es', 'es-MX', es], ['fr', 'fr-CA', fr], ['de', 'de-DE', de], + ['ru', 'ru-RU', ru], ['pt', 'pt-BR', pt], + ] as const)('resolves %s, preserves placeholders, and honors saved preferences', (id, tag, messages) => { + expect(resolveDesktopLocale(tag.toUpperCase())).toEqual({ id, messages }) + expect(resolveDesktopStartupLocale(id, ['zh-CN']).id).toBe(id) + expect(resolveDesktopStartupLocale(null, ['it-IT', tag, 'en-US']).id).toBe(id) + expect(Object.keys(messages)).toEqual(Object.keys(en)) + for (const key of Object.keys(en) as (keyof typeof en)[]) { + const placeholders = (text: string): string[] => (text.match(/\{\w+\}/gu) ?? []).sort() + expect(placeholders(messages[key]), key).toEqual(placeholders(en[key])) + } + }) + + it.each(SHIPPED_LOCALE_IDS)('resolves every shipped language %s without fallback', (id) => { + expect(resolveDesktopLocale(id).id).toBe(id === 'zh' ? 'zh-CN' : id) + expect(resolveDesktopStartupLocale(null, [id]).id).toBe(id === 'zh' ? 'zh-CN' : id) }) it('formats named values without consuming unknown placeholders', () => { diff --git a/apps/desktop/tests/macos-package-settings.spec.ts b/apps/desktop/tests/macos-package-settings.spec.ts index 1daa31c70a..449a453fda 100644 --- a/apps/desktop/tests/macos-package-settings.spec.ts +++ b/apps/desktop/tests/macos-package-settings.spec.ts @@ -2,12 +2,12 @@ import { expect, it } from 'vitest' import { macOSDownloadEnvironment, resolveMacOSPackageSettings } from '../scripts/macos-package-settings.mjs' it('defaults to four workers and keeps download and Apple proxies independent', () => { - expect(resolveMacOSPackageSettings({})).toEqual({ packConcurrency: 4 }) + expect(resolveMacOSPackageSettings({})).toEqual({ packConcurrency: 4, zipCompressionLevel: 3 }) expect(resolveMacOSPackageSettings({ DSH_DESKTOP_MACOS_PACK_CONCURRENCY: '2', DSH_DESKTOP_MACOS_DOWNLOAD_PROXY: 'https://download.example:8080', DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: 'http://apple.example:8081', - })).toEqual({ packConcurrency: 2, downloadProxy: 'https://download.example:8080', notarizationProxy: 'http://apple.example:8081' }) - expect(resolveMacOSPackageSettings({ DSH_DESKTOP_MACOS_DOWNLOAD_PROXY: ' ', DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: '' })).toEqual({ packConcurrency: 4 }) + })).toEqual({ packConcurrency: 2, zipCompressionLevel: 3, downloadProxy: 'https://download.example:8080', notarizationProxy: 'http://apple.example:8081' }) + expect(resolveMacOSPackageSettings({ DSH_DESKTOP_MACOS_DOWNLOAD_PROXY: ' ', DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: '' })).toEqual({ packConcurrency: 4, zipCompressionLevel: 3 }) }) it.each(['', '0', '-1', '1.5', '1e2', 'Infinity', '9007199254740992'])('rejects invalid concurrency %j', (value) => { @@ -32,3 +32,11 @@ it('overrides conflicting child proxy variables while preserving the parent and expect(parent.HTTPS_PROXY).toBe('http://old') expect(parent.NO_PROXY).toBe('*') }) + +it.each(['', '-1', '10', '3.5', '03', 'NaN'])('rejects invalid ZIP compression %j', (value) => { + expect(() => resolveMacOSPackageSettings({ DSH_DESKTOP_MACOS_ZIP_COMPRESSION_LEVEL: value })).toThrow('ZIP_COMPRESSION_LEVEL') +}) + +it.each(['0', '3', '7', '9'])('accepts ZIP compression %s', (value) => { + expect(resolveMacOSPackageSettings({ DSH_DESKTOP_MACOS_ZIP_COMPRESSION_LEVEL: value }).zipCompressionLevel).toBe(Number(value)) +}) diff --git a/apps/desktop/tests/macos-signature.spec.ts b/apps/desktop/tests/macos-signature.spec.ts index afe2092791..2e6a2bd48e 100644 --- a/apps/desktop/tests/macos-signature.spec.ts +++ b/apps/desktop/tests/macos-signature.spec.ts @@ -1,3 +1,4 @@ +import { SHIPPED_LOCALE_IDS } from '../../../scripts/shipped-locales.ts' import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' import { readFileSync } from 'node:fs' import { createRequire } from 'node:module' @@ -51,7 +52,7 @@ describe('desktop macOS release signature', () => { expect(config.protocols).toEqual([{ name: 'DeepSeek Harness', schemes: ['dsh'] }]) expect(portablePath(config.directories.output)).toContain('/.desktop-build/targets/mac-arm64/artifacts') expect(config.mac.extendInfo.NSMicrophoneUsageDescription).toContain('microphone') - expect(config.mac.extendInfo.CFBundleLocalizations).toEqual(['en', 'zh_CN', 'ja']) + expect(config.mac.extendInfo.CFBundleLocalizations).toEqual(SHIPPED_LOCALE_IDS.map(id => id === 'zh' ? 'zh_CN' : id)) expect(config.mac.entitlementsInherit).toBe(config.mac.entitlements) const entitlements = readFileSync(config.mac.entitlements, 'utf8') for (const key of ['com.apple.security.cs.allow-jit', 'com.apple.security.cs.allow-unsigned-executable-memory', diff --git a/apps/desktop/tests/main-startup.spec.ts b/apps/desktop/tests/main-startup.spec.ts index b2d925af6c..20325642a2 100644 --- a/apps/desktop/tests/main-startup.spec.ts +++ b/apps/desktop/tests/main-startup.spec.ts @@ -1,9 +1,11 @@ +import { parsePluginOperationRecord } from '@deepseek-ai/dsh-plugin-manager/diagnostic' +import type { DesktopHostProcess } from '../src/host-process.ts' import type { AccountView } from '@deepseek-ai/dsh-deepseek-account/types' import { WINDOWS_TITLEBAR_HEIGHT } from '../src/windows-layout.ts' import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import type { IpcMainInvokeEvent } from 'electron' import { join } from 'node:path' -import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import type { MenuItemConstructorOptions, MessageBoxOptions } from 'electron' import { DESKTOP_IPC, type DesktopUpdateState } from '../src/ipc.ts' @@ -12,6 +14,7 @@ import { DesktopHostFatalError, DesktopHostUncleanExitError } from '../src/host- import { en, zh } from '../src/locale.ts' import { DesktopUpdatePreparationError } from '../src/update-error.ts' import { writeCrashReport } from '../src/crash-report.ts' +import { runOperationReportJob } from '../src/operation-report-job.ts' type InvokeEvent = { sender?: unknown; senderFrame: { url: string } } type InvokeHandler = (event: InvokeEvent, ...args: unknown[]) => unknown @@ -20,11 +23,12 @@ const fileDrag = vi.hoisted(() => ({ dispose: vi.fn<() => Promise>(), inst vi.mock('../src/file-drag.ts', () => ({ installDesktopFileDrag: () => { fileDrag.install(); return fileDrag.dispose } })) vi.mock('../src/web-document.ts', () => ({ authenticateWebHost: async () => 'test-cookie', serveWebDocument: vi.fn(), forwardWebRequest: vi.fn() })) +vi.mock('../src/operation-report-job.ts', () => ({ runOperationReportJob: vi.fn(async () => ({ appended: false, timedOut: false, cancelled: false })) })) // Report persistence has its own unit tests; here it resolves within microtasks so the fatal // dialog never outlives the test that triggered it. vi.mock('../src/crash-report.ts', async importOriginal => ({ ...await importOriginal(), - writeCrashReport: vi.fn(async () => 'desktop-test-logs/crash-test.log'), + writeCrashReport: vi.fn<(...args: unknown[]) => Promise>(), pruneCrashReports: vi.fn(async () => {}), })) @@ -164,6 +168,8 @@ const harness = await vi.hoisted(async () => { readonly inspectPort?: number, readonly environment?: NodeJS.ProcessEnv, readonly onFailure?: (error: Error) => void, readonly primaryRuntime?: string, readonly packageManager?: { pnpm: string; nodeBin: string }, + readonly onPlatformSession?: ConstructorParameters[8], + readonly onPluginOperation?: ConstructorParameters[9], ) { hosts.push(this) } } const app = Object.assign(new EventEmitter(), { @@ -427,9 +433,10 @@ beforeEach(() => { harness.reset() const userData = mkdtempSync(join(tmpdir(), 'dsh-main-user-data-')) onTestFinished(() => { rmSync(userData, { recursive: true, force: true }) }) - harness.app.getPath.mockImplementation(name => name === 'userData' ? userData : `desktop-test-${name}`) + harness.app.getPath.mockImplementation(name => name === 'userData' ? userData : join(userData, `desktop-test-${name}`)) + vi.mocked(writeCrashReport).mockResolvedValue(join(harness.app.getPath('logs'), 'crash-test.log')) harness.dialog.showMessageBox.mockImplementation((options: { title?: string }) => { - if (options.title !== en.startupFailed) return Promise.resolve({ response: 1 }) + if (options.title !== en.startupFailed && options.title !== zh.startupFailed) return Promise.resolve({ response: 1 }) harness.dialogShown.resolve() return new Promise(() => {}) }) @@ -954,7 +961,7 @@ describe('desktop main startup', () => { expect(window.setBackgroundColor).not.toHaveBeenCalled() }) - it('follows the Windows primary document language and palette without trusting other frames', async () => { + it('follows confirmed language and primary document palette without trusting other frames', async () => { vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') await import('../src/main.ts') await harness.preparing.promise @@ -963,10 +970,12 @@ describe('desktop main startup', () => { const event = { sender: window.webContents, senderFrame: window.webContents.mainFrame } listener({ ...event, senderFrame: { url: 'dsh-app://app/' } }, 'zh-CN', '#ffffff', '#000000') expect(window.setTitleBarOverlay).not.toHaveBeenCalled() + harness.ipcOn.mock.calls.find(([channel]) => channel === DESKTOP_IPC.localeChanged)![1](event, 'zh') listener(event, 'zh-CN', 'rgb(249, 250, 251)', '#0f1115') expect(window.setTitleBarOverlay).toHaveBeenCalledWith({ color: 'rgb(249, 250, 251)', symbolColor: '#0f1115' }) window.webContents.emit('context-menu', {}, { isEditable: false, selectionText: 'text', editFlags: { canCopy: true } }) expect(harness.menu.buildFromTemplate).toHaveBeenLastCalledWith([{ role: 'copy', enabled: true, label: '复制', accelerator: '' }]) + harness.ipcOn.mock.calls.find(([channel]) => channel === DESKTOP_IPC.localeChanged)![1](event, 'en') listener(event, 'en', '#1b1b1c', '#f9fafb') window.webContents.emit('context-menu', {}, { isEditable: false, selectionText: 'text', editFlags: { canCopy: true } }) expect(harness.menu.buildFromTemplate).toHaveBeenLastCalledWith([{ role: 'copy', enabled: true, label: 'Copy', accelerator: '' }]) @@ -979,7 +988,30 @@ describe('desktop main startup', () => { window.webContents.mainFrame.url = 'dsh-app://unowned/index.html' listener(event, 'zh-CN', '#fff', '#000') expect(window.setTitleBarOverlay).not.toHaveBeenCalled() - expect(harness.menu.setApplicationMenu).toHaveBeenCalledOnce() + expect(harness.menu.setApplicationMenu).toHaveBeenCalledTimes(3) + }) + + it('retains cached Chinese for a Host startup crash after the loading page reports English', async () => { + vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') + const directory = join(harness.app.getPath('userData'), 'desktop') + mkdirSync(directory, { recursive: true }) + writeFileSync(join(directory, 'locale-cache'), 'zh-CN\n') + await import('../src/main.ts') + await harness.preparing.promise + const window = harness.windows[0]! + const appearance = harness.ipcOn.mock.calls.find(([channel]) => channel === DESKTOP_IPC.windowsAppearance)![1] + appearance({ sender: window.webContents, senderFrame: window.webContents.mainFrame }, 'en', '#fff', '#000') + harness.prepared.resolve() + await harness.hostStarted.promise + const host = harness.hosts[0]! + const failure = new DesktopHostFatalError('test plugin failed', 'missing required services') + host.onFailure!(failure) + host.ready.reject(failure) + await host.stopping.promise + host.exited.resolve() + await harness.dialogShown.promise + expect(vi.mocked(writeCrashReport).mock.calls[0]![1].app.locale).toBe('zh-CN') + expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).message).toBe(zh.fatalSummary) }) it('maps Windows caption menus to localized native commands and rejects foreign popup requests', async () => { @@ -989,6 +1021,7 @@ describe('desktop main startup', () => { const window = harness.windows[0]! const event = { sender: window.webContents, senderFrame: window.webContents.mainFrame } const appearance = harness.ipcOn.mock.calls.find(([channel]) => channel === DESKTOP_IPC.windowsAppearance)![1] + harness.ipcOn.mock.calls.find(([channel]) => channel === DESKTOP_IPC.localeChanged)![1](event, 'zh') appearance(event, 'zh-CN', '#fff', '#000') const handler = harness.handlers.get(DESKTOP_IPC.windowsMenu)! const foreignEvent = { ...event, sender: {} } @@ -2206,8 +2239,8 @@ describe('desktop main startup', () => { handler(event, 'client mount failed') await harness.dialogShown.promise expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).detail).toContain('client mount failed') - expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).detail).toContain('desktop-test-logs/crash-test.log') - expect(writeCrashReport).toHaveBeenCalledWith('desktop-test-logs', expect.objectContaining({ source: 'web-boot', phase: 'startup' })) + expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).detail).toContain(join(harness.app.getPath('logs'), 'crash-test.log')) + expect(writeCrashReport).toHaveBeenCalledWith(harness.app.getPath('logs'), expect.objectContaining({ source: 'web-boot', phase: 'startup' })) expect(window.urls).toEqual(['dsh-app://app/']) }) @@ -2221,7 +2254,7 @@ describe('desktop main startup', () => { window.webContents.emit('did-fail-load', {}, -2, 'failed', 'dsh-app://app/', true) await harness.dialogShown.promise expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).detail).toContain('Desktop page failed to load') - expect(writeCrashReport).toHaveBeenCalledWith('desktop-test-logs', expect.objectContaining({ source: 'renderer' })) + expect(writeCrashReport).toHaveBeenCalledWith(harness.app.getPath('logs'), expect.objectContaining({ source: 'renderer' })) }) it('offers all recovery choices when resources fail before the Host starts', async () => { @@ -2230,7 +2263,7 @@ describe('desktop main startup', () => { harness.prepared.reject(new Error('runtime resources missing')) await harness.dialogShown.promise expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).detail).toContain('runtime resources missing') - expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).buttons).toEqual(['Exit', 'Restart', 'Disable third-party plugins, back up profile patch, and restart']) + expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).buttons).toEqual(['Exit', 'Restart', 'Disable third-party plugins, back up profile patch, and restart', 'Get diagnostic report']) expect(harness.windows[0]!.urls).toEqual(['dsh-app://app/']) }) @@ -2270,6 +2303,20 @@ describe('desktop main startup', () => { expect(harness.hosts).toHaveLength(0) }) + it('writes operation history under the instance userData instead of the shared logs directory', async () => { + await import('../src/main.ts') + await harness.preparing.promise + harness.prepared.resolve() + await harness.hostStarted.promise + const record = parsePluginOperationRecord({ runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8', transportDropped: 0, + operation: { id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9', time: '2026-10-20T00:00:00.000Z', + reason: 'bundle', phase: 'started', target: 'test', stage: 'enable' } })! + harness.hosts[0]!.onPluginOperation!(record) + const file = join(harness.app.getPath('userData'), 'plugin-operations', 'operations.jsonl') + await vi.waitFor(() => { expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual(record) }) + expect(existsSync(join(harness.app.getPath('logs'), 'plugin-operations'))).toBe(false) + }) + it('writes the Host\'s own diagnostic into a startup-phase crash report when the Host reports a fatal error before ready', async () => { await import('../src/main.ts') await harness.preparing.promise @@ -2285,11 +2332,15 @@ describe('desktop main startup', () => { host.exited.resolve() await harness.dialogShown.promise const [directory, report] = vi.mocked(writeCrashReport).mock.calls[0]! - expect(directory).toBe('desktop-test-logs') + expect(directory).toBe(harness.app.getPath('logs')) expect(report.source).toBe('host') expect(report.phase).toBe('startup') expect(report.error).toBeInstanceOf(DesktopHostFatalError) expect(report.hostDiagnostic).toBe(diagnostic) + expect(runOperationReportJob).toHaveBeenCalledWith({ + reportPath: join(harness.app.getPath('logs'), 'crash-test.log'), directory: join(harness.app.getPath('userData'), 'plugin-operations'), + limits: { bytes: 65536, recordBytes: 4096, records: 100, outputBytes: 65536 }, journal: null, + }, { timeoutMs: 500, cancellationGraceMs: 100 }, expect.any(AbortSignal)) expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).detail).toContain('profile has no cordis.yml') }) @@ -2312,7 +2363,7 @@ describe('desktop main startup', () => { await host.stopping.promise expect(writeCrashReport).toHaveBeenCalledOnce() const [directory, report] = vi.mocked(writeCrashReport).mock.calls[0]! - expect(directory).toBe('desktop-test-logs') + expect(directory).toBe(harness.app.getPath('logs')) expect(report.source).toBe('host') expect(report.phase).toBe('running') expect(report.error).toBeInstanceOf(Error) @@ -2324,7 +2375,76 @@ describe('desktop main startup', () => { await harness.quitCompleted.promise }) - it.each([0, 1, 2])('waits for Host exit before recovery action %s', async (response) => { + it.each([{ rejectCleanup: false, stuck: false }, { rejectCleanup: true, stuck: false }, + { rejectCleanup: true, stuck: true }])('waits for the diagnostic Worker (policy rejects=$rejectCleanup, stuck=$stuck)', async ({ rejectCleanup, stuck }) => { + harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', + allowedAuthOrigins: ['https://login.example.com'], allowedPageOrigins: ['https://downloads.example.com'] } + vi.stubGlobal('fetch', vi.fn().mockImplementation(async () => + Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 }))) + let finishReport!: () => void + let reportSignal: AbortSignal | undefined + let workerExited = false + const report = new Promise<{ appended: boolean; timedOut: boolean; cancelled: boolean }>((resolve) => { + finishReport = () => { workerExited = true; resolve({ appended: false, timedOut: false, cancelled: true }) } + }) + vi.mocked(runOperationReportJob).mockImplementationOnce((_input, _options, signal) => { + reportSignal = signal + return report + }) + let finishPolicy!: () => void + let failPolicy!: (error: Error) => void + const policy = new Promise((resolve, reject) => { finishPolicy = resolve; failPolicy = reject }) + testAuth.dispose.mockImplementationOnce(() => policy) + const failure = new Error('policy Session storage cleanup failed') + const host = await readyForUpdate() + let quitCompleted = false + void harness.quitCompleted.promise.then(() => { quitCompleted = true }) + try { + const window = harness.windows[0]! + window.webContents.emit('render-process-gone', {}, { reason: 'crashed' }) + await harness.dialogShown.promise + expect(runOperationReportJob).toHaveBeenCalledOnce() + host.exited.resolve() + window.emit('session-end', { reasons: ['shutdown'] }) + harness.app.quit() + await vi.advanceTimersByTimeAsync(0) + expect(testAuth.dispose).toHaveBeenCalledOnce() + expect(reportSignal?.aborted).toBe(true) + expect(quitCompleted).toBe(false) + if (rejectCleanup) failPolicy(failure) + else finishPolicy() + await vi.advanceTimersByTimeAsync(0) + if (rejectCleanup) expect(console.error).toHaveBeenCalledWith(failure) + expect(workerExited).toBe(false) + expect(quitCompleted).toBe(false) + if (stuck) { + await vi.advanceTimersByTimeAsync(499) + expect(quitCompleted).toBe(false) + await vi.advanceTimersByTimeAsync(1) + expect(workerExited).toBe(false) + expect(console.error).toHaveBeenCalledWith('dsh desktop: operation report Worker has not exited; continuing shutdown') + } else { + finishReport() + await vi.advanceTimersByTimeAsync(0) + } + expect(quitCompleted).toBe(true) + } finally { + finishPolicy() + finishReport() + host.exited.resolve() + await vi.advanceTimersByTimeAsync(0) + await harness.quitCompleted.promise + } + }) + + it.each([{ response: 0, stuck: false }, { response: 1, stuck: false }, { response: 2, stuck: false }, + { response: 0, stuck: true }])('waits for Host exit and bounds Worker cleanup for recovery $response (stuck=$stuck)', async ({ response, stuck }) => { + let finishReport!: (result: { appended: boolean; timedOut: boolean; cancelled: boolean }) => void + let reportSignal: AbortSignal | undefined + vi.mocked(runOperationReportJob).mockImplementationOnce(async (_input, _options, signal) => { + reportSignal = signal + return new Promise((resolve) => { finishReport = resolve }) + }) harness.dialog.showMessageBox.mockResolvedValue({ response, checkboxChecked: false }) await import('../src/main.ts') await harness.preparing.promise @@ -2338,7 +2458,16 @@ describe('desktop main startup', () => { expect(harness.app.relaunch).not.toHaveBeenCalled() expect(harness.disableAllPlugins).not.toHaveBeenCalled() host.exited.resolve() + await vi.advanceTimersByTimeAsync(0) + expect(reportSignal?.aborted).toBe(true) + expect(harness.app.quit).not.toHaveBeenCalled() + if (stuck) await vi.advanceTimersByTimeAsync(500) + else finishReport({ appended: false, timedOut: false, cancelled: true }) await harness.quitCompleted.promise + if (stuck) { + expect(console.error).toHaveBeenCalledWith('dsh desktop: operation report Worker has not exited; continuing shutdown') + finishReport({ appended: false, timedOut: false, cancelled: true }) + } expect(harness.app.relaunch).toHaveBeenCalledTimes(response === 0 ? 0 : 1) expect(harness.disableAllPlugins).toHaveBeenCalledTimes(response === 2 ? 1 : 0) if (response === 2) { diff --git a/apps/desktop/tests/operation-history.spec.ts b/apps/desktop/tests/operation-history.spec.ts new file mode 100644 index 0000000000..237287d5b0 --- /dev/null +++ b/apps/desktop/tests/operation-history.spec.ts @@ -0,0 +1,172 @@ +import { mkdtemp, mkdir, open, rename, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import { readOperationHistory } from '../src/operation-history.ts' + +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, open: vi.fn(actual.open) } +}) + +const limits = { bytes: 64 * 1024, recordBytes: 2048, records: 100 } +function record(id: string | number) { + return { runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8', transportDropped: 0, + operation: { id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9', time: '2026-10-19T00:00:00.000Z', + reason: 'plugin', phase: 'started', target: String(id), stage: 'enable' } } +} +function line(id: string | number) { return JSON.stringify(record(id)) + '\n' } + +async function fixture() { + const path = await mkdtemp(join(tmpdir(), 'desktop-operation-history-')) + onTestFinished(async () => { await rm(path, { recursive: true, force: true }) }) + return path +} + +it('collects recent complete records and reports malformed and incomplete entries', async () => { + const path = await fixture() + await writeFile(join(path, 'operations.jsonl'), line(1) + '{broken}\n' + line(2) + '{"incomplete":') + await writeFile(join(path, 'operations.previous.jsonl'), line(0)) + const result = await readOperationHistory(path, limits, new AbortController().signal) + expect(result.records).toEqual([record(2), record(1), record(0)]) + expect(result).toMatchObject({ invalidRecords: 1, truncated: true, cancelled: false, unavailableFiles: 0 }) +}) + +it('reads no more than its byte budget from a two GiB file and ignores unrelated history', async () => { + const path = await fixture() + await using large = await open(join(path, 'operations.jsonl'), 'w') + const size = 2 * 1024 * 1024 * 1024 + await large.truncate(size) + const tail = Buffer.from('\n' + line('last')) + await large.write(tail, 0, tail.length, size - tail.length) + await writeFile(join(path, 'pnpm.log'), 'unrelated output') + const result = await readOperationHistory(path, limits, new AbortController().signal) + expect(result.records).toEqual([record('last')]) + expect(result.bytesRead).toBe(limits.bytes) + expect(result.truncated).toBe(true) +}) + +it('bounds parsed record size and output count independently', async () => { + const path = await fixture() + await writeFile(join(path, 'operations.jsonl'), line(1) + '{"large":"' + 'x'.repeat(4096) + '"}\n' + line(2)) + const result = await readOperationHistory(path, { ...limits, records: 2 }, new AbortController().signal) + expect(result.records).toEqual([record(2), record(1)]) + expect(result.invalidRecords).toBe(1) +}) + +it('returns immediately without I/O when already cancelled', async () => { + const result = await readOperationHistory('not-a-directory', limits, AbortSignal.abort()) + expect(result).toMatchObject({ records: [], bytesRead: 0, cancelled: true, unavailableFiles: 0 }) +}) + +it('reports unreadable segments without failing the whole collection', async () => { + const path = await fixture() + await mkdir(join(path, 'operations.jsonl')) + await writeFile(join(path, 'operations.previous.jsonl'), line(1)) + const result = await readOperationHistory(path, limits, new AbortController().signal) + expect(result.records).toEqual([record(1)]) + expect(result.unavailableFiles).toBe(1) +}) + +it('awaits an in-flight read before closing and schedules no further reads after cancellation', async () => { + const path = await fixture() + const filename = join(path, 'operations.jsonl') + await writeFile(filename, ' '.repeat(limits.bytes)) + const handle = await open(filename, 'r') + onTestFinished(async () => { await handle.close() }) + const started = Promise.withResolvers() + const release = Promise.withResolvers() + const opener = vi.mocked(open).mockClear().mockResolvedValueOnce(handle) + const reader = vi.spyOn(handle, 'read').mockImplementationOnce(async () => { + started.resolve(undefined) + await release.promise + return { bytesRead: 1, buffer: Buffer.alloc(1) } + }) + const controller = new AbortController() + let settled = false + const collecting = readOperationHistory(path, limits, controller.signal) + .then((result) => { settled = true; return result }) + try { + await started.promise + controller.abort() + await Promise.resolve(undefined) + expect(settled).toBe(false) + expect(handle.fd).not.toBe(-1) + release.resolve(undefined) + expect(await collecting).toMatchObject({ cancelled: true, bytesRead: 1, records: [] }) + expect(handle.fd).toBe(-1) + expect(reader).toHaveBeenCalledTimes(1) + expect(opener).toHaveBeenCalledTimes(1) + } finally { + release.resolve(undefined) + await collecting + reader.mockRestore() + opener.mockClear() + await handle.close() + } +}) + +it('contains truncation between stat and read and still collects the previous segment', async () => { + const path = await fixture() + const filename = join(path, 'operations.jsonl') + await writeFile(filename, line(2)) + await writeFile(join(path, 'operations.previous.jsonl'), line(1)) + const handle = await open(filename, 'r+') + onTestFinished(async () => { await handle.close() }) + const originalStat = await handle.stat() + const stat = vi.spyOn(handle, 'stat').mockImplementationOnce(async () => { + await handle.truncate(0) + return originalStat + }) + const opener = vi.mocked(open).mockClear().mockResolvedValueOnce(handle) + try { + const result = await readOperationHistory(path, limits, new AbortController().signal) + expect(result).toMatchObject({ records: [record(1)], truncated: true, unavailableFiles: 0 }) + expect(handle.fd).toBe(-1) + } finally { + stat.mockRestore() + opener.mockClear() + await handle.close() + } +}) + +it('rejects invalid resource budgets before opening a file', async () => { + for (const bytes of [0, -1, 0.5, Infinity, Number.MAX_SAFE_INTEGER + 1]) { + await expect(readOperationHistory('not-a-directory', { ...limits, bytes }, new AbortController().signal)) + .rejects.toThrow(RangeError) + } +}) + +it('does not collect the same open segment twice when it rotates during collection', async () => { + const path = await fixture() + const current = join(path, 'operations.jsonl') + await writeFile(current, line(1)) + const handle = await open(current, 'r') + onTestFinished(async () => { await handle.close() }) + const opener = vi.mocked(open).mockImplementationOnce(async () => { + await rename(current, join(path, 'operations.previous.jsonl')) + await writeFile(current, line(2)) + return handle + }) + try { + const result = await readOperationHistory(path, limits, new AbortController().signal) + expect(result.records).toEqual([record(1)]) + expect(result).toMatchObject({ filesRead: 1, truncated: true }) + expect(handle.fd).toBe(-1) + } finally { + opener.mockClear() + await handle.close() + } +}) + +it.each(['absent', 'empty', 'nonempty'])('reports omitted bytes at an exact budget: previous segment %s', async (previous) => { + const path = await fixture() + const current = line(1) + await writeFile(join(path, 'operations.jsonl'), current) + if (previous !== 'absent') await writeFile(join(path, 'operations.previous.jsonl'), previous === 'empty' ? '' : line(0)) + const result = await readOperationHistory(path, + { ...limits, bytes: Buffer.byteLength(current), records: 1 }, new AbortController().signal) + expect(result.records).toEqual([record(1)]) + expect(result.truncated).toBe(previous === 'nonempty') + expect(result.filesRead).toBe(1) +}) diff --git a/apps/desktop/tests/operation-journal.spec.ts b/apps/desktop/tests/operation-journal.spec.ts new file mode 100644 index 0000000000..98e97d36a5 --- /dev/null +++ b/apps/desktop/tests/operation-journal.spec.ts @@ -0,0 +1,115 @@ +import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import { OperationJournal } from '../src/operation-journal.ts' + +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, mkdir: vi.fn(actual.mkdir) } +}) + +async function fixture() { + const directory = await mkdtemp(join(tmpdir(), 'desktop-operation-journal-')) + onTestFinished(async () => { await rm(directory, { recursive: true, force: true }) }) + return directory +} + +it('retains two bounded segments after dense operations across 50 plugins', async () => { + const directory = await fixture() + const journal = new OperationJournal(directory, { recordBytes: 128, segmentBytes: 1024, queuedBytes: 128 * 1000 }) + onTestFinished(async () => { await journal.close() }) + for (let i = 0; i < 1000; i++) expect(journal.enqueue(JSON.stringify({ plugin: i % 50, operation: i }))).toBe(true) + await journal.close() + expect((await readdir(directory)).sort()).toEqual(['operations.jsonl', 'operations.previous.jsonl']) + for (const name of await readdir(directory)) { + expect((await stat(join(directory, name))).size).toBeLessThanOrEqual(1024) + for (const line of (await readFile(join(directory, name), 'utf8')).trim().split('\n')) expect(() => { JSON.parse(line) }).not.toThrow() + } + expect(await readFile(join(directory, 'operations.jsonl'), 'utf8')).toContain('"operation":999') + expect(journal.status()).toEqual({ dropped: 0, failed: 0, queuedBytes: 0, disabled: false, repairedSegments: 0 }) +}) + +it('bounds the queue and encoded record bytes including multibyte characters and newline', async () => { + const directory = await fixture() + const journal = new OperationJournal(directory, { recordBytes: 8, segmentBytes: 32, queuedBytes: 16 }) + onTestFinished(async () => { await journal.close() }) + expect(journal.enqueue('{"中":1}')).toBe(false) + expect(journal.enqueue('{"a":1}')).toBe(true) + expect(journal.enqueue('{"a":2}')).toBe(true) + expect(journal.enqueue('{"a":3}')).toBe(false) + expect(journal.status()).toMatchObject({ queuedBytes: 16, dropped: 2 }) + await journal.close() + expect(await readFile(join(directory, 'operations.jsonl'), 'utf8')).toBe('{"a":1}\n{"a":2}\n') + expect(journal.enqueue('{}')).toBe(false) +}) + +it('disables persistence after a write failure without rejecting producers or close', async () => { + const directory = await fixture() + const blocked = join(directory, 'file') + await writeFile(blocked, 'untouched') + const journal = new OperationJournal(blocked, { recordBytes: 32, segmentBytes: 64, queuedBytes: 64 }) + expect(journal.enqueue('{"operation":1}')).toBe(true) + await expect(journal.close()).resolves.toBeUndefined() + expect(journal.status()).toEqual({ dropped: 0, failed: 1, queuedBytes: 0, disabled: true, repairedSegments: 0 }) + expect(await readFile(blocked, 'utf8')).toBe('untouched') +}) + +it.each(['', '{"old":1}\n'])('preserves both segments when repairing a partial append after %j', async (prefix) => { + const directory = await fixture() + const previous = '{"previous":0}\n' + await writeFile(join(directory, 'operations.previous.jsonl'), previous) + await writeFile(join(directory, 'operations.jsonl'), prefix + '{"partial":') + const journal = new OperationJournal(directory, { recordBytes: 32, segmentBytes: 64, queuedBytes: 64 }) + expect(journal.enqueue('{"new":2}')).toBe(true) + await journal.close() + expect(await readFile(join(directory, 'operations.jsonl'), 'utf8')).toBe(prefix + '{"new":2}\n') + expect(await readFile(join(directory, 'operations.previous.jsonl'), 'utf8')).toBe(previous) + expect(journal.status()).toMatchObject({ repairedSegments: 1, disabled: false }) +}) + +it('bounds both pre-existing oversized segments before writing new records', async () => { + const directory = await fixture() + for (const name of ['operations.jsonl', 'operations.previous.jsonl']) await writeFile(join(directory, name), 'x'.repeat(1000)) + const journal = new OperationJournal(directory, { recordBytes: 32, segmentBytes: 64, queuedBytes: 64 }) + journal.enqueue('{"new":2}') + await journal.close() + for (const name of await readdir(directory)) expect((await stat(join(directory, name))).size).toBeLessThanOrEqual(64) + expect(journal.status()).toMatchObject({ repairedSegments: 2, disabled: false }) +}) + +it('stops scheduling writes after a drain deadline without claiming the in-flight request ended', async () => { + const directory = await fixture() + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + vi.mocked(mkdir).mockImplementationOnce(async () => { entered.resolve(undefined); await release.promise; return undefined }) + const journal = new OperationJournal(directory, { recordBytes: 32, segmentBytes: 64, queuedBytes: 64 }) + onTestFinished(async () => { release.resolve(undefined); await journal.close(); vi.useRealTimers() }) + journal.enqueue('{"operation":1}') + await entered.promise + vi.useFakeTimers() + const draining = journal.drain(500) + await vi.advanceTimersByTimeAsync(500) + expect(await draining).toBe(false) + expect(journal.status()).toMatchObject({ disabled: true, queuedBytes: 16 }) + expect(journal.enqueue('{"operation":2}')).toBe(false) + let repeated: boolean | undefined + void journal.drain(500).then((result) => { repeated = result }) + await vi.advanceTimersByTimeAsync(0) + expect(repeated).toBe(false) + release.resolve(undefined) + await journal.close() + expect(await readdir(directory)).toEqual([]) + expect(journal.status()).toMatchObject({ failed: 1, queuedBytes: 0 }) +}) + +it('can keep recording after successful installer preparation when the installer later fails', async () => { + const directory = await fixture() + const journal = new OperationJournal(directory, { recordBytes: 32, segmentBytes: 64, queuedBytes: 64 }) + onTestFinished(async () => { await journal.close() }) + journal.enqueue('{"operation":1}') + expect(await journal.drain(1000)).toBe(true) + expect(journal.enqueue('{"operation":2}')).toBe(true) + await journal.close() + expect(await readFile(join(directory, 'operations.jsonl'), 'utf8')).toBe('{"operation":1}\n{"operation":2}\n') +}) diff --git a/apps/desktop/tests/operation-report-job.spec.ts b/apps/desktop/tests/operation-report-job.spec.ts new file mode 100644 index 0000000000..82ea02fcd8 --- /dev/null +++ b/apps/desktop/tests/operation-report-job.spec.ts @@ -0,0 +1,103 @@ +import { EventEmitter } from 'node:events' +import { afterEach, expect, it, vi } from 'vitest' +import { runOperationReportJob } from '../src/operation-report-job.ts' + +const create = vi.hoisted(() => vi.fn<(...args: unknown[]) => EventEmitter>()) +vi.mock('node:worker_threads', () => ({ Worker: function (...args: unknown[]) { return create(...args) } })) +afterEach(() => { vi.useRealTimers(); create.mockReset() }) +const input = { reportPath: 'saved.log', directory: 'history', + limits: { bytes: 65536, recordBytes: 4096, records: 100, outputBytes: 65536 }, journal: null } + +it('does not report cancellation complete until the terminated worker exits', async () => { + vi.useFakeTimers() + const worker = Object.assign(new EventEmitter(), { postMessage: vi.fn(), terminate: vi.fn(async () => 1) }) + create.mockReturnValue(worker) + let settled = false + const result = runOperationReportJob(input, { timeoutMs: 500, cancellationGraceMs: 100 }, new AbortController().signal).then((value) => { + settled = true + return value + }) + await vi.advanceTimersByTimeAsync(500) + expect(worker.terminate).toHaveBeenCalledTimes(1) + expect(settled).toBe(false) + worker.emit('exit', 1) + expect(await result).toEqual({ appended: false, timedOut: true, cancelled: true }) + expect(vi.getTimerCount()).toBe(0) +}) + +it('requires successful worker exit after the complete append message', async () => { + vi.useFakeTimers() + const worker = new EventEmitter() + create.mockReturnValue(worker) + const result = runOperationReportJob(input, { timeoutMs: 500, cancellationGraceMs: 100 }, new AbortController().signal) + worker.emit('message', true) + worker.emit('exit', 0) + expect(await result).toEqual({ appended: true, timedOut: false, cancelled: false }) + expect(vi.getTimerCount()).toBe(0) +}) + +it('contains startup and runtime worker failures', async () => { + create.mockImplementationOnce(() => { throw new Error('worker unavailable') }) + expect(await runOperationReportJob(input, { timeoutMs: 500, cancellationGraceMs: 100 }, new AbortController().signal)) + .toEqual({ appended: false, timedOut: false, cancelled: false }) + const worker = new EventEmitter() + create.mockReturnValue(worker) + const result = runOperationReportJob(input, { timeoutMs: 500, cancellationGraceMs: 100 }, new AbortController().signal) + worker.emit('error', new Error('collector failed')) + worker.emit('exit', 1) + expect(await result).toEqual({ appended: false, timedOut: false, cancelled: false }) +}) + +it('retains ownership after termination rejects until the worker actually exits', async () => { + vi.useFakeTimers() + const worker = Object.assign(new EventEmitter(), { postMessage: vi.fn(), terminate: vi.fn(async () => { throw new Error('termination failed') }) }) + create.mockReturnValue(worker) + let settled = false + const result = runOperationReportJob(input, { timeoutMs: 500, cancellationGraceMs: 100 }, new AbortController().signal).then((value) => { + settled = true + return value + }) + await vi.advanceTimersByTimeAsync(500) + expect(worker.terminate).toHaveBeenCalledTimes(1) + expect(settled).toBe(false) + worker.emit('exit', 1) + expect(await result).toEqual({ appended: false, timedOut: true, cancelled: true }) + expect(vi.getTimerCount()).toBe(0) +}) + + +it('allows cooperative exit during the reserved cleanup window', async () => { + vi.useFakeTimers() + const worker = Object.assign(new EventEmitter(), { postMessage: vi.fn(), terminate: vi.fn() }) + create.mockReturnValue(worker) + const result = runOperationReportJob(input, { timeoutMs: 500, cancellationGraceMs: 100 }, new AbortController().signal) + await vi.advanceTimersByTimeAsync(400) + expect(worker.postMessage).toHaveBeenCalledExactlyOnceWith('cancel') + expect(worker.terminate).not.toHaveBeenCalled() + worker.emit('exit', 0) + expect(await result).toEqual({ appended: false, timedOut: true, cancelled: true }) + expect(vi.getTimerCount()).toBe(0) +}) + +it('cancels on application shutdown without extending the cleanup window', async () => { + vi.useFakeTimers() + const worker = Object.assign(new EventEmitter(), { postMessage: vi.fn(), terminate: vi.fn(async () => 1) }) + create.mockReturnValue(worker) + const controller = new AbortController() + const result = runOperationReportJob(input, { timeoutMs: 500, cancellationGraceMs: 100 }, controller.signal) + await vi.advanceTimersByTimeAsync(200) + controller.abort() + controller.abort() + expect(worker.postMessage).toHaveBeenCalledExactlyOnceWith('cancel') + await vi.advanceTimersByTimeAsync(100) + expect(worker.terminate).toHaveBeenCalledTimes(1) + worker.emit('exit', 1) + expect(await result).toEqual({ appended: false, timedOut: false, cancelled: true }) + expect(vi.getTimerCount()).toBe(0) +}) + +it('does not start a collector after shutdown was requested', async () => { + expect(await runOperationReportJob(input, { timeoutMs: 500, cancellationGraceMs: 100 }, AbortSignal.abort())) + .toEqual({ appended: false, timedOut: false, cancelled: true }) + expect(create).not.toHaveBeenCalled() +}) diff --git a/apps/desktop/tests/operation-report-worker.e2e.ts b/apps/desktop/tests/operation-report-worker.e2e.ts new file mode 100644 index 0000000000..fd89dd11da --- /dev/null +++ b/apps/desktop/tests/operation-report-worker.e2e.ts @@ -0,0 +1,81 @@ +/** Built job and packaged Worker acceptance without provider credentials. */ +import { existsSync } from 'node:fs' +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' +import { execa } from 'execa' +import { expect, it, onTestFinished } from 'vitest' + +const job = new URL('../lib/types/operation-report-job.js', import.meta.url) +const worker = new URL('../lib/operation-report-worker.js', import.meta.url) + +it.skipIf(!existsSync(new URL('../lib/types/', import.meta.url)))('appends operation history through the built job and packaged Worker', async () => { + expect(existsSync(job), 'built report job').toBe(true) + expect(existsSync(worker), 'packaged report Worker').toBe(true) + const directory = await mkdtemp(join(tmpdir(), 'desktop-operation-worker-')) + onTestFinished(async () => { await rm(directory, { recursive: true, force: true }) }) + const record = { runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8', transportDropped: 0, + operation: { id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9', time: '2026-10-19T00:00:00.000Z', + reason: 'bundle', phase: 'started', target: 'real-worker-test', stage: 'enable' } } + await writeFile(join(directory, 'operations.jsonl'), JSON.stringify(record) + '\n') + for (const mode of ['job', 'packaged']) { + const reportPath = join(directory, mode + '.log') + await writeFile(reportPath, 'basic report\n') + const input = { reportPath, directory, journal: null, + limits: { bytes: 65536, recordBytes: 4096, records: 100, outputBytes: 65536 } } + const script = join(directory, mode + '.mjs') + await writeFile(script, mode === 'job' + ? `import { runOperationReportJob } from ${JSON.stringify(job.href)};\nconsole.log(JSON.stringify(await runOperationReportJob(${JSON.stringify(input)}, { timeoutMs: 10000, cancellationGraceMs: 100 }, new AbortController().signal)));\n` + : `import { Worker } from 'node:worker_threads';\nconst worker = new Worker(${JSON.stringify(fileURLToPath(worker))}, { workerData: ${JSON.stringify(input)} });\nworker.on('error', error => { throw error });\nworker.on('exit', code => { if (code !== 0) process.exitCode = 1 });\n`) + const result = await execa(process.execPath, [script], { timeout: 30000, reject: false }) + expect(result.timedOut).toBe(false) + expect(result.signal).toBeUndefined() + expect(result.exitCode, result.stderr).toBe(0) + if (mode === 'job') expect(JSON.parse(result.stdout)).toEqual({ appended: true, timedOut: false, cancelled: false }) + const report = await readFile(reportPath, 'utf8') + expect(report.startsWith('basic report\n')).toBe(true) + const summary = JSON.parse(report.split('\n').find(line => line.startsWith('{'))!) as { records: unknown[] } + expect(summary.records).toEqual([record]) + expect(report).toContain('operation history collection complete') + } +}) + +it.skipIf(!existsSync(new URL('../lib/types/', import.meta.url)))('cancels the packaged Worker after an in-flight open settles', async () => { + const directory = await mkdtemp(join(tmpdir(), 'desktop-operation-cancel-')) + onTestFinished(async () => { await rm(directory, { recursive: true, force: true }) }) + const reportPath = join(directory, 'report.log') + await writeFile(reportPath, 'basic report\n') + await writeFile(join(directory, 'operations.jsonl'), '{}\n') + const hook = join(directory, 'hook.mjs') + await writeFile(hook, `import fs from 'node:fs/promises'; +import { syncBuiltinESMExports } from 'node:module'; +import { parentPort } from 'node:worker_threads'; +const original = fs.open; +fs.open = async (...args) => { + const handle = await original(...args); + parentPort.postMessage('opened'); + await new Promise(resolve => parentPort.once('message', resolve)); + return handle; +}; +syncBuiltinESMExports(); +`) + const input = { reportPath, directory, journal: null, + limits: { bytes: 65536, recordBytes: 4096, records: 100, outputBytes: 65536 } } + const script = join(directory, 'cancel.mjs') + await writeFile(script, `import { Worker } from 'node:worker_threads'; +const worker = new Worker(${JSON.stringify(fileURLToPath(worker))}, { + workerData: ${JSON.stringify(input)}, execArgv: ['--import', ${JSON.stringify(pathToFileURL(hook).href)}] +}); +worker.on('message', message => { + if (message === 'opened') worker.postMessage('cancel'); + else console.log(JSON.stringify(message)); +}); +worker.on('error', error => { throw error }); +worker.on('exit', code => { process.exitCode = code }); +`) + const result = await execa(process.execPath, [script], { timeout: 30000, reject: false }) + expect(result.exitCode, result.stderr).toBe(0) + expect(result.stdout).toBe('false') + expect(await readFile(reportPath, 'utf8')).toBe('basic report\n') +}) diff --git a/apps/desktop/tests/operation-report.spec.ts b/apps/desktop/tests/operation-report.spec.ts new file mode 100644 index 0000000000..46e6f6a27f --- /dev/null +++ b/apps/desktop/tests/operation-report.spec.ts @@ -0,0 +1,73 @@ +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished } from 'vitest' +import { appendOperationReport } from '../src/operation-report.ts' +import { writeCrashReport, type CrashReportInput } from '../src/crash-report.ts' + +const input: CrashReportInput = { + operationHistoryPlanned: true, source: 'host', phase: 'startup', error: new Error('startup failed'), + rendererConsole: [], time: new Date('2026-10-19T00:00:00Z'), + app: { name: 'test', version: '1', platform: 'win32', arch: 'x64', electron: '44', node: '24', locale: 'zh-CN' }, +} +const limits = { bytes: 65536, recordBytes: 4096, records: 100, outputBytes: 65536 } +async function fixture() { + const directory = await mkdtemp(join(tmpdir(), 'desktop-operation-report-')) + onTestFinished(async () => { await rm(directory, { recursive: true, force: true }) }) + const report = await writeCrashReport(directory, input) + if (report === undefined) throw new Error('Basic report fixture was not saved') + return { directory, report, basic: await readFile(report, 'utf8') } +} + +it('preserves the independently saved basic report and appends whitelisted recent history', async () => { + const { directory, report, basic } = await fixture() + const record = { runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8', transportDropped: 0, + operation: { id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9', time: '2026-10-19T00:00:00.000Z', + reason: 'bundle', phase: 'started', target: 'test-bundle', stage: 'enable', diagnostic: 'secret' } } + await writeFile(join(directory, 'operations.jsonl'), JSON.stringify(record) + '\n') + expect(await appendOperationReport(report, directory, limits, new AbortController().signal, null)).toBe(true) + const combined = await readFile(report, 'utf8') + expect(combined.startsWith(basic)).toBe(true) + expect(combined).toContain('test-bundle') + expect(combined).not.toContain('secret') + expect(combined).toContain('operation history collection complete') + await expect(combined.slice(basic.length)).toMatchFileSnapshot('./expected/operation-history.txt') +}) + +it('leaves basic bytes unchanged when collection is cancelled or fails before append', async () => { + const { directory, report, basic } = await fixture() + expect(await appendOperationReport(report, directory, limits, AbortSignal.abort(), null)).toBe(false) + expect(await appendOperationReport(report, directory, { ...limits, bytes: 0 }, new AbortController().signal, null)).toBe(false) + expect(await readFile(report, 'utf8')).toBe(basic) + expect(basic).toContain('unavailable or incomplete') +}) + +it('bounds the entire appended section and refuses a budget smaller than its metadata', async () => { + const { directory, report, basic } = await fixture() + expect(await appendOperationReport(report, directory, { ...limits, outputBytes: 1 }, new AbortController().signal, null)).toBe(false) + expect(await readFile(report, 'utf8')).toBe(basic) + expect(await appendOperationReport(report, directory, { ...limits, outputBytes: 512 }, new AbortController().signal, null)).toBe(true) + const summary = (await readFile(report, 'utf8')).slice(basic.length) + expect(Buffer.byteLength(summary)).toBeLessThanOrEqual(512) + expect(summary).toContain('"outputRecordsOmitted":0') +}) + +it('omits oldest records to fit the output budget, counting UTF-8 bytes and all metadata', async () => { + const { directory, report, basic } = await fixture() + const records = Array.from({ length: 20 }, (_, index) => ({ + runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8', transportDropped: 0, + operation: { id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9', time: '2026-10-19T00:00:00.000Z', + reason: 'bundle', phase: 'started', target: `测试插件-${index}`, stage: 'enable' }, + })) + await writeFile(join(directory, 'operations.jsonl'), records.map(record => JSON.stringify(record)).join('\n') + '\n') + expect(await appendOperationReport(report, directory, { ...limits, outputBytes: 1024 }, new AbortController().signal, null)).toBe(true) + const section = (await readFile(report, 'utf8')).slice(basic.length) + expect(Buffer.byteLength(section)).toBeLessThanOrEqual(1024) + const summary = JSON.parse(section.split('\n').find(line => line.startsWith('{'))!) as { + outputRecordsOmitted: number + records: { operation: { target: string } }[] + } + expect(summary.outputRecordsOmitted).toBeGreaterThan(0) + expect(summary.records.length + summary.outputRecordsOmitted).toBe(20) + expect(summary.records[0]?.operation.target).toBe('测试插件-19') +}) diff --git a/apps/desktop/tests/package-target-stages.spec.ts b/apps/desktop/tests/package-target-stages.spec.ts index 9ca7e94e05..37bd38384f 100644 --- a/apps/desktop/tests/package-target-stages.spec.ts +++ b/apps/desktop/tests/package-target-stages.spec.ts @@ -1,4 +1,6 @@ import { writeFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { setImmediate } from 'node:timers/promises' import { afterEach, expect, it, vi } from 'vitest' import { packageTarget, parseDesktopPackageInvocation } from '../scripts/package-target.ts' import { withMacOSNotarizationProxy } from '../scripts/macos-notarization-proxy.ts' @@ -43,6 +45,97 @@ function supervisor(failure?: string) { return { run, stages } } +it.each(['pack', 'runtime'] as const)('overlaps Windows preparation and waits for both before signing when %s finishes first', async (first) => { + const { run, stages } = supervisor() + const pack = Promise.withResolvers() + const runtime = Promise.withResolvers() + const finished = new Set() + run.run.mockImplementation(async (stage) => { + stages.push(stage) + if (stage.startsWith('run release:pack --family dsh ')) await pack.promise + if (stage === 'run prepare:runtime --defer-primary-runtime-smoke') { + await runtime.promise + finished.add('runtime') + } + if (stage.startsWith('--dir native/system/packages/entry pack ')) finished.add('pack') + if (stage === 'run sign:primary-runtime') expect([...finished].sort()).toEqual(['pack', 'runtime']) + }) + const operation = packageTarget(parseDesktopPackageInvocation(['win-x64'], 'win32', 'x64'), environment, run) + const outcome = operation.then(() => undefined, (error: unknown) => error) + try { + await vi.waitFor(() => { + expect(stages.some(stage => stage.startsWith('run release:pack --family dsh '))).toBe(true) + expect(stages).toContain('run prepare:runtime --defer-primary-runtime-smoke') + }) + expect(stages).not.toContain('run sign:primary-runtime') + ;(first === 'pack' ? pack : runtime).resolve(undefined) + await vi.waitFor(() => { expect(finished.has(first)).toBe(true) }) + expect(stages).not.toContain('run sign:primary-runtime') + expect(writeFileSync).not.toHaveBeenCalled() + ;(first === 'pack' ? runtime : pack).resolve(undefined) + expect(await outcome).toBeUndefined() + expect(stages).toContain('run sign:primary-runtime') + expect(writeFileSync).toHaveBeenCalledOnce() + } finally { + pack.resolve(undefined) + runtime.resolve(undefined) + await outcome + } +}) + +it.each(['pack', 'runtime'] as const)('drains the other Windows preparation after %s fails without starting later packing or signing', async (failed) => { + const { run, stages } = supervisor() + const pack = Promise.withResolvers() + const runtime = Promise.withResolvers() + const failure = new Error(`${failed} preparation failed`) + let settled = false + run.run.mockImplementation(async (stage) => { + stages.push(stage) + if (stage.startsWith('run release:pack --family dsh ')) await pack.promise + if (stage === 'run prepare:runtime --defer-primary-runtime-smoke') await runtime.promise + }) + const outcome = packageTarget(parseDesktopPackageInvocation(['win-x64'], 'win32', 'x64'), environment, run).then( + () => { settled = true; return undefined }, + (error: unknown) => { settled = true; return error }, + ) + try { + await vi.waitFor(() => { + expect(stages.some(stage => stage.startsWith('run release:pack --family dsh '))).toBe(true) + expect(stages).toContain('run prepare:runtime --defer-primary-runtime-smoke') + }) + ;(failed === 'pack' ? pack : runtime).reject(failure) + await setImmediate() + expect(settled).toBe(false) + expect(writeFileSync).not.toHaveBeenCalled() + ;(failed === 'pack' ? runtime : pack).resolve(undefined) + expect(await outcome).toBe(failure) + expect(stages.filter(stage => stage.startsWith('run release:pack'))).toHaveLength(1) + expect(stages.some(stage => stage.startsWith('--dir apps/desktop-host pack'))).toBe(false) + expect(stages.some(stage => stage.startsWith('--dir native/system'))).toBe(false) + expect(stages.some(stage => stage.startsWith('run sign:primary-runtime'))).toBe(false) + expect(stages.some(stage => stage.startsWith('run prepare:packages') || stage.startsWith('run prepare:dsh'))).toBe(false) + expect(writeFileSync).not.toHaveBeenCalled() + } finally { + pack.resolve(undefined) + runtime.resolve(undefined) + await outcome + } +}) + +it.each([undefined, '3'])('passes the package cache and selected compression to their subprocesses (%s)', async (level) => { + const { run } = supervisor() + const cache = resolve('fixture-package-cache') + await packageTarget(parseDesktopPackageInvocation(['win-x64'], 'win32', 'x64'), { + ...environment, DSH_DESKTOP_PACKAGE_CACHE_DIR: cache, + ...(level === undefined ? {} : { DSH_DESKTOP_WINDOWS_COMPRESSION_LEVEL: level }), + ELECTRON_BUILDER_COMPRESSION_LEVEL: '0', + }, run) + const prepare = run.run.mock.calls.find(([stage]) => stage.startsWith('run prepare:dsh'))! + expect(prepare[3].env.DSH_DESKTOP_PACKAGE_CACHE_DIR).toBe(cache) + const builder = run.run.mock.calls.find(([stage]) => stage.startsWith('exec electron-builder'))! + expect(builder[3].env.ELECTRON_BUILDER_COMPRESSION_LEVEL).toBe(level ?? '0') +}) + it.each([undefined, '2'])('uses bounded Windows packing while retaining signing and smoke (workers=%s)', async (workers) => { const { run, stages } = supervisor() const settings = workers === undefined ? environment : { ...environment, DSH_DESKTOP_WINDOWS_PACK_CONCURRENCY: workers } @@ -147,7 +240,10 @@ it.each([ const invocation = parseDesktopPackageInvocation([target, '--unsigned'], target === 'win-x64' ? 'win32' : 'darwin', target === 'win-x64' ? 'x64' : 'arm64') await expect(packageTarget(invocation, environment, run)).rejects.toThrow('stage refused') - expect(stages.at(-1)?.startsWith(failure)).toBe(true) + const failedAt = stages.findIndex(stage => stage.startsWith(failure)) + expect(failedAt).toBeGreaterThanOrEqual(0) + expect(stages.slice(failedAt + 1)).toEqual( + target === 'win-x64' && failure.startsWith('exec tsx') ? ['run prepare:runtime'] : []) expect(stages.some(stage => stage.startsWith('--dir apps/desktop-host pack'))).toBe(false) expect(writeFileSync).not.toHaveBeenCalled() }) @@ -253,7 +349,8 @@ it.each([false, true])('keeps signing and runtime verification when notarization await packageTarget(parseDesktopPackageInvocation(['mac-arm64', '--skip-notarization', ...(directory ? ['--dir'] : [])], 'darwin', 'arm64'), { ...environment, CSC_LINK: 'signing.p12', CSC_KEY_PASSWORD: 'fixture-password', }, run) - expect(stages.at(-2)).toBe(`exec electron-builder --config electron-builder.config.mjs --mac --arm64 --publish never${directory ? ' --dir' : ''}`) + expect(stages).toContain('exec electron-builder --config electron-builder.config.mjs --mac --arm64 --publish never --dir') + if (!directory) expect(stages.at(-2)).toContain('--mac zip') expect(stages.at(-1)).toBe('exec tsx scripts/smoke-packaged-runtime.ts --skip-notarization') expect(run.run.mock.calls.at(-2)![3].env).toMatchObject({ DSH_DESKTOP_UNSIGNED: '0', DSH_DESKTOP_MACOS_SKIP_NOTARIZATION: '1', CSC_LINK: 'signing.p12', @@ -263,6 +360,34 @@ it.each([false, true])('keeps signing and runtime verification when notarization expect(writeFileSync).not.toHaveBeenCalled() }) +it.each(['mac-arm64', 'mac-x64'] as const)('applies ZIP compression without changing DMG settings when skipping notarization for %s', async (target) => { + for (const level of [undefined, '3', '7']) { + const { run } = supervisor() + await packageTarget(parseDesktopPackageInvocation([target, '--skip-notarization'], 'darwin', 'arm64'), { + ...environment, ELECTRON_BUILDER_COMPRESSION_LEVEL: '9', + ...(level === undefined ? {} : { DSH_DESKTOP_MACOS_ZIP_COMPRESSION_LEVEL: level }), + }, run) + const builders = run.run.mock.calls.filter(call => call[0].startsWith('exec electron-builder')) + expect(builders).toHaveLength(3) + const [app, dmg, zip] = builders + expect(app![0]).toContain('--dir') + expect(dmg![0]).toContain('--mac dmg') + expect(zip![0]).toContain('--mac zip') + expect(app![3].env.ELECTRON_BUILDER_COMPRESSION_LEVEL).toBe('9') + expect(dmg![3].env.ELECTRON_BUILDER_COMPRESSION_LEVEL).toBe('9') + expect(zip![3].env.ELECTRON_BUILDER_COMPRESSION_LEVEL).toBe(level ?? '3') + for (const call of [dmg!, zip!]) { + expect(call[0]).toContain('--prepackaged') + expect(call[0]).toContain('unnotarized-artifacts') + expect(call[3].env.DSH_DESKTOP_MACOS_SKIP_NOTARIZATION).toBe('1') + expect(call[3].env.DSH_DESKTOP_UNSIGNED).toBe('0') + } + } + expect(packageMacOSArtifacts).not.toHaveBeenCalled() + expect(withMacOSNotarizationProxy).not.toHaveBeenCalled() + expect(writeFileSync).not.toHaveBeenCalled() +}) + it('fails debugging packages when runtime verification fails', async () => { const failure = 'exec tsx scripts/smoke-packaged-runtime.ts --skip-notarization' const { run, stages } = supervisor(failure) @@ -271,3 +396,29 @@ it('fails debugging packages when runtime verification fails', async () => { expect(stages.at(-1)).toBe(failure) expect(writeFileSync).not.toHaveBeenCalled() }) + +it('stops unnotarized ZIP packaging when the DMG stage fails', async () => { + const failure = 'exec electron-builder --config electron-builder.config.mjs --mac dmg' + const { run, stages } = supervisor(failure) + await expect(packageTarget(parseDesktopPackageInvocation(['mac-arm64', '--skip-notarization'], 'darwin', 'arm64'), environment, run)) + .rejects.toThrow('stage refused') + expect(stages.some(stage => stage.includes('--mac zip'))).toBe(false) + expect(stages.some(stage => stage.includes('smoke-packaged-runtime'))).toBe(false) + expect(writeFileSync).not.toHaveBeenCalled() +}) + +it.each([undefined, '7'])('applies file-owned compression only to the final notarized ZIP (%s)', async (level) => { + const { run } = supervisor() + vi.mocked(packageMacOSArtifacts).mockImplementationOnce(async (_request, build) => { + await build({ format: 'dmg', appPath: '/fixture/app', output: '/fixture/dmg' }) + await build({ format: 'zip', appPath: '/fixture/app', output: '/fixture/zip' }) + }) + const settings = { ...environment, ELECTRON_BUILDER_COMPRESSION_LEVEL: '9', + ...(level === undefined ? {} : { DSH_DESKTOP_MACOS_ZIP_COMPRESSION_LEVEL: level }) } + await packageTarget(parseDesktopPackageInvocation(['mac-arm64'], 'darwin', 'arm64'), settings, run) + const zip = run.run.mock.calls.find(call => call[0].includes('--mac zip')) + const dmg = run.run.mock.calls.find(call => call[0].includes('--mac dmg')) + expect(zip?.[3].env.ELECTRON_BUILDER_COMPRESSION_LEVEL).toBe(level ?? '3') + expect(dmg?.[3].env.ELECTRON_BUILDER_COMPRESSION_LEVEL).toBe('9') + expect(writeFileSync).toHaveBeenCalledOnce() +}) diff --git a/apps/desktop/tests/primary-runtime-signing.spec.ts b/apps/desktop/tests/primary-runtime-signing.spec.ts index 5c7b4aa080..2aae8516c5 100644 --- a/apps/desktop/tests/primary-runtime-signing.spec.ts +++ b/apps/desktop/tests/primary-runtime-signing.spec.ts @@ -65,32 +65,84 @@ it('bounds overlapping cache restores and verifies all hits before serial hardwa expect(sign.mock.calls.map(([request]) => request.path)).toEqual(['c.exe', 'd.exe'].map(name => join(root, name))) }) -it.each(['restore', 'verification', 'audit'])('drains active cache restores after %s failure without dispatching more work', async (failure) => { +it('drains active cache restores after failure without dispatching more work', async () => { const root = await fixture(['a.exe', 'b.exe', 'c.exe']) const entered = Promise.withResolvers() const release = Promise.withResolvers() const failed = Promise.withResolvers() - const restored = new Set() const calls: string[] = [] const sign = vi.fn(async () => {}) let settled = false const operation = signWindowsCode(root, { thumbprint, sign, - record: (event) => { - if (failure === 'audit' && 'type' in event && event.type === 'windows-code-signature-verified') { - failed.resolve(undefined) - throw new Error('audit failed') - } - }, - inspect: async (path) => { - if (!restored.has(path)) return unsigned - if (failure === 'verification' && path.endsWith('a.exe')) { failed.resolve(undefined); throw new Error('verification failed') } - return valid - }, + record: () => {}, + inspect: async () => unsigned, cache: { concurrency: 2, restore: async ({ path }) => { calls.push(path) if (path.endsWith('b.exe')) { entered.resolve(undefined); await release.promise; return false } await entered.promise - if (failure === 'restore') { failed.resolve(undefined); throw new Error('restore failed') } + failed.resolve(undefined) + throw new Error('restore failed') + } }, + }).then(() => { settled = true; return undefined }, (error: unknown) => { settled = true; return error }) + try { + await Promise.race([failed.promise, operation]) + await new Promise(resolve => setImmediate(resolve)) + expect(settled).toBe(false) + expect(sign).not.toHaveBeenCalled() + } finally { release.resolve(undefined); await operation } + expect(await operation).toEqual(new Error('restore failed')) + expect(calls).toEqual(['a.exe', 'b.exe'].map(name => join(root, name))) + expect(sign).not.toHaveBeenCalled() +}) + +it.each(['trust', 'timestamp', 'certificate', 'audit'])('rejects restored target %s failures before hardware signing', async (failure) => { + const root = await fixture(['a.exe', 'b.exe', 'miss.exe']) + const restored = new Set() + let restores = 0 + const sign = vi.fn(async () => {}) + await expect(signWindowsCode(root, { thumbprint, sign, + record: (event) => { + if (failure === 'audit' && 'type' in event && event.type === 'windows-code-signature-verified') throw new Error('audit failed') + }, + inspect: async (path) => { + if (!restored.has(path)) return unsigned + expect(restores).toBe(3) + return { + ...valid, + ...(failure === 'trust' ? { status: 'HashMismatch' } : {}), + ...(failure === 'timestamp' ? { timestamped: false } : {}), + ...(failure === 'certificate' ? { thumbprint: 'B'.repeat(40) } : {}), + } + }, + cache: { concurrency: 2, restore: async ({ path }) => { + restores++ + if (path.endsWith('miss.exe')) return false + restored.add(path) + return true + } }, + })).rejects.toThrow(failure === 'audit' ? 'audit failed' : 'signing verification failed') + expect(restores).toBe(3) + expect(sign).not.toHaveBeenCalled() +}) + +it('drains failed restored-target inspection before returning and never signs misses', async () => { + const root = await fixture(['a.exe', 'b.exe', 'miss.exe']) + const entered = Promise.withResolvers() + const failed = Promise.withResolvers() + const release = Promise.withResolvers() + const restored = new Set() + const sign = vi.fn(async () => {}) + let settled = false + const operation = signWindowsCode(root, { thumbprint, sign, record: () => {}, + inspect: async (path) => { + if (!restored.has(path)) return unsigned + if (path.endsWith('b.exe')) { entered.resolve(undefined); await release.promise; return valid } + await entered.promise + failed.resolve(undefined) + throw new Error('verification failed') + }, + cache: { concurrency: 2, restore: async ({ path }) => { + if (path.endsWith('miss.exe')) return false restored.add(path) return true } }, @@ -101,8 +153,7 @@ it.each(['restore', 'verification', 'audit'])('drains active cache restores afte expect(settled).toBe(false) expect(sign).not.toHaveBeenCalled() } finally { release.resolve(undefined); await operation } - expect(await operation).toEqual(new Error(`${failure} failed`)) - expect(calls).toEqual(['a.exe', 'b.exe'].map(name => join(root, name))) + expect(await operation).toEqual(new Error('verification failed')) expect(sign).not.toHaveBeenCalled() }) diff --git a/apps/desktop/tests/runtime-preparation.spec.ts b/apps/desktop/tests/runtime-preparation.spec.ts index d16dd592c2..5da6e9815d 100644 --- a/apps/desktop/tests/runtime-preparation.spec.ts +++ b/apps/desktop/tests/runtime-preparation.spec.ts @@ -12,6 +12,7 @@ const state = vi.hoisted(() => ({ pnpm: '11.7.0' as string | undefined, failure: undefined as 'electron' | 'primary' | 'cli' | undefined, preparePrimary: vi.fn(), + extractElectron: vi.fn(), commandLink: vi.fn(), })) vi.mock('../scripts/desktop-build-paths.mjs', async importOriginal => ({ @@ -22,9 +23,7 @@ vi.mock('../scripts/desktop-build-paths.mjs', async importOriginal => ({ }), })) vi.mock('@electron/get', () => ({ downloadArtifact: async () => 'electron.zip' })) -vi.mock('extract-zip', () => ({ default: async () => { - if (state.failure === 'electron') throw new Error('Electron extraction failed') -} })) +vi.mock('extract-zip', () => ({ default: state.extractElectron })) vi.mock('node:child_process', async importOriginal => ({ ...await importOriginal(), execFileSync: (file: string) => file === '/usr/libexec/PlistBuddy' ? '12.0\n' : '24.18.1\n', @@ -54,6 +53,9 @@ beforeEach(() => { state.failure = undefined process.argv = [process.execPath, 'prepare-runtime.ts'] vi.stubEnv('DSH_DESKTOP_PACKAGING_RUN_DIR', undefined) + state.extractElectron.mockImplementation(async () => { + if (state.failure === 'electron') throw new Error('Electron extraction failed') + }) state.preparePrimary.mockImplementation(async () => { if (state.failure === 'primary') throw new Error('primary preparation failed') const root = join(state.root, 'runtime', 'primary-runtime') @@ -118,3 +120,94 @@ it.each([ await expect(import('../scripts/prepare-runtime.ts')).rejects.toThrow(error) expect(existsSync(join(state.root, 'runtime', 'versions.json'))).toBe(false) }) + +it.each(['electron', 'primary'] as const)('overlaps Windows payloads and waits for %s to finish last before publishing CLI and versions', async (last) => { + state.target = 'win-x64' + const electron = Promise.withResolvers() + const primary = Promise.withResolvers() + const started = new Set() + const finished = new Set() + const preparePrimary = state.preparePrimary.getMockImplementation()! + state.extractElectron.mockImplementation(async () => { + started.add('electron') + await electron.promise + finished.add('electron') + }) + state.preparePrimary.mockImplementation(async () => { + started.add('primary') + await primary.promise + await preparePrimary() + finished.add('primary') + }) + const outcome = import('../scripts/prepare-runtime.ts').then(() => undefined, (error: unknown) => error) + try { + await vi.waitFor(() => { expect([...started].sort()).toEqual(['electron', 'primary']) }, { timeout: 5000 }) + ;(last === 'electron' ? primary : electron).resolve(undefined) + await vi.waitFor(() => { expect(finished.size).toBe(1) }, { timeout: 5000 }) + expect(existsSync(join(state.root, 'runtime', 'cli'))).toBe(false) + expect(existsSync(join(state.root, 'runtime', 'versions.json'))).toBe(false) + ;(last === 'electron' ? electron : primary).resolve(undefined) + expect(await outcome).toBeUndefined() + expect(existsSync(join(state.root, 'runtime', 'cli', 'command-manager.js'))).toBe(true) + expect(existsSync(join(state.root, 'runtime', 'versions.json'))).toBe(true) + } finally { + electron.resolve(undefined) + primary.resolve(undefined) + await outcome + } +}) + +it.each(['electron', 'primary'] as const)('drains the sibling after Windows %s failure without publishing CLI or versions', async (failed) => { + state.target = 'win-x64' + const electron = Promise.withResolvers() + const primary = Promise.withResolvers() + const started = new Set() + const completed = new Set() + const failure = new Error(`${failed} payload failed`) + const prepare = async (name: 'electron' | 'primary', barrier: Promise) => { + started.add(name) + try { await barrier } finally { completed.add(name) } + } + state.extractElectron.mockImplementation(() => prepare('electron', electron.promise)) + state.preparePrimary.mockImplementation(() => prepare('primary', primary.promise)) + const outcome = import('../scripts/prepare-runtime.ts').then( + () => ({ error: undefined, completed: [...completed].sort() }), + (error: unknown) => ({ error, completed: [...completed].sort() }), + ) + try { + await vi.waitFor(() => { expect([...started].sort()).toEqual(['electron', 'primary']) }, { timeout: 5000 }) + ;(failed === 'electron' ? electron : primary).reject(failure) + await vi.waitFor(() => { expect(completed.has(failed)).toBe(true) }, { timeout: 5000 }) + expect(existsSync(join(state.root, 'runtime', 'cli'))).toBe(false) + expect(existsSync(join(state.root, 'runtime', 'versions.json'))).toBe(false) + ;(failed === 'electron' ? primary : electron).resolve(undefined) + expect(await outcome).toEqual({ error: failure, completed: ['electron', 'primary'] }) + expect(existsSync(join(state.root, 'runtime', 'cli'))).toBe(false) + expect(existsSync(join(state.root, 'runtime', 'versions.json'))).toBe(false) + } finally { + electron.resolve(undefined) + primary.resolve(undefined) + await outcome + } +}) + +it.each(['mac-arm64', 'mac-x64'] as const)('keeps %s primary preparation after Electron extraction', async (target) => { + state.target = target + const electron = Promise.withResolvers() + let extracting = false + state.extractElectron.mockImplementation(async () => { + extracting = true + await electron.promise + }) + const outcome = import('../scripts/prepare-runtime.ts').then(() => undefined, (error: unknown) => error) + try { + await vi.waitFor(() => { expect(extracting).toBe(true) }, { timeout: 5000 }) + expect(state.preparePrimary).not.toHaveBeenCalled() + electron.resolve(undefined) + expect(await outcome).toBeUndefined() + expect(state.preparePrimary).toHaveBeenCalledOnce() + } finally { + electron.resolve(undefined) + await outcome + } +}) diff --git a/apps/desktop/tests/runtime-tree.spec.ts b/apps/desktop/tests/runtime-tree.spec.ts index dadc4ca08d..1c8c2c58e1 100644 --- a/apps/desktop/tests/runtime-tree.spec.ts +++ b/apps/desktop/tests/runtime-tree.spec.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' import { DESKTOP_HOST_PACKAGE, DESKTOP_HOST_RUNTIME_FILES } from '../src/core-package-set.ts' -import { DESKTOP_RUNTIME_FILE, readDesktopRuntime, runtimePath, verifyDesktopRuntime } from '../src/runtime-tree.ts' +import { DESKTOP_RUNTIME_FILE, readDesktopRuntime, runtimePath, verifyDesktopRuntime, writeDesktopRuntime, writeDesktopRuntimeAsync } from '../src/runtime-tree.ts' import { runtimeFixture } from './runtime-fixture.ts' const roots: string[] = [] @@ -15,6 +15,29 @@ function fixture(): string { } afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) }) +it('seals final file bytes identically with concurrent and synchronous inventory', async () => { + const dsh = join(fixture(), 'dsh') + const original = readDesktopRuntime(dsh) + const names = original.sharedPackages.map(entry => entry.name) + writeFileSync(join(dsh, 'extra.bin'), Buffer.from([0, 1, 255])) + writeFileSync(join(dsh, 'package.json'), '{"type":"module","private":true}\n') + const expected = writeDesktopRuntime(dsh, original.release, names) + const expectedBytes = readFileSync(join(dsh, DESKTOP_RUNTIME_FILE)) + expect(await writeDesktopRuntimeAsync(dsh, original.release, names)).toEqual(expected) + expect(readFileSync(join(dsh, DESKTOP_RUNTIME_FILE))).toEqual(expectedBytes) + expect(await verifyDesktopRuntime(dsh, original.release.version)).toEqual(expected) +}) + +it.each(['manifest', 'link'])('leaves the descriptor unchanged when concurrent sealing rejects a %s', async (failure) => { + const dsh = join(fixture(), 'dsh') + const original = readDesktopRuntime(dsh) + const before = readFileSync(join(dsh, DESKTOP_RUNTIME_FILE)) + if (failure === 'manifest') writeFileSync(join(dsh, 'node_modules', DESKTOP_HOST_PACKAGE, 'package.json'), '{}') + else symlinkSync(join(dsh, 'node_modules'), join(dsh, 'outside'), process.platform === 'win32' ? 'junction' : 'dir') + await expect(writeDesktopRuntimeAsync(dsh, original.release, original.sharedPackages.map(entry => entry.name))).rejects.toThrow() + expect(readFileSync(join(dsh, DESKTOP_RUNTIME_FILE))).toEqual(before) +}) + it('verifies a runtime after relocation without depending on build paths', async () => { const root = fixture() const before = await verifyDesktopRuntime(join(root, 'dsh'), '1.0.0') diff --git a/apps/desktop/tests/signing-concurrency/README.i18n.yaml b/apps/desktop/tests/signing-concurrency/README.i18n.yaml new file mode 100644 index 0000000000..ea5ef116aa --- /dev/null +++ b/apps/desktop/tests/signing-concurrency/README.i18n.yaml @@ -0,0 +1,25 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write apps/desktop/tests/signing-concurrency/README.md +/: + en: cde5fda2a2f4b53f + zh: 19dbeb4af20f26fa +/windows-signing-concurrency-qualification: + en: bd245a9d93c44d46 + zh: eb74f3edc9bb1f97 +/windows-signing-concurrency-qualification/summary: + en: 0d910efcaf9434da + zh: 0e6e179620e82713 +/windows-signing-concurrency-qualification/table-of-contents: + en: 498f69e40952088d + zh: 506c81b0f6879e9a +/windows-signing-concurrency-qualification/retest-on-another-machine: + en: b90878b9b5756cc9 + zh: e69d017153c10660 +/windows-signing-concurrency-qualification/measured-reference: + en: c2d5b47db6ce1e20 + zh: ca1182b064d63081 +/windows-signing-concurrency-qualification/dev-note: + en: b75c8458928b72b9 + zh: 003ba4e17b4b5269 diff --git a/apps/desktop/tests/signing-concurrency/README.md b/apps/desktop/tests/signing-concurrency/README.md new file mode 100644 index 0000000000..75295ce696 --- /dev/null +++ b/apps/desktop/tests/signing-concurrency/README.md @@ -0,0 +1,47 @@ +--- +description: "Windows signing concurrency measurements and retesting on replacement runners." +--- + +# Windows signing concurrency qualification + +English | [中文](README.zh.md) + +## Summary + +Use this record when choosing signing concurrency on a replacement Windows runner. Results apply to the measured host, token and software combination; repeat qualification after changing them. Production signing remains serial. + +## Table of Contents + +- [Retest on another machine](#retest-on-another-machine) +- [Measured reference](#measured-reference) + + + +## Retest on another machine + +1. Follow the [operator-approved experiment procedure](../../windows-signing/README.md#verification), using a hash-pinned corpus of real runtime, application and installer files. Compare the same inputs across modes; preserve originals and use isolated copies without signature-cache reuse. +2. Run `--corpus` with `--rounds 2` to compare 1/1, 2/2 and 4/4 completion workers/hardware requests, reversing the second round. Run the same corpus with `--pipeline-control --rounds 2` for the 4/1 control. Retain the procedure's first-failure stop and interlock handling. +3. Record the date, test and artifact versions, corpus count/bytes/largest file, CPU/RAM/disk, token/client/provider/SignTool versions, timestamp service, competing jobs and resource pressure. Keep both batch wall times and failure/retry counts; retain detailed output outside Git without credentials. Select a candidate only from completely verified runs, then validate it in the complete signed release workflow. Similar results favor fewer hardware requests; unexpected variation needs more rounds. + + + +## Measured reference + +On 2026-10-22, the experiment in PR #6675 used retained files from release run 39725804188, version `0.2.1-rc.2.20261022.50.2`. Each batch contained 148 runtime and 8 application/installer targets: 156 files, 849.2 MiB unsigned, largest 277.5 MiB. Deleted transient targets and repeated intermediate signing passes were excluded. + +The host had a Ryzen AI 9 HX 470 (12 cores/24 threads), 32 GiB RAM and a 1 TB UMIS RPJYJ1T24RLS1QWY disk. The operator identified the token as SafeNet 5110; the precise variant/firmware was not verified. Signing used SafeNet Authentication Client 10.9.4482.0, `eToken Base Cryptographic Provider` and the unchanged machine test preset's SignTool/timestamp service. Public signature removal alone used SDK 10.0.26100.0 SignTool. Mode-average host CPU was 7.6–8.9%, minimum sampled free RAM was 9.9 GiB, and no Runner.Worker was sampled; other Node processes shared the host. + +Times below are batch wall seconds, including signing, timestamp completion and all file verification. They exclude preparation, lock waiting, build, cache lookup, package assembly and upload. File-system caches were uncontrolled; these are not cold/hot full-release measurements. + +| Completion workers / hardware requests | Round 1 (s) | Round 2 (s) | Mean (s) | Reduction vs serial | +|---|---:|---:|---:|---:| +| 1 / 1 | 732.3 | 718.5 | 725.4 | — | +| 2 / 2 | 398.3 | 394.6 | 396.5 | 45.3% | +| 4 / 4 | 459.4 | 465.0 | 462.2 | 36.3% | +| 4 / 1, separate control | 427.7 | 428.3 | 428.0 | 41.0% | + +All 1,248 signatures, timestamps and final validations passed, with zero hardware failures/timeouts or timestamp retries. Original files and signature-cache payloads remained unchanged. The 2/2 mode was fastest; 4/4 was slower, while pipeline overlap alone delivered most of the observed benefit. This selects candidates for further release testing, not a production default or evidence of parallel operations inside the token. It does not establish a ten-minute complete release. + +## Dev Note + +None. diff --git a/apps/desktop/tests/signing-concurrency/README.zh.md b/apps/desktop/tests/signing-concurrency/README.zh.md new file mode 100644 index 0000000000..52c0a522d5 --- /dev/null +++ b/apps/desktop/tests/signing-concurrency/README.zh.md @@ -0,0 +1,47 @@ +--- +description: "Windows 签名并发实测结果与更换 runner 后的复测方法。" +--- + +# Windows 签名并发验收 + +[English](README.md) | 中文 + +## 摘要 + +更换 Windows runner 后,使用本记录选择签名并发参数。结果仅适用于实测的主机、UKey 和软件组合;更换后需重新验收。生产签名仍为串行。 + +## 目录 + +- [在另一台机器上复测](#retest-on-another-machine) +- [实测参考](#measured-reference) + + + +## 在另一台机器上复测 + +1. 按[经操作人员授权的实验流程](../../windows-signing/README.zh.md#verification),使用哈希固定的真实 runtime、应用和安装器文件集。各模式使用相同输入,保留原件,使用隔离副本且不复用签名缓存。 +2. 使用 `--corpus` 和 `--rounds 2` 比较完成任务数/硬件请求数为 1/1、2/2、4/4 的模式,第二轮反转顺序。对相同文件集使用 `--pipeline-control --rounds 2` 测量 4/1 对照组。保留流程中的首错停止和 interlock 处理。 +3. 记录日期、测试及产物版本、文件数/总大小/最大文件、CPU/内存/磁盘、UKey/客户端/provider/SignTool 版本、时间戳服务、并行任务和资源压力。保留两轮整批墙钟时间及失败/重试次数;详细输出保存在 Git 外且不含凭据。仅从全部验证通过的结果中选择候选参数,再用完整签名发布流程验收。结果接近时优先减少硬件请求;波动异常时增加轮次。 + + + +## 实测参考 + +2026-10-22,PR #6675 中的实验使用发布 run 39725804188 保留的文件,版本为 `0.2.1-rc.2.20261022.50.2`。每批包含 148 个 runtime 和 8 个应用/安装器签名目标:共 156 个文件,无签名总大小 849.2 MiB,最大文件 277.5 MiB。不含已删除的临时目标及中间产物的重复签名调用。 + +主机使用 Ryzen AI 9 HX 470(12 核/24 线程)、32 GiB 内存和 1 TB UMIS RPJYJ1T24RLS1QWY 磁盘。操作人员确认 UKey 为 SafeNet 5110,未核实具体变体/固件。签名使用 SafeNet Authentication Client 10.9.4482.0、`eToken Base Cryptographic Provider`,以及未变更的机器 test preset 中的 SignTool/时间戳服务。仅公开移除签名使用 SDK 10.0.26100.0 SignTool。各模式主机平均 CPU 为 7.6–8.9%,采样可用内存最低 9.9 GiB,未采样到 Runner.Worker;另有 Node 进程共享主机。 + +下表为整批墙钟秒数,包含签名、时间戳完成及全部文件验证。不含准备、等锁、构建、缓存查询、包组装和上传。文件系统缓存未受控,因此不是完整发布的冷/热缓存测量。 + +| 完成任务数 / 硬件请求数 | 第 1 轮(秒) | 第 2 轮(秒) | 平均(秒) | 相对串行减少 | +|---|---:|---:|---:|---:| +| 1 / 1 | 732.3 | 718.5 | 725.4 | — | +| 2 / 2 | 398.3 | 394.6 | 396.5 | 45.3% | +| 4 / 4 | 459.4 | 465.0 | 462.2 | 36.3% | +| 4 / 1,单独对照组 | 427.7 | 428.3 | 428.0 | 41.0% | + +共 1,248 次签名、时间戳及最终验证全部通过,硬件失败/超时及时间戳重试均为零。原文件和签名缓存内容保持不变。2/2 模式最快,4/4 更慢;仅流水线重叠已获得大部分实测收益。这些结果用于选择后续发布测试的候选参数,不是生产默认值,也不能证明 UKey 内部并行执行。它们不能证明完整发布达到十分钟。 + +## 开发备注 + +无。 diff --git a/apps/desktop/tests/windows-asar-unpack.spec.ts b/apps/desktop/tests/windows-asar-unpack.spec.ts index 2fe4b3aaf2..ba417ebce3 100644 --- a/apps/desktop/tests/windows-asar-unpack.spec.ts +++ b/apps/desktop/tests/windows-asar-unpack.spec.ts @@ -125,6 +125,42 @@ async function packageFixture(input: Awaited>) { }).pack([{ src: mapping.from, destination: join(destination, 'dsh'), files, metadata }]) } +it('includes the diagnostic worker in the archive selected by the shipping file rules', async () => { + const root = await mkdtemp(join(tmpdir(), 'diagnostic-worker-asar-')) + roots.push(root) + const appDir = join(root, 'app') + const resources = join(root, 'resources') + const destination = join(resources, 'app') + await mkdir(join(appDir, 'lib'), { recursive: true }) + await mkdir(resources) + const worker = join(appDir, 'lib', 'operation-report-worker.js') + const excluded = join(appDir, 'lib', 'not-shipped.js') + await writeFile(worker, 'export {}') + await writeFile(excluded, 'export {}') + const config = unsignedWindowsConfig('com.example.diagnostics', join(root, 'dsh')) + const filesConfig = config.files.map(entry => typeof entry === 'string' ? entry : { ...entry, filter: [...entry.filter] }) + const matchers = getFileMatchers({ files: filesConfig }, 'files', destination, { + defaultSrc: appDir, globalOutDir: root, customBuildOptions: {}, macroExpander: value => value, + })! + const matcher = matchers.find(entry => entry.from === appDir)! + const filter = matcher.createFilter() + const files: string[] = [] + const metadata = new Map() + for (const file of [worker, excluded]) { + const stat = await lstat(file) + if (filter(file, stat)) { + files.push(file) + metadata.set(file, stat) + } + } + await new AsarPackager({ info: { getWorkspaceRoot: async () => root } }, { + defaultDestination: destination, resourcePath: resources, options: {}, unpackPattern: () => false, + }).pack([{ src: appDir, destination, files, metadata }]) + const archive = await readAsar(join(resources, 'app.asar')) + expect(archive.getFile('lib/operation-report-worker.js').size).toBe(Buffer.byteLength('export {}')) + expect(() => archive.getFile('lib/not-shipped.js')).toThrow() +}) + it.each([false, true])('unpacks PE files through builder source patterns (external=%s)', async (external) => { const input = await fixture(external) const files = await prepareWindowsAsarUnpack(input.context, input.source) diff --git a/apps/desktop/tests/windows-packaging-priority.ps1 b/apps/desktop/tests/windows-packaging-priority.ps1 new file mode 100644 index 0000000000..3a7b6981c6 --- /dev/null +++ b/apps/desktop/tests/windows-packaging-priority.ps1 @@ -0,0 +1,66 @@ +# Exercise priority inheritance in disposable children without changing the test host or runner. +[CmdletBinding()] +param([switch]$Child, [switch]$Failure) +$ErrorActionPreference = 'Stop' +if (-not $IsWindows) { throw 'Requires PowerShell 7 on Windows.' } +$helper = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../scripts/windows-packaging-priority.ps1')) +if ($Failure) { + Add-Type 'public static class DshPackagingPriority { public static int Read(int kind) { throw new System.InvalidOperationException("fixture priority access denied"); } }' + $warnings = @() + $report = & $helper -BestEffort -WarningVariable warnings 3>$null | ConvertFrom-Json + if ($report.comparable -ne $false -or $warnings.Count -ne 1) { throw 'Missing degraded scheduling report.' } + $rejected = $false + try { & $helper } catch { $rejected = $true } + if (-not $rejected) { throw 'Strict priority inspection swallowed failure.' } + exit 0 +} +if ($Child) { + $null = & $helper -InspectOnly + $self = [Diagnostics.Process]::GetCurrentProcess() + try { + $self.PriorityClass = [Diagnostics.ProcessPriorityClass]::BelowNormal + [DshPackagingPriority]::Set(33, 1) + [DshPackagingPriority]::Set(39, 2) + $report = (& $helper | ConvertFrom-Json) + if ($report.before.cpu -ne 'BelowNormal' -or $report.before.io -ne 1 -or $report.before.memory -ne 2) { + throw 'Fixture did not establish background priority.' + } + if ($report.after.cpu -ne 'Normal' -or $report.after.io -ne 2 -or $report.after.memory -ne 5) { + throw 'Packaging shell retained background priority.' + } + $inherited = (& (Join-Path $PSHOME 'pwsh.exe') -NoProfile -File $helper -InspectOnly | ConvertFrom-Json) + if ($LASTEXITCODE -ne 0) { throw 'Priority inspection child failed.' } + if ($inherited.before.cpu -ne 'Normal' -or $inherited.before.io -ne 2 -or $inherited.before.memory -ne 5) { + throw 'Packaging child did not inherit normal priority.' + } + } finally { + $self.Dispose() + } + exit 0 +} +$process = [Diagnostics.Process]::new() +$process.StartInfo.FileName = Join-Path $PSHOME 'pwsh.exe' +$process.StartInfo.UseShellExecute = $false +$process.StartInfo.CreateNoWindow = $true +$process.StartInfo.RedirectStandardError = $true +foreach ($argument in @('-NoProfile', '-File', $PSCommandPath, '-Child')) { + $process.StartInfo.ArgumentList.Add($argument) +} +$started = $false +try { + $started = $process.Start() + if (-not $started) { throw 'Could not start priority test.' } + $errorOutput = $process.StandardError.ReadToEndAsync() + if (-not $process.WaitForExit(30000)) { throw 'Priority test exceeded 30 seconds.' } + if (-not $errorOutput.Wait(5000)) { throw 'Priority test error stream did not close.' } + if ($process.ExitCode -ne 0) { throw "Priority test failed: $($process.ExitCode): $($errorOutput.Result)" } +} finally { + if ($started -and -not $process.HasExited) { + $process.Kill($true) + $process.WaitForExit() + } + $process.Dispose() +} +& (Join-Path $PSHOME 'pwsh.exe') -NoProfile -File $PSCommandPath -Failure +if ($LASTEXITCODE -ne 0) { throw 'Priority failure policy test failed.' } +Write-Output 'Packaging priority normalization, child inheritance and failure policy passed.' diff --git a/apps/desktop/tests/windows-runner-network-process.ps1 b/apps/desktop/tests/windows-runner-network-process.ps1 new file mode 100644 index 0000000000..7b8fe0887b --- /dev/null +++ b/apps/desktop/tests/windows-runner-network-process.ps1 @@ -0,0 +1,140 @@ +# Fake local processes only; no network or signing hardware. +$ErrorActionPreference = 'Stop' +$root = Join-Path ([IO.Path]::GetTempPath()) ('demo-network-' + [guid]::NewGuid().ToString('N')) +$null = New-Item -ItemType Directory $root +try { + foreach ($case in @('ready','not-ready','locked','missing-executable','stale','reused','invalid-config','invalid-delay','bad-record','provider-exit','runner-failure','check-only','recovery','task-route')) { + $base = Join-Path $root $case + $runner = Join-Path $base 'runner' + $network = Join-Path $base 'network' + $null = New-Item -ItemType Directory -Path $network,(Join-Path $runner 'dsh-task') -Force + @' +Set-Content (Join-Path $PSScriptRoot 'child-pid') $PID +Write-Output 'PRIVATE-OUTPUT-MUST-NOT-LEAK' +Start-Sleep -Seconds 60 +'@ | Set-Content (Join-Path $network 'fake.ps1') + @' +param([string]$RunnerRoot,[string]$ConfigRoot) +$network = Join-Path (Split-Path $PSScriptRoot) 'network' +$deadline = [datetime]::UtcNow.AddSeconds(10) +while (-not (Test-Path (Join-Path $network 'child-pid'))) { + if ([datetime]::UtcNow -ge $deadline) { exit 9 } + Start-Sleep -Milliseconds 20 +} +if (Test-Path (Join-Path $network 'fail')) { exit 1 } +exit 0 +'@ | Set-Content (Join-Path $runner 'cold-boot-smoke.ps1') + "Set-Content (Join-Path `$PSScriptRoot 'listened') yes; exit 0" | Set-Content (Join-Path $runner 'dsh-task/start-runner.ps1') + if ($case -eq 'runner-failure') { Set-Content (Join-Path $runner 'dsh-task/start-runner.ps1') "Set-Content (Join-Path `$PSScriptRoot 'listened') yes; exit 7" } + if ($case -in @('recovery','task-route')) { + @' +param([string]$RunnerRoot,[string]$ConfigRoot,[switch]$CheckOnly) +$ErrorActionPreference = 'Stop' +$network = Join-Path $ConfigRoot 'network' +if ($CheckOnly) { + $deadline = [datetime]::UtcNow.AddSeconds(30) + while (-not (Test-Path (Join-Path $network 'child-pid'))) { + if ([datetime]::UtcNow -ge $deadline) { exit 9 } + Start-Sleep -Milliseconds 20 + } + exit 0 +} +Set-Content (Join-Path $PSScriptRoot 'listened') $PID +Write-Output 'RUNNER-STDOUT' +[Console]::Error.WriteLine('RUNNER-STDERR') +for ($iteration = 0; $iteration -lt 2; $iteration++) { + $previous = [int](Get-Content (Join-Path $network 'child-pid')) + $child = Get-Process -Id $previous + try { $child.Kill(); $child.WaitForExit() } finally { $child.Dispose() } + $deadline = [datetime]::UtcNow.AddSeconds(30) + do { + if ([datetime]::UtcNow -ge $deadline) { throw 'Network process was not recovered.' } + Start-Sleep -Milliseconds 50 + $next = Get-Content (Join-Path $network 'child-pid') -Raw + } while (-not $next -or [int]$next -eq $previous) + if ([int](Get-Content (Join-Path $PSScriptRoot 'listened')) -ne $PID) { throw 'Runner was replaced during recovery.' } +} +Write-Output 'RUNNER-SURVIVED-RECOVERY' +exit 0 +'@ | Set-Content (Join-Path $runner 'dsh-task/start-runner.ps1') + } + if ($case -eq 'provider-exit') { + Set-Content (Join-Path $network 'fake.ps1') 'Set-Content (Join-Path $PSScriptRoot "child-pid") $PID; exit 0' + @' +$network = Join-Path (Split-Path $PSScriptRoot) 'network' +$deadline = [datetime]::UtcNow.AddSeconds(10) +do { + if ([datetime]::UtcNow -ge $deadline) { throw 'Provider exit barrier timed out.' } + Start-Sleep -Milliseconds 20 + $record = Join-Path $network 'child-pid' +} while (-not (Test-Path $record) -or (Get-Process -Id ([int](Get-Content $record)) -ErrorAction SilentlyContinue)) +exit 0 +'@ | Set-Content (Join-Path $runner 'cold-boot-smoke.ps1') + } + $exe = if ($case -eq 'missing-executable') { Join-Path $network 'missing.exe' } else { Join-Path $PSHOME 'pwsh.exe' } + @{executable=$exe;arguments=@('-NoProfile','-File',(Join-Path $network 'fake.ps1'));restartDelaySeconds=1} | ConvertTo-Json | Set-Content (Join-Path $network 'launch.json') + if ($case -eq 'invalid-config') { Set-Content (Join-Path $network 'launch.json') '{"executable":"PRIVATE-OUTPUT","arguments":[],"unknown":true}' } + if ($case -eq 'invalid-delay') { @{executable=$exe;arguments=@();restartDelaySeconds=0} | ConvertTo-Json | Set-Content (Join-Path $network 'launch.json') } + if ($case -eq 'bad-record') { Set-Content (Join-Path $network 'process.json') '{"pid":0,"started":1}' } + if ($case -eq 'not-ready') { Set-Content (Join-Path $network 'fail') yes } + $held = if ($case -eq 'locked') { [IO.File]::Open((Join-Path $network 'supervisor.lock'),'OpenOrCreate','ReadWrite','None') } else { $null } + $stale = $null + try { + if ($case -in @('stale','reused')) { + $info = [Diagnostics.ProcessStartInfo]::new($exe) + $info.UseShellExecute = $false + $info.CreateNoWindow = $true + foreach ($argument in @('-NoProfile','-Command','Start-Sleep -Seconds 60')) { $info.ArgumentList.Add($argument) } + $stale = [Diagnostics.Process]::Start($info) + @{pid=$stale.Id;started=($stale.StartTime.ToUniversalTime().Ticks + $(if($case -eq 'reused'){1}else{0}))} | ConvertTo-Json | Set-Content (Join-Path $network 'process.json') + } + [string[]]$options = @(if ($case -eq 'check-only') { '-CheckOnly' }) + if ($case -eq 'task-route') { + $taskRoot = Join-Path $runner 'dsh-task' + Copy-Item (Join-Path $PSScriptRoot '../scripts/run-windows-runner-task.ps1') (Join-Path $taskRoot 'run.ps1') + Copy-Item (Join-Path $PSScriptRoot '../scripts/run-windows-runner-network-process.ps1') $taskRoot + Copy-Item (Join-Path $taskRoot 'start-runner.ps1') (Join-Path $taskRoot 'start.ps1') + @{RunnerRoot=$runner;ConfigRoot=$base;NetworkRoot=$network;RestartCount=1} | ConvertTo-Json | Set-Content (Join-Path $taskRoot 'config.json') + Set-Content (Join-Path $taskRoot 'attempts.txt') 0 + Set-Content (Join-Path $base 'runner-network.json') '{}' + & (Join-Path $PSHOME 'pwsh.exe') -NoProfile -File (Join-Path $taskRoot 'run.ps1') + if ($LASTEXITCODE -ne 1) { throw 'Task wrapper must retain its unexpected-exit result.' } + $output = Get-Content (Get-ChildItem $taskRoot -Filter 'run-*.log').FullName -Raw + if ([int](Get-Content (Join-Path $taskRoot 'attempts.txt')) -ne 1) { throw 'Network recovery consumed task launch budget.' } + } else { + $output = & (Join-Path $PSHOME 'pwsh.exe') -NoProfile -File (Join-Path $PSScriptRoot '../scripts/run-windows-runner-network-process.ps1') -RunnerRoot $runner -ConfigRoot $base -NetworkRoot $network -ReadinessScript (Join-Path $runner 'cold-boot-smoke.ps1') -StartScript (Join-Path $runner 'dsh-task/start-runner.ps1') @options 2>&1 | Out-String + } + if (($LASTEXITCODE -eq 0) -ne ($case -in @('ready','stale','reused','check-only','recovery'))) { throw "Unexpected exit: ${case}: $output" } + if ((Test-Path (Join-Path $runner 'dsh-task/listened')) -ne ($case -in @('ready','stale','reused','runner-failure','recovery','task-route'))) { throw "Listener admission failed: $case" } + if ($case -in @('recovery','task-route')) { + foreach ($expected in @('RUNNER-STDOUT','RUNNER-STDERR','RUNNER-SURVIVED-RECOVERY','Network process exited','Network process restarted (attempt 2)')) { + if (-not $output.Contains($expected)) { throw "Missing recovery evidence: $expected" } + } + } + if ($case -eq 'stale' -and -not $stale.HasExited) { throw 'Owned stale provider was not reaped' } + if ($case -eq 'reused' -and $stale.HasExited) { throw 'A reused PID was killed' } + if ($output.Contains('PRIVATE-OUTPUT')) { throw 'Provider output leaked' } + if (Test-Path (Join-Path $network 'child-pid')) { + $childId = [int](Get-Content (Join-Path $network 'child-pid')) + if (Get-Process -Id $childId -ErrorAction SilentlyContinue) { throw 'Child leaked' } + } + if ($case -ne 'bad-record' -and (Test-Path (Join-Path $network 'process.json'))) { throw 'Ownership record leaked' } + if ($case -eq 'bad-record' -and -not (Test-Path (Join-Path $network 'process.json'))) { throw 'Invalid identity evidence was removed' } + if (-not $held) { + $released = [IO.File]::Open((Join-Path $network 'supervisor.lock'),'OpenOrCreate','ReadWrite','None') + $released.Dispose() + } + Write-Output "PASS: $case" + } finally { + if ($stale) { + if (-not $stale.HasExited) { $stale.Kill(); $stale.WaitForExit() } + $stale.Dispose() + } + if ($held) { $held.Dispose() } + } + } +} finally { + if ([IO.Path]::GetDirectoryName($root).TrimEnd('\') -ne [IO.Path]::GetTempPath().TrimEnd('\')) { throw 'Unsafe cleanup path' } + Remove-Item -LiteralPath $root -Recurse -Force +} +exit 0 diff --git a/apps/desktop/tests/windows-runner-network.ps1 b/apps/desktop/tests/windows-runner-network.ps1 new file mode 100644 index 0000000000..bb9e4fe94e --- /dev/null +++ b/apps/desktop/tests/windows-runner-network.ps1 @@ -0,0 +1,117 @@ +# Isolated proxy fixture; no external requests, runner registration or signing hardware. +param([switch]$CheckStartup) +$ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot '../scripts/windows-runner-network.ps1') +$root = Join-Path ([IO.Path]::GetTempPath()) ('dsh-network-' + [guid]::NewGuid().ToString('N')) +$null = New-Item -ItemType Directory -Path $root +$null = New-Item -ItemType Directory -Path (Join-Path $root 'tools') +$pwshLink = Join-Path $root 'tools/pwsh-7.6.6' +if ($CheckStartup) { $null = New-Item -ItemType Junction -Path $pwshLink -Target $PSHOME } +$server = $null +$saved = @{} +foreach ($name in @('HTTP_PROXY','HTTPS_PROXY','NO_PROXY','NODE_USE_ENV_PROXY')) { $saved[$name] = [Environment]::GetEnvironmentVariable($name,'Process') } +try { + if ($null -ne (Read-RunnerNetwork $root)) { throw 'Absent configuration changed behavior.' } + $fixture = Join-Path $root 'proxy.cjs' + @' +const http = require('node:http'); +const fs = require('node:fs'); +const path = require('node:path'); +const root = process.argv[2]; +const server = http.createServer((req, res) => { + fs.appendFileSync(path.join(root, 'requests'), req.method + ' ' + req.url + '\n'); + if (req.url.includes('/hang')) return; + res.writeHead(req.url.includes('/fail') ? 503 : 200); + res.end(); +}); +server.on('connect', (req, socket) => { + socket.write('HTTP/1.1 200 Connection Established\r\n\r\n'); + server.emit('connection', socket); +}); +server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(root, 'port'), String(server.address().port))); +'@ | Set-Content -LiteralPath $fixture + $info = [Diagnostics.ProcessStartInfo]::new((Get-Command node).Source) + $info.UseShellExecute = $false + $info.CreateNoWindow = $true + $info.ArgumentList.Add($fixture) + $info.ArgumentList.Add($root) + $server = [Diagnostics.Process]::Start($info) + $deadline = [DateTime]::UtcNow.AddSeconds(30) + while (-not (Test-Path (Join-Path $root 'port'))) { + if ($server.HasExited -or [DateTime]::UtcNow -gt $deadline) { throw 'Proxy fixture did not become ready.' } + Start-Sleep -Milliseconds 50 + } + $port = Get-Content (Join-Path $root 'port') -Raw + $config = @{proxyUrl="http://127.0.0.1:$port";noProxy='';serviceName='';probeUrl='http://runner-probe.invalid/ready';attempts=2;timeoutSeconds=2;retrySeconds=1} + function Write-Config { $config | ConvertTo-Json | Set-Content (Join-Path $root 'runner-network.json') } + Write-Config + $parsed = Read-RunnerNetwork $root + Set-RunnerNetwork $parsed + Wait-RunnerNetwork $parsed + if ($env:NODE_USE_ENV_PROXY -ne '1' -or $env:HTTP_PROXY -ne $config.proxyUrl -or $env:HTTPS_PROXY -ne $config.proxyUrl) { throw 'Proxy environment was not applied.' } + # Full startup requires the operator's installed packaging toolchain and persistent PATH. + if ($CheckStartup) { + $output = & (Join-Path $PSHOME 'pwsh.exe') -NoProfile -File (Join-Path $PSScriptRoot '../scripts/start-windows-packaging-runner.ps1') -RunnerRoot $root -ConfigRoot $root -CheckOnly 2>&1 | Out-String + if ($LASTEXITCODE -ne 0 -or -not $output.Contains('Runner network dependency ready')) { throw "Startup integration failed: $output" } + if ((Get-Content (Join-Path $root 'requests')).Count -ne 2) { throw 'Startup did not reach the configured proxy.' } + Clear-Content (Join-Path $root 'requests') + Wait-RunnerNetwork $parsed + } + $config.probeUrl = 'http://runner-probe.invalid/fail' + Write-Config + $failed = $false + try { Wait-RunnerNetwork (Read-RunnerNetwork $root) } catch { $failed = $_.Exception.Message.StartsWith('Runner network dependency unavailable;') } + if (-not $failed -or (Get-Content (Join-Path $root 'requests')).Count -ne 3) { throw 'Failed readiness did not stop at its budget.' } + $config.serviceName = 'fixture-service' + $config.probeUrl = 'http://runner-probe.invalid/ready' + $script:serviceChecks = 0 + function Get-Service { + param($Name) + $script:serviceChecks++ + [pscustomobject]@{ Status = if ($script:serviceChecks -eq 1) { 'Stopped' } else { 'Running' } } + } + try { + Wait-RunnerNetwork $config + if ($script:serviceChecks -ne 2 -or (Get-Content (Join-Path $root 'requests')).Count -ne 4) { throw 'Service readiness did not contain probes.' } + function Get-Service { throw 'fake-secret' } + $failure = $null + try { Wait-RunnerNetwork $config } catch { $failure = $_ } + if (-not $failure -or $failure.ToString().Contains('fake-secret') -or (Get-Content (Join-Path $root 'requests')).Count -ne 4) { throw 'Missing service was not contained.' } + } finally { Remove-Item Function:Get-Service } + $config.serviceName = '' + $config.proxyUrl = 'http://127.0.0.1:1' + $config.noProxy = '127.0.0.1' + $config.probeUrl = "http://127.0.0.1:$port/ready" + Set-RunnerNetwork $config + Wait-RunnerNetwork $config + if ((Get-Content (Join-Path $root 'requests')).Count -ne 5) { throw 'NO_PROXY did not bypass the unavailable proxy.' } + $config.probeUrl = "http://127.0.0.1:$port/hang" + $config.attempts = 1 + $config.timeoutSeconds = 1 + $failure = $null + try { Wait-RunnerNetwork $config } catch { $failure = $_ } + if (-not $failure -or (Get-Content (Join-Path $root 'requests')).Count -ne 6) { throw 'Unresponsive endpoint did not terminate its probe.' } + foreach ($invalid in @('extra','credential','budget','type','wildcard','malformed')) { + $bad = $config.Clone() + switch ($invalid) { + 'extra' { $bad.unknown = 'invalid' } + 'credential' { $bad.proxyUrl = 'http://fake-secret:fake-secret@localhost:1' } + 'budget' { $bad.attempts = 0 } + 'type' { $bad.retrySeconds = '2' } + 'wildcard' { $bad.serviceName = '*' } + } + $json = if ($invalid -eq 'malformed') { '{fake-secret' } else { $bad | ConvertTo-Json } + $json | Set-Content (Join-Path $root 'runner-network.json') + $failure = $null + try { $null = Read-RunnerNetwork $root } catch { $failure = $_ } + if (-not $failure -or $failure.ToString().Contains('fake-secret')) { throw 'Invalid configuration accepted or disclosed.' } + } + Write-Output "PASS: absent config, proxy routing, Node proxy opt-in, service readiness, bounded failure and redacted invalid config; startup integration=$CheckStartup." +} finally { + foreach ($name in $saved.Keys) { [Environment]::SetEnvironmentVariable($name,$saved[$name],'Process') } + if ($server) { if (-not $server.HasExited) { $server.Kill($true); $server.WaitForExit() }; $server.Dispose() } + if ($CheckStartup) { [IO.Directory]::Delete($pwshLink) } + if ([IO.Path]::GetDirectoryName([IO.Path]::GetFullPath($root)).TrimEnd('\') -ne [IO.Path]::GetTempPath().TrimEnd('\')) { throw 'Fixture cleanup escaped the temporary directory.' } + Remove-Item -LiteralPath $root -Recurse -Force +} +exit 0 diff --git a/apps/desktop/tests/windows-runner-task.ps1 b/apps/desktop/tests/windows-runner-task.ps1 index da9a8ff8ac..a01a90c3f4 100644 --- a/apps/desktop/tests/windows-runner-task.ps1 +++ b/apps/desktop/tests/windows-runner-task.ps1 @@ -7,13 +7,18 @@ $source = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../scripts')) $runner = Join-Path $root 'runner with spaces' $null = New-Item -ItemType Directory -Path $runner Set-Content -LiteralPath (Join-Path $runner '.runner') -Value '{}' -foreach ($file in @('windows-runner-task.ps1','run-windows-runner-task.ps1','windows-runner-launcher.cs')) { Copy-Item -LiteralPath (Join-Path $source $file) -Destination $root } +foreach ($file in @('windows-runner-task.ps1','run-windows-runner-task.ps1','windows-runner-launcher.cs','windows-runner-network.ps1','run-windows-runner-network-process.ps1')) { Copy-Item -LiteralPath (Join-Path $source $file) -Destination $root } $manager = Join-Path $root 'windows-runner-task.ps1' @' param([string]$RunnerRoot, [string]$ConfigRoot, [switch]$CheckOnly) if ($CheckOnly) { exit 0 } Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public static class ConsoleProbe { [DllImport("kernel32.dll")] public static extern IntPtr GetConsoleWindow(); }' Add-Content -LiteralPath (Join-Path $RunnerRoot 'consoles.txt') -Value ([ConsoleProbe]::GetConsoleWindow().ToInt64()) +Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public static class SchedulingProbe { [DllImport("ntdll.dll")] static extern int NtQueryInformationProcess(IntPtr handle, int kind, out int value, int size, out int length); public static int Read(IntPtr handle, int kind) { int value, length; int status = NtQueryInformationProcess(handle, kind, out value, 4, out length); if (status != 0) throw new InvalidOperationException("Priority query failed: " + status); return value; } }' +$process = [Diagnostics.Process]::GetCurrentProcess() +try { + @{ Cpu = $process.PriorityClass.ToString(); Io = [SchedulingProbe]::Read($process.Handle, 33); Memory = [SchedulingProbe]::Read($process.Handle, 39) } | ConvertTo-Json -Compress | Add-Content -LiteralPath (Join-Path $RunnerRoot 'priorities.jsonl') +} finally { $process.Dispose() } Add-Content -LiteralPath (Join-Path $RunnerRoot 'starts.txt') -Value $PID if (-not (Test-Path -LiteralPath (Join-Path $RunnerRoot 'failed-once'))) { Set-Content -LiteralPath (Join-Path $RunnerRoot 'failed-once') -Value 'yes' @@ -50,6 +55,7 @@ try { $peOffset = [BitConverter]::ToInt32($image, 0x3c) if ([BitConverter]::ToUInt16($image, $peOffset + 24 + 68) -ne 2) { throw 'Launcher must use the Windows GUI subsystem.' } if ($task.State -ne 'Disabled' -or $task.Settings.ExecutionTimeLimit -ne 'PT0S' -or $task.Settings.MultipleInstances -ne 'IgnoreNew') { throw 'Unexpected task scheduling settings.' } + if ($task.Settings.Priority -ne 4) { throw 'Runner task must use normal CPU, I/O and memory priority.' } Invoke-Manager install -ExpectFailure $runScript = Join-Path $runner 'dsh-task/run.ps1' $originalRun = Get-Content -LiteralPath $runScript -Raw @@ -75,6 +81,8 @@ if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot 'inherited-writer-star if ([int](Get-Content -LiteralPath (Join-Path $runner 'dsh-task/attempts.txt') -Raw) -ne 2) { throw 'Drain recovery did not consume the normal restart budget.' } $consoles = @(Get-Content -LiteralPath (Join-Path $runner 'consoles.txt')) if ($consoles.Count -ne 2 -or @($consoles | Where-Object { $_ -ne '0' }).Count) { throw 'Initial or recovered runner allocated a console.' } + $priorities = @(Get-Content -LiteralPath (Join-Path $runner 'priorities.jsonl') | ForEach-Object { $_ | ConvertFrom-Json }) + if ($priorities.Count -ne 2 -or @($priorities | Where-Object { $_.Cpu -ne 'Normal' -or $_.Io -ne 2 -or $_.Memory -ne 5 }).Count) { throw 'Initial or recovered runner inherited background scheduling priority.' } $childId = [int]@(Get-Content -LiteralPath $starts)[-1] $child = Get-Process -Id $childId Invoke-Manager start diff --git a/apps/desktop/tests/windows-runtime-code.spec.ts b/apps/desktop/tests/windows-runtime-code.spec.ts new file mode 100644 index 0000000000..d3f1530aaf --- /dev/null +++ b/apps/desktop/tests/windows-runtime-code.spec.ts @@ -0,0 +1,128 @@ +/** PE discovery keeps content checks and drains bounded file reads before failure. */ +import { mkdir, mkdtemp, rm, writeFile, type FileHandle } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { setImmediate } from 'node:timers/promises' +import { afterEach, expect, it, vi } from 'vitest' +import { windowsRuntimeCode } from '../scripts/windows-runtime-signature.mjs' + +const hooks = vi.hoisted(() => ({ + opened: undefined as ((handle: FileHandle) => void) | undefined, +})) + +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + open: async (...args: Parameters) => { + const handle = await actual.open(...args) + hooks.opened?.(handle) + return handle + }, + } +}) + +const roots: string[] = [] + +async function fixture(entries: Record): Promise { + const root = await mkdtemp(join(tmpdir(), 'windows-runtime-code-')) + roots.push(root) + for (const [name, contents] of Object.entries(entries)) { + const path = join(root, name) + await mkdir(dirname(path), { recursive: true }) + await writeFile(path, contents) + } + return root +} + +function executable(): Buffer { + const bytes = Buffer.alloc(128) + bytes.writeUInt16LE(0x5a4d, 0) + bytes.writeUInt32LE(64, 0x3c) + bytes.writeUInt32LE(0x4550, 64) + return bytes +} + +afterEach(async () => { + hooks.opened = undefined + vi.restoreAllMocks() + for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true }) +}) + +it('discovers extensionless PE files in nested directories and excludes foreign native modules', async () => { + const root = await fixture({ + 'nested/deeper/extensionless': executable(), + 'nested/runtime.node': executable(), + 'a.exe': executable(), + 'nested/deeper/foreign.node': Buffer.from([0x7f, 0x45, 0x4c, 0x46]), + 'readme.txt': 'ordinary data', + }) + expect(await windowsRuntimeCode(root)).toEqual([ + 'nested/deeper/extensionless', 'nested/runtime.node', 'a.exe', + ].map(name => join(root, name)).sort()) +}) + +it.each([ + ['broken.exe', Buffer.from('not PE')], + ['nested/extensionless', Buffer.from('MZ')], + ['nested/broken.node', Buffer.from('MZ')], + ['nested/deeper/broken.dll', Buffer.alloc(64)], +])('rejects malformed Windows code at %s', async (name, contents) => { + const root = await fixture({ [name]: contents }) + await expect(windowsRuntimeCode(root)).rejects.toThrow(`Windows code: invalid PE file: ${join(root, name)}`) +}) + +it('limits open files to eight and drains pending closes before rejecting a read failure', async () => { + const root = await fixture(Object.fromEntries(Array.from({ length: 24 }, (_, index) => [ + `${String(index).padStart(2, '0')}.txt`, 'ordinary data', + ]))) + const releaseReads = Promise.withResolvers() + const releaseCloses = Promise.withResolvers() + const failedClosed = Promise.withResolvers() + const failure = new Error('controlled PE header read failure') + let opened = 0 + let active = 0 + let peak = 0 + let settled = false + hooks.opened = (handle) => { + const index = opened++ + active++ + peak = Math.max(peak, active) + const close = handle.close.bind(handle) + vi.spyOn(handle, 'read').mockImplementationOnce(async () => { + await releaseReads.promise + if (index === 0) throw failure + return { bytesRead: 0, buffer: Buffer.alloc(64) } + }) + vi.spyOn(handle, 'close').mockImplementationOnce(async () => { + if (index !== 0) await releaseCloses.promise + await close() + active-- + if (index === 0) failedClosed.resolve(undefined) + }) + } + const operation = windowsRuntimeCode(root).then( + (result) => { settled = true; return result }, + (error: unknown) => { settled = true; return error }, + ) + try { + await vi.waitFor(() => { expect(opened).toBe(8) }) + expect(active).toBe(8) + releaseReads.resolve(undefined) + await failedClosed.promise + await setImmediate() + expect(settled).toBe(false) + expect(opened).toBe(8) + expect(active).toBe(7) + releaseCloses.resolve(undefined) + expect(await operation).toBe(failure) + expect(opened).toBe(8) + expect(peak).toBe(8) + expect(active).toBe(0) + } finally { + hooks.opened = undefined + releaseReads.resolve(undefined) + releaseCloses.resolve(undefined) + await operation + } +}) diff --git a/apps/desktop/tests/windows-sign.spec.ts b/apps/desktop/tests/windows-sign.spec.ts index e5d5a7cd3f..3e0ec371a7 100644 --- a/apps/desktop/tests/windows-sign.spec.ts +++ b/apps/desktop/tests/windows-sign.spec.ts @@ -317,7 +317,9 @@ describe('Windows token signing', () => { 'C:\\release\\setup.exe', ['token-secret'], ) - expect(failure.message).toBe('Windows release signing failed for C:\\release\\setup.exe (exit 1): provider rejected ') + expect(failure.message).toContain('Windows release signing failed for C:\\release\\setup.exe (exit 1): provider rejected ') + expect(failure.message).toContain('After replacing the UKey') + expect(failure.message).toContain('does not establish device lock status') expect(failure.message).not.toContain('token-secret') expect(failure).not.toHaveProperty('cause') expect(failure).not.toHaveProperty('cmd') diff --git a/apps/desktop/tests/windows-signing-concurrency.perf.ts b/apps/desktop/tests/windows-signing-concurrency.perf.ts new file mode 100644 index 0000000000..93c1eb3f18 --- /dev/null +++ b/apps/desktop/tests/windows-signing-concurrency.perf.ts @@ -0,0 +1,209 @@ +/** Operator-only comparison of serial signing and bounded concurrent signature completion. */ +import { execFile } from 'node:child_process' +import { createHash, X509Certificate } from 'node:crypto' +import { existsSync } from 'node:fs' +import { copyFile, mkdir, readFile, writeFile } from 'node:fs/promises' +import { homedir, cpus, totalmem, freemem } from 'node:os' +import { extname, isAbsolute, join, resolve } from 'node:path' +import { parseArgs, promisify } from 'node:util' +import { fileURLToPath } from 'node:url' +import { loadDesktopPackageEnvironment } from '../scripts/desktop-package-environment.mjs' +import { createPackagingRun, recordPackagingEvent } from '../scripts/packaging-run.mjs' +import { beginWindowsSigningAttempt } from '../scripts/windows-signing-state.mjs' +import { withWindowsSigningStage } from '../scripts/windows-signing-stage.mjs' +import { inspectWindowsTokenIdentity, windowsTokenIdentityFailure } from '../scripts/windows-token-identity.ts' +import { buildWindowsSigningEnvironment, createWindowsTokenSigner, scrubWindowsSigningEnvironment } from '../scripts/windows-sign.mjs' +import { inspectWindowsRuntimeSignature } from '../scripts/windows-runtime-signature.mjs' +import { completeWindowsSignature, normalizeWindowsSignature } from '../scripts/windows-timestamp.mjs' +import { runSigningExperimentBatch } from './helpers/windows-signing-experiment.ts' +import { prepareSigningCorpus } from './helpers/windows-signing-corpus.ts' + +const APP_ROOT = fileURLToPath(new URL('..', import.meta.url)) +const MODES = [ + { name: 'serial', jobs: 1, hardwareConcurrency: 1 }, + { name: 'pipeline', jobs: 2, hardwareConcurrency: 1 }, + { name: 'hardware2', jobs: 2, hardwareConcurrency: 2 }, +] as const +const CORPUS_MODES = [ + { name: 'serial', jobs: 1, hardwareConcurrency: 1 }, + { name: 'hardware2', jobs: 2, hardwareConcurrency: 2 }, + { name: 'hardware4', jobs: 4, hardwareConcurrency: 4 }, +] as const + +/** + * Run an explicitly opted-in hardware experiment, retaining unsigned inputs, signed copies and audit records. + * @param args CLI arguments; omission uses the current process arguments. + * @returns Resolves after all requested batches verify; a failure during a batch retains its interlock and stops later modes. + */ +export async function runWindowsSigningConcurrencyExperiment(args = process.argv.slice(2)): Promise { + const { values } = parseArgs({ args, options: { + execute: { type: 'boolean' }, 'config-root': { type: 'string' }, rounds: { type: 'string', default: '2' }, + corpus: { type: 'string' }, 'pipeline-control': { type: 'boolean' }, 'strip-tool': { type: 'string' }, + } }) + if (!values.execute) { + console.log('Operator hardware experiment: node apps/desktop/tests/windows-signing-concurrency.perf.ts --execute --config-root [--rounds 1|2] [--corpus ] [--strip-tool ] [--pipeline-control]') + return + } + if (process.platform !== 'win32' || !values['config-root'] || !isAbsolute(values['config-root']) + || !['1', '2'].includes(values.rounds)) throw new Error('Requires Windows, an absolute config-root and rounds 1 or 2') + if (values.corpus !== undefined && !isAbsolute(values.corpus)) throw new Error('Signing corpus manifest must be an absolute path') + if (values['pipeline-control'] && !values.corpus) throw new Error('Pipeline control requires a real-file corpus') + if (values['strip-tool'] !== undefined && (!values.corpus || !isAbsolute(values['strip-tool']))) throw new Error('Signature stripping override requires a corpus and an absolute SignTool path') + const modes = values['pipeline-control'] ? [{ name: 'pipeline4', jobs: 4, hardwareConcurrency: 1 } as const] + : values.corpus ? CORPUS_MODES : MODES + const environment = loadDesktopPackageEnvironment('win32', { + ...process.env, DSH_PACKAGING_PRESET: 'test', DSH_PACKAGING_CONFIG_DIR: values['config-root'], + }) + const certificateFile = environment.DSH_DESKTOP_WINDOWS_CER_FILE! + const signTool = environment.DSH_DESKTOP_WINDOWS_SIGNTOOL! + const stripTool = values['strip-tool'] ?? signTool + const tokenPin = environment.DSH_DESKTOP_WINDOWS_TOKEN_PIN! + const keyContainer = environment.DSH_DESKTOP_WINDOWS_KEY_CONTAINER!.trim() + // Construction validates the same signing inputs; the production serial hook is never invoked here. + createWindowsTokenSigner({ certificateFile, signTool, tokenPin, keyContainer }) + const certificate = await readFile(certificateFile) + const leaf = new X509Certificate(certificate) + if (Date.now() < Date.parse(leaf.validFrom) || Date.now() > Date.parse(leaf.validTo)) { + throw new Error('Signing experiment requires a currently valid public certificate') + } + const thumbprint = leaf.fingerprint.replaceAll(':', '') + const safeEnvironment = scrubWindowsSigningEnvironment(environment) + delete safeEnvironment.NODE_OPTIONS + delete safeEnvironment.NODE_PATH + const run = createPackagingRun(join(APP_ROOT, '.desktop-build', 'qualification', 'signing-concurrency'), { + kind: 'operator-signing-concurrency', certificateSha256: createHash('sha256').update(certificate).digest('hex'), + node: process.version, cpu: cpus()[0]?.model, logicalCpus: cpus().length, memoryBytes: totalmem(), + rounds: Number(values.rounds), corpus: values.corpus ?? null, stripTool, modes, + cache: 'disabled', probeExecuted: false, + }, { parallel: true, secrets: [tokenPin, keyContainer] }) + console.log(`SIGNING_EXPERIMENT_RECORD ${run.directory}`) + const controller = new AbortController() + const abort = (): void => { controller.abort(new Error('Operator interrupted the signing experiment')) } + process.once('SIGINT', abort) + process.once('SIGTERM', abort) + const record = (event: object): void => { recordPackagingEvent(run.directory, event) } + let success = false + try { + await withWindowsSigningStage({ stage: 'operator-signing-concurrency', signal: controller.signal, record }, async () => { + if (existsSync(join(homedir(), '.dsh-desktop-signing', 'attempt.json'))) { + throw new Error('Retained signing interlock requires operator inspection; experiment refused') + } + const identity = await inspectWindowsTokenIdentity({ certificate, container: keyContainer, environment: safeEnvironment }) + record({ type: 'experiment-public-identity', result: identity, pinSupplied: false }) + if (identity !== 'matched') throw new Error(windowsTokenIdentityFailure(identity)) + let templates: string[] = [] + if (values.corpus) { + let removalIndex = 0 + const corpus = await prepareSigningCorpus(values.corpus, join(run.directory, 'unsigned'), async (path) => { + await run.run(`remove-signature-${removalIndex++}`, stripTool, ['remove', '/s', path], + { cwd: run.directory, env: safeEnvironment, timeoutMs: 60_000 }) + }, controller.signal) + await writeFile(join(run.directory, 'corpus.json'), `${JSON.stringify(corpus, null, 2)}\n`, { flag: 'wx' }) + templates = corpus.map(file => file.path) + record({ type: 'experiment-corpus', files: corpus.length, bytes: corpus.reduce((sum, file) => sum + file.bytes, 0) }) + } else { + const source = join(run.directory, 'probe.cs') + await writeFile(source, 'internal static class SigningProbe { private static int Main() { return 0; } }\n', { flag: 'wx' }) + for (const size of [0, 1024 * 1024, 16 * 1024 * 1024]) { + controller.signal.throwIfAborted() + const resource = join(run.directory, `resource-${size}.bin`) + if (size) await writeFile(resource, Buffer.alloc(size, 0x5a), { flag: 'wx' }) + const output = join(run.directory, `unsigned-${size}.exe`) + await run.run(`compile-probe-${size}`, join(environment.SystemRoot ?? 'C:\\Windows', 'Microsoft.NET/Framework64/v4.0.30319/csc.exe'), + ['/nologo', '/target:exe', '/platform:x64', `/out:${output}`, ...(size ? [`/resource:${resource}`] : []), source], + { cwd: run.directory, env: safeEnvironment, timeoutMs: 30_000 }) + if ((await inspectWindowsRuntimeSignature(output)).status !== 'NotSigned') throw new Error('Probe must be unsigned') + templates.push(output, output) + } + } + const results: { round: number; mode: string; elapsedMs: number; files: number }[] = [] + for (let round = 1; round <= Number(values.rounds); round++) { + const order = round % 2 ? modes : [...modes].reverse() + for (const mode of order) { + controller.signal.throwIfAborted() + const directory = join(run.directory, `round-${round}-${mode.name}`) + await mkdir(directory) + const files: string[] = [] + for (const [index, template] of templates.entries()) { + const file = join(directory, `probe-${index}${extname(template)}`) + await copyFile(template, file) + if (Buffer.compare(await readFile(template), await readFile(file)) !== 0) throw new Error('Signing experiment batch copy differs from its template') + files.push(file) + } + record({ type: 'experiment-batch-plan', round, ...mode, files }) + const attempt = beginWindowsSigningAttempt({ runDirectory: run.directory, target: directory }) + let commandIndex = 0 + const started = performance.now() + try { + record({ type: 'experiment-resources', round, mode: mode.name, point: 'start', freeMemoryBytes: freemem(), cpuTimes: cpus().map(cpu => cpu.times), processMemory: process.memoryUsage() }) + await runSigningExperimentBatch(files, { + ...mode, signal: controller.signal, + sign: async (_file, path) => { + controller.signal.throwIfAborted() + const stage = `experiment-sign-${round}-${mode.name}-${commandIndex++}` + record({ type: 'experiment-hardware-start', stage, path }) + const interpreter = environment.ComSpec ?? join(environment.SystemRoot ?? 'C:\\Windows', 'System32', 'cmd.exe') + await run.run(stage, interpreter, + ['/d', '/v:off', '/c', 'windows-sign.cmd'], { + cwd: join(APP_ROOT, 'scripts'), timeoutMs: 60_000, + env: buildWindowsSigningEnvironment(safeEnvironment, { + certificateFile, signTool, tokenPin, keyContainer, path, isNest: false, + }), + }) + record({ type: 'experiment-hardware-exited', stage, path }) + const signature = await inspectWindowsRuntimeSignature(path) + if (signature.status !== 'Valid' || signature.timestamped || signature.thumbprint?.toUpperCase() !== thumbprint.toUpperCase()) { + throw new Error('Primary signature verification failed') + } + record({ type: 'experiment-hardware-verified', stage, path }) + }, + complete: async (path, sign) => { + const fileStarted = performance.now() + await completeWindowsSignature(path, { + thumbprint, sign, inspect: inspectWindowsRuntimeSignature, evidenceDirectory: run.directory, record, + normalize: file => normalizeWindowsSignature(file, signTool, safeEnvironment), + timestamp: async (file) => { + await promisify(execFile)(signTool, ['timestamp', '/v', '/tr', 'http://timestamp.digicert.com', '/td', 'sha256', file], { + env: safeEnvironment, windowsHide: true, timeout: 60_000, + }) + }, + }) + const signature = await inspectWindowsRuntimeSignature(path) + if (signature.status !== 'Valid' || !signature.timestamped || signature.thumbprint?.toUpperCase() !== thumbprint.toUpperCase()) { + throw new Error('Published probe signature verification failed') + } + record({ type: 'experiment-file-verified', path, ...signature, elapsedMs: performance.now() - fileStarted, + freeMemoryBytes: freemem(), processMemory: process.memoryUsage(), + sha256: createHash('sha256').update(await readFile(path)).digest('hex') }) + }, + }) + controller.signal.throwIfAborted() + const result = { round, mode: mode.name, elapsedMs: performance.now() - started, files: files.length } + record({ type: 'experiment-resources', round, mode: mode.name, point: 'end', freeMemoryBytes: freemem(), cpuTimes: cpus().map(cpu => cpu.times), processMemory: process.memoryUsage() }) + results.push(result) + record({ type: 'experiment-batch-complete', ...result }) + await writeFile(join(run.directory, 'measurements.json'), `${JSON.stringify(results, null, 2)}\n`, { flush: true }) + attempt.success() + console.log(`SIGNING_EXPERIMENT_SAMPLE ${JSON.stringify(result)}`) + } catch (error) { + attempt.failure(null, 'Signing concurrency experiment failed; inspect retained records before recovery') + throw error + } + } + } + }) + success = true + } finally { + process.removeListener('SIGINT', abort) + process.removeListener('SIGTERM', abort) + run.finish(success) + } +} + +if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + runWindowsSigningConcurrencyExperiment().catch(() => { + // Child-process errors can embed arguments; the retained supervisor output is already redacted. + console.error('Signing experiment stopped; inspect its retained record. No automatic hardware retry or interlock recovery.') + process.exitCode = 1 + }) +} diff --git a/apps/desktop/tests/windows-signing-concurrency.spec.ts b/apps/desktop/tests/windows-signing-concurrency.spec.ts new file mode 100644 index 0000000000..bb82cd7062 --- /dev/null +++ b/apps/desktop/tests/windows-signing-concurrency.spec.ts @@ -0,0 +1,235 @@ +/** Driver ownership tests replace every native signing and device boundary. */ +import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { runWindowsSigningConcurrencyExperiment } from './windows-signing-concurrency.perf.ts' +import { loadDesktopPackageEnvironment } from '../scripts/desktop-package-environment.mjs' +import { createPackagingRun } from '../scripts/packaging-run.mjs' +import { beginWindowsSigningAttempt } from '../scripts/windows-signing-state.mjs' +import { inspectWindowsTokenIdentity } from '../scripts/windows-token-identity.ts' +import { prepareSigningCorpus } from './helpers/windows-signing-corpus.ts' + +const state = vi.hoisted(() => ({ + root: '', environment: {} as NodeJS.ProcessEnv, + identity: 'matched', failure: '' as '' | 'primary' | 'final' | 'audit', + signed: new Set(), completed: new Set(), stages: [] as string[], + events: [] as object[], successes: 0, failures: 0, + removals: [] as { executable: string; args: readonly string[]; environment: NodeJS.ProcessEnv }[], +})) + +vi.mock('node:child_process', () => ({ + execFile: vi.fn(() => { throw new Error('Native subprocesses are forbidden in driver tests') }), +})) +vi.mock('node:os', async original => ({ ...await original(), homedir: () => state.root })) +vi.mock('node:crypto', async original => ({ + ...await original(), + X509Certificate: class { + fingerprint = 'A'.repeat(40) + validFrom = 'Jan 1 2000 GMT' + validTo = 'Jan 1 2100 GMT' + }, +})) +vi.mock('../scripts/desktop-package-environment.mjs', () => ({ + loadDesktopPackageEnvironment: vi.fn(() => state.environment), +})) +vi.mock('../scripts/windows-sign.mjs', async original => ({ + ...await original(), + createWindowsTokenSigner: vi.fn(() => { throw new Error('unconfigured constructor') }), +})) +vi.mock('../scripts/windows-token-identity.ts', () => ({ + inspectWindowsTokenIdentity: vi.fn(async () => state.identity), + windowsTokenIdentityFailure: (result: string) => `Identity refused: ${result}`, +})) +vi.mock('./helpers/windows-signing-corpus.ts', () => ({ + prepareSigningCorpus: vi.fn(async () => { + const files = [] + for (let index = 0; index < 6; index++) { + const path = join(state.root, `real-${index}.dll`) + await writeFile(path, 'inert real file') + files.push({ path, bytes: 15, sha256: 'a'.repeat(64) }) + } + return files + }), +})) +vi.mock('../scripts/windows-signing-stage.mjs', () => ({ + withWindowsSigningStage: vi.fn(async (_options: object, operation: () => Promise) => operation()), +})) +vi.mock('../scripts/packaging-run.mjs', () => ({ + createPackagingRun: vi.fn(() => ({ + directory: join(state.root, 'run'), + finish: vi.fn(), + run: vi.fn(async (stage: string, executable: string, args: readonly string[], options: { env: NodeJS.ProcessEnv }) => { + state.stages.push(stage) + if (stage.startsWith('compile-')) { + await writeFile(args.find(arg => arg.startsWith('/out:'))!.slice(5), 'inert probe') + } else if (stage.startsWith('remove-signature-')) { + state.removals.push({ executable, args, environment: options.env }) + } else { + state.signed.add(options.env.DSH_DESKTOP_WINDOWS_SIGN_TARGET!) + } + }), + })), + recordPackagingEvent: (_directory: string, event: object) => { + if (state.failure === 'audit' && 'type' in event && event.type === 'experiment-file-verified') throw new Error('Audit failed') + state.events.push(event) + }, +})) +vi.mock('../scripts/windows-signing-state.mjs', () => ({ + beginWindowsSigningAttempt: vi.fn((options: { runDirectory: string; target: string; stateDirectory?: string }) => { + expect(options.stateDirectory).toBeUndefined() + const lock = join(state.root, '.dsh-desktop-signing', 'attempt.json') + mkdirSync(dirname(lock), { recursive: true }) + writeFileSync(lock, 'batch attempt', { flag: 'wx' }) + return { + success: () => { + const verified = state.events.filter(event => 'type' in event && event.type === 'experiment-file-verified' + && 'path' in event && typeof event.path === 'string' && dirname(event.path) === options.target) + expect(verified).toHaveLength(6) + expect(readFileSync(join(options.runDirectory, 'measurements.json'), 'utf8')).toContain('"files": 6') + unlinkSync(lock) + state.successes++ + }, + failure: () => { state.failures++ }, + } + }), +})) +vi.mock('../scripts/windows-runtime-signature.mjs', () => ({ + inspectWindowsRuntimeSignature: vi.fn(async (path: string) => { + if (!state.signed.has(path)) return { status: 'NotSigned', timestamped: false, thumbprint: null } + const timestamped = state.completed.has(path) + const failed = state.failure === (timestamped ? 'final' : 'primary') + return { status: failed ? 'HashMismatch' : 'Valid', timestamped, thumbprint: 'A'.repeat(40) } + }), +})) +vi.mock('../scripts/windows-timestamp.mjs', () => ({ + completeWindowsSignature: vi.fn(async (path: string, options: { sign: (path: string) => Promise }) => { + await options.sign(path) + state.completed.add(path) + }), + normalizeWindowsSignature: vi.fn(() => { throw new Error('Native normalization is forbidden in driver tests') }), +})) + +const platform = Object.getOwnPropertyDescriptor(process, 'platform')! +beforeEach(async () => { + vi.clearAllMocks() + state.root = await mkdtemp(join(tmpdir(), 'signing-driver-')) + mkdirSync(join(state.root, 'run')) + state.identity = 'matched'; state.failure = ''; state.successes = 0; state.failures = 0 + state.signed.clear(); state.completed.clear(); state.stages = []; state.events = []; state.removals = [] + state.environment = { + DSH_DESKTOP_WINDOWS_CER_FILE: join(state.root, 'certificate.cer'), + DSH_DESKTOP_WINDOWS_SIGNTOOL: 'forbidden-signer', DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'fixture-pin', + DSH_DESKTOP_WINDOWS_KEY_CONTAINER: ' fixture-container ', API_KEY: 'fixture-secret', NODE_OPTIONS: 'forbidden-option', + } + await writeFile(state.environment.DSH_DESKTOP_WINDOWS_CER_FILE!, 'inert certificate') + Object.defineProperty(process, 'platform', { value: 'win32', configurable: true }) + const { createWindowsTokenSigner } = await import('../scripts/windows-sign.mjs') + vi.mocked(createWindowsTokenSigner).mockReturnValue(vi.fn(async () => { throw new Error('Production signer is forbidden') })) + vi.spyOn(console, 'log').mockImplementation(() => {}) +}) +afterEach(async () => { + Object.defineProperty(process, 'platform', platform) + vi.useRealTimers() + vi.restoreAllMocks() + await rm(state.root, { recursive: true, force: true, maxRetries: 3 }) +}) + +const execute = () => runWindowsSigningConcurrencyExperiment(['--execute', '--config-root', state.root, '--rounds', '1']) +const lock = () => join(state.root, '.dsh-desktop-signing', 'attempt.json') + +it('requires opt-in before reading configuration or querying a device', async () => { + await runWindowsSigningConcurrencyExperiment([]) + expect(loadDesktopPackageEnvironment).not.toHaveBeenCalled() + expect(inspectWindowsTokenIdentity).not.toHaveBeenCalled() + expect(createPackagingRun).not.toHaveBeenCalled() +}) + +it.each(['1999-01-01', '2101-01-01'])('rejects certificate validity at %s before querying or signing', async (date) => { + vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(new Date(date)) + await expect(execute()).rejects.toThrow('currently valid') + expect(inspectWindowsTokenIdentity).not.toHaveBeenCalled() + expect(beginWindowsSigningAttempt).not.toHaveBeenCalled() + expect(state.stages).toEqual([]) +}) + +it.each(['certificate-mismatch', 'provider-unavailable', 'container-unavailable', 'unknown'])('refuses public identity %s before any signing', async (identity) => { + state.identity = identity + await expect(execute()).rejects.toThrow('Identity refused') + expect(state.stages).toEqual([]) + expect(beginWindowsSigningAttempt).not.toHaveBeenCalled() +}) + +it('retains an existing default-account interlock without accessing the device', async () => { + mkdirSync(dirname(lock()), { recursive: true }); writeFileSync(lock(), 'prior failure') + await expect(execute()).rejects.toThrow('Retained signing interlock') + expect(inspectWindowsTokenIdentity).not.toHaveBeenCalled() + expect(readFileSync(lock(), 'utf8')).toBe('prior failure') +}) + +it('completes all three modes and releases each default-account batch only after recording every verification', async () => { + await execute() + expect(state.successes).toBe(3) + expect(state.failures).toBe(0) + expect(state.signed.size).toBe(18) + expect(existsSync(lock())).toBe(false) + expect(beginWindowsSigningAttempt).toHaveBeenCalledTimes(3) + expect(inspectWindowsTokenIdentity).toHaveBeenCalledWith(expect.objectContaining({ + container: 'fixture-container', environment: {}, + })) + expect(JSON.stringify(state.events)).not.toMatch(/fixture-pin|fixture-secret|fixture-container/u) +}) + +it('uses fresh real-file copies for 1, 2, 4 workers and reverses the second round', async () => { + await runWindowsSigningConcurrencyExperiment(['--execute', '--config-root', state.root, '--corpus', join(state.root, 'manifest.json')]) + expect(state.successes).toBe(6) + expect(state.signed.size).toBe(36) + expect(state.stages.some(stage => stage.startsWith('compile-'))).toBe(false) + expect(prepareSigningCorpus).toHaveBeenCalledOnce() + expect(state.events.filter(event => 'type' in event && event.type === 'experiment-batch-plan')).toEqual([ + expect.objectContaining({ round: 1, jobs: 1, hardwareConcurrency: 1 }), + expect.objectContaining({ round: 1, jobs: 2, hardwareConcurrency: 2 }), + expect.objectContaining({ round: 1, jobs: 4, hardwareConcurrency: 4 }), + expect.objectContaining({ round: 2, jobs: 4, hardwareConcurrency: 4 }), + expect.objectContaining({ round: 2, jobs: 2, hardwareConcurrency: 2 }), + expect.objectContaining({ round: 2, jobs: 1, hardwareConcurrency: 1 }), + ]) + expect(existsSync(lock())).toBe(false) +}) + +it('offers a separate four-job control with only one hardware request', async () => { + await runWindowsSigningConcurrencyExperiment(['--execute', '--config-root', state.root, '--rounds', '1', '--corpus', join(state.root, 'manifest.json'), '--pipeline-control']) + expect(state.successes).toBe(1) + expect(state.events).toContainEqual(expect.objectContaining({ type: 'experiment-batch-plan', jobs: 4, hardwareConcurrency: 1 })) +}) + +it('refuses corpus preparation failure before beginning a hardware attempt', async () => { + vi.mocked(prepareSigningCorpus).mockRejectedValueOnce(new Error('changed input')) + await expect(runWindowsSigningConcurrencyExperiment(['--execute', '--config-root', state.root, '--corpus', join(state.root, 'manifest.json')])).rejects.toThrow('changed input') + expect(beginWindowsSigningAttempt).not.toHaveBeenCalled() + expect(state.signed.size).toBe(0) +}) + +it('uses the stripping override only for public removal on a corpus copy', async () => { + const copy = join(state.root, 'copy.exe') + const stripTool = join(state.root, 'sdk-signtool.exe') + vi.mocked(prepareSigningCorpus).mockImplementationOnce(async (_manifest, _directory, remove) => { + await remove(copy) + throw new Error('stop before hardware') + }) + await expect(runWindowsSigningConcurrencyExperiment(['--execute', '--config-root', state.root, '--corpus', join(state.root, 'manifest.json'), '--strip-tool', stripTool])).rejects.toThrow('stop before hardware') + expect(state.removals).toEqual([{ executable: stripTool, args: ['remove', '/s', copy], environment: {} }]) + expect(beginWindowsSigningAttempt).not.toHaveBeenCalled() +}) + +it.each(['primary', 'final', 'audit'] as const)('retains the batch interlock and stops later modes after %s failure', async (failure) => { + state.failure = failure + await expect(execute()).rejects.toThrow(failure === 'audit' ? 'Audit failed' : 'signature verification failed') + expect(state.successes).toBe(0) + expect(state.failures).toBe(1) + expect(beginWindowsSigningAttempt).toHaveBeenCalledOnce() + expect(state.signed.size).toBe(1) + expect(existsSync(lock())).toBe(true) + expect(state.stages.some(stage => stage.includes('pipeline') || stage.includes('hardware2'))).toBe(false) +}) diff --git a/apps/desktop/tests/windows-signing-corpus.spec.ts b/apps/desktop/tests/windows-signing-corpus.spec.ts new file mode 100644 index 0000000000..1849c2ea7a --- /dev/null +++ b/apps/desktop/tests/windows-signing-corpus.spec.ts @@ -0,0 +1,71 @@ +/** Corpus preparation touches only private copies; public signature inspection is simulated. */ +import { createHash } from 'node:crypto' +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { prepareSigningCorpus } from './helpers/windows-signing-corpus.ts' +import { inspectWindowsRuntimeSignature } from '../scripts/windows-runtime-signature.mjs' + +vi.mock('../scripts/windows-runtime-signature.mjs', () => ({ inspectWindowsRuntimeSignature: vi.fn() })) +let root: string +let source: string +let manifest: string +const digest = (data: Buffer | string) => createHash('sha256').update(data).digest('hex') +beforeEach(async () => { + vi.resetAllMocks() + root = await mkdtemp(join(tmpdir(), 'signing-corpus-')) + source = join(root, 'original.dll') + manifest = join(root, 'manifest.json') + await writeFile(source, 'signed original') + await writeFile(manifest, JSON.stringify([{ path: source, sha256: digest('signed original') }])) + vi.mocked(inspectWindowsRuntimeSignature).mockResolvedValue({ status: 'NotSigned', timestamped: false, thumbprint: null }) +}) +afterEach(async () => { await rm(root, { recursive: true, force: true, maxRetries: 3 }) }) + +it('strips only a pinned private copy and preserves the original bytes', async () => { + vi.mocked(inspectWindowsRuntimeSignature).mockResolvedValueOnce({ status: 'Valid', timestamped: true, thumbprint: 'A' }) + const remove = vi.fn(async (path: string) => { expect(path).not.toBe(source); await writeFile(path, 'unsigned copy') }) + const files = await prepareSigningCorpus(manifest, join(root, 'copies'), remove, new AbortController().signal) + expect(remove).toHaveBeenCalledOnce() + expect(files).toEqual([{ path: join(root, 'copies', '0.dll'), sha256: digest('unsigned copy'), bytes: 13 }]) + expect(await readFile(source, 'utf8')).toBe('signed original') +}) + +it('accepts already unsigned input without invoking removal', async () => { + const remove = vi.fn() + const files = await prepareSigningCorpus(manifest, join(root, 'copies'), remove, new AbortController().signal) + expect(remove).not.toHaveBeenCalled() + expect(files[0]?.sha256).toBe(digest('signed original')) +}) + +it.each([[], {}, [{ path: 'relative', sha256: 'a'.repeat(64) }], [{ path: 'ignored', sha256: 'invalid' }]])('rejects malformed manifest %j', async (value) => { + await writeFile(manifest, JSON.stringify(value)) + const remove = vi.fn() + await expect(prepareSigningCorpus(manifest, join(root, 'copies'), remove, new AbortController().signal)).rejects.toThrow('Signing corpus') + expect(remove).not.toHaveBeenCalled() +}) + +it('rejects source content changed since the manifest was created', async () => { + await writeFile(source, 'changed source') + await expect(prepareSigningCorpus(manifest, join(root, 'copies'), vi.fn(), new AbortController().signal)).rejects.toThrow('pinned digest') + expect(inspectWindowsRuntimeSignature).not.toHaveBeenCalled() +}) + +it.each(['HashMismatch', 'NotTrusted'])('rejects invalid source signature %s without removal', async (status) => { + vi.mocked(inspectWindowsRuntimeSignature).mockResolvedValue({ status, timestamped: false, thumbprint: null }) + const remove = vi.fn() + await expect(prepareSigningCorpus(manifest, join(root, 'copies'), remove, new AbortController().signal)).rejects.toThrow('invalid signature') + expect(remove).not.toHaveBeenCalled() +}) + +it('rejects a copy whose signature removal did not finish', async () => { + vi.mocked(inspectWindowsRuntimeSignature).mockResolvedValue({ status: 'Valid', timestamped: true, thumbprint: 'A' }) + await expect(prepareSigningCorpus(manifest, join(root, 'copies'), vi.fn(), new AbortController().signal)).rejects.toThrow('must be unsigned') +}) + +it('stops before copying after cancellation', async () => { + const controller = new AbortController(); controller.abort(new Error('cancelled')) + await expect(prepareSigningCorpus(manifest, join(root, 'copies'), vi.fn(), controller.signal)).rejects.toThrow('cancelled') + expect(inspectWindowsRuntimeSignature).not.toHaveBeenCalled() +}) diff --git a/apps/desktop/tests/windows-signing-experiment.spec.ts b/apps/desktop/tests/windows-signing-experiment.spec.ts new file mode 100644 index 0000000000..d14e9399eb --- /dev/null +++ b/apps/desktop/tests/windows-signing-experiment.spec.ts @@ -0,0 +1,288 @@ +import { expect, it, vi } from 'vitest' +import { runSigningExperimentBatch } from './helpers/windows-signing-experiment.ts' + +function barrier() { + const pending = Promise.withResolvers() + return { promise: pending.promise, resolve: () => { pending.resolve(undefined) } } +} +const observe = (operation: Promise) => operation.then( + () => ({ ok: true as const }), (error: unknown) => ({ ok: false as const, error }), +) + +it('drains four issued hardware calls after failure without dispatching a fifth', async () => { + const allStarted = barrier() + const release = barrier() + const failed = barrier() + const started: number[] = [] + const finished: number[] = [] + const outcome = observe(runSigningExperimentBatch([1, 2, 3, 4, 5, 6], { + jobs: 4, hardwareConcurrency: 4, + sign: async (item) => { + started.push(item) + if (started.length === 4) allStarted.resolve() + await allStarted.promise + if (item === 1) { failed.resolve(); throw new Error('hardware failure') } + await release.promise + finished.push(item) + }, + complete: async (item, sign) => { await sign(`staged-${item}`) }, + })) + let settled = false + void outcome.then(() => { settled = true }) + try { + await failed.promise + expect(started).toEqual([1, 2, 3, 4]) + expect(settled).toBe(false) + } finally { release.resolve() } + expect(await outcome).toEqual({ ok: false, error: new Error('hardware failure') }) + expect(finished.sort()).toEqual([2, 3, 4]) + expect(started).toEqual([1, 2, 3, 4]) +}) + +it('finishes each item before beginning the next in serial mode', async () => { + const events: string[] = [] + await runSigningExperimentBatch([1, 2], { + jobs: 1, hardwareConcurrency: 1, + sign: async (item, path) => { expect(path).toBe(`staged-${item}`); events.push(`sign ${item}`) }, + complete: async (item, sign) => { + events.push(`start ${item}`) + await sign(`staged-${item}`) + events.push(`complete ${item}`) + }, + }) + expect(events).toEqual(['start 1', 'sign 1', 'complete 1', 'start 2', 'sign 2', 'complete 2']) +}) + +it('overlaps completion with the next signature while keeping hardware concurrency at one', async () => { + const firstSigning = barrier() + const releaseFirstSignature = barrier() + const secondStarted = barrier() + const firstPost = barrier() + const secondSigned = barrier() + const releaseCompletion = barrier() + const started: number[] = [] + let active = 0 + let peak = 0 + const outcome = observe(runSigningExperimentBatch([1, 2, 3], { + jobs: 2, hardwareConcurrency: 1, + sign: async (item) => { + active++ + peak = Math.max(peak, active) + try { + if (item === 1) { firstSigning.resolve(); await releaseFirstSignature.promise } + if (item === 2) secondSigned.resolve() + } finally { active-- } + }, + complete: async (item, sign) => { + started.push(item) + if (item === 2) secondStarted.resolve() + await sign(`staged-${item}`) + if (item === 1) firstPost.resolve() + await releaseCompletion.promise + }, + })) + try { + await Promise.all([firstSigning.promise, secondStarted.promise]) + expect(active).toBe(1) + releaseFirstSignature.resolve() + await Promise.all([firstPost.promise, secondSigned.promise]) + expect(started).toEqual([1, 2]) + expect(peak).toBe(1) + } finally { + releaseFirstSignature.resolve() + releaseCompletion.resolve() + expect(await outcome).toEqual({ ok: true }) + } + expect(started).toEqual([1, 2, 3]) +}) + +it.each([2, 4] as const)('allows %i hardware requests but keeps later items queued until a job completes', async (limit) => { + const bothSigning = barrier() + const release = barrier() + const started: number[] = [] + let active = 0 + let peak = 0 + const outcome = observe(runSigningExperimentBatch(Array.from({ length: limit + 1 }, (_, index) => index + 1), { + jobs: limit, hardwareConcurrency: limit, + sign: async () => { + active++ + peak = Math.max(peak, active) + if (active === limit) bothSigning.resolve() + try { await release.promise } finally { active-- } + }, + complete: async (item, sign) => { started.push(item); await sign(`staged-${item}`) }, + })) + try { + await bothSigning.promise + expect(started).toEqual(Array.from({ length: limit }, (_, index) => index + 1)) + expect(active).toBe(limit) + } finally { release.resolve(); expect(await outcome).toEqual({ ok: true }) } + expect(peak).toBe(limit) + expect(active).toBe(0) +}) + +it.each([new Error('hardware failed'), undefined])('stops queued signatures and new items after a hardware rejection (%s)', async (failure) => { + const secondStarted = barrier() + const sign = vi.fn(async () => { await secondStarted.promise; throw failure }) + const started: number[] = [] + const result = await observe(runSigningExperimentBatch([1, 2, 3], { + jobs: 2, hardwareConcurrency: 1, sign, + complete: async (item, request) => { + started.push(item) + if (item === 2) secondStarted.resolve() + await request(`staged-${item}`) + }, + })) + expect(result).toEqual({ ok: false, error: failure }) + expect(sign).toHaveBeenCalledTimes(1) + expect(started).toEqual([1, 2]) +}) + +it('drains concurrent hardware after the first failure and retains that failure', async () => { + const secondSigning = barrier() + const firstFailed = barrier() + const releaseSecond = barrier() + const failure = new Error('first hardware failure') + const calls: number[] = [] + let active = 0 + let settled = false + const outcome = observe(runSigningExperimentBatch([1, 2, 3], { + jobs: 2, hardwareConcurrency: 2, + sign: async (item) => { + calls.push(item) + active++ + try { + if (item === 1) { await secondSigning.promise; throw failure } + secondSigning.resolve() + await releaseSecond.promise + throw new Error('later hardware failure') + } finally { active-- } + }, + complete: async (item, sign) => { + try { await sign(`staged-${item}`) } + catch (error) { if (item === 1) firstFailed.resolve(); throw error } + }, + })).then((result) => { settled = true; return result }) + try { + await firstFailed.promise + expect(settled).toBe(false) + expect(active).toBe(1) + expect(calls).toEqual([1, 2]) + } finally { releaseSecond.resolve(); expect(await outcome).toEqual({ ok: false, error: failure }) } + expect(active).toBe(0) + expect(calls).toEqual([1, 2]) +}) + +it('preserves an undefined completion failure and starts no further work', async () => { + const sign = vi.fn(async () => {}) + const complete = vi.fn(async () => { throw undefined }) + expect(await observe(runSigningExperimentBatch([1, 2], { + jobs: 1, hardwareConcurrency: 1, complete, sign, + }))).toEqual({ ok: false, error: undefined }) + expect(complete).toHaveBeenCalledTimes(1) + expect(sign).not.toHaveBeenCalled() +}) + +it('prevents a waiting signature when completion fails and drains the issued hardware request', async () => { + const secondSigning = barrier() + const releaseSecond = barrier() + const failureObserved = barrier() + const failure = new Error('timestamp failed') + const calls: number[] = [] + let pending: ReturnType | undefined + let settled = false + const outcome = observe(runSigningExperimentBatch([1, 2, 3], { + jobs: 2, hardwareConcurrency: 1, + sign: async (item) => { + calls.push(item) + if (item === 2) { secondSigning.resolve(); await releaseSecond.promise } + }, + complete: async (item, sign) => { + await sign(`staged-${item}`) + if (item === 1) { + await secondSigning.promise + // Failure can interrupt a completion that already owns a queued request. + const waiting = observe(sign(`staged-retry-${item}`)).then((result) => { failureObserved.resolve(); return result }) + pending = waiting + throw failure + } + }, + })).then((result) => { settled = true; return result }) + try { + await failureObserved.promise + expect(settled).toBe(false) + expect(calls).toEqual([1, 2]) + } finally { releaseSecond.resolve(); expect(await outcome).toEqual({ ok: false, error: failure }) } + expect(calls).toEqual([1, 2]) + expect(await pending).toEqual({ ok: false, error: failure }) +}) + +it('drains both completion workers after one fails without starting more items', async () => { + const secondPost = barrier() + const releaseSecondPost = barrier() + const failed = barrier() + const failure = new Error('verification failed') + const started: number[] = [] + let settled = false + const outcome = observe(runSigningExperimentBatch([1, 2, 3], { + jobs: 2, hardwareConcurrency: 2, sign: async () => {}, + complete: async (item, sign) => { + started.push(item) + await sign(`staged-${item}`) + if (item === 1) { await secondPost.promise; failed.resolve(); throw failure } + secondPost.resolve() + await releaseSecondPost.promise + }, + })).then((result) => { settled = true; return result }) + try { + await failed.promise + expect(settled).toBe(false) + expect(started).toEqual([1, 2]) + } finally { releaseSecondPost.resolve(); expect(await outcome).toEqual({ ok: false, error: failure }) } + expect(started).toEqual([1, 2]) +}) + +it('cancels waiting signatures and new items while waiting for issued hardware to finish', async () => { + const controller = new AbortController() + const secondStarted = barrier() + const release = barrier() + const waitingRejected = barrier() + const reason = new Error('operator cancelled') + const calls: number[] = [] + let active = false + let settled = false + const outcome = observe(runSigningExperimentBatch([1, 2, 3], { + jobs: 2, hardwareConcurrency: 1, signal: controller.signal, + sign: async (item) => { + calls.push(item) + active = true + try { await release.promise } finally { active = false } + }, + complete: async (item, sign) => { + if (item === 2) secondStarted.resolve() + try { await sign(`staged-${item}`) } + catch (error) { if (item === 2) waitingRejected.resolve(); throw error } + }, + })).then((result) => { settled = true; return result }) + try { + await secondStarted.promise + controller.abort(reason) + await waitingRejected.promise + expect(active).toBe(true) + expect(settled).toBe(false) + expect(calls).toEqual([1]) + } finally { release.resolve(); expect(await outcome).toEqual({ ok: false, error: reason }) } + expect(active).toBe(false) + expect(calls).toEqual([1]) +}) + +it('does not begin work when cancellation was already requested', async () => { + const reason = new Error('already cancelled') + const complete = vi.fn(async () => {}) + const sign = vi.fn(async () => {}) + expect(await observe(runSigningExperimentBatch([1], { + jobs: 2, hardwareConcurrency: 2, signal: AbortSignal.abort(reason), complete, sign, + }))).toEqual({ ok: false, error: reason }) + expect(complete).not.toHaveBeenCalled() + expect(sign).not.toHaveBeenCalled() +}) diff --git a/apps/desktop/tests/windows-signing-preflight.spec.ts b/apps/desktop/tests/windows-signing-preflight.spec.ts index e560654e80..008b9bfcc0 100644 --- a/apps/desktop/tests/windows-signing-preflight.spec.ts +++ b/apps/desktop/tests/windows-signing-preflight.spec.ts @@ -63,15 +63,32 @@ async function fixture() { sequence.push('compile'); await writeFile(output, 'inert unsigned probe') }) const sign = vi.fn(async () => { sequence.push('sign') }) + const inspectIdentity = vi.fn(async () => 'matched' as const) const inspect = vi.fn(async (_path: string) => { sequence.push('inspect') return sign.mock.calls.length === 0 ? { status: 'NotSigned', timestamped: false, thumbprint: null } : { status: 'Valid', timestamped: true, thumbprint: 'A'.repeat(40) } }) - return { root, compiler, sequence, runDirectory: run.directory, environment, stateDirectory: join(root, 'state'), compile, sign, inspect } + return { root, compiler, sequence, runDirectory: run.directory, environment, stateDirectory: join(root, 'state'), compile, sign, inspect, inspectIdentity } } +it.each(['provider-unavailable', 'container-unavailable', 'certificate-mismatch', 'unknown'] as const) +('stops before compilation and signing on public identity result %s', async (result) => { + const options = await fixture() + const inspectIdentity = vi.fn(async (_input: { environment: NodeJS.ProcessEnv }) => result) + await expect(preflightWindowsSigning({ ...options, inspectIdentity })).rejects.toThrow('No PIN was supplied') + expect(options.compile).not.toHaveBeenCalled() + expect(options.sign).not.toHaveBeenCalled() + expect(inspectIdentity).toHaveBeenCalledOnce() + expect(inspectIdentity.mock.calls[0]![0].environment).not.toHaveProperty('DSH_DESKTOP_WINDOWS_TOKEN_PIN') + expect(inspectIdentity.mock.calls[0]![0].environment).not.toHaveProperty('DSH_DESKTOP_WINDOWS_SIGNTOOL') + const events = await readFile(join(options.runDirectory, 'events.jsonl'), 'utf8') + expect(events).toContain(`"result":"${result}"`) + expect(events).not.toContain('fixture-pin') + expect(events).not.toContain('fixture-container') +}) + it('compiles one new probe and verifies one production-format signature before success', async () => { const options = await fixture() await preflightWindowsSigning(options) diff --git a/apps/desktop/tests/windows-token-identity.spec.ts b/apps/desktop/tests/windows-token-identity.spec.ts new file mode 100644 index 0000000000..e56cd689b5 --- /dev/null +++ b/apps/desktop/tests/windows-token-identity.spec.ts @@ -0,0 +1,113 @@ +import { execFileSync } from 'node:child_process' +import { X509Certificate } from 'node:crypto' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { rootCertificates } from 'node:tls' +import { expect, it, vi } from 'vitest' +import { inspectWindowsTokenIdentity, windowsTokenIdentityFailure } from '../scripts/windows-token-identity.ts' + +const launch = vi.hoisted(() => vi.fn(async (_file: string, _args: string[], _options: { env: NodeJS.ProcessEnv; timeout: number }) => ({ stdout: '', stderr: '' }))) +vi.mock('node:child_process', async (importOriginal) => { + const original = await importOriginal() + const { promisify } = await import('node:util') + return { ...original, execFile: Object.assign(vi.fn(), { [promisify.custom]: launch }) } +}) + +const certificate = new X509Certificate(rootCertificates.find(pem => new X509Certificate(pem).publicKey.asymmetricKeyType === 'rsa')!) +const jwk = certificate.publicKey.export({ format: 'jwk' }) +const modulus = Buffer.from(jwk.n!, 'base64url') +const exponent = Buffer.from(jwk.e!, 'base64url').reduce((value, byte) => value * 256 + byte, 0) +const blob = Buffer.alloc(20 + modulus.length) +blob[0] = 6; blob[1] = 2 +blob.writeUInt32LE(0x2400, 4); blob.writeUInt32LE(0x31415352, 8) +blob.writeUInt32LE(modulus.length * 8, 12); blob.writeUInt32LE(exponent, 16) +Buffer.from(modulus).reverse().copy(blob, 20) +const input = { certificate: certificate.raw, container: 'fixture-container', environment: {} } + +it('compares the returned public key with the certificate, not the container name', async () => { + const query = vi.fn(async () => JSON.stringify({ status: 'public-keys', publicKeys: [blob.toString('base64')] })) + expect(await inspectWindowsTokenIdentity({ ...input, query })).toBe('matched') + expect(query).toHaveBeenCalledOnce() + const other = Buffer.from(blob) + other[20] = other[20]! ^ 2 + expect(await inspectWindowsTokenIdentity({ ...input, query: async () => JSON.stringify({ + status: 'public-keys', publicKeys: [other.toString('base64')], + }) })).toBe('certificate-mismatch') +}) + +it.each(['provider-unavailable', 'container-unavailable', 'unknown'])('preserves public query result %s', async (status) => { + expect(await inspectWindowsTokenIdentity({ ...input, query: async () => JSON.stringify({ status }) })).toBe(status) +}) + +it.each(['not json', '{}', '{"status":"public-keys","publicKeys":[]}', + '{"status":"public-keys","publicKeys":["bad"]}', '{"status":"matched"}', + JSON.stringify({ status: 'public-keys', publicKeys: [blob.toString('base64'), 'bad'] })]) +('rejects incomplete or malformed public data without accepting a partial match: %s', async (output) => { + expect(await inspectWindowsTokenIdentity({ ...input, query: async () => output })).toBe('unknown') +}) + +it('contains query failures without retrying or exposing diagnostics', async () => { + const query = vi.fn(async () => { throw new Error('private fixture diagnostic') }) + expect(await inspectWindowsTokenIdentity({ ...input, query })).toBe('unknown') + expect(query).toHaveBeenCalledOnce() +}) + +it('launches only the public query with no PIN, signing tool or inherited secrets', async () => { + launch.mockClear() + launch.mockResolvedValueOnce({ stdout: JSON.stringify({ status: 'public-keys', publicKeys: [blob.toString('base64')] }), stderr: '' }) + expect(await inspectWindowsTokenIdentity({ ...input, environment: { + PATH: 'fixture-path', DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'must-not-pass', API_KEY: 'must-not-pass', + DSH_DESKTOP_WINDOWS_SIGNTOOL: 'must-not-run', NODE_OPTIONS: 'must-not-pass', NODE_PATH: 'must-not-pass', + } })).toBe('matched') + expect(launch).toHaveBeenCalledOnce() + const [file, args, options] = launch.mock.calls[0]! + expect(file).toBe('pwsh') + expect(args).toContain('-NonInteractive') + expect(args.at(-1)).toMatch(/windows-token-public-key\.ps1$/u) + expect(options.timeout).toBe(15_000) + expect(options.env).toEqual({ PATH: 'fixture-path', DSH_TOKEN_PUBLIC_CONTAINER: 'fixture-container' }) +}) + +it('reports a helper timeout or stderr as unknown without retry', async () => { + launch.mockClear() + launch.mockRejectedValueOnce(new Error('timeout with private diagnostic')) + expect(await inspectWindowsTokenIdentity(input)).toBe('unknown') + expect(launch).toHaveBeenCalledOnce() + launch.mockResolvedValueOnce({ stdout: JSON.stringify({ status: 'public-keys', publicKeys: [blob.toString('base64')] }), stderr: 'unexpected' }) + expect(await inspectWindowsTokenIdentity(input)).toBe('unknown') +}) + +it('reports a missing query launcher without exposing process diagnostics or retrying', async () => { + launch.mockClear() + launch.mockRejectedValueOnce(Object.assign(new Error('private launcher diagnostic'), { code: 'ENOENT' })) + const result = await inspectWindowsTokenIdentity(input) + expect(result).toBe('unknown') + expect(launch).toHaveBeenCalledOnce() + const message = windowsTokenIdentityFailure('unknown') + expect(message).toContain('PowerShell 7 (pwsh) can start') + expect(message).not.toContain('private launcher diagnostic') + expect(message).toContain('no signing was attempted') +}) + +it.skipIf(process.platform !== 'win32')('exercises native control flow with a fake CSP and never constructs the native adapter', () => { + const root = mkdtempSync(join(tmpdir(), 'token-public-test-')) + try { + const source = resolve(import.meta.dirname, '../scripts/windows-token-public-key.cs') + const runner = join(root, 'test.ps1') + const fixture = resolve(import.meta.dirname, 'fixtures/windows-token-public-key-fake.cs') + writeFileSync(runner, `param([string]$Source, [string]$Fixture) +$ErrorActionPreference = 'Stop' +Add-Type -TypeDefinition ((Get-Content -LiteralPath $Source -Raw) + (Get-Content -LiteralPath $Fixture -Raw)) +[FakeTokenPublicKey]::Test() +`) + expect(execFileSync('pwsh', ['-NoProfile', '-NonInteractive', '-File', runner, source, fixture], { encoding: 'utf8', timeout: 30_000 })) + .toContain('fake CSP cases passed') + const native = readFileSync(source, 'utf8') + const provider = /Provider = "([^"]+)"/u.exec(native)![1] + expect(readFileSync(resolve(import.meta.dirname, '../scripts/windows-sign.cmd'), 'utf8')).toContain(`/csp "${provider}"`) + expect(native).toContain('CryptAcquireContextW(out context, container, Provider, 1, PublicContextFlags)') + expect(native).toContain('CryptExportKey(key, IntPtr.Zero, 6, 0, bytes, ref length)') + expect(native).not.toMatch(/CryptSign|CryptSetProvParam|CryptGenKey|CryptAcquireCertificatePrivateKey/u) + } finally { rmSync(root, { recursive: true, force: true, maxRetries: 3 }) } +}) diff --git a/apps/desktop/tsconfig.host.json b/apps/desktop/tsconfig.host.json index 21cda5fcf8..44992641d5 100644 --- a/apps/desktop/tsconfig.host.json +++ b/apps/desktop/tsconfig.host.json @@ -12,7 +12,7 @@ "path": "../../packages/boot/app-boot" }, { - "path": "../../packages/boot/official-bundles" + "path": "../../packages/util/official-bundles" }, { "path": "../../packages/util/home-paths" @@ -35,6 +35,9 @@ { "path": "../../packages/client/product-analytics/tsconfig.host.json" }, + { + "path": "../../packages/boot/plugin-manager" + }, { "path": "../../packages/util/file-drag" } diff --git a/apps/desktop/tsdown.config.ts b/apps/desktop/tsdown.config.ts index d4f034252d..40ed1a0316 100644 --- a/apps/desktop/tsdown.config.ts +++ b/apps/desktop/tsdown.config.ts @@ -33,6 +33,12 @@ if (clientVersion === undefined) throw new Error('desktop build: the client envi const clientVersionDefine = { 'process.env.DSH_CLIENT_VERSION': JSON.stringify(clientVersion) } export default defineConfig([ + { + entry: ['lib/types/operation-report-worker.js'], + plugins: [packagedImportsPlugin({ packages: new Set(), nodeBuiltins: true })], + outDir: 'lib', format: ['esm'], platform: 'node', target: 'es2024', + fixedExtension: false, dts: false, clean: false, codeSplitting: false, + }, { entry: ['lib/types/command-manager-entry.js'], plugins: [packagedImportsPlugin({ packages: new Set(), nodeBuiltins: true })], diff --git a/apps/desktop/windows-signing/README.i18n.yaml b/apps/desktop/windows-signing/README.i18n.yaml index f64f0ef778..c1354ca9e8 100644 --- a/apps/desktop/windows-signing/README.i18n.yaml +++ b/apps/desktop/windows-signing/README.i18n.yaml @@ -21,23 +21,26 @@ en: bb889e9514678d1c zh: 48cbec1e907d6a2b /windows-signing-and-runner-operations/machine-setup-and-runner-startup/supervised-startup: - en: d8e2ed7bde76ed7e - zh: 475917ecbd158b48 + en: cada81c15a20ecc2 + zh: 80b7a4af7b1e0e5d +/windows-signing-and-runner-operations/machine-setup-and-runner-startup/optional-network-dependency: + en: 60f34f8637b3c252 + zh: 805435964ab20263 /windows-signing-and-runner-operations/signing-configuration: en: 4b5548818375eb9a zh: 8c975adbb1dca9c8 /windows-signing-and-runner-operations/signing-and-timestamp-completion: - en: e42565e00283e3f6 - zh: 584a33f07b50fd5b + en: a8d23c931cafc236 + zh: 28fd4860549cdc7b /windows-signing-and-runner-operations/failure-records-and-operator-recovery: en: 5401b605a2f3a44e zh: fc1f6ee667bcd20d /windows-signing-and-runner-operations/signature-cache-and-concurrent-stages: - en: c2686bf2e9589521 - zh: 58dfecf61e4f95da + en: 6e8208d19ad510e5 + zh: eee42e8938c0f603 /windows-signing-and-runner-operations/verification-limits: - en: 94a471410c84a1c7 - zh: 115228e4ca36581d + en: 53f1fe23f54af84e + zh: d219606367ff2d72 /windows-signing-and-runner-operations/dev-note: en: b75c8458928b72b9 zh: 003ba4e17b4b5269 diff --git a/apps/desktop/windows-signing/README.md b/apps/desktop/windows-signing/README.md index ec8312eddc..f7b48b9b3e 100644 --- a/apps/desktop/windows-signing/README.md +++ b/apps/desktop/windows-signing/README.md @@ -38,14 +38,24 @@ Run `pwsh -NoProfile -File apps/desktop/scripts/setup-windows-packaging.ps1 -Roo For the complete registration, label, routing and approval sequence, start with [CI publication setup](../publishing/ci/README.md#setup-sequence). The task installer requires the Windows .NET Framework 4.5+ compiler at `%SystemRoot%/Microsoft.NET/Framework64/v4.0.30319/csc.exe`. It compiles a GUI executable into `runner/dsh-task/launcher.exe`; this executable starts PowerShell with no console and waits for it to exit. The output and errors of `run.ps1` itself go to uniquely named `launcher-*.out.log` and `launcher-*.err.log`; filenames include UTC time, PID and a random identifier. Launcher failures disable periodic starts, including failures before the retry budget can be read. Task result `2` indicates launcher failure; `3` means its error log could not be written; `4` means disabling the task also failed and an operator must disable it in Task Scheduler. After the direct child exits, output draining is limited to five seconds. A timeout returns `5` with a `launcher-*.drain.log` diagnostic: output may be incomplete, but periodic recovery continues within the existing restart budget. Descendant processes may outlive the exited runner; draining logs does not terminate them. The recorded stop target is the launcher process, so stop includes the launcher and its descendants. Normal runner output remains in `run-*.log`. -Run `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -RunnerRoot -ConfigRoot /packaging` as the runner's Windows user, using its installed PowerShell 7. The installer checks the environment and copies startup scripts into `runner/dsh-task`; registration, tools and secrets remain separate. It registers a disabled, limited-permission interactive Task Scheduler task without storing an account password. For `-Action start` or `-Action status`, pass only `-RunnerRoot`; configuration and retry options apply only to installation. The task starts after this user's desktop login, including after reboot, and stops on logout. It does not provide unattended boot or unlock a signing Token. +Run `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -RunnerRoot -ConfigRoot /packaging` as the runner's Windows user, using its installed PowerShell 7. The installer checks the environment and copies startup scripts into `runner/dsh-task`; registration, tools and secrets remain separate. It registers a disabled, limited-permission interactive Task Scheduler task without storing an account password. Task priority 4 gives the runner and its children normal CPU, I/O and memory priority; the scheduler default 7 lowers all three and slows dependency installation. Existing tasks retain their settings: while the runner is idle, stop, uninstall and reinstall the task before starting it again. For `-Action start` or `-Action status`, pass only `-RunnerRoot`; configuration and retry options apply only to installation. The task starts after this user's desktop login, including after reboot, and stops on logout. It does not provide unattended boot or unlock a signing Token. The task permits one instance and has no execution time limit. A repeating trigger checks every `-RestartMinutes` minutes (default `1`) and restarts an exited launcher, including an unexpected zero exit. The persisted budget permits the initial launch plus `-RestartCount` restarts (default `10`) between explicit starts. Every desktop login also consumes this budget; `status` shows the remaining launches. After the budget is exhausted, login alone cannot restart the runner. Starting an already running task does not reset the budget. Missing or invalid budget/configuration files disable automatic starts until repaired. GitHub's launcher owns runner updates; task recovery does not rerun a failed workflow or clear signing interlocks. After retries are exhausted, inspect `runner/dsh-task/run-*.log`, the runner's `_diag` logs and `status`, correct the cause, then run `start`. A running task alone does not prove connectivity: verify `Connected to GitHub` and `Listening for Jobs`, then verify assignment in Actions. Both `run-*.log` and `launcher-*.log` are retained for operator-managed cleanup. -Before maintenance, pause new workflow dispatch and wait for the runner to become idle. `-Action stop` refuses an active worker for this runner, disables future starts and stops its task process tree; the local check cannot prevent a concurrent GitHub assignment. `-Action uninstall` requires a stopped, disabled task and retains registration, configuration and logs. Pulling repository changes does not update the installed copy. To upgrade it, record the configuration directory and retry settings, then run `stop`, `uninstall`, `install` with those settings, and `start` from the updated checkout. Confirm listening and job assignment again. When migrating a manually launched runner, stop its existing launcher only after it is idle, then start the task; never run both launchers together. +Before maintenance, pause new workflow dispatch and wait for the runner to become idle. `-Action stop` refuses an active worker for this runner, disables future starts and stops its task process tree; the local check cannot prevent a concurrent GitHub assignment. `-Action uninstall` requires a stopped, disabled task and retains registration, configuration and logs. Pulling repository changes does not update the installed copy. To upgrade it, record the original -ConfigRoot, optional -NetworkRoot and retry settings, then run `stop`, `uninstall`, `install` with those settings, and `start` from the updated checkout. Confirm listening and job assignment again. When migrating a manually launched runner, stop its existing launcher only after it is idle, then start the task; never run both launchers together. Operators can run `pwsh -NoProfile -File apps/desktop/tests/windows-runner-task.ps1` on Windows to exercise installation, console-free initial launch and automatic recovery, duplicate-start prevention, stop, child-process teardown, containment of startup/logging failures and uninstall against an isolated fake runner. This opt-in test creates a temporary task and retains diagnostic files; it does not contact GitHub or access signing hardware. `pwsh -NoProfile -File apps/desktop/tests/windows-runner-launcher.ps1` checks the GUI executable, child console absence, exit status, diagnostic output and bounded draining with an inherited writer without Task Scheduler; Windows CI runs it. Real-machine acceptance additionally checks an idle runner coming online without a visible Terminal window, an Actions job being assigned, and login after an operator-approved reboot. Signed packaging and logout/reboot acceptance require separate operator verification. +### Optional network dependency + +Without `runner-network.json` in `ConfigRoot`, startup retains its scrubbed direct-network behavior. To configure a network dependency, create that operator-owned JSON file outside the checkout with exactly `proxyUrl`, `noProxy`, `serviceName`, `probeUrl`, `attempts`, `timeoutSeconds` and `retrySeconds`. The first four fields are strings; the three budgets are integers from 1 through 60. Use an empty `proxyUrl` for direct access and an empty `serviceName` when no Windows service owns the dependency. URLs must use HTTP(S) without credentials, queries or fragments; the proxy URL cannot include a path. Startup applies `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` and `NODE_USE_ENV_PROXY` after environment scrubbing, then requires a successful Node HEAD probe before admitting the runner. Service readiness checks never start or stop a Windows service. + +For a dedicated child process, add `-NetworkRoot ` to task installation. That directory must contain `launch.json` with exactly an absolute `executable` filename, an `arguments` string array and an integer `restartDelaySeconds` from 1 through 3600. This mode requires `runner-network.json`; set its `serviceName` to empty. Give the child its own data directory, listener bindings and executable identity, distinct from applications managed by desktop software; separate ports alone do not prevent another manager from terminating a process by executable name. The scripts do not alter desktop network settings. Keep actual provider names, paths, addresses, ports and arguments in machine configuration, never in repository files or shared logs. Restrict access to both configuration directories to the runner operator. + +Installation starts the dependency for readiness checking and stops it before registering the task. While the runner lives, the supervisor restarts only an exited owned network process after the configured delay, including repeated launch failures; it does not restart the runner or retry jobs or signing. Exit, restart and launch-failure messages appear in `run-*.log`; provider output is discarded. Restart messages establish process creation, not network availability: confirm reconnection in runner logs. A live but unresponsive dependency requires operator diagnosis. The supervisor exclusively locks `NetworkRoot`, verifies PID, start time and executable before reclaiming a stale child, and stops its child when the runner exits. Unrecoverable supervision errors leave the active runner alive until it exits and report that recovery has stopped. Preserve `NetworkRoot` when reinstalling; pulling changes alone does not replace installed helpers. + +Windows CI runs `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network.ps1` and `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network-process.ps1` with isolated local fixtures. On a configured packaging machine, add `-CheckStartup` to the first command to verify network configuration after the actual startup environment scrub. These tests use no signing hardware or external network endpoints. + ## Signing configuration @@ -66,6 +76,8 @@ Follow the [version and build instructions](../packaging/README.md#release-versi Signed Windows builds run a supervised signing preflight before compilation or dependency preparation. Static configuration, certificate validity, audit storage, compiler availability and any retained signing interlock are checked without token access. The local .NET Framework C# compiler creates a small private probe; the production signer signs it once, and verification requires the configured certificate and a timestamp before building continues. The probe is never executed. The overall 60-second preflight deadline includes timestamp attempts; deadline expiry, hardware signing errors and verification failures stop the run without another hardware attempt. Success proves the current signing path works, not that the PIN was independently authenticated: SafeNet may reuse login state. Do not log out or repeat authentication to test the PIN. `--check`, preparation-only and `--unsigned` modes do not run this hardware preflight; unsigned artifacts remain ineligible for release upload. Automated regression tests use a fake signer; release operators qualify real hardware separately. +Public identity queries require PowerShell 7 (`pwsh`) on the build account’s `PATH`; an unavailable or failed query process stops signing with an unknown identity result. Before compiling the probe, a separate noninteractive process reads public keys from the fixed eToken CSP using `CRYPT_VERIFYCONTEXT | CRYPT_SILENT`. It receives the container name but no PIN or signing credentials, and has a 15-second deadline within the existing preflight deadline. Both RSA key slots must be read completely (an absent slot is allowed); at least one public key must match the configured certificate. Provider/container access failure, unsupported public reads, malformed output, timeout or mismatch stops before hardware signing. A container-access error does not establish that the device or container is absent. Public information can be cached by middleware: a match does not authenticate the device, validate the PIN or establish remaining retries. This path is covered by a simulated CSP; the installed SafeNet version still requires separate operator qualification. No failure automatically retries authentication or clears the existing interlock. + Insert and unlock the token before packaging. The electron-builder hook passes each artifact to the CRLF `scripts/windows-sign.cmd`, which invokes the configured SignTool once with `/f`, SafeNet `/kc "[{{PIN}}]=container"`, `/csp "eToken Base Cryptographic Provider"`, a SHA-256 file digest, without a timestamp. The hook then completes a DigiCert SHA-256 RFC 3161 timestamp on isolated copies without signing credentials. The hook never substitutes electron-builder's bundled SignTool and never retries a failed signing request. Windows release packaging fails instead of emitting unsigned artifacts when the SignTool, certificate, container, PIN, token, or signature is unavailable. Timestamp completion retries only a normally exited timestamp command returning failure or warning, at most three times with one- and two-second delays. Each attempt starts from the same verified primary signature. Launch errors, uncertain termination and verification failures stop immediately. SignTool operates on short private paths; publication copies verified bytes to the target volume before atomic replacement. Final Windows trust, certificate, timestamp and normalized full-file equality are required. Exhaustion stops packaging and preserves evidence without another hardware call. See the [signature completion decision](../../../.agents/notes/implemented/process/2026-09-17-windows-signature-completion.md). @@ -88,9 +100,11 @@ Runtime signing shares complete signed files across the current Windows account' Preflight, primary-runtime signing, application-runtime signing and artifact creation each hold the account's signing-stage lock until their supervised child processes settle. Other builds wait before entering those stages; compilation and preparation do not hold the lock. Runtime signing workers own their locks, so terminating only the outer packaging process does not unlock a surviving cache user. Migration and maintenance acquire the same lock; older or external signing commands do not participate and must be scheduled separately. Stage waiting is outside the preflight deadline. Closing the stage handle releases ordinary contention without removing the separate hardware-attempt interlock; a retained hardware failure still requires operator recovery. -Cache-hit copying, hashing and per-file trust checks run with `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_CONCURRENCY` workers from `.env.windows` (default `4`, integer `1`–`8`). All restores and their post-verification finish before cache misses enter serial hardware signing. A restore or verification failure stops new dispatch and drains active work before releasing the stage lock; hardware signing, runtime smoke checks and final integrity validation remain required. +Cache-hit copying, hashing and per-file candidate trust checks run with `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_CONCURRENCY` workers from `.env.windows` (default `4`, integer `1`–`8`). After all restores finish, bounded PowerShell batches verify every restored target's trust, timestamp and certificate before cache misses enter serial hardware signing. A restore failure stops new restores and drains active workers; a target-verification failure drains its inspection batch and prevents hardware signing. Runtime smoke checks and final integrity validation remain required. -Windows packaging reads `DSH_DESKTOP_WINDOWS_PACK_CONCURRENCY` from `.env.windows` or the selected preset: a positive integer, defaulting to `4`. Packaging batches first-party and vendor tarballs with bounded workers, then validates every payload and records publication order. Setting the limit to `1` selects serial packing; standalone `release:pack` defaults to `1`. +PE discovery reads every regular file's header with at most eight open files, rejects links and malformed Windows executables, and drains active reads and closes before reporting failure. Packaging records `windows:enumerate-code` and `windows:inspect-signatures` as nested phases of signing and artifact verification; their timings are included in the enclosing stages. + +Windows packaging reads `DSH_DESKTOP_WINDOWS_PACK_CONCURRENCY` from `.env.windows` or the selected preset: a positive integer, defaulting to `4`. Packaging batches first-party and vendor tarballs with bounded workers, then validates every payload and records publication order. After the complete build succeeds, tarball packing overlaps Electron and primary-runtime preparation in separate output directories. Both must finish successfully before runtime signing; preparation failure stops new packing commands and drains active processes before returning. Setting the limit to `1` selects serial tarball workers; standalone `release:pack` defaults to `1`. Each runtime stage writes `SIGNATURE_CACHE_SUMMARY` to stdout and its packaging journal, including the actual directory, policy identity, hit/miss counts, newly published and retained entries, signing requests, avoided signing requests and validation failures. Timings distinguish signing, trust verification of restored and newly signed files, and restoration; restoration includes its trust check and staging cleanup. These counters exclude preflight, final artifact signing and the outer runtime signature checks. Stage lock events record waiting separately. Concurrent timings sum per-file work rather than stage wall time. @@ -100,7 +114,13 @@ Use `pnpm --dir apps/desktop run cache:windows-signatures --usage` to inspect st ## Verification limits -Real hardware and installation evidence is owned by the [Desktop qualification record](../tests/README.md) and [installed-update procedure](../tests/installed-update/README.md). This document does not authorize PIN retries, automatic interlock deletion, device initialization or changes to the accepted isolation policy. +Signing performance evidence and replacement-runner retesting are owned by the [signing concurrency qualification](../tests/signing-concurrency/README.md). Update and installation evidence is owned by the [Desktop qualification record](../tests/README.md) and [installed-update procedure](../tests/installed-update/README.md). This document does not authorize PIN retries, automatic interlock deletion, device initialization or changes to the accepted isolation policy. + +For operator-approved concurrency experiments, run `node apps/desktop/tests/windows-signing-concurrency.perf.ts --execute --config-root --rounds 2`. Without `--execute`, it only prints usage. The default compares serial completion, two completion workers with one hardware request, and two concurrent hardware requests on six synthetic PE copies per batch. The second round reverses mode order. + +Add `--corpus ` to compare 1, 2 and 4 workers on real release files. The manifest is a nonempty JSON array of objects with an absolute `path` and its lowercase hexadecimal `sha256`. Preparation copies each pinned file, verifies its signature and removes any valid signature from the copy; invalid signatures or changed bytes stop preparation. Signature removal requires SignTool with `remove /s`; `--strip-tool ` overrides only that public preparation tool when the configured version lacks support. Hardware signing and timestamping still use the machine preset. Every batch uses fresh, byte-checked copies of the unsigned templates, preserving manifest order. `--pipeline-control` with a corpus instead runs four completion workers with one hardware request. Original files and release caches remain unchanged. + +The experiment uses the machine test preset, checks public identity, holds the account signing-stage lock and retains one hardware-attempt interlock per batch. The first failure stops dispatch and drains issued work; up to four hardware calls may already be in flight. Only complete signature, timestamp and file verification permits normal interlock release. Files are never executed. Records remain under `.desktop-build/qualification/signing-concurrency`, including batch and per-file elapsed times, batch endpoint host CPU counters, free memory and driver-process memory samples. These memory samples exclude child processes and do not establish peak memory. Timings exclude input preparation, lock waiting and package assembly. Replaying ready-made artifacts also excludes build dependencies between them; the experiment does not enable production concurrency or establish full-release performance. ## Dev Note diff --git a/apps/desktop/windows-signing/README.zh.md b/apps/desktop/windows-signing/README.zh.md index 3b957c5f57..0b7ff50cd2 100644 --- a/apps/desktop/windows-signing/README.zh.md +++ b/apps/desktop/windows-signing/README.zh.md @@ -38,14 +38,24 @@ description: "配置和维护 Windows 打包 runner、签名凭据、EV Token 完整的注册、标签、路由和审批配置顺序见 [CI 发布配置](../publishing/ci/README.zh.md#setup-sequence)。任务安装器需要 Windows .NET Framework 4.5+ 编译器,路径为 `%SystemRoot%/Microsoft.NET/Framework64/v4.0.30319/csc.exe`。它将 GUI 可执行文件编译到 `runner/dsh-task/launcher.exe`;该程序不分配控制台地启动 PowerShell,并等待其退出。`run.ps1` 自身的输出和错误分别写入名称唯一的 `launcher-*.out.log` 和 `launcher-*.err.log`,文件名包含 UTC 时间、PID 和随机标识。启动器失败时禁用周期启动,包括尚未读取重试预算时发生的失败。任务结果 `2` 表示启动器失败,`3` 表示无法写入错误日志,`4` 表示禁用任务也失败,需要操作者在计划任务中手动禁用。直接子进程退出后,最多等待五秒排空输出;超时返回 `5`,将诊断写入 `launcher-*.drain.log`:输出可能不完整,但周期恢复仍受原有重试预算约束。后代进程可能在 runner 退出后继续运行;日志排空不会终止它们。记录的停止目标是启动器进程,因此 stop 覆盖启动器及其后代。正常 runner 输出仍保存在 `run-*.log`。 -以 runner 的 Windows 用户运行 `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -RunnerRoot -ConfigRoot /packaging`,使用该机器安装的 PowerShell 7。安装器检查环境,并将启动脚本复制到 `runner/dsh-task`;注册、工具和凭据仍单独管理。它注册一个初始禁用、权限受限的交互式计划任务,不保存账户密码。执行 `-Action start` 或 `-Action status` 时只传 `-RunnerRoot`;配置目录及重试选项仅适用于安装。任务在该用户登录桌面后启动,重启后也需要登录,注销时停止。它不提供无人值守开机,也不解锁签名 Token。 +以 runner 的 Windows 用户运行 `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -RunnerRoot -ConfigRoot /packaging`,使用该机器安装的 PowerShell 7。安装器检查环境,并将启动脚本复制到 `runner/dsh-task`;注册、工具和凭据仍单独管理。它注册一个初始禁用、权限受限的交互式计划任务,不保存账户密码。任务优先级 4 让 runner 及子进程使用普通 CPU、I/O 和内存优先级;计划任务默认值 7 会降低三者的优先级,使依赖安装变慢。已有任务保留原设置:在 runner 空闲时停止、卸载并重新安装任务,再启动。执行 `-Action start` 或 `-Action status` 时只传 `-RunnerRoot`;配置目录及重试选项仅适用于安装。任务在该用户登录桌面后启动,重启后也需要登录,注销时停止。它不提供无人值守开机,也不解锁签名 Token。 任务只允许一个实例,且没有执行时限。周期触发器每隔 `-RestartMinutes` 分钟(默认 `1`)检查一次,并恢复已退出的启动器,包括意外的零退出码。持久预算允许首次启动及 `-RestartCount` 次重启(默认 `10`),直到再次显式启动。每次桌面登录也会消耗预算,`status` 显示剩余启动次数;预算耗尽后,仅登录不能重启 runner。对正在运行的任务执行 start 不会重置预算。预算或配置文件缺失、无效时,自动启动会禁用,需修复后恢复。GitHub 启动器负责 runner 更新;任务恢复不会重跑失败的 workflow,也不会清除签名互锁。重试耗尽后,检查 `runner/dsh-task/run-*.log`、runner 的 `_diag` 日志和 `status`,修复原因后运行 `start`。任务运行不等于连接成功:确认出现 `Connected to GitHub` 和 `Listening for Jobs`,再到 Actions 确认任务分配。`run-*.log` 和 `launcher-*.log` 均保留,由操作者管理清理。 -维护前暂停新 workflow 的触发,等待 runner 空闲。`-Action stop` 在该 runner 存在活跃 worker 时拒绝停止,否则禁用后续启动并停止任务进程树;本地检查无法阻止 GitHub 同时分配任务。`-Action uninstall` 要求任务已停止并禁用,保留注册、配置和日志。拉取仓库更新不会更新已安装的副本。升级时先记录配置目录和重试设置,再从更新后的 checkout 依次执行 `stop`、`uninstall`、携带原设置的 `install` 和 `start`,最后重新确认监听与 job 分配。迁移手动启动的 runner 时,只在空闲后停止原启动器,再启动计划任务;不要同时运行两个启动器。 +维护前暂停新 workflow 的触发,等待 runner 空闲。`-Action stop` 在该 runner 存在活跃 worker 时拒绝停止,否则禁用后续启动并停止任务进程树;本地检查无法阻止 GitHub 同时分配任务。`-Action uninstall` 要求任务已停止并禁用,保留注册、配置和日志。拉取仓库更新不会更新已安装的副本。升级时先记录原来的 -ConfigRoot、可选的 -NetworkRoot 和重试设置,再从更新后的 checkout 依次执行 `stop`、`uninstall`、携带原设置的 `install` 和 `start`,最后重新确认监听与 job 分配。迁移手动启动的 runner 时,只在空闲后停止原启动器,再启动计划任务;不要同时运行两个启动器。 操作者可在 Windows 上运行 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-task.ps1`,使用隔离的假 runner 验证安装、无控制台的首次启动与自动恢复、防止重复启动、停止、子进程退出、启动/日志失败时的禁用处理和卸载。此显式运行的测试创建临时任务并保留诊断文件,不连接 GitHub 或访问签名硬件。`pwsh -NoProfile -File apps/desktop/tests/windows-runner-launcher.ps1` 无需计划任务,检查 GUI 可执行文件、子进程无控制台、退出状态、诊断输出以及存在继承管道写端时的有界排空;Windows CI 会执行该测试。真实机器验收还需检查空闲 runner 上线且不出现 Terminal 窗口、Actions job 分配,以及经操作者批准的重启后登录。签名打包和注销/重启验收需要操作者单独验证。 +### 可选网络依赖 + +`ConfigRoot` 中没有 `runner-network.json` 时,启动仍使用清理继承环境后的直连行为。要配置网络依赖,请在 checkout 外创建操作者管理的该 JSON 文件,且只包含 `proxyUrl`、`noProxy`、`serviceName`、`probeUrl`、`attempts`、`timeoutSeconds` 和 `retrySeconds`。前四个字段为字符串,后三个预算为 1 至 60 的整数。直连时将 `proxyUrl` 留空,没有 Windows 服务管理依赖时将 `serviceName` 留空。URL 必须使用 HTTP(S),不能包含凭据、查询参数或片段;代理 URL 不能包含路径。启动脚本在清理环境后设置 `HTTP_PROXY`、`HTTPS_PROXY`、`NO_PROXY` 和 `NODE_USE_ENV_PROXY`,并要求 Node HEAD 探测成功才允许启动 runner。服务就绪检查不会启动或停止 Windows 服务。 + +若使用专用子进程,在安装任务时添加 `-NetworkRoot `。该目录必须包含 `launch.json`,且只包含绝对路径的 `executable` 文件名、字符串数组 `arguments`,以及 1 至 3600 的整数 `restartDelaySeconds`。此模式要求存在 `runner-network.json`,其中 `serviceName` 应留空。为子进程分配独立的数据目录、监听绑定和可执行文件标识,与桌面软件管理的应用分离;仅使用不同端口无法防止其他管理器按可执行文件名终止进程。脚本不会修改桌面网络设置。实际服务商名称、路径、地址、端口和参数只保存在机器配置中,不得写入仓库文件或共享日志。将两个配置目录的访问权限限制为 runner 操作者。 + +安装时会启动依赖进行就绪检查,并在注册任务前停止它。runner 存活期间,守卫仅在自己拥有的网络进程退出后,按配置间隔重新启动它;启动连续失败时仍会重试,但不会重启 runner、重跑任务或重试签名。退出、重启和启动失败消息写入 `run-*.log`,依赖进程的输出会被丢弃。重启消息只表明进程已创建,不代表网络可用;请在 runner 日志中确认重新连接。进程仍存活但无响应时需要操作者排查。守卫独占锁定 `NetworkRoot`,回收残留子进程前核对 PID、启动时间和可执行文件,并在 runner 退出时停止子进程。不可恢复的守卫错误会保留活动 runner 直到其退出,并报告恢复已停止。重新安装时保留 `NetworkRoot`;仅拉取代码不会替换已安装的辅助脚本。 + +Windows CI 使用隔离的本地 fixture 运行 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network.ps1` 和 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network-process.ps1`。在已配置的打包机器上,给第一条命令添加 `-CheckStartup`,可验证实际启动环境清理后的网络配置。这些测试不会使用签名硬件或外部网络端点。 + ## 签名配置 @@ -66,6 +76,8 @@ PIN 不能包含 `]`、引号或换行,因为这些字符用于分隔 SafeNet Windows 签名构建在编译或准备依赖前执行受监督的签名预检。静态配置、证书有效期、审计存储、编译器可用性及遗留签名锁的检查不访问 Token。本地 .NET Framework C# 编译器生成一个专用小探针,由正式签名器仅签名一次,随后必须验出配置的证书和时间戳才能继续构建。探针绝不执行。预检的整体 60 秒期限包含时间戳尝试;超时、硬件签名报错或验签失败都会停止本轮流程,不再次调用硬件。成功只证明当前签名路径可用,不证明 PIN 已独立认证:SafeNet 可能复用登录状态。不要为了验证 PIN 而注销或重复认证。`--check`、仅准备和 `--unsigned` 模式不执行此硬件预检;未签名产物仍不能发布上传。自动回归测试使用假签名器,真实硬件由发布操作人员单独验收。 +公开身份查询要求构建账户的 `PATH` 中有 PowerShell 7(`pwsh`);查询进程不可用或失败时,以身份未知结果停止签名。编译探针前,独立非交互进程使用 `CRYPT_VERIFYCONTEXT | CRYPT_SILENT` 从固定的 eToken CSP 读取公钥。该进程只接收容器名,不接收 PIN 或签名凭据;15 秒期限计入已有预检总期限。两个 RSA 密钥槽必须完整读取(允许槽不存在),且至少一个公钥与配置证书匹配。提供程序或容器访问失败、不支持公开读取、输出损坏、超时或不匹配时,在硬件签名前停止。容器访问错误不能证明设备或容器不存在。中间件可能缓存公开信息,因此匹配不代表设备已认证、PIN 正确或已确认剩余尝试次数。此路径已由模拟 CSP 覆盖,当前 SafeNet 版本仍需操作人员单独验收。任何失败都不会自动重试认证或清除已有保护锁。 + 打包前插入并解锁 Token。electron-builder 钩子把每个产物交给采用 CRLF 的 `scripts/windows-sign.cmd`;该 CMD 只调用一次已配置的 SignTool,并指定 `/f`、SafeNet `/kc "[{{PIN}}]=容器"`、`/csp "eToken Base Cryptographic Provider"`和 SHA-256 文件摘要,不请求时间戳。随后钩子在隔离副本上完成 DigiCert SHA-256 RFC 3161 时间戳,不传递签名凭据。钩子不会改用 electron-builder 内置的 SignTool,也不会重试失败的签名请求。SignTool、证书、容器、PIN、Token 或签名不可用时,Windows 发布打包会失败,不会生成未签名产物。 时间戳处理仅对正常退出但返回失败或警告的时间戳命令重试,最多尝试三次,间隔为一秒和两秒。每次均从同一份已验证的主签名开始。启动错误、终止状态不确定或验签失败会立即停止。SignTool 使用短的私有路径;发布时先把已验证字节复制到目标卷,再原子替换。最终必须通过 Windows 信任、证书、时间戳和规范化全文件相等检查。尝试耗尽后停止打包并保留证据,不再次调用硬件。参见[签名完成决策](../../../.agents/notes/implemented/process/2026-09-17-windows-signature-completion.zh.md)。 @@ -88,9 +100,11 @@ Windows 打包命令通过 `DESKTOP_PACKAGING_RECORD` 输出 `.desktop-build/pac 预检、主要运行时签名、应用运行时签名和产物生成分别持有账户级签名阶段锁,直到受监督的子进程结束。其他构建进入这些阶段前等待;编译和准备步骤不持锁。运行时签名进程自行持锁,因此仅终止外层打包进程不会释放仍在访问缓存的阶段锁。迁移及维护获取同一把锁;旧版或外部签名命令不参与排队,应另行避免并发。阶段等待不计入预检期限。关闭阶段句柄会释放普通竞争锁,不删除独立的硬件尝试互锁;遗留硬件失败仍需操作人员恢复。 -缓存命中的复制、摘要和逐文件信任检查使用 `.env.windows` 中的 `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_CONCURRENCY` 个工作任务(默认 `4`,整数 `1`–`8`)。所有恢复及后置验签完成后,未命中项才进入串行硬件签名。恢复或验签失败会停止派发新任务,并在释放阶段锁前等待在途工作结束;硬件签名、运行时 smoke 检查和最终完整性校验仍须执行。 +缓存命中的复制、摘要和逐文件候选信任检查使用 `.env.windows` 中的 `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_CONCURRENCY` 个工作任务(默认 `4`,整数 `1`–`8`)。所有恢复完成后,有界 PowerShell 批次逐项验证恢复目标的信任、时间戳和证书,通过后未命中项才进入串行硬件签名。恢复失败会停止派发新的恢复任务并等待在途工作结束;目标验签失败会等待当前检查批次结束并阻止硬件签名。运行时 smoke 检查和最终完整性校验仍须执行。 -Windows 打包从 `.env.windows` 或所选预设读取 `DSH_DESKTOP_WINDOWS_PACK_CONCURRENCY`:必须为正整数,默认 `4`。Windows 使用有界 worker 批量打包第一方和 vendor tarball,随后校验每个产物并记录发布顺序。设为 `1` 时串行打包;独立的 `release:pack` 默认使用 `1`。 +PE 发现会读取每个普通文件的头部,同时最多打开八个文件,拒绝链接和损坏的 Windows 可执行文件,并在报告失败前等待在途读取和关闭结束。打包将 `windows:enumerate-code` 与 `windows:inspect-signatures` 记录为签名和产物验证的嵌套阶段;其耗时已包含在外层阶段中。 + +Windows 打包从 `.env.windows` 或所选预设读取 `DSH_DESKTOP_WINDOWS_PACK_CONCURRENCY`:必须为正整数,默认 `4`。Windows 使用有界 worker 批量打包第一方和 vendor tarball,随后校验每个产物并记录发布顺序。完整构建成功后,tarball 打包与 Electron、主要运行时准备在各自输出目录中并行执行。两者都成功结束后才开始运行时签名;准备失败会停止新的打包命令,并等待在途进程结束后返回。设为 `1` 时 tarball worker 串行执行;独立的 `release:pack` 默认使用 `1`。 每个运行时阶段向标准输出及打包日志写入 `SIGNATURE_CACHE_SUMMARY`,包含实际目录、策略标识、命中及未命中数、新发布及保留项数、签名请求数、省去的签名请求数和验证失败数。计时区分签名、恢复文件和新签名文件的信任验证及恢复;恢复耗时包含其信任检查和暂存清理。这些统计不包含预检、最终产物签名及外层运行时验签。阶段锁事件单独记录等待时间。 并发计时累加逐文件工作耗时,不代表阶段墙钟时间。 @@ -100,7 +114,13 @@ Windows 打包从 `.env.windows` 或所选预设读取 `DSH_DESKTOP_WINDOWS_PACK ## 验证范围 -真实硬件与安装证据由[Desktop 验证记录](../tests/README.zh.md)和[已安装更新流程](../tests/installed-update/README.zh.md)维护。本文档不授权 PIN 重试、自动删除 interlock、设备初始化或改变已接受的隔离策略。 +签名性能证据与更换 runner 后的复测由[签名并发验收](../tests/signing-concurrency/README.zh.md)维护。更新与安装证据由[Desktop 验证记录](../tests/README.zh.md)和[已安装更新流程](../tests/installed-update/README.zh.md)维护。本文档不授权 PIN 重试、自动删除 interlock、设备初始化或改变已接受的隔离策略。 + +经操作人员授权后,可运行 `node apps/desktop/tests/windows-signing-concurrency.perf.ts --execute --config-root <打包配置目录的绝对路径> --rounds 2` 做并发实验。不加 `--execute` 只打印用法。默认比较完全串行、两个完成任务共用单路硬件签名,以及两路硬件签名,每批使用六个合成 PE 副本。第二轮反转模式顺序。 + +加上 `--corpus <清单 JSON 的绝对路径>` 后,改用真实发布文件比较 1、2、4 个并发任务。清单是非空 JSON 数组,每项包含绝对路径 `path` 及对应的小写十六进制 `sha256`。准备阶段复制哈希固定的文件,验证签名并仅移除副本上的有效签名;签名无效或字节变化会中止准备。移除签名要求 SignTool 支持 `remove /s`;配置中的版本不支持时,可用 `--strip-tool ` 仅覆盖这个公开准备工具。硬件签名和时间戳仍使用机器 preset。每批使用经过字节比对的全新无签名模板副本,保持清单顺序。配合语料使用 `--pipeline-control` 时,改为四个完成任务共用一个硬件请求。原文件和发布缓存保持不变。 + +实验读取机器 test preset,核对公开身份,持有账户签名阶段锁,每批保留一条硬件尝试保护记录。首错停止派发并排空已发出的工作;最多可能已有四条硬件请求在途。只有全部签名、时间戳和文件验证成功才正常释放保护记录。文件从不执行。记录保留在 `.desktop-build/qualification/signing-concurrency`,包含整批及单文件耗时、批次起止时的主机 CPU 计数、可用内存和驱动进程内存采样。内存采样不含子进程,不能用于确定峰值内存。计时不含输入准备、等锁和包组装。重放现成产物还排除了它们之间的构建依赖;实验不启用生产并发,也不代表完整发布性能。 ## 开发备注 diff --git a/apps/plugin-market-generator/package.json b/apps/plugin-market-generator/package.json index b013bc93ff..b9b31d1912 100644 --- a/apps/plugin-market-generator/package.json +++ b/apps/plugin-market-generator/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-plugin-market-generator", "description": "Reference generator of plugin market index files from a list of npm packages and Git repositories", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "private": true, "type": "module", "scripts": { diff --git a/apps/web/package.json b/apps/web/package.json index b5ec233d82..b967ed8b39 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-web-frontend", "description": "Web application entry: vite build over the @deepseek-ai/dsh-client-web shell library; dist/ served by apps/cli's dsh web", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, diff --git a/apps/web/tests/additional-locales.e2e.ts b/apps/web/tests/additional-locales.e2e.ts new file mode 100644 index 0000000000..007aab3e14 --- /dev/null +++ b/apps/web/tests/additional-locales.e2e.ts @@ -0,0 +1,61 @@ +/** Shipped language selection, metadata and narrow settings through the assembled Web profile. */ +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { chromium, type Browser } from 'playwright' +import { expect, it, onTestFailed, onTestFinished } from 'vitest' +import { acknowledgeReloadConnectionLoss, captureStableAria, compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold } from './scaffold.ts' +import { saveFailureShot } from './support.ts' + +const languages = [ + ['es', 'es-MX', 'Menú de cuenta', 'Configuración', 'Complementos', 'Idioma', 'Español'], + ['fr', 'fr-CA', 'Menu du compte', 'Paramètres', 'Plugins', 'Langue', 'Français'], + ['de', 'de-DE', 'Kontomenü', 'Einstellungen', 'Plugins', 'Sprache', 'Deutsch'], + ['ru', 'ru-RU', 'Меню аккаунта', 'Настройки', 'Плагины', 'Язык', 'Русский'], + ['pt', 'pt-BR', 'Menu da conta', 'Configurações', 'Plug-ins', 'Idioma', 'Português'], +] as const + +it.each(languages)('selects %s from the browser, localizes metadata and persists an explicit choice', async (id, tag, accountMenu, settings, plugins, language, label) => { + const resources: { scaffold?: WebScaffold; browser?: Browser } = {} + onTestFinished(async () => { + try { await resources.browser?.close() } finally { await resources.scaffold?.close() } + }) + const scaffold = await launchWebScaffold() + resources.scaffold = scaffold + const browser = await chromium.launch() + resources.browser = browser + const page = await browser.newPage({ locale: tag, viewport: { width: 1440, height: 960 } }) + const tripwire = watchConsole(page) + onTestFailed(() => saveFailureShot(page, `additional-locale-${id}`)) + await page.goto(scaffold.authenticatedUrl) + await expect.poll(() => page.evaluate(() => document.documentElement.lang)).toBe(id) + await page.getByRole('button', { name: plugins, exact: true }).click() + const panel = page.locator('[data-plugin-panel]') + const metadata = JSON.parse(await readFile(new URL(`../../../packages/experimental/auto-review/locale/${id}.json`, import.meta.url), 'utf8')) as { meta: { title: string; description: string } } + await panel.getByText(metadata.meta.title, { exact: true }).waitFor() + await panel.getByText(metadata.meta.description, { exact: true }).waitFor() + await compareOrRefreshGolden(fileURLToPath(new URL(`./expected/additional-locales/${id}.expected.md`, import.meta.url)), + await captureStableAria(page, `[data-plugin-panel] li:has-text(${JSON.stringify(metadata.meta.title)})`, scaffold.workspaceCwd), webSnapshotMode()) + await page.getByRole('button', { name: accountMenu, exact: true }).click() + await page.getByRole('menuitem', { name: settings, exact: true }).click() + const dialog = page.getByRole('dialog', { name: settings, exact: true }) + await dialog.getByText(language, { exact: true }).waitFor() + await dialog.getByRole('button', { name: label, exact: true }).waitFor() + await page.setViewportSize({ width: 390, height: 844 }) + await expect.poll(() => dialog.evaluate((element) => { + const content = element.lastElementChild! + return { panel: element.scrollWidth <= element.clientWidth + 1, content: content.scrollWidth <= content.clientWidth + 1 } + })).toEqual({ panel: true, content: true }) + await dialog.getByRole('button', { name: label, exact: true }).click() + await page.getByRole('menuitem', { name: label, exact: true }).click() + await expect.poll(() => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')).toContain(`preference: ${id}`) + await dialog.getByRole('button', { name: label, exact: true }).click() + await page.getByRole('menuitem', { name: 'English', exact: true }).click() + await expect.poll(() => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')).toContain('preference: en') + const warningsBeforeReload = tripwire.warnings.length + await page.reload() + acknowledgeReloadConnectionLoss(tripwire, warningsBeforeReload) + await expect.poll(() => page.evaluate(() => document.documentElement.lang)).toBe('en') + expect(tripwire.warnings).toEqual([]) + expect(tripwire.pageErrors).toEqual([]) +}) diff --git a/apps/web/tests/assembled-remote.ts b/apps/web/tests/assembled-remote.ts index 401508bc2c..87f9288d42 100644 --- a/apps/web/tests/assembled-remote.ts +++ b/apps/web/tests/assembled-remote.ts @@ -288,8 +288,11 @@ export function createAssembledRemote(options: AssembledRemoteOptions = {}): Ass }) mock.unary('session/attachment', (request: unknown) => { request = recordValue(request, 'request') - const attachmentId = recordString(request, 'attachmentId') - return attachments.get(attachmentId) ?? { + const attachment = recordValue(request, 'attachment') + const attachmentId = recordString(attachment, 'attachmentId') + const stored = attachments.get(attachmentId) + if (stored !== undefined) return ok({ attachment, data: recordString(recordValue(stored, 'value'), 'data') }) + return { ok: false, error: { code: 'session/attachment-invalid', diff --git a/apps/web/tests/bundle-platform.e2e.ts b/apps/web/tests/bundle-platform.e2e.ts new file mode 100644 index 0000000000..55d22be94d --- /dev/null +++ b/apps/web/tests/bundle-platform.e2e.ts @@ -0,0 +1,62 @@ +/** Unsupported Host platforms leave the profile and running PTC configuration untouched. */ +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { chromium, type Browser } from 'playwright' +import type {} from '@deepseek-ai/dsh-ptc-runtime' +import { expect, it, onTestFinished } from 'vitest' +import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, webSnapshotMode, type WebScaffold } from './scaffold.ts' +import { connectFreshWorkspaceZh, ZH_BROWSER_LOCALE } from './support.ts' + +it('disables unsupported bundles, shows the Host restriction, and refuses direct activation without changing PTC', async () => { + const root = await mkdtemp(join(tmpdir(), 'bundle-platform-web-')) + const owned: { scaffold?: WebScaffold; browser?: Browser } = {} + onTestFinished(async () => { + try { await owned.browser?.close() } finally { + try { await owned.scaffold?.close() } finally { await rm(root, { recursive: true, force: true }) } + } + }) + const name = 'host-platform-only' + await writeFile(join(root, 'package.json'), JSON.stringify({ name, version: '1.0.0', dsh: { bundle: { + patch: './cordis.patch.yml', platforms: [process.platform === 'darwin' ? 'win32' : 'darwin'], + } } })) + await writeFile(join(root, 'cordis.patch.yml'), '- id: ptc-runtime\n config:\n executionMode: persistent-in-memory\n') + const scaffold = owned.scaffold = await launchWebScaffold({ profile: { packages: [{ dir: root }] } }) + const browser = owned.browser = await chromium.launch() + const page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) + await page.goto(scaffold.authenticatedUrl) + await connectFreshWorkspaceZh(page, scaffold.workspaceCwd) + await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click() + const reason = '此插件不支持运行 DSH 的主机操作系统' + const card = page.locator(`[data-plugin-package="${name}"]`) + await card.getByText(reason, { exact: true }).waitFor() + expect(await card.getByRole('switch').isEnabled()).toBe(false) + expect(await card.getByRole('switch').getAttribute('aria-checked')).toBe('false') + await compareOrRefreshGolden(fileURLToPath(new URL('./expected/bundle-platform/unsupported-platform.expected.md', import.meta.url)), + await captureStableAria(page, `[data-plugin-package="${name}"] p[role="status"]`, scaffold.workspaceCwd), webSnapshotMode()) + const manifest = join(scaffold.harnessHome, 'profiles/scaffold/package.json') + const before = await readFile(manifest, 'utf8') + const runtimeId = () => [...scaffold.ctx.loader.entries()].find(entry => entry.options.id === 'ptc-runtime')?.fiber?.uid + const beforeRuntime = runtimeId() + expect(beforeRuntime).toBeTypeOf('number') + expect(scaffold.ctx.ptcRuntime.programFormat).toBe('function-body') + const names = [name] + await page.locator('[data-plugin-panel]').getByRole('button', { name: '更多', exact: true }).click() + const cua = page.locator('[data-plugin-package="@deepseek-ai/dsh-cua-bundle"]') + expect(await cua.count()).toBe(0) + if (process.platform !== 'darwin') { + expect((await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === '@deepseek-ai/dsh-cua-bundle')) + .toMatchObject({ listedByDefault: false, enabled: false, error: { code: 'unsupported-platform' } }) + names.push('@deepseek-ai/dsh-cua-bundle') + } + for (const bundle of names) { + expect(await scaffold.ctx.pluginManager.setBundleEnabled(bundle, true)).toMatchObject({ + changed: false, application: 'failed', error: { code: 'unsupported-platform' }, + }) + } + expect(await readFile(manifest, 'utf8')).toBe(before) + expect(runtimeId()).toBe(beforeRuntime) + expect(scaffold.ctx.ptcRuntime.programFormat).toBe('function-body') + expect(scaffold.ctx.get('computerUse')).toBeUndefined() +}) diff --git a/apps/web/tests/chat-fold-opened-group.e2e.ts b/apps/web/tests/chat-fold-opened-group.e2e.ts index 184255f48a..a419c25a0a 100644 --- a/apps/web/tests/chat-fold-opened-group.e2e.ts +++ b/apps/web/tests/chat-fold-opened-group.e2e.ts @@ -1,9 +1,9 @@ /** * Scroll continuity when "On next message" folds a process group the reader opened. The latest Turn has * one Step; the reader opened its group and expanded the reasoning inside, so the group body is capped and - * scrollable, then sends the next message from the floor. A held prompt keeps the new Turn from starting - * until the fold settles, so only the fold moves the view while the scrollport is sampled on every - * animation frame. + * scrollable, then sends the next message from the floor. Agent maintenance keeps the accepted message in + * the inbox, so its echo folds the group before the new Turn starts, and only the fold moves the view while + * the scrollport is sampled on every animation frame. * * - A long answer leaves the folded group above the viewport. The scroll position changes in one direction * only: the fold never scrolls the view away and then snaps it back. @@ -13,7 +13,7 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import type { Browser, Page, Route } from 'playwright' +import type { Browser, Page } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import type { StreamChunk } from '@deepseek-ai/dsh-llm' @@ -223,8 +223,8 @@ interface World { readonly page: Page readonly session: SessionId readonly tripwire: ReturnType - /** Releases the held prompt; the new Turn starts after this. */ - readonly releasePrompt: () => void + /** Ends the Agent maintenance that keeps the accepted message in the inbox; the new Turn starts after this. */ + readonly releaseTurn: () => void /** Releases the held model stream; the new Step's output arrives after this. */ readonly releaseModel: () => void readonly ended: Promise @@ -232,8 +232,8 @@ interface World { } /** - * Seed and open the case, open the latest group, and send the next message from the floor with the prompt - * and the model stream held. + * Seed and open the case, open the latest group, and send the next message from the floor with the new Turn + * and its model stream held. */ async function sendFromOpenedGroup(browser: Browser, id: string, answerParagraphs: number): Promise { const replayDir = await mkdtemp(join(tmpdir(), 'dsh-open-fold-')) @@ -249,17 +249,15 @@ async function sendFromOpenedGroup(browser: Browser, id: string, answerParagraph await model.promise for await (const chunk of next()) yield chunk }) - const prompt = Promise.withResolvers() - const holdPrompt = async (route: Route): Promise => { - await prompt.promise - await route.continue() - } + const turn = Promise.withResolvers() + let maintenance: Promise = Promise.resolve(undefined) const page = await newEnglishPage(browser, 826) const close = async (): Promise => { - prompt.resolve(undefined) + turn.resolve(undefined) model.resolve(undefined) disposeHold() const failures: unknown[] = [] + await maintenance.catch((error: unknown) => failures.push(error)) await page.context().close().catch((error: unknown) => failures.push(error)) await scaffold.close().catch((error: unknown) => failures.push(error)) await rm(replayDir, { recursive: true, force: true }).catch((error: unknown) => failures.push(error)) @@ -280,7 +278,9 @@ async function sendFromOpenedGroup(browser: Browser, id: string, answerParagraph await toBottom(page) await openLatestGroup(page) await toBottom(page) - await page.route('**/api/session/prompt', holdPrompt) + const resolved = await scaffold.ctx.sessionController.resolveAgent(session) + if ('error' in resolved) throw resolved.error + maintenance = resolved.agent.runMaintenance(() => turn.promise) const ended = new Promise((resolveEnded, reject) => { const timer = setTimeout(() => { off(); reject(new Error(`${id}: no turn/end within 60000ms`)) }, 60_000) const off = scaffold.ctx.on('session/event', (owner: { id: SessionId }, event: SessionEvent) => { @@ -299,7 +299,7 @@ async function sendFromOpenedGroup(browser: Browser, id: string, answerParagraph await stableScroll(page) return { scaffold, page, session, tripwire, ended, close, - releasePrompt: () => { prompt.resolve(undefined) }, + releaseTurn: () => { turn.resolve(undefined) }, releaseModel: () => { model.resolve(undefined) }, } } catch (error) { @@ -330,7 +330,7 @@ describe.skipIf(MODE === 'record')('web e2e: next-message fold of an opened proc expect.soft(reversals, `scroll direction changes; per-frame movements ${JSON.stringify(steps)}`).toBe(0) const settled = frames.at(-1)! expect.soft(settled.floor - settled.top, 'distance from the floor after the fold').toBeLessThanOrEqual(1) - world.releasePrompt() + world.releaseTurn() world.releaseModel() await world.ended expect(world.tripwire.pageErrors).toEqual([]) @@ -345,7 +345,7 @@ describe.skipIf(MODE === 'record')('web e2e: next-message fold of an opened proc const folded = (await readTrace(world.page)).frames.at(-1)! expect.soft(folded.spacer, 'fold room below the short answer').toBeGreaterThan(0) expect.soft(folded.pinned, 'tail pin while fold room remains').toBe(false) - world.releasePrompt() + world.releaseTurn() // The running Step's group row is the first row after the user message; output stays held until then. await world.page.locator(`${ROOT} [data-chat-group-key][data-chat-turn="${String(TURNS + 1)}"]`).waitFor({ timeout: 30_000 }) await world.page.locator(`${ROOT} [data-chat-running]`).waitFor() diff --git a/apps/web/tests/chat-long-interactions.e2e.ts b/apps/web/tests/chat-long-interactions.e2e.ts index dec6749ab9..25cbcf590d 100644 --- a/apps/web/tests/chat-long-interactions.e2e.ts +++ b/apps/web/tests/chat-long-interactions.e2e.ts @@ -307,15 +307,17 @@ describe('web e2e: long Chat interaction contract', () => { await expect.poll(() => page.evaluate(() => navigator.clipboard.readText()), { timeout: 5_000 }) .toBe(expectedUserText) + const existing = new Set(scaffold.ctx.agents.list().map(agent => agent.id)) await turnTailRow.hover() await turnTailRow.getByRole('button', { name: 'Branch into a new conversation', exact: true }).click() await expect.poll( - () => scaffold.ctx.agents.list().find(agent => agent.session.header.parentSession === SessionId(SESSION_ID)), + () => scaffold.ctx.agents.list().find(agent => !existing.has(agent.id)), { timeout: 15_000 }, ).toBeDefined() const child = scaffold.ctx.agents.list() - .find(agent => agent.session.header.parentSession === SessionId(SESSION_ID)) + .find(agent => !existing.has(agent.id)) if (child === undefined) throw new Error('message branch did not create a child session') + expect(child.session.header.parentSession).toBeUndefined() expect(child.session.inheritedEventCount).toBe(boundary.seq + 1) expect(child.session.snapshotEvents().some(event => carries(event, branchAssistantMarker))).toBe(true) expect(child.session.snapshotEvents().some(event => carries(event, FIXTURE.markers.user(BRANCH_TURN + 1)))).toBe(false) diff --git a/apps/web/tests/chat-scroll-contract.e2e.ts b/apps/web/tests/chat-scroll-contract.e2e.ts index 49675a473a..6092eddc02 100644 --- a/apps/web/tests/chat-scroll-contract.e2e.ts +++ b/apps/web/tests/chat-scroll-contract.e2e.ts @@ -6,7 +6,7 @@ import { access, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' -import type { Browser, Page, Route } from 'playwright' +import type { Browser, Page } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import type { StreamChunk } from '@deepseek-ai/dsh-llm' @@ -679,14 +679,11 @@ describe('web e2e: long Chat scroll contract', () => { yield chunk } }) + const resolved = await world.scaffold.ctx.sessionController.resolveAgent(SessionId(`visible-fold-${scenario.name}`)) + if ('error' in resolved) throw resolved.error + // Maintenance keeps the accepted message in the inbox, so its echo folds the earlier work before the Turn starts. const promptGate = Promise.withResolvers() - const promptBlocked = Promise.withResolvers() - const holdPrompt = async (route: Route): Promise => { - promptBlocked.resolve(undefined) - await promptGate.promise - await route.continue() - } - await page.route('**/api/session/prompt', holdPrompt) + const maintenance = resolved.agent.runMaintenance(() => promptGate.promise) const trace = page.evaluate(({ marker, race }) => new Promise((resolveTrace) => { const host = document.querySelector('[data-conversation-scroll]')! const column = host.querySelector('[data-chat-flow]:has(> [data-slot="conversation.chat.flow"])')! @@ -781,7 +778,7 @@ describe('web e2e: long Chat scroll contract', () => { await page.clock.resume() } } else await page.getByRole('button', { name: 'Send message', exact: true }).click() - await promptBlocked.promise + await expect.poll(() => page.locator('[data-composer-input]').last().textContent()).toBe('') await page.getByText(input, { exact: true }).waitFor() await expect.poll(() => page.locator('[data-chat-motion="collapse"]').count()).toBe(0) if (scenario.name !== 'cancel-all-during-fold') await expectBottom(page) @@ -801,6 +798,7 @@ describe('web e2e: long Chat scroll contract', () => { }) await page.locator('[data-conversation-scroll]').evaluate(host => host.dispatchEvent(new Event('dsh-test-fold-growth'))) promptGate.resolve(undefined) + await maintenance release() await finishBlocked.promise await page.getByText('VISIBLE_FOLD_DONE', { exact: false }).waitFor() @@ -808,8 +806,8 @@ describe('web e2e: long Chat scroll contract', () => { await nextPaint(page) } finally { promptGate.resolve(undefined) + await maintenance release() - await page.unroute('**/api/session/prompt', holdPrompt) await page.locator('[data-conversation-scroll]').evaluate(host => host.dispatchEvent(new Event('dsh-test-fold-stop'))) samples = await trace finishGate.resolve(undefined) diff --git a/apps/web/tests/client-ui-stats-panel.e2e.ts b/apps/web/tests/client-ui-stats-panel.e2e.ts new file mode 100644 index 0000000000..fc0a51b3b5 --- /dev/null +++ b/apps/web/tests/client-ui-stats-panel.e2e.ts @@ -0,0 +1,160 @@ +// Keyless assembled-browser coverage for the opt-in Statistics view: the +// experimental client plugin is mounted only by the test overlay, so this Web +// composition is the package's user-visible evidence outside the jsdom lane. +import { fileURLToPath } from 'node:url' +import { join } from 'node:path' +import { readFileSync } from 'node:fs' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import * as yaml from 'js-yaml' +import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { + createAssistantMessage, createMessage, createUserMessage, ToolCallId, + type AssistantStreamRecord, type TokenUsage, +} from '@deepseek-ai/dsh-llm' +import { + assertFixtureInventory, captureStableAria, compareOrRefreshGolden, + launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' +import { + connectFreshWorkspace, newEnglishPage, pinBrowserClock, pinHostClock, saveFailureShot, +} from './support.ts' + +const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/client-ui-stats-panel', import.meta.url)) +const PANEL_EXPECTED = join(SNAPSHOT_DIR, 'panel.expected.md') +const OVERLAY = fileURLToPath(new URL('./client-ui-stats-panel.overlay.yml', import.meta.url)) +const INSTALL_ANCHORS = [ + fileURLToPath(new URL('../../../packages/experimental/client-ui-stats/package.json', import.meta.url)), +] +const MODE = webSnapshotMode() + +/** Overlay layer entries, for the composition guard below. */ +function profileEntries(path: string): unknown[] { + const parsed = yaml.load(readFileSync(path, 'utf8'), { schema: entryListSchema }) + if (!Array.isArray(parsed)) throw new Error(`profile layer at ${path} must be a list`) + return parsed +} + +/** Usage one fixture assistant round reports. */ +const USAGE: TokenUsage = { + inputTokens: 1_200, + outputTokens: 240, + cacheReadTokens: 3_600, + cacheWriteTokens: 400, +} + +/** Compact stream whose first token arrives at the absolute Session time `firstTokenAt`. */ +function stream(firstTokenAt: number): AssistantStreamRecord[] { + return [{ type: 'text-chunks', time0: firstTokenAt, index: 0, dt: [200], texts: ['Ready.'] }] +} + +describe('Statistics view overlay', () => { + it('mounts the experimental client plugin over the shipped Web surface', () => { + expect(profileEntries(OVERLAY)).toEqual([{ + insert: [{ id: 'ui-client-ui-stats', name: '@deepseek-ai/dsh-experimental-client-ui-stats' }], + }]) + }) +}) + +describe('web e2e: Statistics view', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + let clock: ReturnType + + beforeAll(async () => { + clock = pinHostClock() + scaffold = await launchWebScaffold({ extraOverlayPath: OVERLAY, extraInstallAnchors: INSTALL_ANCHORS }) + browser = await chromium.launch() + page = await newEnglishPage(browser) + await pinBrowserClock(page) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + const agent = scaffold.ctx.agents.list()[0] + if (agent === undefined) throw new Error('connected workspace did not create an Agent') + agent.session.append('turn/start', { turn: 1 }) + agent.session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Show the measured round.' }], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + agent.session.append('step/start', { turn: 1, step: 1 }) + await new Promise((resolve) => { setTimeout(resolve, 60) }) + // Real timestamps: the compact stream's time0 is an absolute Session time, + // so the measured first token must sit between this step's start and the + // settled message, exactly as a live round records them. + const firstTokenAt = Date.now() - 10 + agent.session.append('assistant/message', { + turn: 1, + step: 1, + message: createAssistantMessage({ + content: [{ type: 'text', text: 'Ready.' }], + source: { provider: 'fixture', model: 'fixture' }, + }), + stream: stream(firstTokenAt), + usage: USAGE, + }, { surfaceOp: 'append' }) + agent.session.append('tool/call', { + turn: 1, + step: 1, + callId: ToolCallId('call-1'), + name: 'read', + arguments: JSON.stringify({ file_path: '/work/notes.md' }), + }) + agent.session.append('tool/result', { + turn: 1, + step: 1, + message: createMessage({ + role: 'tool', + content: [{ type: 'text', text: 'one\ntwo' }], + source: { kind: 'tool', callId: ToolCallId('call-1') }, + toolCallId: ToolCallId('call-1'), + }), + }, { surfaceOp: 'append' }) + agent.session.append('step/end', { turn: 1, step: 1 }) + agent.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + await scaffold.ctx.sessions.flush(agent.session) + await page.getByText('Ready.').waitFor({ timeout: 10_000 }) + }, 120_000) + + afterAll(async () => { + await browser?.close() + clock?.mockRestore() + await scaffold?.close() + }) + + it('renders the measured context, timing, cache, and tool columns', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-client-ui-stats-panel')) + await page.getByRole('tab', { name: 'Statistics', exact: true }).click() + const table = page.locator('table[aria-label="Statistics"]') + await table.waitFor({ timeout: 10_000 }) + expect(await table.getByRole('columnheader', { name: 'Context', exact: true }).count()).toBe(1) + expect(await table.getByRole('columnheader', { name: 'Output', exact: true }).count()).toBe(1) + expect(await table.getByRole('columnheader', { name: 'Cache hit', exact: true }).count()).toBe(1) + expect(await table.getByText('Turn 1', { exact: false }).count()).toBeGreaterThan(0) + expect(await table.getByText('Step 1', { exact: false }).count()).toBeGreaterThan(0) + expect(await table.getByText('read ×1', { exact: false }).count()).toBeGreaterThan(0) + // The measured columns carry the fixture's real accounting, and the timing + // columns are measured rather than the dash placeholder. Durations and the + // derived throughput/clock vary with the run, so the golden tokenizes them. + const cells = await table.locator('tbody tr').first().locator('td').allInnerTexts() + expect(cells[3]).toBe('5.2K') + expect(cells[4]).toBe('0.24K') + expect(cells[5]).toBe('69.23%') + expect(cells[6]).not.toBe('—') + expect(cells[8]).not.toBe('—') + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + const snapshot = await captureStableAria(page, 'table[aria-label="Statistics"]', scaffold.workspaceCwd, { + replacements: [[cells[6]!, '{{ttft}}'], [cells[8]!, '{{tps}}']], + }) + await compareOrRefreshGolden(PANEL_EXPECTED, snapshot, MODE) + }, 60_000) + + it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => { + await assertFixtureInventory(SNAPSHOT_DIR, ['panel.expected.md']) + }) +}) diff --git a/apps/web/tests/client-ui-stats-panel.overlay.yml b/apps/web/tests/client-ui-stats-panel.overlay.yml new file mode 100644 index 0000000000..7f55221244 --- /dev/null +++ b/apps/web/tests/client-ui-stats-panel.overlay.yml @@ -0,0 +1,7 @@ +# Test-only composition: mount the experimental @@STATSORMANCE@@ view beside Chat +# and Trajectory over the shipped Web surface. No shipped profile mounts this +# package (default-product isolation forbids it), so this overlay is the only +# real-Web composition that can render it. +- insert: + - id: ui-client-ui-stats + name: '@deepseek-ai/dsh-experimental-client-ui-stats' diff --git a/apps/web/tests/collapse-timing.e2e.ts b/apps/web/tests/collapse-timing.e2e.ts index a19b71192b..7d363a8dc4 100644 --- a/apps/web/tests/collapse-timing.e2e.ts +++ b/apps/web/tests/collapse-timing.e2e.ts @@ -3,7 +3,7 @@ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { basename, join } from 'node:path' import { fileURLToPath } from 'node:url' -import type { Browser, Page, Route } from 'playwright' +import type { Browser, Page } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import { deriveReplayScript } from '@deepseek-ai/dsh-llm-replay' @@ -146,34 +146,23 @@ describe.skipIf(MODE === 'record')('web e2e: recorded collapse timing', () => { const input = page.locator('[data-composer-input]').last() await writeComposerDraft(page, input, prompt) await expectProcess(1, true) + const resolved = await scaffold.ctx.sessionController.resolveAgent(SessionId(SEED_ID)) + if ('error' in resolved) throw resolved.error + // Maintenance keeps the accepted message in the inbox, so its echo stays before the Turn starts. const release = Promise.withResolvers() - const promptBlocked = Promise.withResolvers() - const holdPrompt = async (route: Route): Promise => { - promptBlocked.resolve(undefined) - await release.promise - await route.continue() - } - await page.route('**/api/session/prompt', holdPrompt) + const maintenance = resolved.agent.runMaintenance(() => release.promise) try { await page.getByRole('button', { name: 'Send message', exact: true }).click() - const blockedTimeout = setTimeout(() => { - promptBlocked.reject(new Error('session prompt did not reach the route barrier')) - }, UI_WAIT.timeout) - try { - await promptBlocked.promise - } finally { - clearTimeout(blockedTimeout) - } await expect.poll(() => page.locator('[data-submission-echo]').count(), UI_WAIT).toBe(1) await expectProcess(1, false) expect(await page.locator('[data-turn-process="2"]').count()).toBe(0) await capture('input-pending.expected.md') const settled = scaffold.whenTurnSettled() release.resolve(undefined) + await maintenance expect(await settled).toBe(SEED_ID) } finally { release.resolve(undefined) - await page.unrouteAll({ behavior: 'wait' }) } await expect.poll(() => page.getByText('DONE', { exact: true }).count(), UI_WAIT).toBe(2) await expect.poll(() => page.locator('[data-streaming="true"]').count(), UI_WAIT).toBe(0) diff --git a/apps/web/tests/conversation-view-tabs.e2e.ts b/apps/web/tests/conversation-view-tabs.e2e.ts new file mode 100644 index 0000000000..3995e03b45 --- /dev/null +++ b/apps/web/tests/conversation-view-tabs.e2e.ts @@ -0,0 +1,110 @@ +// Browser hit testing for the conversation view tabs: each tab accepts presses +// beyond its label, and the selected tab's bar stays above the Trajectory +// view's sticky toolbar where the two meet. +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { createChatScrollFixture } from './chat-scroll-fixture.ts' +import { launchWebScaffold, seedSession, watchConsole, type WebScaffold } from './scaffold.ts' +import { newEnglishPage, saveFailureShot } from './support.ts' + +const FIXTURE = createChatScrollFixture({ + markerPrefix: 'VIEW_TABS', + title: 'VIEW_TABS short session', + turns: 4, +}) +const SEED_ID = 'conversation-view-tabs-web-e2e' + +/** Label and button rectangles of one tab, and which element owns each probe point. */ +interface TabProbe { + readonly label: { left: number; top: number; right: number; bottom: number } + readonly button: { left: number; top: number; right: number; bottom: number } + readonly ownsAboveLabel: boolean + readonly ownsBesideLabel: boolean + readonly ownsBarOverhang: boolean +} + +/** + * Probe one tab: the run above and beside its label, and the bar's lowest + * half pixel, below the button box. + * @param page - the page under test. + * @param name - the tab's accessible name. + * @returns the tab's rectangles and probe owners. + */ +async function probeTab(page: Page, name: string): Promise { + return page.getByRole('tab', { name, exact: true }).evaluate((tab) => { + const range = document.createRange() + range.selectNodeContents(tab) + const label = range.getBoundingClientRect() + const button = tab.getBoundingClientRect() + const owns = (x: number, y: number): boolean => document.elementFromPoint(x, y)?.closest('[role="tab"]') === tab + const centerX = (label.left + label.right) / 2 + return { + label: { left: label.left, top: label.top, right: label.right, bottom: label.bottom }, + button: { left: button.left, top: button.top, right: button.right, bottom: button.bottom }, + ownsAboveLabel: owns(centerX, label.top - 8), + ownsBesideLabel: owns(label.left - 8, (label.top + label.bottom) / 2), + ownsBarOverhang: owns(centerX, button.bottom + 0.5), + } + }) +} + +async function openSeededSession(page: Page): Promise { + const searchButton = page.getByRole('button', { name: 'Search sessions' }) + if (await searchButton.getAttribute('aria-expanded') !== 'true') await searchButton.click() + await page.getByRole('textbox', { name: 'Search session names', exact: true }).fill(FIXTURE.markers.user(1)) + const results = page.getByRole('tree', { name: 'Search results' }).getByRole('treeitem') + const deadline = Date.now() + 60_000 + while (await results.count() !== 1) { + if (Date.now() > deadline) throw new Error('seeded session never appeared in the sidebar search results') + await page.waitForTimeout(200) + } + await results.click() +} + +describe('web e2e: conversation view tabs', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + scaffold = await launchWebScaffold({}) + await seedSession(scaffold, FIXTURE.log, SEED_ID) + browser = await chromium.launch() + page = await newEnglishPage(browser, 900) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await openSeededSession(page) + await page.getByText(FIXTURE.markers.assistant(FIXTURE.turns), { exact: false }).last() + .waitFor({ timeout: 30_000 }) + }, 180_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + }) + + it('takes presses above and beside the label', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-conversation-view-tabs-target')) + const chat = await probeTab(page, 'Chat') + expect(chat.button.top).toBeLessThan(chat.label.top - 8) + expect(chat.button.left).toBeLessThan(chat.label.left - 8) + expect(chat.ownsAboveLabel).toBe(true) + expect(chat.ownsBesideLabel).toBe(true) + expect(tripwire.pageErrors).toEqual([]) + }) + + it('keeps the selected bar above the Trajectory toolbar', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-conversation-view-tabs-trajectory')) + await page.getByRole('tab', { name: 'Trajectory', exact: true }).click() + const toolbar = page.getByRole('toolbar', { name: 'Trajectory toolbar' }) + await toolbar.waitFor({ timeout: 30_000 }) + const trajectory = await probeTab(page, 'Trajectory') + // The toolbar must start within the bar's overhang, or the probe cannot fail. + expect((await toolbar.boundingBox())!.y).toBeLessThanOrEqual(trajectory.button.bottom + 1) + expect(trajectory.ownsBarOverhang).toBe(true) + expect(tripwire.pageErrors).toEqual([]) + }) +}) diff --git a/apps/web/tests/cot-translation-paid.e2e.ts b/apps/web/tests/cot-translation-paid.e2e.ts index f8afb08a67..37c2199298 100644 --- a/apps/web/tests/cot-translation-paid.e2e.ts +++ b/apps/web/tests/cot-translation-paid.e2e.ts @@ -196,7 +196,7 @@ it.skipIf(MODE === 'record')('reuses saved native Account Flash translations acr await panel.getByText(`v${bundleVersion}`, { exact: true }).waitFor() await panel.getByText(bundleVersion, { exact: true }).waitFor() // The bundle's detail document is shown between its components and its source. - await panel.locator('[data-detail-document]').getByRole('heading', { name: '使用方法', exact: true }).waitFor() + await panel.locator('[data-detail-document]').getByRole('img', { name: '展开的思考行从英文翻译成中文,并显示“查看原文”按钮', exact: true }).waitFor() await compareOrRefreshGolden(join(EXPECTED, 'paid-choices.expected.md'), await captureStableAria(settings, '[data-plugin-panel]', scaffold.workspaceCwd, { replacements: [[BUNDLE, '{{bundle}}'], [bundleVersion, '{{version}}']], diff --git a/apps/web/tests/cot-translation.e2e.ts b/apps/web/tests/cot-translation.e2e.ts index cf10562c90..c4db45b575 100644 --- a/apps/web/tests/cot-translation.e2e.ts +++ b/apps/web/tests/cot-translation.e2e.ts @@ -213,7 +213,7 @@ it.skipIf(MODE === 'record')('persists Bing reasoning translation across reopen await panel.getByText(`v${bundleVersion}`, { exact: true }).waitFor() await panel.getByText(bundleVersion, { exact: true }).waitFor() // The bundle's detail document is shown between its components and its source. - await panel.locator('[data-detail-document]').getByRole('heading', { name: '使用方法', exact: true }).waitFor() + await panel.locator('[data-detail-document]').getByRole('img', { name: '展开的思考行从英文翻译成中文,并显示“查看原文”按钮', exact: true }).waitFor() await compareOrRefreshGolden(join(EXPECTED, 'preferences.expected.md'), await captureStableAria(settings, '[data-plugin-panel]', scaffold.workspaceCwd, { replacements: [[BUNDLE, '{{bundle}}'], [bundleVersion, '{{version}}']], diff --git a/apps/web/tests/creation-recommendations.e2e.ts b/apps/web/tests/creation-recommendations.e2e.ts new file mode 100644 index 0000000000..119a2ef3f7 --- /dev/null +++ b/apps/web/tests/creation-recommendations.e2e.ts @@ -0,0 +1,130 @@ +/** The completed answer offers creation through a propose_action card; choosing a location does not start it. */ +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { chromium, type Browser, type Page } from 'playwright' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { + acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden, + fixtureUserPrompts, launchWebScaffold, watchConsole, type WebScaffold, +} from './scaffold.ts' +import { connectFreshWorkspace, newEnglishPage } from './support.ts' + +const directory = fileURLToPath(new URL('../../../snapshots/web/creation-recommendations', import.meta.url)) +const fixture = join(directory, 'session.v4.jsonl') + +describe('creation recommendation after an explicit wish', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + + beforeAll(async () => { + scaffold = await launchWebScaffold({ replayFixture: fixture, compareReplaySession: true, + profile: { packages: [{ dir: fileURLToPath(new URL('../../../packages/experimental/personalized-recommendations', import.meta.url)), enabled: true }] }, + }) + browser = await chromium.launch() + page = await newEnglishPage(browser) + }) + afterAll(async () => { await browser?.close(); await scaffold?.close() }) + + it('shows one card below the answer, lets the user change location, and restores a dismissal', async () => { + const tripwire = watchConsole(page) + await page.setViewportSize({ width: 620, height: 900 }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + const input = page.locator('[data-composer-input]').first() + const settled = scaffold.whenTurnSettled() + await input.fill(fixtureUserPrompts(await readFile(fixture, 'utf8'))[0]!) + await input.press('Enter') + await settled + const card = page.locator('[data-action-card]') + await card.waitFor({ state: 'visible' }) + expect(await card.count()).toBe(1) + expect(await page.locator('[data-turn-tail] [data-action-card]').count()).toBe(1) + const answer = page.getByText('I can create a persistent counter with increment and reset controls. Choose its location below.', { exact: true }) + const answerBox = await answer.boundingBox() + const cardBox = await card.boundingBox() + expect(answerBox).not.toBeNull() + expect(cardBox!.y).toBeGreaterThanOrEqual(answerBox!.y + answerBox!.height) + expect(await card.getByRole('button', { name: 'Create', exact: true }).isEnabled()).toBe(true) + await compareOrRefreshGolden(join(directory, 'offered.expected.md'), await captureStableAria(page, '[data-action-card]', scaffold.workspaceCwd), scaffold.mode) + const info = card.getByRole('button', { name: 'How creation works and token usage', exact: true }) + expect(await info.getAttribute('aria-expanded')).toBe('true') + expect(await card.getByRole('note').innerText()).toContain('large number of tokens') + await info.focus() + await info.press('Space') + expect(await card.getByRole('note').count()).toBe(0) + const infoWarnings = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + await card.waitFor({ state: 'visible' }) + acknowledgeReloadConnectionLoss(tripwire, infoWarnings) + expect(await info.getAttribute('aria-expanded')).toBe('false') + await info.focus() + await info.press('Enter') + expect(await info.getAttribute('aria-expanded')).toBe('true') + expect(await card.getByRole('note').innerText()).toContain('large number of tokens') + expect(await card.getByRole('note').innerText()).toContain('keep chatting here') + expect(await card.getByRole('button', { name: 'Create', exact: true }).isEnabled()).toBe(true) + expect(await card.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + await compareOrRefreshGolden(join(directory, 'info.expected.md'), await captureStableAria(page, '[data-action-card]', scaffold.workspaceCwd), scaffold.mode) + await info.press('Space') + expect(await info.getAttribute('aria-expanded')).toBe('false') + expect(await card.getByRole('note').count()).toBe(0) + const expand = card.getByRole('button', { name: 'Show more', exact: true }) + const plan = page.locator(`[id="${await expand.getAttribute('aria-controls')}"]`) + const compactHeight = await plan.evaluate(element => element.clientHeight) + const previewText = await plan.innerText() + expect(previewText.endsWith('…')).toBe(true) + // The preview keeps about 260 Latin-letter widths before the ellipsis; a trailing space may be trimmed. + const previewLength = Array.from(new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(previewText)).length + expect(previewLength).toBeGreaterThan(200) + expect(previewLength).toBeLessThanOrEqual(261) + await expand.click() + expect(await plan.evaluate(element => element.clientHeight)).toBeGreaterThan(compactHeight) + expect(await card.getByRole('button', { name: 'Create', exact: true }).isEnabled()).toBe(true) + await compareOrRefreshGolden(join(directory, 'expanded.expected.md'), await captureStableAria(page, '[data-action-card]', scaffold.workspaceCwd), scaffold.mode) + await card.getByRole('button', { name: 'Show less', exact: true }).click() + const location = card.getByRole('button', { name: 'Add to: Right sidebar', exact: true }) + await location.click() + expect(await page.getByRole('menuitem').count()).toBe(4) + await compareOrRefreshGolden(join(directory, 'location-menu.expected.md'), await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd), scaffold.mode) + await page.getByRole('menuitem').first().press('Escape') + expect(await page.getByRole('menu').count()).toBe(0) + expect(await location.evaluate(element => element === document.activeElement)).toBe(true) + await location.click() + await page.getByRole('menuitem', { name: /Write your own/ }).click() + const custom = card.getByRole('textbox', { name: 'Where should it appear?', exact: true }) + expect(await card.getByRole('button', { name: 'Create', exact: true }).isEnabled()).toBe(false) + await custom.fill('A left sidebar entry that opens a full-page calendar') + expect(await card.getByRole('button', { name: 'Create', exact: true }).isEnabled()).toBe(true) + await compareOrRefreshGolden(join(directory, 'custom-location.expected.md'), await captureStableAria(page, '[data-action-card]', scaffold.workspaceCwd), scaffold.mode) + await card.getByRole('button', { name: 'Add to: Write your own', exact: true }).click() + await page.getByRole('menuitem', { name: /Session tab/ }).click() + expect(await card.getByRole('button', { name: 'Add to: Session tab', exact: true }).isVisible()).toBe(true) + expect(await custom.count()).toBe(0) + await compareOrRefreshGolden(join(directory, 'options.expected.md'), await captureStableAria(page, '[data-action-card]', scaffold.workspaceCwd), scaffold.mode) + expect(await card.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + await card.getByRole('button', { name: 'Not now', exact: true }).click() + await card.getByRole('status').getByText('Dismissed', { exact: true }).waitFor() + const warnings = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + await card.getByRole('status').getByText('Dismissed', { exact: true }).waitFor() + acknowledgeReloadConnectionLoss(tripwire, warnings) + expect(await card.getByRole('button', { name: 'Create', exact: true }).count()).toBe(0) + expect(await card.getByRole('button', { name: 'Show more', exact: true }).isVisible()).toBe(true) + expect((await scaffold.ctx.pluginManager.listBundles()).some(bundle => bundle.name.startsWith('@dsh-local/view-'))).toBe(false) + await compareOrRefreshGolden(join(directory, 'dismissed.expected.md'), await captureStableAria(page, '[data-action-card]', scaffold.workspaceCwd), scaffold.mode) + const statusSettled = scaffold.whenTurnSettled() + await input.fill(fixtureUserPrompts(await readFile(fixture, 'utf8'))[1]!) + await input.press('Enter') + await statusSettled + await page.getByText('The counter proposal was dismissed. Creation never started.', { exact: true }).waitFor() + expect(await card.count()).toBe(1) + expect(await card.getByRole('button', { name: 'Create', exact: true }).count()).toBe(0) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + if (scaffold.mode === 'replay') await assertFixtureInventory(directory, [ + 'session.v4.jsonl', 'offered.expected.md', 'info.expected.md', 'expanded.expected.md', 'options.expected.md', 'dismissed.expected.md', 'location-menu.expected.md', 'custom-location.expected.md', 'system-prompt.expected.md', 'tool-schemas.expected.json', + ]) + }) +}) diff --git a/apps/web/tests/cua-optin.e2e.ts b/apps/web/tests/cua-optin.e2e.ts index f08cd4a54b..a9ddcde869 100644 --- a/apps/web/tests/cua-optin.e2e.ts +++ b/apps/web/tests/cua-optin.e2e.ts @@ -1,5 +1,5 @@ -/** Optional CUA uses existing plugin activation and offers a separate persistent PTC action. */ -import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +/** CUA follows PTC Agent scopes and changes the default only from its detail page. */ +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' @@ -8,52 +8,86 @@ import { readProfileManifest } from '@deepseek-ai/dsh-app-boot' import { SessionId } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-ptc-runtime' import type {} from '@deepseek-ai/dsh-agent-preset-registry' +import { load } from 'js-yaml' import { expect, it, vi } from 'vitest' import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, webSnapshotMode, type WebScaffold } from './scaffold.ts' import { connectFreshWorkspaceZh, ZH_BROWSER_LOCALE } from './support.ts' -it.each([undefined, 'minimal'] as const)('adds CUA to PTC sessions while preserving default %s until the explicit persistent-runtime action', async (selectedDefault) => { +// The shipped bundle admits only macOS Hosts; unsupported Hosts are exercised in bundle-platform.e2e.ts. +it.skipIf(process.platform !== 'darwin').each([ + { selectedDefault: undefined, codingTools: false, script: false }, + { selectedDefault: undefined, codingTools: true, script: false }, + { selectedDefault: 'minimal', codingTools: true, script: false }, + { selectedDefault: undefined, codingTools: true, script: true }, +] as const)('preserves Coding Tools=$codingTools and default=$selectedDefault and Script=$script across CUA toggles', async ({ selectedDefault, codingTools, script }) => { const directory = await mkdtemp(join(tmpdir(), 'cua-optin-web-')) let ownedScaffold: WebScaffold | undefined let browser: Browser | undefined try { const patch = join(directory, 'native-fixture.yml') - // The executable cannot answer native permission queries, so setup must offer retry in the detail page. - await writeFile(patch, JSON.stringify([{ id: 'cua', disabled: false, config: { helperPath: process.execPath } }])) - // Install the test provider explicitly so the helper override also exercises session wiring on Linux. + // Permission inspection fails against this non-helper executable; activation still permits dismissing setup. + await writeFile(patch, JSON.stringify([{ id: 'cua', config: { helperPath: process.execPath } }])) + const defaults = join(directory, 'script-defaults') + if (script) { + await mkdir(defaults) + await writeFile(join(defaults, 'package.json'), JSON.stringify({ name: 'cua-script-defaults', version: '1.0.0', dsh: { bundle: { patch: 'cordis.patch.yml' } } })) + await writeFile(join(defaults, 'cordis.patch.yml'), '- id: ptc-runtime\n config:\n executionMode: vm-script\n scriptPersistence: false\n') + } + const harnessHome = join(directory, 'home') const scaffold = ownedScaffold = await launchWebScaffold({ - profile: { packages: [{ dir: fileURLToPath(new URL('../../../packages/experimental/cua-macos', import.meta.url)), enabled: false }] }, - harnessHome: join(directory, 'home'), extraOverlayPath: [ + profile: { packages: script ? [{ dir: defaults, enabled: true }] : [] }, + harnessHome, extraOverlayPath: [ fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), patch, ] }) const initialDefault = selectedDefault ?? 'standard' if (selectedDefault !== undefined) await scaffold.ctx.settings.update('agent-preset-registry', { selectedDefault }) + await scaffold.ctx.settings.update('ui-settings', { enabled: codingTools }) + const settingsPath = join(harnessHome, 'profiles/scaffold/cordis.patch.yml') + const beforeEnable = await readFile(settingsPath, 'utf8') browser = await chromium.launch() const page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) - await page.goto(scaffold.authenticatedUrl) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await connectFreshWorkspaceZh(page, scaffold.workspaceCwd) - const originalAgent = scaffold.ctx.agents.list()[0]! - const ptcAgent = (await scaffold.ctx.agents.create({ sessionId: SessionId('cua-existing-ptc'), - setup: async (ctx) => { await scaffold.ctx.agentPresets.mount(ctx, 'ptc') }, - })).agent - const runtimeFiber = () => [...scaffold.ctx.loader.entries()].find(entry => entry.options.id === 'ptc-runtime')?.fiber - const originalRuntime = scaffold.ctx.ptcRuntime - const originalRuntimeFiber = runtimeFiber() - expect(originalRuntimeFiber).toBeDefined() - expect(scaffold.ctx.ptcRuntime.programFormat).toBe('function-body') - const settingsPath = join(scaffold.harnessHome, 'profiles/scaffold/cordis.patch.yml') - const before = await readFile(settingsPath, 'utf8') - const selected = () => readProfileManifest('scaffold', join(scaffold.harnessHome, 'profiles/scaffold')).dsh?.profile?.bundles await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click() const plugins = page.locator('[data-plugin-panel]') await plugins.getByRole('button', { name: '更多', exact: true }).waitFor() expect(await page.locator('[data-plugin-package="@deepseek-ai/dsh-cua-bundle"]').count()).toBe(0) await plugins.getByRole('button', { name: '更多', exact: true }).click() const card = page.locator('[data-plugin-package="@deepseek-ai/dsh-cua-bundle"]') - expect(await card.getByText('实验性', { exact: true }).count()).toBe(1) - const toggle = card.getByRole('switch', { name: '启用 Computer Use', exact: true }) - expect(await toggle.getAttribute('aria-checked')).toBe('false') - expect(await card.textContent()).toContain('请切换到 PTC 模式') + expect(await card.count()).toBe(0) + expect((await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === '@deepseek-ai/dsh-cua-bundle')) + .toMatchObject({ listedByDefault: false, enabled: false, installed: false }) + await plugins.getByRole('button', { name: '返回插件', exact: true }).click() + const offerCua = async () => { + await plugins.getByRole('button', { name: '添加插件', exact: true }).click() + const dialog = page.getByRole('dialog', { name: '添加插件', exact: true }) + await dialog.getByRole('textbox', { name: '包名或地址', exact: true }).fill('@deepseek-ai/dsh-cua-bundle') + await dialog.getByRole('button', { name: '安装', exact: true }).click() + const ready = page.getByRole('dialog', { name: '插件已随 DSH 提供', exact: true }) + await ready.waitFor() + expect(await ready.getByText('无需下载,启用即可使用', { exact: true }).count()).toBe(1) + return ready.getByRole('button', { name: '立即启用', exact: true }) + } + const enableNow = await offerCua() + let toggle = card.getByRole('switch', { name: '启用 Computer Use', exact: true }) + const originalAgent = scaffold.ctx.agents.list()[0]! + const ptcAgent = (await scaffold.ctx.agents.create({ + sessionId: SessionId('cua-existing-ptc'), + setup: async (ctx) => { await scaffold.ctx.agentPresets.mount(ctx, 'ptc') }, + })).agent + expect(scaffold.ctx.tools.schemas(ptcAgent).some(tool => tool.name === 'cua')).toBe(false) + const runtimeFiber = () => [...scaffold.ctx.loader.entries()].find(entry => entry.options.id === 'ptc-runtime')?.fiber + const originalRuntimeFiber = runtimeFiber() + expect(originalRuntimeFiber).toBeDefined() + const originalRuntime = scaffold.ctx.ptcRuntime + expect(scaffold.ctx.agentPresets.defaultId).toBe(initialDefault) + expect(originalRuntime.programFormat).toBe(script ? 'script' : 'function-body') + expect(scaffold.ctx.get('computerUse')).toBeUndefined() + const profileManifest = () => readProfileManifest('scaffold', join(scaffold.harnessHome, 'profiles/scaffold')) + const selected = () => profileManifest().dsh?.profile?.bundles + const dependencies = profileManifest().dependencies + expect(selected()).not.toContain('@deepseek-ai/dsh-cua-bundle') + const enabling = Promise.withResolvers() const setEnabled = scaffold.ctx.pluginManager.setBundleEnabled.bind(scaffold.ctx.pluginManager) let applying: ReturnType | undefined @@ -63,11 +97,12 @@ it.each([undefined, 'minimal'] as const)('adds CUA to PTC sessions while preserv return applying }) try { - await toggle.click() - await card.getByRole('status').getByText('正在应用 Computer Use 的更改', { exact: true }).waitFor() - expect(await toggle.isEnabled()).toBe(false) + await enableNow.click() + await expect.poll(() => enableNow.isEnabled()).toBe(false) + expect(await enableNow.getAttribute('aria-busy')).toBe('true') + expect(await card.count()).toBe(0) await compareOrRefreshGolden(fileURLToPath(new URL('./expected/cua-permissions/enabling.expected.md', import.meta.url)), - await captureStableAria(page, '[data-plugin-package="@deepseek-ai/dsh-cua-bundle"]', scaffold.workspaceCwd), webSnapshotMode()) + await captureStableAria(page, '[data-install-phase="done"] button[aria-busy]', scaffold.workspaceCwd), webSnapshotMode()) } finally { enabling.resolve(undefined) enableCall.mockRestore() @@ -79,70 +114,150 @@ it.each([undefined, 'minimal'] as const)('adds CUA to PTC sessions while preserv const setup = page.getByRole('dialog', { name: '使用 Computer Use 前需要设置', exact: true }) await setup.waitFor() expect(await setup.getByText('Computer Use 插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) - await setup.getByRole('button', { name: '稍后', exact: true }).click() - expect(selected()).toContain('@deepseek-ai/dsh-cua-bundle') - expect(await readFile(settingsPath, 'utf8')).toBe(before) - expect(runtimeFiber() === originalRuntimeFiber).toBe(true) - expect(scaffold.ctx.ptcRuntime.programFormat).toBe('function-body') + await compareOrRefreshGolden(fileURLToPath(new URL('./expected/cua-permissions/setup.expected.md', import.meta.url)), + await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), webSnapshotMode()) + expect(await setup.getByRole('button', { name: '设为 PTC', exact: true }).count()).toBe(0) expect(scaffold.ctx.agentPresets.defaultId).toBe(initialDefault) + expect(selected()).toContain('@deepseek-ai/dsh-cua-bundle') + expect(profileManifest().dependencies).toEqual(dependencies) + expect(await card.getByText('实验性', { exact: true }).count()).toBe(1) + expect(await card.textContent()).not.toContain('将 PTC 模式改为可持久化') + expect(await card.textContent()).toContain('请切换到 PTC 模式') + expect(await card.textContent()).toContain('Windows 支持正在开发中') + expect(await card.textContent()).not.toContain('Swift') + const description = await card.getByRole('button', { name: '查看 Computer Use', exact: true }).evaluate((button) => { + const element = document.getElementById(button.getAttribute('aria-describedby')!)! + const style = getComputedStyle(element) + return { lines: style.webkitLineClamp, height: element.getBoundingClientRect().height, + lineHeight: Number.parseFloat(style.lineHeight) } + }) + expect(description.lines).toBe('1') + expect(description.height).toBeLessThanOrEqual(description.lineHeight + 1) + expect(scaffold.ctx.get('computerUse')).toBeDefined() expect(scaffold.ctx.agents.get(originalAgent.id) === originalAgent).toBe(true) + expect(scaffold.ctx.agents.get(ptcAgent.id) === ptcAgent).toBe(true) + expect(scaffold.ctx.agentPresets.composedPreset(originalAgent.ctx)).toBe(initialDefault) expect(scaffold.ctx.tools.schemas(originalAgent).some(tool => tool.name === 'cua')).toBe(false) expect(scaffold.ctx.tools.schemas(ptcAgent).some(tool => tool.name === 'cua')).toBe(true) expect((await scaffold.ctx.systemPrompt.assemble({ scope: ptcAgent })).tools.map(tool => tool.name)).toEqual(['run_code']) - const fresh = await scaffold.ctx.agents.create({ sessionId: SessionId('cua-new-ptc'), - setup: async (ctx) => { await scaffold.ctx.agentPresets.mount(ctx, 'ptc') }, + for (const preset of ['ptc', 'standard', 'ptc', initialDefault]) { + await scaffold.ctx.agentPresets.select(originalAgent, preset) + expect(scaffold.ctx.tools.schemas(originalAgent).some(tool => tool.name === 'cua')).toBe(preset === 'ptc') + } + const child = await scaffold.ctx.agents.create({ + sessionId: SessionId('cua-child'), parentAgent: ptcAgent, + setup: (ctx) => { scaffold.ctx.agentPresets.composeFrom(ctx, ptcAgent.ctx) }, }) - expect(scaffold.ctx.tools.schemas(fresh.agent).some(tool => tool.name === 'cua')).toBe(true) - await toggle.click() - await toggle.and(page.locator('[aria-checked="false"]')).waitFor({ state: 'visible' }) - expect(scaffold.ctx.get('computerUse')).toBeUndefined() - for (const agent of [ptcAgent, fresh.agent]) expect(scaffold.ctx.tools.schemas(agent).some(tool => tool.name === 'cua')).toBe(false) + expect(scaffold.ctx.tools.schemas(child.agent).some(tool => tool.name === 'cua')).toBe(true) + await child.dispose() + expect(scaffold.ctx.tools.schemas(child.agent).some(tool => tool.name === 'cua')).toBe(false) + expect(scaffold.ctx.agentPresets.defaultId).toBe(initialDefault) expect(runtimeFiber() === originalRuntimeFiber).toBe(true) - expect(scaffold.ctx.ptcRuntime.programFormat).toBe('function-body') - expect(await readFile(settingsPath, 'utf8')).toBe(before) + expect(scaffold.ctx.ptcRuntime.programFormat).toBe(script ? 'script' : 'function-body') + await setup.waitFor() + expect(await setup.getByText('Computer Use 插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) + await setup.getByRole('button', { name: '稍后', exact: true }).click() + await setup.waitFor({ state: 'hidden' }) + let saved = await readFile(settingsPath, 'utf8') + expect(saved).toBe(beforeEnable) + expect(scaffold.ctx.settings.describe().find(row => row.ns === 'ui-settings')?.value).toMatchObject({ enabled: codingTools }) + expect(saved).not.toContain('executionMode:') + if (selectedDefault === undefined) { + expect(load(saved)).not.toEqual(expect.arrayContaining([expect.objectContaining({ id: 'agent-preset-registry' })])) + } else { + expect(load(saved)).toEqual(expect.arrayContaining([ + expect.objectContaining({ id: 'agent-preset-registry', config: { default: 'standard', selectedDefault } }), + ])) + } + const freshDefault = (await scaffold.ctx.agents.create({ + sessionId: SessionId('cua-new-default'), + setup: async (ctx) => { await scaffold.ctx.agentPresets.mount(ctx) }, + })).agent + expect(scaffold.ctx.agentPresets.composedPreset(freshDefault.ctx)).toBe(initialDefault) + expect(scaffold.ctx.tools.schemas(freshDefault).some(tool => tool.name === 'cua')).toBe(false) + const fresh = (await scaffold.ctx.agents.create({ + sessionId: SessionId('cua-new-ptc'), + setup: async (ctx) => { await scaffold.ctx.agentPresets.mount(ctx, 'ptc') }, + })).agent + expect(scaffold.ctx.agentPresets.composedPreset(fresh.ctx)).toBe('ptc') + expect(scaffold.ctx.tools.schemas(fresh).some(tool => tool.name === 'cua')).toBe(true) await card.getByRole('button', { name: '查看 Computer Use', exact: true }).click() - const detailToggle = page.locator('[data-plugin-panel]').getByRole('switch', { name: '启用 Computer Use', exact: true }) - await detailToggle.click() - await detailToggle.and(page.locator('[aria-checked="true"]')).waitFor({ state: 'visible' }) - const panel = page.locator('[data-cua-settings]') - await panel.waitFor() - const defaultSetting = panel.getByRole('group', { name: '新会话默认模式', exact: true }) + toggle = page.locator('[data-plugin-panel]').getByRole('switch', { name: '启用 Computer Use', exact: true }) + const persistent = page.getByRole('group', { name: 'PTC 执行方式', exact: true }) + const beforePersistent = scaffold.ctx.ptcRuntime + await persistent.getByRole('button', { name: '设为持久化', exact: true }).click() + await persistent.getByRole('button', { name: '已设为持久化', exact: true }).waitFor() + expect(scaffold.ctx.ptcRuntime.programFormat).toBe(script ? 'script' : 'repl') + expect(scaffold.ctx.ptcRuntime.retainsState).toBe(true) + expect(scaffold.ctx.ptcRuntime === beforePersistent).toBe(false) + saved = await readFile(settingsPath, 'utf8') + expect(saved).toContain(`executionMode: ${script ? 'vm-script' : 'persistent-in-memory'}`) + expect(saved).toContain(`scriptPersistence: ${script}`) + const runtime = scaffold.ctx.ptcRuntime + const persistentRuntimeFiber = runtimeFiber() + const owner = {} + const program = 'globalThis.counter = (globalThis.counter ?? 0) + 1' + expect((await runtime.run(runtime.resolve({ program, bindings: [], stateOwner: owner }))).value).toBe(1) + await toggle.click() + await toggle.waitFor({ state: 'hidden' }) + await card.waitFor({ state: 'hidden' }) + expect(scaffold.ctx.get('computerUse')).toBeUndefined() + expect(runtimeFiber() === persistentRuntimeFiber).toBe(true) + expect(scaffold.ctx.agentPresets.defaultId).toBe(initialDefault) + expect(scaffold.ctx.agents.get(ptcAgent.id) === ptcAgent).toBe(true) + for (const agent of [ptcAgent, fresh]) { + expect(scaffold.ctx.tools.schemas(agent).some(tool => tool.name === 'cua')).toBe(false) + expect((await scaffold.ctx.systemPrompt.assemble({ scope: agent })).tools.map(tool => tool.name)).toEqual(['run_code']) + } + expect((await runtime.run(runtime.resolve({ program, bindings: [], stateOwner: owner }))).value).toBe(2) + expect(await readFile(settingsPath, 'utf8')).toBe(saved) + await (await offerCua()).click() + await toggle.and(page.locator('[aria-checked="true"]')).waitFor({ state: 'visible' }) + await setup.waitFor() + expect(await setup.getByText('Computer Use 插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) + expect(scaffold.ctx.agentPresets.defaultId).toBe(initialDefault) + await setup.getByRole('button', { name: '前往设置', exact: true }).click() + await setup.waitFor({ state: 'hidden' }) + await page.getByRole('region', { name: '给 Computer Use 授权', exact: true }).getByRole('alert').waitFor() + if (!codingTools) { + expect(await readFile(settingsPath, 'utf8')).toBe(saved) + expect(scaffold.ctx.settings.describe().find(row => row.ns === 'ui-settings')?.value).toMatchObject({ enabled: false }) + expect(scaffold.ctx.agentPresets.defaultId).toBe(initialDefault) + expect((await runtime.run(runtime.resolve({ program, bindings: [], stateOwner: owner }))).value).toBe(3) + await runtime.release(owner) + return + } + const defaultSetting = page.getByRole('group', { name: '新会话默认模式', exact: true }) await expect.poll(() => defaultSetting.getByRole('button', { name: '设为 PTC', exact: true }).isEnabled()).toBe(true) + await compareOrRefreshGolden(fileURLToPath(new URL('./expected/cua-permissions/default-mode.expected.md', import.meta.url)), + await captureStableAria(page, '[role="group"][aria-label="新会话默认模式"]', scaffold.workspaceCwd), webSnapshotMode()) await defaultSetting.getByRole('button', { name: '设为 PTC', exact: true }).click() await expect.poll(() => scaffold.ctx.agentPresets.defaultId).toBe('ptc') expect(scaffold.ctx.agentPresets.composedPreset(originalAgent.ctx)).toBe(initialDefault) - expect(runtimeFiber() === originalRuntimeFiber).toBe(true) - expect(scaffold.ctx.ptcRuntime.programFormat).toBe('function-body') - const confirmed = await scaffold.ctx.agents.create({ sessionId: SessionId('cua-confirmed-default'), + expect(scaffold.ctx.agentPresets.composedPreset(freshDefault.ctx)).toBe(initialDefault) + const confirmed = (await scaffold.ctx.agents.create({ + sessionId: SessionId('cua-confirmed-default'), setup: async (ctx) => { await scaffold.ctx.agentPresets.mount(ctx) }, - }) - expect(scaffold.ctx.tools.schemas(confirmed.agent).some(tool => tool.name === 'cua')).toBe(true) - const saved = await readFile(settingsPath, 'utf8') - expect(saved).toContain('selectedDefault: ptc') - expect(saved).not.toContain('executionMode:') - const persistent = panel.getByRole('group', { name: 'PTC 执行方式', exact: true }) - await persistent.getByRole('button', { name: '设为持久化', exact: true }).click() - await persistent.getByRole('button', { name: '已设为持久化', exact: true }).waitFor() - expect(scaffold.ctx.ptcRuntime.programFormat).toBe('repl') - expect(scaffold.ctx.ptcRuntime === originalRuntime).toBe(false) - const persistentRuntimeFiber = runtimeFiber() - const runtime = scaffold.ctx.ptcRuntime, owner = {} - const program = 'globalThis.counter = (globalThis.counter ?? 0) + 1' - expect((await runtime.run(runtime.resolve({ program, bindings: [], stateOwner: owner }))).value).toBe(1) - const configured = await readFile(settingsPath, 'utf8') - expect(configured).toContain('executionMode: persistent-in-memory') - expect(scaffold.ctx.agentPresets.defaultId).toBe('ptc') - expect(scaffold.ctx.agentPresets.composedPreset(originalAgent.ctx)).toBe(initialDefault) - await detailToggle.click() - await detailToggle.and(page.locator('[aria-checked="false"]')).waitFor({ state: 'visible' }) - expect(await readFile(settingsPath, 'utf8')).toBe(configured) - expect(runtimeFiber() === persistentRuntimeFiber).toBe(true) - expect((await runtime.run(runtime.resolve({ program, bindings: [], stateOwner: owner }))).value).toBe(2) - await detailToggle.click() - await detailToggle.and(page.locator('[aria-checked="true"]')).waitFor({ state: 'visible' }) - expect(await readFile(settingsPath, 'utf8')).toBe(configured) + })).agent + expect(scaffold.ctx.agentPresets.composedPreset(confirmed.ctx)).toBe('ptc') + expect(scaffold.ctx.tools.schemas(confirmed).some(tool => tool.name === 'cua')).toBe(true) expect(runtimeFiber() === persistentRuntimeFiber).toBe(true) + expect(scaffold.ctx.tools.schemas(ptcAgent).some(tool => tool.name === 'cua')).toBe(true) expect((await runtime.run(runtime.resolve({ program, bindings: [], stateOwner: owner }))).value).toBe(3) + const confirmedSettings = await readFile(settingsPath, 'utf8') + expect(load(confirmedSettings)).toEqual(expect.arrayContaining([ + expect.objectContaining({ id: 'agent-preset-registry', config: { default: 'standard', selectedDefault: 'ptc' } }), + ])) + await toggle.click() + await toggle.waitFor({ state: 'hidden' }) + await card.waitFor({ state: 'hidden' }) + await (await offerCua()).click() + await toggle.and(page.locator('[aria-checked="true"]')).waitFor({ state: 'visible' }) + await setup.waitFor() + expect(await setup.getByText('Computer Use 插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) + expect(await setup.getByRole('button', { name: '设为 PTC', exact: true }).count()).toBe(0) + expect(await readFile(settingsPath, 'utf8')).toBe(confirmedSettings) + expect(scaffold.ctx.settings.describe().find(row => row.ns === 'ui-settings')?.value).toMatchObject({ enabled: codingTools }) await runtime.release(owner) } finally { try { await browser?.close() } finally { diff --git a/apps/web/tests/cua-permissions.e2e.ts b/apps/web/tests/cua-permissions.e2e.ts index fa8f95a4f8..4835557ce8 100644 --- a/apps/web/tests/cua-permissions.e2e.ts +++ b/apps/web/tests/cua-permissions.e2e.ts @@ -1,5 +1,5 @@ /** Built permission UI talks to the real provider; the isolated helper substitutes only macOS privilege observations. */ -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' @@ -33,17 +33,16 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr icon: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAADElEQVQImWNgZGIGAAAOAAeCcsnOAAAAAElFTkSuQmCC' } await writeFile(state, JSON.stringify({ accessibility: false, screenRecording: false, launchApplication })) await writeFile(join(root, 'observe-helper'), '') - const fixtureBundle = join(root, 'fixture-bundle') - await mkdir(fixtureBundle) - await writeFile(join(fixtureBundle, 'package.json'), JSON.stringify({ name: 'cua-permission-fixture', version: '1.0.0', - dsh: { bundle: { patch: 'cordis.patch.yml' } } })) - await writeFile(join(fixtureBundle, 'cordis.patch.yml'), `- id: cua\n config: ${JSON.stringify({ helperPath: helper })}\n`) + const fixturePatch = join(root, 'native-fixture.yml') + // Keep the external helper override above bundle order changes when CUA is re-enabled. + await writeFile(fixturePatch, JSON.stringify([{ id: 'cua', config: { helperPath: helper } }])) const scaffold = await launchWebScaffold({ - profile: { packages: [{ dir: bundle, enabled: true }, { dir: fixtureBundle, enabled: true }] }, + profile: { packages: [{ dir: bundle, enabled: true }] }, + extraOverlayPath: fixturePatch, }) resources.scaffold = scaffold - await scaffold.ctx.settings.mutate('cua', [{ op: 'set', path: ['allowedApps'], - value: [{ id: 'a'.repeat(64), name: 'Fixture', executablePath: '/Applications/Fixture.app' }] }]) + expect((await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === '@deepseek-ai/dsh-cua-bundle')) + .toMatchObject({ listedByDefault: false, enabled: true, installed: true }) const browser = await chromium.launch() resources.browser = browser const page = await newEnglishPage(browser), tripwire = watchConsole(page) @@ -53,7 +52,6 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr const agent = scaffold.ctx.agents.list()[0]! await scaffold.ctx.agentPresets.select(agent, 'ptc') scaffold.ctx.approval.setPolicy(agent, 'never') - await scaffold.ctx.settings.mutate('cua', [{ op: 'set', path: ['allowedApps'], value: [] }]) // Application consent remains independent of the session's tool-approval policy. const grant = scaffold.ctx.tools.execute({ agent, signal: new AbortController().signal, calls: [{ type: 'tool-call', id: ToolCallId('cua-app-approval'), name: 'run_code', @@ -82,7 +80,7 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr const plugins = page.locator('[data-plugin-panel]') const openDetails = page.getByRole('button', { name: 'View Computer use', exact: true }) await openDetails.scrollIntoViewIfNeeded() - expect(await plugins.evaluate(element => element.scrollTop)).toBeGreaterThan(0) + expect(await plugins.locator('[data-plugin-body]').evaluate(element => element.scrollTop)).toBeGreaterThan(0) await openDetails.click() const panel = page.locator('[data-cua-settings]') const accessibility = panel.getByRole('group', { name: 'Accessibility', exact: true }) @@ -145,7 +143,10 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr await panel.getByRole('button', { name: 'Allow asking again', exact: true }).click() await panel.getByText('Fixture', { exact: true }).waitFor({ state: 'hidden' }) const saved = await readFile(join(scaffold.harnessHome, 'profiles/scaffold/cordis.patch.yml'), 'utf8') - expect(saved).toContain('allowedApps: []') + expect(saved).not.toContain('allowedApps:') + const files = await readdir(join(scaffold.workspaceCwd, '.dsh-storages')) + expect(files.some(file => file.startsWith('cua_permissions_') && file.endsWith('.json'))).toBe(true) + expect((await scaffold.ctx.cuaAccess.applications()).allowedApps).toEqual([]) const events = (await readFile(audit, 'utf8')).trim().split('\n').map(line => JSON.parse(line) as { event: string; method: string; params: object }) .filter(record => record.event === 'call').map(({ method, params }) => ({ method, params })) expect(events).toContainEqual({ method: 'requestPermission', params: { permission: 'accessibility' } }) @@ -194,10 +195,15 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr await trace.evaluate((value) => { value.layouts.length = 0; value.documents.length = 0 }) for (let cycle = 0; cycle < 3; cycle++) { await toggle.click() + await expect.poll(async () => (await scaffold.ctx.pluginManager.listBundles()) + .find(bundle => bundle.name === '@deepseek-ai/dsh-cua-bundle')) + .toMatchObject({ enabled: false, installed: true }) await expect.poll(() => toggle.getAttribute('aria-checked'), { timeout: PLUGIN_TOGGLE_SETTLE_MS }).toBe('false') await expect.poll(() => toggle.isEnabled(), { timeout: PLUGIN_TOGGLE_SETTLE_MS }).toBe(true) await toggle.click() await expect.poll(() => toggle.getAttribute('aria-checked'), { timeout: PLUGIN_TOGGLE_SETTLE_MS }).toBe('true') + const setup = page.getByRole('dialog', { name: 'Set up computer use before use', exact: true }) + await setup.getByRole('button', { name: 'Later', exact: true }).click() await expect.poll(() => panel.getAttribute('aria-busy'), { timeout: PLUGIN_TOGGLE_SETTLE_MS }).toBe('false') expect(await trace.evaluate(value => value.errors)).toEqual([]) } @@ -219,7 +225,7 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr await diagnostic.waitFor() const diagnosticText = await diagnostic.innerText() const height = await panel.evaluate(element => element.getBoundingClientRect().height) - const rowToggle = plugins.getByRole('switch', { name: 'Enable component @deepseek-ai/dsh-experimental-cua-macos', exact: true }) + const rowToggle = plugins.getByRole('switch', { name: 'Enable component macOS Computer Use provider', exact: true }) const release = Promise.withResolvers() const changeRow = scaffold.ctx.pluginManager.setPluginEnabled.bind(scaffold.ctx.pluginManager) let changing: ReturnType | undefined diff --git a/apps/web/tests/desktop-locale.e2e.ts b/apps/web/tests/desktop-locale.e2e.ts index cc43d697f1..4ede5dee36 100644 --- a/apps/web/tests/desktop-locale.e2e.ts +++ b/apps/web/tests/desktop-locale.e2e.ts @@ -21,7 +21,7 @@ describe.skipIf(MODE === 'record')('web e2e: native and Client locale preference let page: Page let tripwire: ReturnType const reported: string[] = [] - let languages = ['fr-FR', 'zh-CN', 'en-US'] + let languages = ['it-IT', 'zh-CN', 'en-US'] beforeAll(async () => { scaffold = await launchWebScaffold() diff --git a/apps/web/tests/entry-customization.e2e.ts b/apps/web/tests/entry-customization.e2e.ts index 4ea12f0238..8161012d28 100644 --- a/apps/web/tests/entry-customization.e2e.ts +++ b/apps/web/tests/entry-customization.e2e.ts @@ -25,37 +25,33 @@ describe('default navigation entry customization', () => { try { await browser?.close() } finally { await scaffold?.close() } }) - it('unpins a sidebar panel across reloads while its panel stays reachable from More', async () => { + it('keeps navigation outside More and offers only browsing and creation after reload', async () => { onTestFailed(() => saveFailureShot(page, 'entry-customization')) const nav = page.getByRole('navigation', { name: 'Global panels' }) - const plugins = nav.getByRole('button', { name: 'Plugins', exact: true }) const tasks = nav.getByRole('button', { name: 'Automation tasks', exact: true }) const more = nav.getByRole('button', { name: 'More', exact: true }) - await plugins.waitFor() await tasks.waitFor() - await more.waitFor() - const menu = page.getByRole('menu') - - await more.click() - expect(await menu.getByRole('menuitem', { name: 'Plugins', exact: true }).count()).toBe(0) - await menu.getByRole('menuitem', { name: 'Unpin from left sidebar: Automation tasks', exact: true }).click() - await tasks.waitFor({ state: 'detached' }) - await menu.getByRole('menuitem', { name: 'Automation tasks', exact: true }).click() + await tasks.click() await page.getByRole('heading', { name: 'Automation tasks', exact: true }).waitFor() - // The selected panel keeps its row until another panel is selected. - await tasks.waitFor() - expect(await tasks.getAttribute('aria-current')).toBe('page') - await plugins.click() - await tasks.waitFor({ state: 'detached' }) - expect(await plugins.getAttribute('aria-current')).toBe('page') - - await page.reload({ waitUntil: 'load' }) - await plugins.waitFor() - await more.waitFor() - expect(await tasks.count()).toBe(0) - await more.click() - await menu.getByRole('menuitem', { name: 'Pin to left sidebar: Automation tasks', exact: true }).click() - await tasks.waitFor() + for (const reload of [false, true]) { + if (reload) { + await page.reload({ waitUntil: 'load' }) + await tasks.click() + await page.getByRole('heading', { name: 'Automation tasks', exact: true }).waitFor() + } + await tasks.waitFor() + await more.click() + const menu = page.getByRole('menu') + await menu.getByRole('menuitem', { name: 'Browse other plugins', exact: true }).waitFor() + expect(await menu.getByRole('menuitem').allTextContents()).toEqual(['Browse other plugins', 'Create your plugin']) + expect(await menu.getByRole('separator').count()).toBe(0) + expect(await tasks.getAttribute('aria-current')).toBe('page') + await menu.getByRole('menuitem', { name: 'Browse other plugins', exact: true }).click() + await menu.waitFor({ state: 'detached' }) + expect(await nav.getByRole('button', { name: 'Plugins', exact: true }).getAttribute('aria-current')).toBe('page') + await tasks.click() + await page.getByRole('heading', { name: 'Automation tasks', exact: true }).waitFor() + } expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) }) diff --git a/apps/web/tests/expected/additional-locales/de.expected.md b/apps/web/tests/expected/additional-locales/de.expected.md new file mode 100644 index 0000000000..1f6b2b5a77 --- /dev/null +++ b/apps/web/tests/expected/additional-locales/de.expected.md @@ -0,0 +1,5 @@ +- listitem: + - button "Siehe Automatische Autorisierungsüberprüfung": Automatische Autorisierungsüberprüfung + - text: "Experimentell Fügt den Zugriffsmodus „Auto review“ hinzu: Vor jedem Tool-Aufruf prüft ein Modell den Aufruf anhand Ihrer Anforderung; zugelassene Aufrufe laufen sofort, abgelehnte Aufrufe warten auf Ihre Genehmigung." + - status + - switch "Aktivieren Sie Automatische Autorisierungsüberprüfung" diff --git a/apps/web/tests/expected/additional-locales/es.expected.md b/apps/web/tests/expected/additional-locales/es.expected.md new file mode 100644 index 0000000000..a2a434ac84 --- /dev/null +++ b/apps/web/tests/expected/additional-locales/es.expected.md @@ -0,0 +1,5 @@ +- listitem: + - button "Ver Revisión de autorización automática": Revisión de autorización automática + - text: "Experimental Añade el modo de acceso “Auto review”: antes de cada llamada a una herramienta, un modelo comprueba la llamada frente a lo que usted pidió; las llamadas permitidas se ejecutan de inmediato y las denegadas esperan su aprobación." + - status + - switch "Habilitar Revisión de autorización automática" diff --git a/apps/web/tests/expected/additional-locales/fr.expected.md b/apps/web/tests/expected/additional-locales/fr.expected.md new file mode 100644 index 0000000000..c589a1ec21 --- /dev/null +++ b/apps/web/tests/expected/additional-locales/fr.expected.md @@ -0,0 +1,5 @@ +- listitem: + - button "Voir Examen des autorisations automatiques": Examen des autorisations automatiques + - text: "Expérimental Ajoute le mode d'accès « Auto review » : avant chaque appel d'outil, un modèle vérifie l'appel par rapport à ce que vous avez demandé ; les appels autorisés s'exécutent immédiatement et les appels refusés attendent votre approbation." + - status + - switch "Activer Examen des autorisations automatiques" diff --git a/apps/web/tests/expected/additional-locales/pt.expected.md b/apps/web/tests/expected/additional-locales/pt.expected.md new file mode 100644 index 0000000000..a9393bf830 --- /dev/null +++ b/apps/web/tests/expected/additional-locales/pt.expected.md @@ -0,0 +1,5 @@ +- listitem: + - button "Ver Revisão de autorização automática": Revisão de autorização automática + - text: "Experimental Adiciona o modo de acesso “Auto review”: antes de cada chamada de ferramenta, um modelo verifica a chamada em relação ao que você pediu; as chamadas permitidas são executadas imediatamente e as negadas aguardam sua aprovação." + - status + - switch "Ativar Revisão de autorização automática" diff --git a/apps/web/tests/expected/additional-locales/ru.expected.md b/apps/web/tests/expected/additional-locales/ru.expected.md new file mode 100644 index 0000000000..5d48baee88 --- /dev/null +++ b/apps/web/tests/expected/additional-locales/ru.expected.md @@ -0,0 +1,5 @@ +- listitem: + - button "Посмотреть Проверка автоматической авторизации": Проверка автоматической авторизации + - text: "Экспериментальный Добавляет режим доступа «Auto review»: перед каждым вызовом инструмента модель сверяет вызов с вашей просьбой; разрешённые вызовы выполняются сразу, а отклонённые ждут вашего одобрения." + - status + - switch "Включить Проверка автоматической авторизации" diff --git a/apps/web/tests/expected/bundle-platform/unsupported-platform.expected.md b/apps/web/tests/expected/bundle-platform/unsupported-platform.expected.md new file mode 100644 index 0000000000..b6aa94aa05 --- /dev/null +++ b/apps/web/tests/expected/bundle-platform/unsupported-platform.expected.md @@ -0,0 +1 @@ +- status: 此插件不支持运行 DSH 的主机操作系统 diff --git a/apps/web/tests/expected/cot-translation-paid/paid-choices.expected.md b/apps/web/tests/expected/cot-translation-paid/paid-choices.expected.md index a141beff7b..dedc4bb631 100644 --- a/apps/web/tests/expected/cot-translation-paid/paid-choices.expected.md +++ b/apps/web/tests/expected/cot-translation-paid/paid-choices.expected.md @@ -6,57 +6,10 @@ - text: v{{version}} 实验性 - paragraph: - code: "@deepseek-ai/dsh-experimental-cot-translation-bundle" -- paragraph: 机器翻译展开的思考内容;原文会发送给所选服务 +- paragraph: 智能体输出时,把展开的“思考”行翻译成你选择的语言,点击“查看原文”可切换回原文。 - region "详细介绍": - paragraph: - img "展开的思考行从英文翻译成中文,并显示“查看原文”按钮" - - paragraph: - - text: 展开 - - strong: 思考 - - text: 行,即可用界面语言阅读其中的思考内容。智能体输出时会逐段翻译;最新的内容在能够翻译之前保持原文。 - - heading "使用方法" [level=2] - - list: - - listitem: - - text: 展开 - - strong: 思考 - - text: 行。点击 - - strong: 查看原文 - - text: 显示原文,点击 - - strong: 查看译文 - - text: 切换回译文。 - - listitem: - - text: 在此插件的页面中选择 - - strong: 翻译服务 - - text: 和 - - strong: 目标语言 - - text: ,然后点击 - - strong: 保存 - - text: 。 - - code: auto - - text: 表示跟随界面语言;也可以填写 - - code: zh - - text: 、 - - code: en - - text: 、 - - code: ja - - text: 等语言代码。 - - listitem: - - text: 翻译失败时,原文保持显示,并提供 - - strong: 重试 - - text: 。 - - heading "注意事项" [level=2] - - list: - - listitem: 你展开的思考内容可能包含你的代码和对话细节。 - - listitem: 默认使用 Bing,也可以选择 Google。两者都无需账号或 API key,但都不保证可用,也不保证免费额度。 - - listitem: - - text: 如果已配置 DeepSeek 账号或官方 API,还会出现 - - strong: DeepSeek Flash · 账号(付费) - - text: 和 - - strong: DeepSeek Flash · 官方 API(付费) - - text: 。此时每段没有已保存译文的内容都是一次付费请求。 - - listitem: 译文保存在会话中,重新打开时直接复用。原始思考内容和模型的输入都不会改变。 - - listitem: 折叠时显示的摘要保持原文。翻译可能改变 Markdown 格式或代码。 - - listitem: 关闭此插件会移除它的按钮并取消未完成的翻译;已保存的译文仍保留在会话中。 - paragraph: 展开的思考内容会发送给所选翻译服务,可能包含私有代码或对话细节。 - paragraph: 每个未缓存片段都会通过所选账号或官方 API 凭据单独发送一次付费的 DeepSeek Flash 请求;重新展开会复用已保存的译文,更改服务、语言、原文或请求设置可能发送新的付费请求 - text: 翻译服务 已覆盖 diff --git a/apps/web/tests/expected/cot-translation/preferences.expected.md b/apps/web/tests/expected/cot-translation/preferences.expected.md index 6404a2d8bc..c3da36d678 100644 --- a/apps/web/tests/expected/cot-translation/preferences.expected.md +++ b/apps/web/tests/expected/cot-translation/preferences.expected.md @@ -6,57 +6,10 @@ - text: v{{version}} 实验性 - paragraph: - code: "@deepseek-ai/dsh-experimental-cot-translation-bundle" -- paragraph: 机器翻译展开的思考内容;原文会发送给所选服务 +- paragraph: 智能体输出时,把展开的“思考”行翻译成你选择的语言,点击“查看原文”可切换回原文。 - region "详细介绍": - paragraph: - img "展开的思考行从英文翻译成中文,并显示“查看原文”按钮" - - paragraph: - - text: 展开 - - strong: 思考 - - text: 行,即可用界面语言阅读其中的思考内容。智能体输出时会逐段翻译;最新的内容在能够翻译之前保持原文。 - - heading "使用方法" [level=2] - - list: - - listitem: - - text: 展开 - - strong: 思考 - - text: 行。点击 - - strong: 查看原文 - - text: 显示原文,点击 - - strong: 查看译文 - - text: 切换回译文。 - - listitem: - - text: 在此插件的页面中选择 - - strong: 翻译服务 - - text: 和 - - strong: 目标语言 - - text: ,然后点击 - - strong: 保存 - - text: 。 - - code: auto - - text: 表示跟随界面语言;也可以填写 - - code: zh - - text: 、 - - code: en - - text: 、 - - code: ja - - text: 等语言代码。 - - listitem: - - text: 翻译失败时,原文保持显示,并提供 - - strong: 重试 - - text: 。 - - heading "注意事项" [level=2] - - list: - - listitem: 你展开的思考内容可能包含你的代码和对话细节。 - - listitem: 默认使用 Bing,也可以选择 Google。两者都无需账号或 API key,但都不保证可用,也不保证免费额度。 - - listitem: - - text: 如果已配置 DeepSeek 账号或官方 API,还会出现 - - strong: DeepSeek Flash · 账号(付费) - - text: 和 - - strong: DeepSeek Flash · 官方 API(付费) - - text: 。此时每段没有已保存译文的内容都是一次付费请求。 - - listitem: 译文保存在会话中,重新打开时直接复用。原始思考内容和模型的输入都不会改变。 - - listitem: 折叠时显示的摘要保持原文。翻译可能改变 Markdown 格式或代码。 - - listitem: 关闭此插件会移除它的按钮并取消未完成的翻译;已保存的译文仍保留在会话中。 - paragraph: 展开的思考内容会发送给所选翻译服务,可能包含私有代码或对话细节。 - paragraph: Bing 和 Google 翻译无需额外登录或 API key,但匿名接口可能拒绝或限制请求 - text: 翻译服务 diff --git a/apps/web/tests/expected/cua-permissions/application-approval.expected.md b/apps/web/tests/expected/cua-permissions/application-approval.expected.md index fc9007a938..74989b3ae3 100644 --- a/apps/web/tests/expected/cua-permissions/application-approval.expected.md +++ b/apps/web/tests/expected/cua-permissions/application-approval.expected.md @@ -2,7 +2,7 @@ - group "Approval details": - strong: Fixture - text: Allow computer use to launch, read, capture and control this application? - - paragraph: Session access lasts until DSH restarts or computer use is disabled. + - paragraph: Allowing or denying applies to every version and copy sharing the same application identity. Session access and denial apply only to this conversation. - button "Reject" - button "Allow for this session" - button "Always allow" diff --git a/apps/web/tests/expected/cua-permissions/default-mode.expected.md b/apps/web/tests/expected/cua-permissions/default-mode.expected.md new file mode 100644 index 0000000000..36996c4d69 --- /dev/null +++ b/apps/web/tests/expected/cua-permissions/default-mode.expected.md @@ -0,0 +1,4 @@ +- group "新会话默认模式": + - strong: 新会话默认模式 + - paragraph: Computer Use 仅在 PTC 模式中可用。 + - button "设为 PTC" diff --git a/apps/web/tests/expected/cua-permissions/enabling.expected.md b/apps/web/tests/expected/cua-permissions/enabling.expected.md index b0e8e66529..b9d6557e3e 100644 --- a/apps/web/tests/expected/cua-permissions/enabling.expected.md +++ b/apps/web/tests/expected/cua-permissions/enabling.expected.md @@ -1,5 +1 @@ -- listitem: - - button "查看 Computer Use": Computer Use - - text: 实验性 目前仅支持 macOS,Windows 支持正在开发中。为已有及新建 PTC 会话加载 Computer Use。请切换到 PTC 模式来使用,并授予辅助功能和屏幕录制权限。 - - status: 正在应用 Computer Use 的更改 - - switch "启用 Computer Use" [disabled] +- button "立即启用" [disabled] diff --git a/apps/web/tests/expected/cua-permissions/setup.expected.md b/apps/web/tests/expected/cua-permissions/setup.expected.md new file mode 100644 index 0000000000..0ee5870bf3 --- /dev/null +++ b/apps/web/tests/expected/cua-permissions/setup.expected.md @@ -0,0 +1,6 @@ +- dialog "使用 Computer Use 前需要设置": + - heading "使用 Computer Use 前需要设置" [level=2] + - button "关闭" + - paragraph: Computer Use 插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。 + - button "稍后" + - button "前往设置" diff --git a/apps/web/tests/expected/goal-bar/blocked.expected.md b/apps/web/tests/expected/goal-bar/blocked.expected.md new file mode 100644 index 0000000000..dbfcf5563b --- /dev/null +++ b/apps/web/tests/expected/goal-bar/blocked.expected.md @@ -0,0 +1,4 @@ +- text: Blocked Goal retry with the edited plan +- button "Resume goal" +- button "Edit goal" +- button "Clear goal" diff --git a/apps/web/tests/expected/japanese-plugin-metadata/card.expected.md b/apps/web/tests/expected/japanese-plugin-metadata/card.expected.md index 0fa58e0c23..df7ab7b97b 100644 --- a/apps/web/tests/expected/japanese-plugin-metadata/card.expected.md +++ b/apps/web/tests/expected/japanese-plugin-metadata/card.expected.md @@ -1,5 +1,5 @@ - listitem: - button "自動認可レビューを表示": 自動認可レビュー - - text: 実験的 各ツール呼び出しの前にモデルが認可を判断する、自動認可レビュー権限モードを提供します。 + - text: 実験的 「自動認可レビュー」アクセスモードを追加します。各ツール呼び出しの前に、モデルがその呼び出しをあなたの依頼内容と照らし合わせて確認し、許可された呼び出しは即座に実行され、拒否された呼び出しはあなたの承認を待ちます。 - status - switch "自動認可レビューを有効化" diff --git a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md index 6ea83d310a..bde82cec8f 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md @@ -37,7 +37,7 @@ - text: 上下文窗口 - textbox "上下文窗口 1": - /placeholder: 1M - - text: 1M + - text: "1048576" - text: 最大输出 token 数 - textbox "最大输出 token 数 1": - /placeholder: 256K diff --git a/apps/web/tests/expected/plugin-config/official.expected.md b/apps/web/tests/expected/plugin-config/official.expected.md index c3f1cafc28..0140faf9af 100644 --- a/apps/web/tests/expected/plugin-config/official.expected.md +++ b/apps/web/tests/expected/plugin-config/official.expected.md @@ -24,7 +24,7 @@ - list: - listitem: - button "查看 智能体团队": 智能体团队 - - text: 实验性 启用团队协作、团队工具、成员列表和共享任务看板。 + - text: 实验性 让与你对话的智能体把工作分给有名字的队友,在共享任务看板上跟踪进度,并汇总队友的结果向你汇报。 - status - switch "启用 智能体团队" - listitem: @@ -33,13 +33,13 @@ - status - switch "启用 语音输入" - listitem: - - button "查看 自定义插件市场": 自定义插件市场 - - text: 实验性 在插件页添加「发现」标签页,从你添加的插件市场索引浏览和安装插件。 + - button "查看 自定义插件索引": 自定义插件索引 + - text: 实验性 在插件页添加“发现”标签页,从你添加的插件索引中浏览和安装插件。 - status - - switch "启用 自定义插件市场" + - switch "启用 自定义插件索引" - listitem: - button "查看 自动授权审查": 自动授权审查 - - text: 实验性 提供自动审查权限模式,由模型在每次工具调用前判断是否授权。 + - text: 实验性 提供“自动审查”访问模式:每次工具调用前,由模型对照你的要求检查,获准的调用立即运行,被拒绝的调用等你审批。 - status - switch "启用 自动授权审查" - heading "已安装插件" [level=3] diff --git a/apps/web/tests/expected/plugin-manager/live-enabled.expected.md b/apps/web/tests/expected/plugin-manager/live-enabled.expected.md index fd91449871..d5cb4aac9a 100644 --- a/apps/web/tests/expected/plugin-manager/live-enabled.expected.md +++ b/apps/web/tests/expected/plugin-manager/live-enabled.expected.md @@ -24,7 +24,7 @@ - list: - listitem: - button "查看 智能体团队": 智能体团队 - - text: 实验性 启用团队协作、团队工具、成员列表和共享任务看板。 + - text: 实验性 让与你对话的智能体把工作分给有名字的队友,在共享任务看板上跟踪进度,并汇总队友的结果向你汇报。 - status - switch "启用 智能体团队" - listitem: @@ -33,13 +33,13 @@ - status - switch "启用 语音输入" - listitem: - - button "查看 自定义插件市场": 自定义插件市场 - - text: 实验性 在插件页添加「发现」标签页,从你添加的插件市场索引浏览和安装插件。 + - button "查看 自定义插件索引": 自定义插件索引 + - text: 实验性 在插件页添加“发现”标签页,从你添加的插件索引中浏览和安装插件。 - status - - switch "启用 自定义插件市场" + - switch "启用 自定义插件索引" - listitem: - button "查看 自动授权审查": 自动授权审查 - - text: 实验性 提供自动审查权限模式,由模型在每次工具调用前判断是否授权。 + - text: 实验性 提供“自动审查”访问模式:每次工具调用前,由模型对照你的要求检查,获准的调用立即运行,被拒绝的调用等你审批。 - status - switch "启用 自动授权审查" - heading "已安装插件" [level=3] diff --git a/apps/web/tests/expected/plugin-manager/manager.expected.md b/apps/web/tests/expected/plugin-manager/manager.expected.md index 730b82532f..3d0660724f 100644 --- a/apps/web/tests/expected/plugin-manager/manager.expected.md +++ b/apps/web/tests/expected/plugin-manager/manager.expected.md @@ -24,7 +24,7 @@ - list: - listitem: - button "查看 智能体团队": 智能体团队 - - text: 实验性 启用团队协作、团队工具、成员列表和共享任务看板。 + - text: 实验性 让与你对话的智能体把工作分给有名字的队友,在共享任务看板上跟踪进度,并汇总队友的结果向你汇报。 - status - switch "启用 智能体团队" - listitem: @@ -33,13 +33,13 @@ - status - switch "启用 语音输入" - listitem: - - button "查看 自定义插件市场": 自定义插件市场 - - text: 实验性 在插件页添加「发现」标签页,从你添加的插件市场索引浏览和安装插件。 + - button "查看 自定义插件索引": 自定义插件索引 + - text: 实验性 在插件页添加“发现”标签页,从你添加的插件索引中浏览和安装插件。 - status - - switch "启用 自定义插件市场" + - switch "启用 自定义插件索引" - listitem: - button "查看 自动授权审查": 自动授权审查 - - text: 实验性 提供自动审查权限模式,由模型在每次工具调用前判断是否授权。 + - text: 实验性 提供“自动审查”访问模式:每次工具调用前,由模型对照你的要求检查,获准的调用立即运行,被拒绝的调用等你审批。 - status - switch "启用 自动授权审查" - heading "已安装插件" [level=3] diff --git a/apps/web/tests/expected/shared-inspector/metadata-en.expected.md b/apps/web/tests/expected/shared-inspector/metadata-en.expected.md index 8a700d7178..e030d3d965 100644 --- a/apps/web/tests/expected/shared-inspector/metadata-en.expected.md +++ b/apps/web/tests/expected/shared-inspector/metadata-en.expected.md @@ -1,5 +1,5 @@ - bundle: Developer tools - description: Inspect and debug raw session data, grouped chat messages, and the NodeJS backend. + description: For troubleshooting: view what DSH recorded for a session in Session log, inspect per-turn and per-step statistics in the Statistics tab, and debug the DSH backend in Chrome DevTools. - component: NodeJS inspector description: Press Ctrl/Cmd+Shift+. to open Chrome DevTools in the bottom panel for development and debugging. - component: Session log diff --git a/apps/web/tests/expected/shared-inspector/metadata-zh.expected.md b/apps/web/tests/expected/shared-inspector/metadata-zh.expected.md index ac290833d9..25e2845741 100644 --- a/apps/web/tests/expected/shared-inspector/metadata-zh.expected.md +++ b/apps/web/tests/expected/shared-inspector/metadata-zh.expected.md @@ -1,5 +1,5 @@ - bundle: 开发者工具 - description: 查看调试会话原始数据、聊天消息分组数据,以及调试 NodeJS 后端 + description: 用于排查问题:在「会话数据诊断」中查看 DSH 为会话记录的内容,在「统计」页签查看每轮/每步的上下文、耗时、缓存和工具成本,并在 Chrome DevTools 中调试 DSH 后端。 - component: NodeJS 诊断 description: 按 Ctrl/Cmd+Shift+. 在底部面板打开 Chrome DevTools 进行开发调试 - component: 会话数据诊断 diff --git a/apps/web/tests/file-upload-round.e2e.ts b/apps/web/tests/file-upload-round.e2e.ts index 7ff564de92..9c5b5a7b33 100644 --- a/apps/web/tests/file-upload-round.e2e.ts +++ b/apps/web/tests/file-upload-round.e2e.ts @@ -279,17 +279,16 @@ describe('web e2e: generic file upload through the real assembly', () => { await expect.poll(() => send.isEnabled(), { timeout: 15_000 }).toBe(true) const settled = scaffold.whenTurnSettled() await send.click() - const restoreDeadline = Date.now() + 10_000 - let retainedCards = 0 - while (retainedCards === 0 - && !sessionEvents.some(event => event.type === 'turn/start') - && Date.now() < restoreDeadline) { + // The draft cards stay until the Host accepts the prompt, then leave with the cleared draft. + const acceptDeadline = Date.now() + 15_000 + let retainedCards = await rail.locator(':scope > *').count() + while (retainedCards !== 0 && Date.now() < acceptDeadline) { await page.waitForTimeout(100) retainedCards = await rail.locator(':scope > *').count() } if (retainedCards !== 0) { const feedback = await page.locator('[role="alert"], [role="status"]').allTextContents() - throw new Error(`submission retained ${String(retainedCards)} draft cards; feedback=${JSON.stringify(feedback)}; events=${sessionEvents.map(event => event.type).join(',')}`) + throw new Error(`the Host did not accept the submission; ${String(retainedCards)} draft cards remain; feedback=${JSON.stringify(feedback)}; events=${sessionEvents.map(event => event.type).join(',')}`) } const sessionId = await settled if (MODE === 'record') await recordFixture(scaffold, sessionId, FIXTURE) diff --git a/apps/web/tests/fold-blank-matrix.e2e.ts b/apps/web/tests/fold-blank-matrix.e2e.ts index 25b4e2d874..c46a62c711 100644 --- a/apps/web/tests/fold-blank-matrix.e2e.ts +++ b/apps/web/tests/fold-blank-matrix.e2e.ts @@ -10,7 +10,7 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' -import type { Browser, Page, Route } from 'playwright' +import type { Browser, Page } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import type { StreamChunk } from '@deepseek-ai/dsh-llm' @@ -695,31 +695,37 @@ async function run(world: World, scenario: Case): Promise { const disposeFailure = scenario.origin === 'error' ? scaffold.ctx.on('system-prompt/assemble', async () => { throw new Error('FOLDMX_TURN_FAILED') }) : () => undefined - // A subagent child's composer sends through the subagent continuation route. - const promptRoute = scenario.surface === 'side' ? '**/api/subagents/prompt' : '**/api/session/prompt' - const promptGate = Promise.withResolvers() - const promptHeld = Promise.withResolvers() - const holdPrompt = async (route: Route): Promise => { - promptHeld.resolve(undefined) - await promptGate.promise - await route.continue() + // The accepted message waits before its model call, so the fold settles before the Turn streams. + const turnGate = Promise.withResolvers() + let held: Promise = Promise.resolve() + let disposeHold = (): void => {} + if (scenario.surface === 'side') { + // A subagent child's composer sends through the continuation route, which resumes the cold child. + disposeHold = scaffold.ctx.on('agent/pre-step', async ({ agent }, next) => { + if (agent.id === target) await turnGate.promise + return await next() + }) + } else { + const agent = scaffold.ctx.agents.get(target) + if (agent === undefined) throw new Error(`${scenario.id}: the target Agent is not live`) + // Maintenance keeps the accepted message in the inbox without starting its Turn. + held = agent.runMaintenance(() => turnGate.promise) } - await page.route(promptRoute, holdPrompt) const ended = turnEnded(scaffold, target) try { await expandSeededSteps(page, root, scenario) await placeReader(page, root, scenario.reader) await begin() await send(world, NEXT_INPUT) - await promptHeld.promise await page.locator(`${root} [data-submission-echo]`).waitFor() afterFold = await folded() - promptGate.resolve(undefined) + turnGate.resolve(undefined) + await held await ended } finally { - promptGate.resolve(undefined) + turnGate.resolve(undefined) + disposeHold() disposeFailure() - await page.unroute(promptRoute, holdPrompt) } break } diff --git a/apps/web/tests/fork-mid-turn.e2e.ts b/apps/web/tests/fork-mid-turn.e2e.ts index 2ffa330007..15c8d67512 100644 --- a/apps/web/tests/fork-mid-turn.e2e.ts +++ b/apps/web/tests/fork-mid-turn.e2e.ts @@ -114,7 +114,7 @@ describe('web e2e: exact-boundary fork seeds branch closers and continues', () = const child = scaffold.ctx.sessions.get(childId) if (child === undefined) throw new Error('fork did not publish a live child session') - expect(child.header.parentSession).toBe(SessionId(SEED_ID)) + expect(child.header.parentSession).toBeUndefined() // inheritedEventCount counts only the copied parent prefix; the closers are child work. expect(child.inheritedEventCount).toBe(forkAt + 1) expect(child.snapshotEvents()[forkAt]?.type).toBe('tool/call') diff --git a/apps/web/tests/goal-bar.e2e.ts b/apps/web/tests/goal-bar.e2e.ts index a93c9d7c13..132d44569b 100644 --- a/apps/web/tests/goal-bar.e2e.ts +++ b/apps/web/tests/goal-bar.e2e.ts @@ -2,7 +2,7 @@ // The command creates a real projected goal in a real Host session. The // goldens pin the active and disarmed strips, while the clear gesture proves // the acknowledged tombstone leaves neither stale chrome nor a -// duplicate-mutation error. +// duplicate-mutation error. A blocked goal stays resumable after an edit. import { fileURLToPath } from 'node:url' import { join } from 'node:path' import type { Browser, Page } from 'playwright' @@ -18,6 +18,7 @@ import { connectFreshWorkspace, expectTooltipOnTop, newEnglishPage, saveFailureS const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/goal-bar', import.meta.url)) const ACTIVE_EXPECTED = join(SNAPSHOT_DIR, 'active.expected.md') const INACTIVE_EXPECTED = join(SNAPSHOT_DIR, 'inactive.expected.md') +const BLOCKED_EXPECTED = join(SNAPSHOT_DIR, 'blocked.expected.md') const OVERLAY = fileURLToPath(new URL('./goal-bar.overlay.yml', import.meta.url)) const MODE = webSnapshotMode() @@ -108,7 +109,46 @@ describe('web e2e: goal bar clear convergence', () => { expect(tripwire.warnings).toEqual([]) }, 60_000) + it('resumes a blocked goal after its objective is edited', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-goal-bar-blocked-resume')) + // `/goal ` refuses to replace an unfinished goal, so start from none. + for (const existing of scaffold.ctx.agents.list()) { + const current = scaffold.ctx.goals.get(existing) + if (current !== undefined) scaffold.ctx.goals.clear(existing, current) + } + const input = page.locator('[data-composer-input]') + await input.fill('/goal retry after a blocker') + await input.press('Enter') + const bar = page.locator('[data-goal-bar]') + await bar.getByRole('button', { name: 'Pause goal' }).waitFor({ timeout: 10_000 }) + + const agents = scaffold.ctx.agents.list() + expect(agents).toHaveLength(1) + const agent = agents[0]! + const active = scaffold.ctx.goals.get(agent)! + scaffold.ctx.goals.block(agent, active, { code: 'stalled', message: 'No progress in 3 rounds' }) + await bar.getByText('Blocked Goal').waitFor({ timeout: 10_000 }) + expect(await bar.getByRole('button', { name: 'Resume goal' }).count()).toBe(1) + + await bar.getByRole('button', { name: 'Edit goal' }).click() + await bar.getByRole('textbox', { name: 'Goal objective' }).fill('retry with the edited plan') + await bar.getByRole('button', { name: 'Save goal' }).click() + await bar.getByRole('button', { name: 'Edit goal' }).waitFor({ timeout: 10_000 }) + await bar.getByText('retry with the edited plan').waitFor({ timeout: 10_000 }) + expect(scaffold.ctx.goals.get(agent)?.phase).toBe('blocked') + const blocked = await captureStableAria(page, '[data-goal-bar]', scaffold.workspaceCwd) + await compareOrRefreshGolden(BLOCKED_EXPECTED, blocked, MODE) + + await bar.getByRole('button', { name: 'Resume goal' }).click() + await bar.getByRole('button', { name: 'Pause goal' }).waitFor({ timeout: 10_000 }) + expect(scaffold.ctx.goals.get(agent)).toMatchObject({ + phase: 'active', activation: 'armed', objective: 'retry with the edited plan', + }) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }, 60_000) + it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => { - await assertFixtureInventory(SNAPSHOT_DIR, ['active.expected.md', 'inactive.expected.md']) + await assertFixtureInventory(SNAPSHOT_DIR, ['active.expected.md', 'blocked.expected.md', 'inactive.expected.md']) }) }) diff --git a/apps/web/tests/idle-submission-handoff.e2e.ts b/apps/web/tests/idle-submission-handoff.e2e.ts index 25fcebadb6..958c1f5e30 100644 --- a/apps/web/tests/idle-submission-handoff.e2e.ts +++ b/apps/web/tests/idle-submission-handoff.e2e.ts @@ -1,13 +1,10 @@ /** Keep idle submissions in Chat across independently delivered Inbox and transcript frames. */ -import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { readFile } from 'node:fs/promises' import { fileURLToPath } from 'node:url' import { chromium, type Page } from 'playwright' import { expect, it, onTestFinished } from 'vitest' import type { InboxState } from '@deepseek-ai/dsh-agent/types' import type { SessionEvent } from '@deepseek-ai/dsh-session/types' -import { deriveReplayScript, parseSessionLog } from '@deepseek-ai/dsh-llm-replay' import { parseRemoteStreamClientMessage, parseRemoteStreamServerMessage, } from '@deepseek-ai/dsh-api-gateway/stream-protocol' @@ -71,7 +68,6 @@ class HistoryDeliveryGate { turnStartDelivery(): Delivery | undefined { return this.buffered.find(item => item.event?.type === 'turn/start') } - turnEndDelivery(): Delivery | undefined { return this.buffered.find(item => item.event?.type === 'turn/end') } releaseThrough(target: Delivery): void { let reached = false @@ -123,8 +119,6 @@ it.skipIf(webSnapshotMode() === 'record').each(['inbox-first', 'transcript-first 'keeps an idle submission in Chat under CPU throttling (%s)', async (order) => { const scaffold = await launchWebScaffold({ replayFixture: FIXTURE, compareReplaySession: false }) onTestFinished(() => scaffold.close()) - const releasePrompt = Promise.withResolvers() - const promptBlocked = Promise.withResolvers() const gate = new HistoryDeliveryGate() try { await seedSession(scaffold, await readFile(FIXTURE, 'utf8'), SESSION_ID) @@ -140,21 +134,15 @@ it.skipIf(webSnapshotMode() === 'record').each(['inbox-first', 'transcript-first await page.getByRole('button', { name: 'Send message', exact: true }).waitFor() const cdp = await page.context().newCDPSession(page) await cdp.send('Emulation.setCPUThrottlingRate', { rate: 6 }) - await page.route('**/api/session/prompt', async (route) => { - promptBlocked.resolve(undefined) - await releasePrompt.promise - await route.continue() - }, { times: 1 }) const trace: Array<{ phase: string } & Awaited>> = [] gate.holding = true + const settled = whenTurnSettled(scaffold) const input = page.locator('[data-composer-input]').first() await input.fill(TEXT) await input.press('Enter') - await promptBlocked.promise + // The prompt receipt is not a stream frame: the accepted echo shows while the gate holds every Host frame. await poll(() => placement(page)).toMatchObject({ echo: 1, dock: 0, durable: 0 }) - trace.push({ phase: 'optimistic', ...await placement(page) }) - const settled = whenTurnSettled(scaffold) - releasePrompt.resolve(undefined) + trace.push({ phase: 'accepted', ...await placement(page) }) if (order === 'transcript-first') { await poll(() => gate.turnStartDelivery()).toBeDefined() @@ -198,88 +186,6 @@ it.skipIf(webSnapshotMode() === 'record').each(['inbox-first', 'transcript-first await cdp.detach() expect(tripwire.pageErrors).toEqual([]) } finally { - releasePrompt.resolve(undefined) - gate.releaseAll() - } - }, -) - -it.skipIf(webSnapshotMode() === 'record').each(['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA'])( - 'hands off three rapid submissions through all Turns in Host order %s', async (hostOrder) => { - const root = await mkdtemp(join(tmpdir(), 'dsh-input-handoff-')) - onTestFinished(() => rm(root, { recursive: true, force: true })) - const releases = new Map(['A', 'B', 'C'].map(id => [id, Promise.withResolvers()])) - const blocked = new Set() - const gate = new HistoryDeliveryGate() - try { - const fixture = await readFile(FIXTURE, 'utf8') - const recorded = deriveReplayScript(parseSessionLog(fixture)) - expect(recorded).toHaveLength(1) - const override = join(root, 'replay.override.json') - await writeFile(override, JSON.stringify([recorded[0], recorded[0], recorded[0]])) - const scaffold = await launchWebScaffold({ replayFixture: FIXTURE, replayOverride: override, compareReplaySession: false }) - onTestFinished(() => scaffold.close()) - await seedSession(scaffold, fixture, SESSION_ID) - const browser = await chromium.launch() - onTestFinished(() => browser.close()) - const page = await newEnglishPage(browser) - const tripwire = watchConsole(page) - await gate.install(page) - await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) - await page.locator('[role="treeitem"]').first().click() - await page.locator('[role="treeitem"]').nth(1).click() - await page.locator('[data-chat-flow-kind="user"]').first().waitFor() - await page.getByRole('button', { name: 'Send message', exact: true }).waitFor() - const text = (id: string) => `RAPID_INPUT_${id}` - await page.route('**/api/session/prompt', async (route) => { - const request = route.request().postData() ?? '' - const id = [...releases.keys()].find(id => request.includes(text(id))) - if (id === undefined) throw new Error('unexpected prompt in rapid input fixture') - blocked.add(id) - await releases.get(id)!.promise - await route.continue() - }) - gate.holding = true - const input = page.locator('[data-composer-input]').first() - for (const id of releases.keys()) { - await input.fill(text(id)) - await input.press('Enter') - await poll(() => blocked.has(id)).toBe(true) - await poll(() => placement(page, text(id))).toMatchObject({ echo: 1, dock: 0, durable: 0 }) - } - const entered: string[] = [] - for (const id of hostOrder) { - const settled = whenTurnSettled(scaffold) - releases.get(id)!.resolve(undefined) - await poll(() => gate.turnStartDelivery()).toBeDefined() - gate.releaseThrough(gate.turnStartDelivery()!) - await poll(() => gate.admissionDelivery(text(id))).toBeDefined() - gate.releaseThrough(gate.admissionDelivery(text(id))!) - entered.push(id) - for (const candidate of releases.keys()) { - const admitted = entered.includes(candidate) - await poll(() => placement(page, text(candidate))).toMatchObject({ - echo: admitted ? 0 : 1, dock: 0, durable: admitted ? 1 : 0, - }) - } - await poll(() => gate.inboxDelivery(true, text(id))).toBeDefined() - gate.releaseThrough(gate.inboxDelivery(true, text(id))!) - await poll(() => placement(page, text(id))).toMatchObject({ echo: 0, dock: 0, durable: 1 }) - await poll(() => gate.inboxDelivery(false, text(id))).toBeDefined() - gate.releaseThrough(gate.inboxDelivery(false, text(id))!) - await poll(() => gate.turnEndDelivery()).toBeDefined() - gate.releaseThrough(gate.turnEndDelivery()!) - await settled - } - gate.releaseAll() - const actual = await page.locator('[data-chat-flow-kind="user"]').allTextContents() - expect(actual.filter(value => value.includes('RAPID_INPUT_')).map(value => - [...releases.keys()].find(id => value.includes(text(id))))).toEqual(hostOrder.split('')) - expect(await page.locator('[data-submission-echo]').count()).toBe(0) - expect(await page.locator('[data-queue-dock]').count()).toBe(0) - expect(tripwire.pageErrors).toEqual([]) - } finally { - for (const release of releases.values()) release.resolve(undefined) gate.releaseAll() } }, diff --git a/apps/web/tests/japanese-plugin-metadata.e2e.ts b/apps/web/tests/japanese-plugin-metadata.e2e.ts index fb56add4f1..9d9103cff9 100644 --- a/apps/web/tests/japanese-plugin-metadata.e2e.ts +++ b/apps/web/tests/japanese-plugin-metadata.e2e.ts @@ -3,7 +3,7 @@ import { fileURLToPath } from 'node:url' import { chromium, type Browser } from 'playwright' import { expect, it, onTestFailed, onTestFinished } from 'vitest' import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold } from './scaffold.ts' -import { saveFailureShot } from './support.ts' +import { experimentalBundleDescription, saveFailureShot } from './support.ts' it('displays Japanese plugin titles and descriptions from package metadata', async () => { const resources: { scaffold?: WebScaffold; browser?: Browser } = {} @@ -23,7 +23,7 @@ it('displays Japanese plugin titles and descriptions from package metadata', asy const title = panel.getByRole('button', { name: '自動認可レビューを表示', exact: true }) await title.waitFor() const card = title.locator('xpath=ancestor::li') - await card.getByText('各ツール呼び出しの前にモデルが認可を判断する、自動認可レビュー権限モードを提供します。', { exact: true }).waitFor() + await card.getByText(experimentalBundleDescription('auto-review', 'ja'), { exact: true }).waitFor() const expected = fileURLToPath(new URL('./expected/japanese-plugin-metadata/card.expected.md', import.meta.url)) await compareOrRefreshGolden(expected, await captureStableAria(page, '[data-plugin-panel] li:has(button[aria-label="自動認可レビューを表示"])', scaffold.workspaceCwd), webSnapshotMode()) diff --git a/apps/web/tests/markdown-image-refresh.e2e.ts b/apps/web/tests/markdown-image-refresh.e2e.ts new file mode 100644 index 0000000000..bade81cd1e --- /dev/null +++ b/apps/web/tests/markdown-image-refresh.e2e.ts @@ -0,0 +1,87 @@ +// A rewritten local image file shows its current bytes in a newly rendered Markdown image. +import { writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { createMessage, createUserMessage } from '@deepseek-ai/dsh-llm' +import { SESSION_FORMAT_VERSION, Session, SessionId } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-session-title' +import { launchWebScaffold, seedSession, watchConsole, type WebScaffold } from './scaffold.ts' +import { newEnglishPage, saveFailureShot, WEB_FIXTURE_TIME } from './support.ts' + +const ALT = 'Rewritten chart' +const chart = (width: number, color: string): string => + `` + +/** Build one closed session whose reply shows `{{cwd}}/chart.svg`. */ +function chartFixture(title: string): string { + const session = Session.create(SessionId('markdown-image-refresh-source')) + session.append('turn/start', { turn: 1 }) + const user = session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Draw the chart.' }], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + session.append('session/title', { title, messageSeqs: [user.seq], source: { kind: 'fallback' } }) + session.append('step/start', { turn: 1, step: 1 }) + session.append('assistant/message', { + stream: [], + turn: 1, + step: 1, + message: createMessage({ + role: 'assistant', + content: [{ type: 'text', text: `${title}\n\n![${ALT}]({{cwd}}/chart.svg)` }], + source: { kind: 'model', provider: 'fixture', model: 'fixture' }, + }), + }, { surfaceOp: 'append' }) + session.append('step/end', { turn: 1, step: 1 }) + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + const header = { + type: 'session', version: SESSION_FORMAT_VERSION, id: '{{sessionId}}', createdAt: 0, + cwd: '{{cwd}}', isSeeded: false, delegationDepth: 0, + } + return [JSON.stringify(header), ...session.snapshotEvents().map(event => JSON.stringify({ ...event, time: WEB_FIXTURE_TIME + event.seq * 1_000 })), ''].join('\n') +} + +describe('web e2e: rewritten Markdown image files', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + scaffold = await launchWebScaffold({}) + await writeFile(join(scaffold.workspaceCwd, 'chart.svg'), chart(120, 'red')) + await seedSession(scaffold, chartFixture('First chart'), 'markdown-image-refresh-first', undefined, + { createdAt: WEB_FIXTURE_TIME - 120_000 }) + await seedSession(scaffold, chartFixture('Second chart'), 'markdown-image-refresh-second', undefined, + { createdAt: WEB_FIXTURE_TIME - 60_000 }) + browser = await chromium.launch() + page = await newEnglishPage(browser) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + }, 120_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + }) + + it('loads the current file for an image mounted after the file changes', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-markdown-image-refresh')) + const width = () => page.getByRole('img', { name: ALT }).evaluate(element => (element as HTMLImageElement).naturalWidth) + await page.getByRole('treeitem').first().click() + // Seeded sessions list newest first under the expanded workspace. + await page.getByRole('treeitem').nth(2).click() + await page.getByText('First chart', { exact: true }).last().waitFor() + await expect.poll(width, { timeout: 10_000 }).toBe(120) + + await writeFile(join(scaffold.workspaceCwd, 'chart.svg'), chart(240, 'blue')) + await page.getByRole('treeitem').nth(1).click() + await page.getByText('Second chart', { exact: true }).last().waitFor() + await expect.poll(width, { timeout: 10_000 }).toBe(240) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }, 60_000) +}) diff --git a/apps/web/tests/message-actions.e2e.ts b/apps/web/tests/message-actions.e2e.ts index 2f96305714..405e70b57f 100644 --- a/apps/web/tests/message-actions.e2e.ts +++ b/apps/web/tests/message-actions.e2e.ts @@ -371,13 +371,15 @@ describe('web e2e: message IconActions and clocks on settled history', () => { it.skipIf(MODE === 'record')('forks through the settled-message and session-row actions', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-message-fork')) // The second answer is followed by another completed user turn in the source. + const existing = new Set(scaffold.ctx.agents.list().map(agent => agent.id)) await page.getByRole('button', { name: 'Branch into a new conversation' }).nth(1).click() await expect.poll( - () => scaffold.ctx.agents.list().find(agent => agent.session.header.parentSession === SessionId(SEED_ID)), + () => scaffold.ctx.agents.list().find(agent => !existing.has(agent.id)), { timeout: 15_000 }, ).toBeDefined() const child = scaffold.ctx.agents.list().find(agent => - agent.session.header.parentSession === SessionId(SEED_ID))! + !existing.has(agent.id))! + expect(child.session.header.parentSession).toBeUndefined() expect(child.inbox.nextTurn).toEqual([]) expect(child.session.snapshotEvents().some(event => event.type === 'agent/inbox/spliced' && event.data.inserted.some(message => message.content.some(part => @@ -405,11 +407,13 @@ describe('web e2e: message IconActions and clocks on settled history', () => { const buttonBox = await actionButton.boundingBox() if (buttonBox === null) throw new Error('fork source row action has no layout box') await page.mouse.click(buttonBox.x + buttonBox.width / 2, buttonBox.y + buttonBox.height / 2) + const beforeNested = new Set(scaffold.ctx.agents.list().map(agent => agent.id)) await page.getByRole('menuitem', { name: 'Fork session' }).click() await expect.poll( - () => scaffold.ctx.agents.list().filter(agent => agent.session.header.parentSession !== undefined).length, + () => scaffold.ctx.agents.list().filter(agent => !beforeNested.has(agent.id)).length, { timeout: 15_000 }, - ).toBe(2) + ).toBe(1) + expect(scaffold.ctx.agents.list().find(agent => !beforeNested.has(agent.id))!.session.header.parentSession).toBeUndefined() await expect.poll( () => page.locator('[role="treeitem"]').count(), { timeout: 10_000 }, @@ -445,8 +449,10 @@ describe('web e2e: message IconActions and clocks on settled history', () => { expect(scaffold.ctx.agents.get(id)).toBeUndefined() await row.hover() await row.locator('button[aria-label^="Session actions for "]').click() + const existing = new Set(scaffold.ctx.agents.list().map(agent => agent.id)) await page.getByRole('menuitem', { name: 'Fork session', exact: true }).click() - await expect.poll(() => scaffold.ctx.agents.list().some(agent => agent.session.header.parentSession === id)).toBe(true) + await expect.poll(() => scaffold.ctx.agents.list().some(agent => !existing.has(agent.id))).toBe(true) + expect(scaffold.ctx.agents.list().find(agent => !existing.has(agent.id))!.session.header.parentSession).toBeUndefined() expect(scaffold.ctx.agents.get(id)).toBeUndefined() expect(await row.getAttribute('aria-selected')).not.toBe('true') }) @@ -481,6 +487,7 @@ describe('web e2e: message IconActions and clocks on settled history', () => { if (path === '/api/session/fork') forkRequests.push(path) } page.on('request', trackFork) + const existing = new Set(scaffold.ctx.agents.list().map(agent => agent.id)) try { await row.hover() await row.locator('button[aria-label^="Session actions for "]').click() @@ -501,7 +508,7 @@ describe('web e2e: message IconActions and clocks on settled history', () => { expect(await readdir(directory)).toContain(`session.v${SESSION_FORMAT_VERSION}.jsonl.zstd`) expect(await readFile(predecessor)).toEqual(source) expect(forkRequests).toEqual(['/api/session/fork']) - expect(scaffold.ctx.agents.list().filter(agent => agent.session.header.parentSession === id)).toEqual([]) + expect(scaffold.ctx.agents.list().filter(agent => !existing.has(agent.id) && agent.id !== id)).toEqual([]) } finally { page.off('request', trackFork) } diff --git a/apps/web/tests/minimal-preset.snapshot.ts b/apps/web/tests/minimal-preset.snapshot.ts index bec53293a7..ee65497459 100644 --- a/apps/web/tests/minimal-preset.snapshot.ts +++ b/apps/web/tests/minimal-preset.snapshot.ts @@ -1,11 +1,12 @@ import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit' -import { mkdir, readFile, writeFile } from 'node:fs/promises' +import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { fileURLToPath } from 'node:url' -import type { Browser, Page } from 'playwright' +import type { Browser, Locator, Page } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import type { AgentHandle } from '@deepseek-ai/dsh-agent' +import type { SessionAttachmentValue } from '@deepseek-ai/dsh-api-session-controller' import { ToolCallId, createUserMessage } from '@deepseek-ai/dsh-llm' import type { GenerateOptions } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' @@ -18,11 +19,15 @@ import { compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, + parseSeedFixture, + rawSessionLog, + renderSeedFixture, + seedSession, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' -import { newEnglishPage, saveFailureShot } from './support.ts' +import { expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './support.ts' const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/minimal-preset', import.meta.url)) const FIXTURE = join(SNAPSHOT_DIR, 'session.v3.jsonl') @@ -322,6 +327,38 @@ describe('minimal image reading', () => { let browser: Browser | undefined let page: Page | undefined + async function openSession(id: SessionId): Promise { + if (browser === undefined) throw new Error('image scenario browser has not started') + await page?.close() + page = await newEnglishPage(browser) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.locator('[role="treeitem"]').first().click() + await page.locator(`[data-row-key="session:${id}"]`).click() + return page + } + + async function imageCard(current: Page): Promise { + const card = current.locator('[data-tool="read_image"]').first() + await card.waitFor({ state: 'attached' }) + await expandOwningTurnProcess(current, card) + const row = card.locator('[data-disclosure-row]') + if (await row.getAttribute('aria-expanded') === 'false') await row.click() + return card + } + + function interruptedTurn(turn: number, text: string): string { + return [ + { type: 'turn/start', data: { turn } }, + { type: 'step/start', data: { turn, step: 1 } }, + { + type: 'user/message', surfaceOp: 'append', + data: createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }), + }, + { type: 'step/end', data: { turn, step: 1 } }, + { type: 'turn/end', data: { turn, reason: { kind: 'interrupted' } } }, + ].map(event => JSON.stringify(event)).join('\n') + } + beforeAll(async () => { scaffold = await launchWebScaffold({ replayFixture: join(snapshotDir, 'session.v4.jsonl'), compareReplaySession: true, paceMs: 10, @@ -337,6 +374,7 @@ describe('minimal image reading', () => { }) handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: prompt }], source: { kind: 'user' } })) await handle.agent.whenIdle() + if (MODE !== 'record') browser = await chromium.launch() }) afterAll(async () => { @@ -363,21 +401,10 @@ describe('minimal image reading', () => { it.skipIf(MODE === 'record')('renders the existing image tool card and preview', async () => { onTestFailed(() => { if (page !== undefined) void saveFailureShot(page, 'web-minimal-read-image') }) - browser = await chromium.launch() - page = await newEnglishPage(browser) + page = await openSession(handle.agent.session.id) const tripwire = watchConsole(page) - await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) - await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) - await page.locator('[role="treeitem"]').first().click() - await page.locator('[role="treeitem"]').nth(1).click() await page.getByText('MINIMAL_IMAGE_OK', { exact: true }).waitFor() - await page.locator('[data-turn-process]').click() - const group = page.locator('[data-chat-group-key]').first() - await group.locator('[data-process-activity]').click() - const card = group.locator('[data-tool="read_image"]').first() - const row = card.locator('[data-disclosure-row]') - await row.click() - await expect.poll(() => row.getAttribute('aria-expanded')).toBe('true') + const card = await imageCard(page) const preview = card.locator('img').first() await preview.waitFor() await expect.poll(() => preview.evaluate(img => img instanceof HTMLImageElement && img.naturalWidth)).toBe(1) @@ -387,9 +414,143 @@ describe('minimal image reading', () => { expect(tripwire.warnings).toEqual([]) }) + it.skipIf(MODE === 'record')('reads image bytes and preserves the supplied reference with another Session as the gateway scope', async () => { + const image = handle.agent.session.deriveMessages().flatMap(message => message.content).find(block => block.type === 'image') + if (image?.type !== 'image') throw new Error('minimal read_image produced no durable image') + const unrelated = await scaffold.ctx.agents.create({ sessionId: SessionId('minimal-image-unrelated') }) + try { + expect(unrelated.agent.session.deriveMessages().flatMap(message => message.content).some(block => block.type === 'image')).toBe(false) + const read = async (attachment: unknown, rpcId: string) => { + const response = await scaffold.hostFetch('/api/session/attachment', { + method: 'POST', headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + type: 'client-request', rpcId, method: 'session/attachment', + payload: { args: { request: { sessionId: unrelated.agent.session.id, attachment } } }, + }), + }) + expect(response.ok).toBe(true) + return await response.json() as { result: { ok: boolean; value?: SessionAttachmentValue; error?: { code: string } } } + } + const reference = { ...image.attachment, name: 'caller-preview.png' } + const body = await read(reference, 'minimal-image-unrelated') + const stored = await scaffold.ctx.attachments.readImage(image.attachment) + expect(body.result).toEqual({ + ok: true, + value: { attachment: reference, data: Buffer.from(stored.data).toString('base64') }, + }) + const mismatches = [ + { mediaType: 'image/jpeg' }, { bytes: reference.bytes + 1 }, + { width: reference.width + 1 }, { height: reference.height + 1 }, + ] + for (const [index, mismatch] of mismatches.entries()) { + const rejected = await read({ ...reference, ...mismatch }, `minimal-image-mismatch-${index}`) + expect(rejected.result).toMatchObject({ + ok: false, error: { code: 'session/attachment-invalid', details: { reason: 'ATTACHMENT_CORRUPT' } }, + }) + expect(rejected.result.value).toBeUndefined() + } + const invalidFields = [ + { mediaType: 'image/svg+xml' }, { bytes: String(reference.bytes) }, + { width: String(reference.width) }, { height: String(reference.height) }, + ] + for (const [index, invalid] of invalidFields.entries()) { + const rejected = await read({ ...reference, ...invalid }, `minimal-image-schema-${index}`) + expect(rejected.result).toMatchObject({ ok: false, error: { code: 'gateway/input-invalid' } }) + expect(rejected.result.value).toBeUndefined() + } + } finally { + await unrelated.dispose() + } + }) + + it.skipIf(MODE === 'record')('loads persisted images after opening, paging older history, and forking', async () => { + onTestFailed(() => { if (page !== undefined) void saveFailureShot(page, 'web-historical-read-image') }) + const { headerLine, events } = parseSeedFixture(rawSessionLog(handle.agent.session)) + const recorded = renderSeedFixture(headerLine, events) + // User-only interrupted turns move the recorded image beyond the 50-message initial page without inventing model output. + const laterTurns = Array.from({ length: 52 }, (_, index) => + interruptedTurn(index + 2, `Later image-history message ${index + 2}`)) + const historicalId = SessionId('minimal-image-cold') + await seedSession(scaffold, `${recorded}${laterTurns[0]}\n`, historicalId, 'minimal') + expect(scaffold.ctx.agents.get(historicalId)).toBeUndefined() + page = await openSession(historicalId) + let card = await imageCard(page) + await expect.poll(() => card.locator('img').first().evaluate(img => img instanceof HTMLImageElement && img.naturalWidth)).toBe(1) + + const pagedId = await seedSession(scaffold, `${recorded}${laterTurns.join('\n')}\n`, 'minimal-image-paged', 'minimal') + expect(scaffold.ctx.agents.get(pagedId)).toBeUndefined() + page = await openSession(pagedId) + await page.getByText('Later image-history message 53', { exact: true }).waitFor() + expect(await page.locator('[data-tool="read_image"]').count()).toBe(0) + await page.getByRole('button', { name: 'Load earlier', exact: true }).click() + card = await imageCard(page) + await expect.poll(() => card.locator('img').first().evaluate(img => img instanceof HTMLImageElement && img.naturalWidth)).toBe(1) + + const response = await scaffold.hostFetch('/api/session/fork', { + method: 'POST', headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + type: 'client-request', rpcId: 'minimal-image-fork', method: 'session/fork', + payload: { args: { request: { sessionId: historicalId } } }, + }), + }) + expect(response.ok).toBe(true) + const body = await response.json() as { result: { ok: boolean; value?: { sessionId: string } } } + expect(body.result.ok).toBe(true) + if (body.result.value === undefined) throw new Error('image fork did not return a Session ID') + page = await openSession(SessionId(body.result.value.sessionId)) + card = await imageCard(page) + await expect.poll(() => card.locator('img').first().evaluate(img => img instanceof HTMLImageElement && img.naturalWidth)).toBe(1) + }) + + it.skipIf(MODE === 'record')('ends loading with a retryable failure when the persisted image is missing', async () => { + onTestFailed(() => { if (page !== undefined) void saveFailureShot(page, 'web-missing-read-image') }) + const image = handle.agent.session.deriveMessages().flatMap(message => message.content).find(block => block.type === 'image') + if (image?.type !== 'image') throw new Error('minimal read_image produced no durable image') + // The blue pixel owns a different storage object from the recorded red pixel. + const missingImage = await scaffold.ctx.attachments.saveImage({ + data: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGNgYPgPAAEDAQAIicLsAAAAAElFTkSuQmCC', 'base64'), + mediaType: 'image/png', name: 'red.png', + }) + expect(missingImage.attachmentId).not.toBe(image.attachment.attachmentId) + const { headerLine, events } = parseSeedFixture(rawSessionLog(handle.agent.session)) + const missingEvents = events.map(event => event.type === 'tool/result' + ? { + ...event, + data: { + ...event.data, + message: { + ...event.data.message, + content: event.data.message.content.map(block => block.type === 'image' + ? { ...block, attachment: missingImage } + : block), + }, + }, + } + : event) + const missingId = await seedSession(scaffold, + `${renderSeedFixture(headerLine, missingEvents)}${interruptedTurn(2, 'Check the missing image')}\n`, + 'minimal-image-missing', 'minimal') + const stored = await scaffold.ctx.attachments.readImage(missingImage) + const path = scaffold.ctx.attachments.imageHostPath(missingImage) + if (path === undefined) throw new Error('local attachment store did not return the stored image path') + await unlink(path) + try { + page = await openSession(missingId) + const card = await imageCard(page) + await card.getByRole('button', { name: 'Image failed to load; click to retry', exact: true }).waitFor() + expect(await card.getByText('Loading image…', { exact: true }).count()).toBe(0) + expect(await card.locator('[aria-busy="true"]').count()).toBe(0) + expect(await card.locator('img').count()).toBe(0) + await compareOrRefreshGolden(join(snapshotDir, 'missing-image.expected.md'), + await captureStableAria(page, '[data-tool="read_image"]', scaffold.workspaceCwd), MODE) + } finally { + await scaffold.ctx.attachments.saveImage({ data: stored.data, mediaType: stored.ref.mediaType }) + } + }) + it('keeps its snapshot inventory closed', async () => { await assertFixtureInventory(snapshotDir, [ - 'session.v4.jsonl', 'system-prompt.expected.md', 'tool-schemas.expected.json', 'ui.expected.md', + 'session.v4.jsonl', 'system-prompt.expected.md', 'tool-schemas.expected.json', 'ui.expected.md', 'missing-image.expected.md', ]) }) }) diff --git a/apps/web/tests/permission-policy-context.e2e.ts b/apps/web/tests/permission-policy-context.e2e.ts index c57ee84667..0490e0cb89 100644 --- a/apps/web/tests/permission-policy-context.e2e.ts +++ b/apps/web/tests/permission-policy-context.e2e.ts @@ -183,13 +183,13 @@ describe('web e2e: current sandbox policy reaches the model before tools', () => expect(contexts).toHaveLength(4) expect(contexts[0]).toContain('Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode.') expect(contexts[0]).toContain('Do not refuse a required modification from this policy alone') - expect(contexts[0]).toContain('Approval policy: ask.') + expect(contexts[0]).toContain('Approval prompts are enabled in this session') expect(contexts[1]).toContain('Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.') expect(contexts[1]).toContain('Approval prompts are disabled in this session') if (sessionWorkspace === undefined) throw new Error('permission-policy scenario observed no session workspace') expect(contexts[2]).toContain(`Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: ${JSON.stringify(canonicalPath(sessionWorkspace))}. Some platform temporary areas may also be writable.`) - expect(contexts[2]).toContain('Approval policy: ask.') + expect(contexts[2]).toContain('Approval prompts are enabled in this session') expect(contexts[2]).not.toContain('Approval prompts are disabled in this session') expect(contexts[3]).toContain('Current DSH file policy: read-only.') diff --git a/apps/web/tests/plan-control-row.e2e.ts b/apps/web/tests/plan-control-row.e2e.ts index 99146362a1..c32960a14e 100644 --- a/apps/web/tests/plan-control-row.e2e.ts +++ b/apps/web/tests/plan-control-row.e2e.ts @@ -256,6 +256,27 @@ describe('web e2e: plan chip click area at the narrow viewport', () => { expect(tripwire.warnings).toEqual([]) }, 200_000) + // The suite above only reaches the icon through the Plan chip's width. This + // case keeps the row otherwise empty: a long model name must still exceed + // the row above the mobile minimum, so a row-relative width cap cannot hide + // the demand behind a shrunken, ellipsized name. + it('collapses the model text on a narrow composer without another control', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-model-collapse-no-plan')) + await page.locator('[data-composer-input]').first().waitFor({ timeout: 10_000 }) + await resizeControls(page, 1680) + await selectModel(page, LONG_MODEL) + await expectControlLayout(page, false) + + await resizeControls(page, 440) + await expectControlLayout(page, true) + const trigger = page.getByRole('button', { name: /Select model/ }) + expect(await trigger.getAttribute('title')).toContain(LONG_MODEL) + expect(await trigger.getAttribute('aria-label')).toContain(LONG_MODEL) + + await resizeControls(page, 1680) + await expectControlLayout(page, false) + }, 120_000) + it('keeps the snapshot inventory closed', async () => { await assertFixtureInventory(SNAPSHOT_DIR, ['session.v3.jsonl']) }) diff --git a/apps/web/tests/plugin-manager.e2e.ts b/apps/web/tests/plugin-manager.e2e.ts index a6df6faab4..efb336cb09 100644 --- a/apps/web/tests/plugin-manager.e2e.ts +++ b/apps/web/tests/plugin-manager.e2e.ts @@ -17,7 +17,7 @@ import { launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' import { - ZH_BROWSER_LOCALE, connectFreshWorkspaceZh, openSettings, PLUGIN_TOGGLE_SETTLE_MS, saveFailureShot, + ZH_BROWSER_LOCALE, connectFreshWorkspaceZh, experimentalBundleDescription, openSettings, PLUGIN_TOGGLE_SETTLE_MS, saveFailureShot, } from './support.ts' const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/plugin-manager', import.meta.url)) @@ -837,19 +837,19 @@ describe('web e2e: plugin manager', () => { expect(await panel.locator('[data-plugin-group="basic"] [data-plugin-item]').count()).toBe(4) expect(await panel.locator('[data-plugin-package="@deepseek-ai/dsh-experimental-inspector"]').count()).toBe(0) expect(await panel.getByRole('switch', { name: '启用 语音输入', exact: true }).getAttribute('aria-checked')).toBe('false') - expect(await panel.getByRole('switch', { name: '启用 自定义插件市场', exact: true }).getAttribute('aria-checked')).toBe('false') + expect(await panel.getByRole('switch', { name: '启用 自定义插件索引', exact: true }).getAttribute('aria-checked')).toBe('false') expect(await panel.getByRole('switch', { name: '启用 开发者工具', exact: true }).count()).toBe(0) expect(await panel.getByText(/Cordis|Chrome DevTools/).count()).toBe(0) await panel.getByRole('button', { name: '更多', exact: true }).click() await panel.getByRole('heading', { name: '实验性插件', exact: true, level: 1 }).waitFor() - expect(await panel.getByText('查看调试会话原始数据、聊天消息分组数据,以及调试 NodeJS 后端', { exact: true }).count()).toBe(1) + expect(await panel.getByText(experimentalBundleDescription('inspector-profile', 'zh'), { exact: true }).count()).toBe(1) const bundles = await scaffold.ctx.pluginManager.listBundles() expect(bundles.some(bundle => bundle.name === '@deepseek-ai/dsh-experimental-terminal-bundle')).toBe(true) expect(await panel.getByRole('switch', { name: '启用 持久终端', exact: true }).count()).toBe(0) expect(await panel.locator('[data-plugin-group="more"] [data-plugin-package]').count()) .toBe(bundles.filter(bundle => bundle.name !== '@deepseek-ai/dsh-experimental-terminal-bundle' && bundle.official && (bundle.listedByDefault !== false || bundle.enabled || bundle.installed)).length) - for (const name of ['@deepseek-ai/dsh-experimental-session-search', '@deepseek-ai/dsh-experimental-ralph-bundle']) { + for (const name of ['@deepseek-ai/dsh-cua-bundle', '@deepseek-ai/dsh-experimental-session-search', '@deepseek-ai/dsh-experimental-ralph-bundle']) { expect((await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === name)) .toMatchObject({ enabled: false, optional: true, availability: 'installation', listedByDefault: false }) expect(await panel.locator(`[data-plugin-package="${name}"]`).count()).toBe(0) @@ -863,8 +863,8 @@ describe('web e2e: plugin manager', () => { ['@deepseek-ai/dsh-experimental-voice-input-bundle', 1], ['@deepseek-ai/dsh-experimental-plugin-market-bundle', 1], ['@deepseek-ai/dsh-experimental-auto-review', 1], + ['@deepseek-ai/dsh-personalized-recommendations', 1], ['@deepseek-ai/dsh-experimental-inspector-profile', 1], - ['@deepseek-ai/dsh-cua-bundle', 1], ['@deepseek-ai/dsh-experimental-tool-worktree', 1], ['@deepseek-ai/dsh-experimental-cot-translation-bundle', 1], ['@deepseek-ai/dsh-experimental-session-titles-bundle', 1], @@ -1096,7 +1096,7 @@ describe('web e2e: plugin manager', () => { await panel.getByRole('button', { name: '查看 智能体团队', exact: true }).click() const packageName = panel.locator('[data-plugin-name]') expect(await packageName.textContent()).toBe('@deepseek-ai/dsh-experimental-agent-team-profile') - expect(await panel.getByText('启用团队协作、团队工具、成员列表和共享任务看板。').count()).toBe(1) + expect(await panel.getByText(experimentalBundleDescription('agent-team-profile', 'zh')).count()).toBe(1) const child = panel.locator('[data-plugin-row]', { hasText: 'tool-agent-team' }) await child.getByText('团队工具', { exact: true }).waitFor() expect(await child.getByText('为智能体提供成员协调、消息通信和共享任务管理工具。', { exact: true }).count()).toBe(1) @@ -1104,7 +1104,7 @@ describe('web e2e: plugin manager', () => { await setLanguage('en') await panel.getByRole('heading', { name: 'Agent teams', exact: true }).waitFor() expect(await packageName.textContent()).toBe('@deepseek-ai/dsh-experimental-agent-team-profile') - expect(await panel.getByText('Enable team collaboration, team tools, the member roster, and the shared task board.').count()).toBe(1) + expect(await panel.getByText(experimentalBundleDescription('agent-team-profile', 'en')).count()).toBe(1) await child.getByText('Team tools', { exact: true }).waitFor() expect(await child.getByText('Give agents tools to coordinate members, exchange messages, and manage shared tasks.', { exact: true }).count()).toBe(1) await panel.getByRole('button', { name: 'Back to plugins' }).click() diff --git a/apps/web/tests/plugin-recommendations.e2e.ts b/apps/web/tests/plugin-recommendations.e2e.ts new file mode 100644 index 0000000000..f45bddb05a --- /dev/null +++ b/apps/web/tests/plugin-recommendations.e2e.ts @@ -0,0 +1,95 @@ +/** Replay model output through the shipped Web profile and decide its real propose_action card. */ +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { chromium, type Browser, type Page } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import type {} from '@deepseek-ai/dsh-plugin-manager' +import { + acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden, + fixtureUserPrompts, launchWebScaffold, watchConsole, type WebScaffold, +} from './scaffold.ts' +import { connectFreshWorkspace, newEnglishPage } from './support.ts' + +const directory = fileURLToPath(new URL('../../../snapshots/web/plugin-recommendations', import.meta.url)) +const fixture = join(directory, 'session.v4.jsonl') +const voiceBundle = '@deepseek-ai/dsh-experimental-voice-input-bundle' + +describe('official plugin recommendation in a conversation', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let restoreCatalog: (() => void) | undefined + + beforeAll(async () => { + scaffold = await launchWebScaffold({ replayFixture: fixture, compareReplaySession: true, + profile: { packages: [{ dir: fileURLToPath(new URL('../../../packages/experimental/personalized-recommendations', import.meta.url)), enabled: true }] }, + }) + // The recorded conversation exercises voice input; unrelated installed plugins vary by Host. + // Keep the real inventory read so accidental enablement still changes the observed selection. + const listBundles = scaffold.ctx.pluginManager.listBundles.bind(scaffold.ctx.pluginManager) + const catalog = vi.spyOn(scaffold.ctx.pluginManager, 'listBundles') + .mockImplementation(async () => (await listBundles()).filter(bundle => bundle.name === voiceBundle)) + restoreCatalog = () => { catalog.mockRestore() } + browser = await chromium.launch() + page = await newEnglishPage(browser) + }) + + afterAll(async () => { + try { await browser?.close() } finally { + try { await scaffold?.close() } finally { restoreCatalog?.() } + } + }) + + it('offers the propose_action call as one card below the answer, and reports a dismissal on the next request', async () => { + const tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + const input = page.locator('[data-composer-input]').first() + const settled = scaffold.whenTurnSettled() + const prompts = fixtureUserPrompts(await readFile(fixture, 'utf8')) + await input.fill(prompts[0]!) + await input.press('Enter') + await settled + const card = page.locator('[data-action-card]') + await card.waitFor({ state: 'visible' }) + expect(await card.count()).toBe(1) + expect(await page.locator('[data-turn-tail] [data-action-card][data-action="enable_official_plugin"]').count()).toBe(1) + const answer = page.getByText('Voice input transcribes your recordings locally into the composer. You can enable it below.', { exact: true }) + const answerBox = await answer.boundingBox() + const cardBox = await card.boundingBox() + expect(answerBox).not.toBeNull() + expect(cardBox!.y).toBeGreaterThanOrEqual(answerBox!.y + answerBox!.height) + expect(await page.getByText('enable_official_plugin').count()).toBe(0) + await card.getByText('Voice input', { exact: true }).waitFor() + expect(await card.getByRole('button', { name: 'Enable', exact: true }).isEnabled()).toBe(true) + expect((await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === voiceBundle)?.enabled).toBe(false) + await compareOrRefreshGolden(join(directory, 'offered.expected.md'), await captureStableAria(page, '[data-action-card]', scaffold.workspaceCwd), scaffold.mode) + await page.setViewportSize({ width: 620, height: 900 }) + expect(await card.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + await card.getByRole('button', { name: 'Not now', exact: true }).click() + await card.getByRole('status').getByText('Dismissed', { exact: true }).waitFor() + const warnings = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + await card.getByRole('status').getByText('Dismissed', { exact: true }).waitFor() + acknowledgeReloadConnectionLoss(tripwire, warnings) + expect(await card.count()).toBe(1) + expect(await card.getByRole('button').count()).toBe(1) + expect((await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === voiceBundle)?.enabled).toBe(false) + await compareOrRefreshGolden(join(directory, 'dismissed.expected.md'), await captureStableAria(page, '[data-action-card]', scaffold.workspaceCwd), scaffold.mode) + const statusSettled = scaffold.whenTurnSettled() + await input.fill(prompts[1]!) + await input.press('Enter') + await statusSettled + await page.getByText('Voice input is not enabled: you dismissed the card.', { exact: true }).waitFor() + expect(await card.count()).toBe(1) + await card.getByRole('button', { name: 'View details: Voice input', exact: true }).click() + await page.locator(`[data-plugin-detail="${voiceBundle}"]`).waitFor({ state: 'visible' }) + expect((await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === voiceBundle)?.enabled).toBe(false) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + if (scaffold.mode === 'replay') await assertFixtureInventory(directory, [ + 'session.v4.jsonl', 'offered.expected.md', 'dismissed.expected.md', 'system-prompt.expected.md', 'tool-schemas.expected.json', + ]) + }) +}) diff --git a/apps/web/tests/present.e2e.ts b/apps/web/tests/present.e2e.ts index 6a9a790de7..c8d4abc172 100644 --- a/apps/web/tests/present.e2e.ts +++ b/apps/web/tests/present.e2e.ts @@ -164,6 +164,8 @@ fs.appendFileSync(${JSON.stringify(openLog)}, JSON.stringify({ path, action, con const revealResponse = page.waitForResponse(response => response.url().includes('action=reveal') && response.request().method() === 'POST') await page.getByRole('menuitem', { name: 'Show file location', exact: true }).click() expect((await revealResponse).status()).toBe(204) + await page.waitForFunction(() => document.querySelector('[data-presented-files-row] button:disabled') === null) + expect(await page.getByRole('alert').count()).toBe(0) await expect.poll(opened).toHaveLength(beforeReveal + 1) expect((await opened()).at(-1)).toEqual({ action: 'reveal', content: null, path: await realpath(process.platform === 'darwin' ? join(cwd, 'report.txt') : cwd) }) for (const [name, bytes] of [['report.txt', 'EDITED_REPORT\n'], ['说明.txt', 'EDITED_NOTE\n']] as const) { @@ -172,34 +174,11 @@ fs.appendFileSync(${JSON.stringify(openLog)}, JSON.stringify({ path, action, con await row.locator('[data-presented-file]').filter({ hasText: name }).getByRole('button', { name: 'Open in Test Editor', exact: true }).click() expect((await response).status()).toBe(204) await page.waitForFunction(() => document.querySelector('[data-presented-files-row] button:disabled') === null) + expect(await page.getByRole('alert').count()).toBe(0) + expect(await row.locator('[data-presented-file] [role="status"]').count()).toBe(0) expect(await opened()).toHaveLength(count + 1) expect((await opened()).at(-1)).toEqual({ action: 'open', path: await realpath(join(cwd, name)), content: bytes }) } - const success = row.locator('[data-presented-file]').filter({ hasText: '说明.txt' }).locator('[data-success]') - await success.waitFor() - const animation = await success.evaluate((element) => { - const style = getComputedStyle(element) - const fade = element.getAnimations()[0] - if (fade === undefined) throw new Error('Successful file feedback has no fade animation') - // Seek the CSS animation so the 200 ms fade does not race the assertion. - fade.pause() - fade.currentTime = 5100 - return { - delay: style.animationDelay, duration: style.animationDuration, - fill: style.animationFillMode, opacity: Number(getComputedStyle(element).opacity), - } - }) - expect(animation.delay).toBe('5s') - expect(animation.duration).toBe('0.2s') - expect(animation.fill).toBe('forwards') - expect(animation.opacity).toBeGreaterThan(0) - expect(animation.opacity).toBeLessThan(1) - try { - await page.emulateMedia({ reducedMotion: 'reduce' }) - expect(await success.evaluate(element => getComputedStyle(element).animationName)).toBe('none') - } finally { - await page.emulateMedia({ reducedMotion: 'no-preference' }) - } } expect(downloads).toEqual([]) const response = await page.request.get(new URL(`/api/session.export?sessionId=${sessionId}`, scaffold.authenticatedUrl).href) @@ -318,4 +297,64 @@ fs.appendFileSync(${JSON.stringify(openLog)}, JSON.stringify({ path, action, con expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) }) + + it('announces mobile native opens and reveals on another device, and reports a deleted file', async () => { + const context = await browser.newContext({ + storageState: await page.context().storageState(), + userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_6 like Mac OS X) AppleWebKit/605.1.15 Version/18.6 Mobile/15E148 Safari/604.1', + viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true, locale: 'en-US', timezoneId: 'Asia/Shanghai', + }) + try { + const phone = await context.newPage() + const consoleWatch = watchConsole(phone) + const phoneDownloads: string[] = [] + phone.on('download', (download) => { phoneDownloads.push(download.suggestedFilename()) }) + await phone.goto(page.url(), { waitUntil: 'load' }) + await phone.getByText(/^PRESENT_DONE\.?$/).waitFor({ timeout: 30_000 }) + const card = phone.locator('[data-presented-file]').filter({ hasText: '说明.txt' }) + const open = card.getByRole('button', { name: 'Open in Test Editor', exact: true }) + await open.waitFor() + const notices: string[] = [] + const beforeOpen = (await opened()).length + const openResponse = phone.waitForResponse(response => response.url().includes('/api/present.open?') && response.request().method() === 'POST') + await open.tap() + expect((await openResponse).status()).toBe(204) + const success = phone.getByRole('alert').filter({ hasText: 'Opened on another device' }) + await success.waitFor() + notices.push(`## Open\n\n${await success.ariaSnapshot()}`) + await expect.poll(opened).toHaveLength(beforeOpen + 1) + expect((await opened()).at(-1)).toEqual({ action: 'open', path: await realpath(join(cwd, '说明.txt')), content: 'EDITED_NOTE\n' }) + expect(await card.locator('[role="status"]').count()).toBe(0) + const bounds = await success.boundingBox() + expect(bounds).not.toBeNull() + expect(bounds!.x).toBeGreaterThanOrEqual(0) + expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(390) + + await card.getByRole('button', { name: 'More ways to open', exact: true }).tap() + const revealResponse = phone.waitForResponse(response => response.url().includes('action=reveal') && response.request().method() === 'POST') + await phone.getByRole('menuitem', { name: 'Show file location', exact: true }).tap() + expect((await revealResponse).status()).toBe(204) + const revealed = phone.getByRole('alert').filter({ hasText: 'File location shown on another device' }) + await revealed.waitFor() + notices.push(`## Show file location\n\n${await revealed.ariaSnapshot()}`) + await expect.poll(opened).toHaveLength(beforeOpen + 2) + expect((await opened()).at(-1)).toEqual({ action: 'reveal', content: null, path: await realpath(process.platform === 'darwin' ? join(cwd, '说明.txt') : cwd) }) + + await unlink(join(cwd, '说明.txt')) + const missingResponse = phone.waitForResponse(response => response.url().includes('/api/present.open?') && response.request().method() === 'POST') + await open.tap() + expect((await missingResponse).status()).toBe(404) + const failure = phone.getByRole('alert').filter({ hasText: 'Could not open. Try again.' }) + await failure.waitFor() + notices.push(`## Missing file\n\n${await failure.ariaSnapshot()}`) + await card.getByText('Could not open. Click to retry.', { exact: true }).waitFor() + expect(await opened()).toHaveLength(beforeOpen + 2) + expect(phoneDownloads).toEqual([]) + await compareOrRefreshGolden(join(DIR, 'mobile-open.expected.md'), notices.join('\n\n'), MODE) + expect(consoleWatch.pageErrors).toEqual([]) + expect(consoleWatch.warnings).toEqual([]) + } finally { + await context.close() + } + }) }) diff --git a/apps/web/tests/preset-migration.snapshot.ts b/apps/web/tests/preset-migration.snapshot.ts index 3ca55f2f85..302aea3fdc 100644 --- a/apps/web/tests/preset-migration.snapshot.ts +++ b/apps/web/tests/preset-migration.snapshot.ts @@ -85,11 +85,11 @@ describe.skipIf(webSnapshotMode() === 'record')('historical preset restoration t await expect(readFile(childSuccessor)).rejects.toMatchObject({ code: 'ENOENT' }) const signal = new AbortController().signal const address = { kind: 'subagent', parentSessionId: id, childSessionId: childId, mode: 'one-shot' } as const - const childPage = await scaffold.ctx.sessionController.page({ address, throughSeq: childRows.length - 1 }, signal) + const childPage = await scaffold.ctx.sessionController.events({ address, throughSeq: childRows.length - 1 }, signal) expect(childPage.records.map(record => record.event.type)).toEqual(childRows.map(row => row['type'])) - await expect(scaffold.ctx.sessionController.page({ address: { ...address, childSessionId: brokenId, mode: 'unknown' }, throughSeq: 1 }, signal)) + await expect(scaffold.ctx.sessionController.events({ address: { ...address, childSessionId: brokenId, mode: 'unknown' }, throughSeq: 1 }, signal)) .rejects.toThrow() - await expect(scaffold.ctx.sessionController.page({ address: { kind: 'session', sessionId: id }, throughSeq: rows.length - 1 }, signal)) + await expect(scaffold.ctx.sessionController.events({ address: { kind: 'session', sessionId: id }, throughSeq: rows.length - 1 }, signal)) .resolves.toMatchObject({ hasMore: false }) const childWriter = await scaffold.ctx.sessionPersistence.open(childId, 'write') await childWriter.close() diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index 80aa4603f6..daa7944c36 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -43,6 +43,7 @@ import { import { VFS_EXAMPLE_SESSION_IDS, VFS_EXAMPLE_REASONING, + VFS_EXAMPLE_SPACING_TITLE, VFS_EXAMPLE_WRAPPED_COMMAND, buildVfsExampleFiles, } from '../../../packages/experimental/webworker-runtime/tests/vfs-example-fixture.ts' @@ -470,6 +471,9 @@ async function bootPreview(site: Site, manifest: ImageManifest, browser: Browser const sessions = page.getByRole('tree', { name: 'Sessions' }) const showcase = sessions.getByRole('treeitem').filter({ hasText: SHOWCASE_TITLE }) await expect.poll(() => showcase.count(), { timeout: 15_000 }).toBe(1) + // The current-generation spacing sample ships beside the showcase and must be listed cold. + const spacingSample = sessions.getByRole('treeitem').filter({ hasText: VFS_EXAMPLE_SPACING_TITLE }) + await expect.poll(() => spacingSample.count(), { timeout: 15_000 }).toBe(1) // The packed deployment ships the Schedule rows, and the preview storage // seeds the showcase Session with active tasks. expect(await showcase.locator('[data-session-schedule-mark]').count()).toBe(1) @@ -697,22 +701,17 @@ async function toggleOptionalBundles(page: Page): Promise { }) expect(result.optional.map(entry => entry.name).sort()).toEqual([...OPTIONAL_BUNDLES].sort()) expect(result.optional.filter(entry => entry.enabled || entry.availability !== 'installation')).toEqual([]) - expect(result.optional.filter(entry => entry.error !== null)).toEqual([]) + expect(result.optional.filter(entry => entry.error !== null)).toEqual([ + expect.objectContaining({ name: '@deepseek-ai/dsh-cua-bundle', error: { code: 'unsupported-platform' } }), + ]) // Metadata resolves through the Worker's Node internal modules: every optional bundle shows its title and icon. expect(result.optional.filter(entry => entry.metaError !== null || entry.title !== 'object' || entry.icon !== 'string')).toEqual([]) expect(result.inventoryErrors).toEqual([]) console.info(`preview boot: optional bundle toggles ${JSON.stringify(result.toggles.map(({ name, enable, disable, error }) => ({ name, enable, disable, error })))}`) - const cua = result.toggles.find(toggle => toggle.name === '@deepseek-ai/dsh-cua-bundle')! - expect(cua).toMatchObject({ - enable: 'applied', disable: 'applied', - error: null, - restored: true, + expect(result.toggles.find(toggle => toggle.name === '@deepseek-ai/dsh-cua-bundle')).toMatchObject({ + enable: 'failed', disable: 'applied', error: { code: 'unsupported-platform' }, + changed: 0, inactive: [], restored: true, }) - expect(cua.changed).toBeGreaterThan(0) - expect(cua.inactive).toEqual([]) - expect(cua.plugins).toContainEqual(expect.objectContaining({ - moduleName: '@deepseek-ai/dsh-experimental-cua-macos', enabled: false, fiberPhase: null, - })) const supported = result.toggles.filter(toggle => toggle.name !== '@deepseek-ai/dsh-cua-bundle') expect(supported.filter(toggle => toggle.enable !== 'applied' || toggle.disable !== 'applied') .map(({ name, enable, disable }) => ({ name, enable, disable }))).toEqual([]) diff --git a/apps/web/tests/prompt-admission.e2e.ts b/apps/web/tests/prompt-admission.e2e.ts new file mode 100644 index 0000000000..7a7b104f65 --- /dev/null +++ b/apps/web/tests/prompt-admission.e2e.ts @@ -0,0 +1,75 @@ +// Keyless browser coverage for Host acceptance through the shipped Web +// composition and the real wire: while the prompt request of a sent message is +// held, the composer stays read-only behind the sending control and Chat shows +// no echo; once the Host accepts the prompt the composer clears and takes the +// keyboard back. queue-actions covers a refused prompt keeping its draft. +import { fileURLToPath } from 'node:url' +import type { Browser, Route } from 'playwright' +import { chromium } from 'playwright' +import { afterEach, describe, expect, it, onTestFailed } from 'vitest' +import type { SessionEvent } from '@deepseek-ai/dsh-session' +import { launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold } from './scaffold.ts' +import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts' + +const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/live-interactions/session.v3.jsonl', import.meta.url)) +const MODE = webSnapshotMode() + +const HELD = 'Message held until the Host accepts it' +const FOLLOW_UP = 'Typed once the message was accepted' + +describe('web e2e: prompt admission', () => { + let scaffold: WebScaffold | undefined + let browser: Browser | undefined + + afterEach(async () => { + const failures: unknown[] = [] + await browser?.close().catch((error: unknown) => failures.push(error)) + browser = undefined + const closing = scaffold + scaffold = undefined + await closing?.close().catch((error: unknown) => failures.push(error)) + if (failures.length === 1) throw failures[0] + if (failures.length > 1) throw new AggregateError(failures, 'prompt-admission teardown failed') + }) + + it.skipIf(MODE === 'record')('holds a message in the read-only composer until the Host accepts it', async () => { + const sessionEvents: SessionEvent[] = [] + scaffold = await launchWebScaffold({ replayFixture: FIXTURE, compareReplaySession: false }) + const host = scaffold + host.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) }) + const userMessages = (): number => sessionEvents + .filter(event => event.type === 'user/message' && event.data.source.kind === 'user').length + browser = await chromium.launch() + const page = await newEnglishPage(browser) + const tripwire = watchConsole(page) + await page.goto(host.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await connectFreshWorkspace(page, host.workspaceCwd) + onTestFailed(() => saveFailureShot(page, 'web-e2e-prompt-admission')) + const input = page.locator('[data-composer-input]').first() + + const held = Promise.withResolvers() + await page.route('**/api/session/prompt', (route) => { held.resolve(route) }, { times: 1 }) + await input.fill(HELD) + await input.press('Enter') + const prompt = await held.promise + const sending = page.getByRole('button', { name: 'Sending message', exact: true }) + await expect.poll(() => sending.getAttribute('aria-busy')).toBe('true') + expect(await input.getAttribute('contenteditable')).toBe('false') + expect(await input.textContent()).toBe(HELD) + expect(await page.locator('[data-submission-echo]').count()).toBe(0) + expect(userMessages()).toBe(0) + + const settled = host.whenTurnSettled() + await prompt.continue() + await settled + await expect.poll(() => input.textContent()).toBe('') + expect(await input.getAttribute('contenteditable')).toBe('true') + // The keyboard returns to the composer, so the next message can be typed at once. + await page.keyboard.type(FOLLOW_UP) + await expect.poll(() => input.textContent()).toBe(FOLLOW_UP) + await page.locator('[data-chat-flow-kind="user"]', { hasText: HELD }).waitFor() + expect(userMessages()).toBe(1) + expect(tripwire.pageErrors).toEqual([]) + }) +}) diff --git a/apps/web/tests/queue-actions.e2e.ts b/apps/web/tests/queue-actions.e2e.ts index d6e619ef01..fb7c805388 100644 --- a/apps/web/tests/queue-actions.e2e.ts +++ b/apps/web/tests/queue-actions.e2e.ts @@ -124,21 +124,15 @@ describe('web e2e: queue row actions', () => { await input.fill(REMOVE) await input.press('Enter') await received.promise - const pending = page.locator('[data-queue-dock] [data-submission-echo]') - await pending.getByRole('status').waitFor() - expect(await pending.getByRole('status').textContent()).toBe('Sending…') - expect(await pending.getByRole('button').count()).toBe(3) - expect(await pending.getByRole('button').evaluateAll(buttons => - buttons.every(button => (button as HTMLButtonElement).disabled))).toBe(true) - expect(await input.textContent()).toBe('') - expect(await input.getAttribute('contenteditable')).toBe('true') + // The composer keeps the message, read-only, until the Host accepts it; the queue shows nothing yet. + const sendingButton = page.getByRole('button', { name: 'Sending message', exact: true }) + await sendingButton.waitFor() + expect(await sendingButton.getAttribute('aria-busy')).toBe('true') + expect(await input.textContent()).toBe(REMOVE) + expect(await input.getAttribute('contenteditable')).toBe('false') + expect(await page.locator('[data-queue-dock] [data-submission-echo]').count()).toBe(0) const sending = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd) await compareOrRefreshGolden(SENDING_EXPECTED, sending, MODE) - await page.setViewportSize({ width: 390, height: 1000 }) - await page.locator('[data-sidebar-collapsed="true"]').waitFor() - await expect.poll(() => pending.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) - await page.setViewportSize({ width: 1680, height: 1000 }) - await page.locator('[data-sidebar-collapsed="true"]').waitFor({ state: 'detached' }) } finally { release.resolve(undefined) } @@ -148,6 +142,8 @@ describe('web e2e: queue row actions', () => { expect(await page.locator('[data-queue-dock]').getByRole('status').count()).toBe(0) await input.fill(EDIT) await input.press('Enter') + // The Host queue row can arrive before the prompt reply that clears the composer. + await expect.poll(() => input.textContent(), { timeout: 10_000 }).toBe('') const queueHeader = page.getByRole('button', { name: '2 queued messages' }) await expect.poll(() => queueHeader.getAttribute('aria-expanded'), { timeout: 10_000 }) .toBe('false') @@ -365,10 +361,11 @@ describe('web e2e: queue row actions', () => { await page.locator('[data-testid="todo-panel"]').waitFor({ timeout: 10_000 }) for (const text of ['Layout queue first', 'Layout queue second']) { - // A just-submitted composer is read-only for the prompt round-trip. await page.locator('[data-composer-input][contenteditable="true"]').first().waitFor({ timeout: 10_000 }) await input.fill(text) await input.press('Enter') + // The composer keeps a sent message, still editable, until the Host accepts it. + await expect.poll(() => input.textContent(), { timeout: 10_000 }).toBe('') } const queueHeader = page.getByRole('button', { name: '2 queued messages' }) await expect.poll(() => queueHeader.getAttribute('aria-expanded'), { timeout: 10_000 }) diff --git a/apps/web/tests/queue-image.e2e.ts b/apps/web/tests/queue-image.e2e.ts index fa6fe753a0..bfea309698 100644 --- a/apps/web/tests/queue-image.e2e.ts +++ b/apps/web/tests/queue-image.e2e.ts @@ -96,7 +96,8 @@ describe('web e2e: queued image submission', () => { await input.press('Enter') await expect.poll(() => existsSync(readyFile), { timeout: 15_000 }).toBe(true) - // A just-submitted composer is read-only for the prompt round-trip. + // The composer keeps the sent prompt, still editable, until the Host accepts it. + await expect.poll(() => input.textContent(), { timeout: 10_000 }).toBe('') await page.locator('[data-composer-input][contenteditable="true"]').first().waitFor({ timeout: 10_000 }) await pasteImage(page, await readFile(PNG)) await page.getByRole('img', { name: 'queued.png' }).waitFor({ timeout: 10_000 }) @@ -126,17 +127,20 @@ describe('web e2e: queued image submission', () => { try { await input.fill(QUEUED_TEXT) await input.press('Enter') - await dockThumb.waitFor({ timeout: 15_000 }) - await expect.poll(() => dockThumb.getAttribute('src'), { timeout: 15_000 }).toMatch(/^blob:/) - expect(await page.locator('[data-queue-dock] [data-submission-echo]').count()).toBe(1) + // The composer keeps the text and image, read-only, until the Host accepts the prompt. + await expect.poll(() => input.getAttribute('contenteditable'), { timeout: 15_000 }).toBe('false') + expect(await page.getByRole('img', { name: 'queued.png' }).count()).toBe(1) + expect(await page.locator('[data-queue-dock] [data-submission-echo]').count()).toBe(0) releasePrompt.resolve(undefined) await expect.poll(() => imageRequested, { timeout: 15_000 }).toBe(true) - await page.getByText(QUEUED_TEXT, { exact: true }).waitFor() + // The Host queue row can arrive before the prompt reply that clears the composer. + await expect.poll(() => input.textContent(), { timeout: 15_000 }).toBe('') + await page.locator('[data-queue-dock]').getByText(QUEUED_TEXT, { exact: true }).waitFor() await page.getByRole('button', { name: 'Remove queued message', disabled: false }).waitFor({ timeout: 15_000 }) expect(await page.locator('[data-queue-dock] [data-submission-echo]').count()).toBe(0) expect(await dockThumb.count()).toBe(0) releaseImage.resolve(undefined) - // Admission replaces the optimistic image; wait for the durable row's own thumbnail. + // The Host queue row replaces the accepted echo; wait for the durable row's own thumbnail. const durableThumb = page.locator('[data-queue-dock] li:not([data-submission-echo]) img[alt="Queued message image"]') await durableThumb.waitFor({ timeout: 15_000 }) await expect.poll(() => durableThumb.getAttribute('src'), { timeout: 15_000 }).toMatch(/^blob:/) diff --git a/apps/web/tests/replay-round-trip.e2e.ts b/apps/web/tests/replay-round-trip.e2e.ts index 6e7725cde6..82f436c837 100644 --- a/apps/web/tests/replay-round-trip.e2e.ts +++ b/apps/web/tests/replay-round-trip.e2e.ts @@ -131,7 +131,7 @@ describe('web e2e: fresh round trip through the real assembly', () => { key: 'Enter', code: 'Enter', bubbles: true, cancelable: true, })) // sendSession registered its paint yield first. This frame observes the - // committed echo while admission remains queued on the following task. + // composer holding the message while the Host has not accepted it yet. await new Promise((resolve) => { requestAnimationFrame(() => { resolve() }) }) const echo = document.querySelector('[data-submission-echo]') return [ @@ -145,6 +145,10 @@ describe('web e2e: fresh round trip through the real assembly', () => { expect(await response.json()).toMatchObject({ result: { ok: true, value: { accepted: true } } }) accepted = true await compareOrRefreshGolden(ECHO_EXPECTED, echoSnapshot, MODE) + // Acceptance publishes the echo and clears the composer; maintenance keeps the Turn from starting. + await page.locator('[data-submission-echo]', { hasText: PROMPT }).waitFor() + await expect.poll(() => input.textContent()).toBe('') + expect(await input.getAttribute('contenteditable')).toBe('true') const row = page.getByRole('tree', { name: 'Sessions', exact: true }) .locator('[role="treeitem"][aria-selected="true"]') await expect.poll(() => row.getAttribute('draggable'), { timeout: 5_000 }).toBe('true') diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index 4ce50f5075..6a0c089a9a 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -1209,7 +1209,7 @@ async function assertReplaySession( let expectedPath = fixturePath const userPrompts = fixtureUserPrompts(expected) const candidates = sessions.filter((session) => { - if (session.header.parentSession !== undefined) return false + if (session.header.origin === 'subagent' || session.header.isSeeded) return false const actual = session.snapshotEvents().flatMap((event) => { if (event.type !== 'user/message' || event.data.source.kind !== 'user') return [] const text = event.data.content.filter(block => block.type === 'text').map(block => block.text).join('') diff --git a/apps/web/tests/schedule-after.e2e.ts b/apps/web/tests/schedule-after.e2e.ts index 1fc1ef2395..fb45d6c76a 100644 --- a/apps/web/tests/schedule-after.e2e.ts +++ b/apps/web/tests/schedule-after.e2e.ts @@ -20,6 +20,7 @@ import type { ContextFormed, GenerateOptions, StreamChunk } from '@deepseek-ai/d import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' import { ScheduleId, + createAfterScheduleRecord, createEveryScheduleRecord, foldScheduleEvents, type EveryScheduleRecord, @@ -1259,4 +1260,86 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { await page.clock.setFixedTime(new Date(CATALOG_NOW)) } }, 60_000) + + it('removes every ended task from the page and keeps the active ones', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-schedule-clear-ended')) + const endedSession = SessionId('schedule-manager-ended-clear') + const domain = scaffold.ctx.storageDomain.get('schedule') + if (domain === undefined) throw new Error('Schedule domain was not opened') + const endedIds = [ScheduleId('schedule-ended-first'), ScheduleId('schedule-ended-second')] + const endedTitles = ['Ended release check', 'Ended metrics check'] as const + // An earlier scenario may leave an ended row behind; the confirmation states + // the whole ended set, so the lane starts from an empty one. + await scaffold.ctx.schedule.deleteInactive() + for (const [index, id] of endedIds.entries()) { + const title = endedTitles[index]! + const record = createAfterScheduleRecord(id, title, 60, Date.now(), title) + const receipt = { + scheduledAt: record.scheduledAt, + deliveredAt: new Date(Date.parse(record.scheduledAt) + 1_000).toISOString(), + messageId: MessageId(`${id}-delivery`), + } + await domain.table('tasks').put(record.id, { + sessionId: endedSession, record, status: 'inactive', lastDelivery: receipt, + deliveryHistory: { records: [receipt], earlierRecordsUnavailable: false }, + }) + } + // The running task is what the cleanup must leave alone. Creating it also + // announces a committed Host change, so the open page reads the rows seeded + // above without waiting for its own first catalog read. + const kept = await scaffold.ctx.schedule.create(endedSession, { + prompt: 'Keep this running task', title: 'Keep this running task', at: '2099-08-25T12:08:00.000Z', + }) + try { + await page.getByRole('button', { name: 'Automation tasks', exact: true }).click() + const manager = page.getByTestId('task-manager-page') + // Earlier scenarios leave their own search text and status filter on this + // shared page; this scenario asserts the complete list. + await manager.getByRole('searchbox', { name: 'Search tasks' }).fill('') + await manager.getByRole('button', { name: 'All', exact: true }).click() + const more = manager.getByRole('button', { name: 'More task actions', exact: true }) + await more.waitFor({ timeout: 15_000 }) + + // The confirmation states the Host-side target and removes nothing until it + // is confirmed. + await more.click() + await page.getByRole('menuitem', { name: 'Clear all inactive tasks', exact: true }).click() + const confirmation = page.getByRole('dialog', { name: 'Clear inactive tasks (2)?' }) + await confirmation.getByRole('button', { name: 'Cancel', exact: true }).click() + expect((await scaffold.ctx.schedule.catalog()).filter(task => task.status === 'inactive')).toHaveLength(2) + + await more.click() + await page.getByRole('menuitem', { name: 'Clear all inactive tasks', exact: true }).click() + await confirmation.getByRole('button', { name: 'Clear tasks', exact: true }).click() + await expect.poll( + async () => (await scaffold.ctx.schedule.catalog()).filter(task => task.status === 'inactive'), + { timeout: 15_000 }, + ).toEqual([]) + const remaining = await scaffold.ctx.schedule.catalog() + expect(remaining.some(task => endedIds.includes(task.id))).toBe(false) + expect(remaining.map(task => task.title)).toContain('Keep this running task') + await page.getByText('Cleared 2 inactive tasks.', { exact: true }).waitFor({ timeout: 15_000 }) + // The trigger left with the rows it removed, so the page heading owns the + // focus after the confirmation closes; this confirms the heading fallback + // in a real browser. + await expect.poll(() => page.evaluate(() => document.activeElement?.tagName), { timeout: 15_000 }) + .toBe('H1') + // The page follows the acknowledged removal: no ended row or cleanup action + // remains, and the running task is still listed. + await expect.poll(() => manager.getByRole('button', { name: 'More task actions', exact: true }).count(), { timeout: 15_000 }) + .toBe(0) + await manager.getByRole('button', { name: 'All', exact: true }).click() + await expect.poll(() => manager.getByRole('list', { name: 'Task catalog' }) + .getByRole('button', { name: kept.title, exact: true }).count(), { timeout: 15_000 }).toBe(1) + expect((await scaffold.ctx.schedule.catalog()).filter(task => task.status === 'inactive')).toEqual([]) + expect(tripwire.pageErrors).toEqual([]) + } finally { + // The shared page and Host outlive a failed assertion: remove every row + // this scenario introduced so the next one starts from the same state. A + // teardown rejection must not mask the assertion that failed first. + await Promise.allSettled( + [kept.id, ...endedIds].map(id => scaffold.ctx.schedule.delete({ sessionId: endedSession, id })), + ) + } + }, 60_000) }) diff --git a/apps/web/tests/search-empty-include.e2e.ts b/apps/web/tests/search-empty-include.e2e.ts new file mode 100644 index 0000000000..d14c715616 --- /dev/null +++ b/apps/web/tests/search-empty-include.e2e.ts @@ -0,0 +1,63 @@ +/** Recorded empty-include searches retain the specialized Web result cards. */ +import { readFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import { chromium, type Browser, type Page } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { + assertFixtureInventory, captureStableAria, compareOrRefreshGolden, + launchWebScaffold, seedSession, selectedSessionFixture, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' +import { expandTurnProcesses, newEnglishPage, saveFailureShot } from './support.ts' + +const ROOT = fileURLToPath(new URL('../../../snapshots', import.meta.url)) +const MODE = webSnapshotMode() + +describe.skipIf(MODE === 'record')('web e2e: search-empty-include', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + scaffold = await launchWebScaffold({}) + const fixture = await selectedSessionFixture(`${ROOT}/session/toolcall-unused-args/session.v4.jsonl`) + await seedSession(scaffold, await readFile(fixture, 'utf8'), 'search-empty-include') + browser = await chromium.launch() + page = await newEnglishPage(browser) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + }) + + afterAll(async () => { + try { + await browser?.close() + } finally { + await scaffold?.close() + } + }) + + it('renders both recorded searches as file-grouped matches rather than generic JSON', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-search-empty-include')) + await page.locator('[role="treeitem"]').first().click() + await page.locator('[role="treeitem"]').nth(1).click() + await page.getByText('DONE', { exact: true }).waitFor({ timeout: 15_000 }) + await expandTurnProcesses(page) + const calls = page.locator('[data-variant="search"]') + expect(await calls.count()).toBe(2) + const views: string[] = [] + for (const [index, extension] of ['.ts', '.md'].entries()) { + const call = calls.nth(index) + await call.locator('[data-expandable]').click() + const matches = call.locator('[data-search="matches"]') + await matches.waitFor() + expect(await matches.textContent()).toContain(`example${extension}`) + expect(await matches.textContent()).toContain('marker') + views.push(await captureStableAria(page, `[data-variant="search"] >> nth=${index}`, scaffold.workspaceCwd)) + } + const snapshotDir = `${ROOT}/web/search-empty-include` + await compareOrRefreshGolden(`${snapshotDir}/ui.expected.md`, views.join('\n'), MODE) + await assertFixtureInventory(snapshotDir, ['ui.expected.md']) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }) +}) diff --git a/apps/web/tests/settings-chrome.e2e.ts b/apps/web/tests/settings-chrome.e2e.ts index 4110b72e95..a3ecc0de18 100644 --- a/apps/web/tests/settings-chrome.e2e.ts +++ b/apps/web/tests/settings-chrome.e2e.ts @@ -977,18 +977,18 @@ describe('web e2e: settings modal and General preferences', () => { it('opens a browser asking for no shipped language in English', async () => { // The product default for "no usable signal": a French browser ships - // neither zh nor en, so resolution falls to FALLBACK_LOCALE (en) rather + // names no shipped language, so resolution falls to FALLBACK_LOCALE (en) rather // than to Chinese. const fresh = await launchWebScaffold({ developerTools: false }) - const frPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: 'fr-FR' }) - const frTripwire = watchConsole(frPage) - onTestFailed(() => saveSettingsFailureShot(frPage, 'settings-unshipped-language')) + const unsupportedPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: 'it-IT' }) + const unsupportedTripwire = watchConsole(unsupportedPage) + onTestFailed(() => saveSettingsFailureShot(unsupportedPage, 'settings-unshipped-language')) try { - await frPage.goto(fresh.authenticatedUrl, { waitUntil: 'load' }) - await frPage.waitForSelector('[class*="frame"]', { timeout: 30_000 }) - expect(await frPage.evaluate(() => localStorage.getItem('dsh.locale'))).toBeNull() - await openSettings(frPage, 'en') - const dialog = frPage.getByRole('dialog', { name: 'Settings' }) + await unsupportedPage.goto(fresh.authenticatedUrl, { waitUntil: 'load' }) + await unsupportedPage.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + expect(await unsupportedPage.evaluate(() => localStorage.getItem('dsh.locale'))).toBeNull() + await openSettings(unsupportedPage, 'en') + const dialog = unsupportedPage.getByRole('dialog', { name: 'Settings' }) await dialog.waitFor({ timeout: 10_000 }) await dialog.getByRole('button', { name: 'English' }).waitFor({ timeout: 10_000 }) // A locale-owned nav label proves the dictionaries resolved to en. @@ -996,17 +996,17 @@ describe('web e2e: settings modal and General preferences', () => { // The markup already ships `en`, so this alone cannot prove the sync ran // — the zh scenario above is the discriminating half. Asserted here too // so a future change that resolves en but writes the wrong tag is caught. - expect(await frPage.evaluate(() => document.documentElement.lang)).toBe('en') + expect(await unsupportedPage.evaluate(() => document.documentElement.lang)).toBe('en') // Golden of the English fallback dialog — the visible output this change // produces. The zh golden above covers the detected-locale surface, so // the pair pins both directions of the resolution. await dialog.getByText(`Current version: ${version}`, { exact: true }).waitFor() - const snapshot = await captureStableAria(frPage, '[role="dialog"]', fresh.workspaceCwd, versionCapture) + const snapshot = await captureStableAria(unsupportedPage, '[role="dialog"]', fresh.workspaceCwd, versionCapture) await compareOrRefreshGolden(DIALOG_EN_EXPECTED, snapshot, MODE) - expect(frTripwire.pageErrors).toEqual([]) - expect(frTripwire.warnings).toEqual([]) + expect(unsupportedTripwire.pageErrors).toEqual([]) + expect(unsupportedTripwire.warnings).toEqual([]) } finally { - await frPage.close() + await unsupportedPage.close() await fresh.close() } }, 90_000) diff --git a/apps/web/tests/shared-inspector.e2e.ts b/apps/web/tests/shared-inspector.e2e.ts index d72ff60197..ee0229ebfc 100644 --- a/apps/web/tests/shared-inspector.e2e.ts +++ b/apps/web/tests/shared-inspector.e2e.ts @@ -5,6 +5,7 @@ import { join } from 'node:path' import { chromium, type Browser } from 'playwright' import { expect, it, onTestFinished } from 'vitest' import { compareOrRefreshGolden, launchWebScaffold, seedSession, selectedSessionFixture, watchConsole, webSnapshotMode, type WebScaffold } from './scaffold.ts' +import { experimentalBundleDescription } from './support.ts' const bundle = fileURLToPath(new URL('../../../packages/experimental/inspector-profile', import.meta.url)) const fixture = fileURLToPath(new URL('../../../snapshots/web/fresh-round-trip/session.v4.jsonl', import.meta.url)) @@ -87,14 +88,14 @@ it('toggles bottom DevTools from the page and iframe without a selected Session' it.each([ { locale: 'zh-CN', file: 'zh', plugins: '插件', open: '查看 开发者工具', bundle: '开发者工具', - description: '查看调试会话原始数据、聊天消息分组数据,以及调试 NodeJS 后端', + description: experimentalBundleDescription('inspector-profile', 'zh'), inspector: 'NodeJS 诊断', inspectorDescription: '按 Ctrl/Cmd+Shift+. 在底部面板打开 Chrome DevTools 进行开发调试', session: '会话数据诊断', sessionDescription: '在会话侧边栏启用当前会话的原始数据和聊天分组数据分析功能', openSidebar: '打开右侧边栏', sidebarDescription: '在侧边栏分析当前会话原始日志和聊天分组数据', }, { locale: 'en-US', file: 'en', plugins: 'Plugins', open: 'View Developer tools', bundle: 'Developer tools', - description: 'Inspect and debug raw session data, grouped chat messages, and the NodeJS backend.', + description: experimentalBundleDescription('inspector-profile', 'en'), inspector: 'NodeJS inspector', inspectorDescription: 'Press Ctrl/Cmd+Shift+. to open Chrome DevTools in the bottom panel for development and debugging.', session: 'Session log', sessionDescription: "Enable analysis of the current session's raw data and grouped chat messages in the session sidebar.", openSidebar: 'Open right sidebar', sidebarDescription: 'Analyze raw logs and grouped chat messages for the current session in the sidebar.', diff --git a/apps/web/tests/shortcuts-workspace.e2e.ts b/apps/web/tests/shortcuts-workspace.e2e.ts index db74374ae7..410fa3ce84 100644 --- a/apps/web/tests/shortcuts-workspace.e2e.ts +++ b/apps/web/tests/shortcuts-workspace.e2e.ts @@ -93,14 +93,17 @@ describe.skipIf(mode === 'record')('web e2e: workspace shortcuts', () => { await bind('Fork session') const original = await readPersistedEvents(scaffold, sourceId) const lastEnd = original.findLastIndex(event => event.type === 'turn/end') + const existing = new Set(scaffold.ctx.agents.list().map(agent => agent.id)) await page.keyboard.press('Meta+Shift+Comma') - await expect.poll(() => scaffold.ctx.agents.list().find(agent => agent.session.header.parentSession === sourceId)).toBeDefined() - const child = scaffold.ctx.agents.list().find(agent => agent.session.header.parentSession === sourceId)! + await expect.poll(() => scaffold.ctx.agents.list().find(agent => !existing.has(agent.id))).toBeDefined() + const child = scaffold.ctx.agents.list().find(agent => !existing.has(agent.id))! + expect(child.session.header.parentSession).toBeUndefined() const childId = child.session.header.id await expect.poll(async () => (await readPersistedEvents(scaffold, childId)).some(event => event.type === 'session/title' && event.data.title === 'T4 source (1)')).toBe(true) const copied = await readPersistedEvents(scaffold, childId) expect(copied.slice(0, lastEnd + 1)).toEqual(original.slice(0, lastEnd + 1)) const sourceRow = page.getByRole('treeitem').filter({ has: page.getByText('T4 source', { exact: true }) }) + expect(child.session.header.parentSession).toBeUndefined() const childRow = page.getByRole('treeitem').filter({ has: page.getByText('T4 source (1)', { exact: true }) }) await childRow.waitFor() expect(await sourceRow.getAttribute('aria-selected')).toBe('true') @@ -218,6 +221,7 @@ it.skipIf(mode === 'record')('explains a first-turn fork refusal and retries fro await connectFreshWorkspace(page, scaffold.workspaceCwd) const source = scaffold.ctx.agents.list().find(agent => !before.has(agent.id)) if (source === undefined) throw new Error('The workspace did not create a Session') + const existing = new Set(scaffold.ctx.agents.list().map(agent => agent.id)) source.session.append('turn/start', { turn: 1 }) const user = source.session.append('user/message', createUserMessage({ content: [{ type: 'text', text: 'The first turn has not ended.' }], source: { kind: 'user' }, @@ -240,7 +244,7 @@ it.skipIf(mode === 'record')('explains a first-turn fork refusal and retries fro await compareOrRefreshGolden(join(root, 'fork-unavailable.expected.md'), await unavailable.ariaSnapshot(), mode) expect(await selected.textContent()).toContain('First turn') - expect(scaffold.ctx.agents.list().filter(agent => agent.session.header.parentSession === source.id)).toHaveLength(0) + expect(scaffold.ctx.agents.list().filter(agent => !existing.has(agent.id))).toHaveLength(0) expect(forkWarnings).toEqual([]) source.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) @@ -252,8 +256,9 @@ it.skipIf(mode === 'record')('explains a first-turn fork refusal and retries fro await scaffold.ctx.sessions.flush(source.session) await page.getByText('The second turn has not ended.', { exact: true }).waitFor() await page.keyboard.press('Meta+Shift+Comma') - await expect.poll(() => scaffold.ctx.agents.list().find(agent => agent.session.header.parentSession === source.id)).toBeDefined() - const child = scaffold.ctx.agents.list().find(agent => agent.session.header.parentSession === source.id)! + await expect.poll(() => scaffold.ctx.agents.list().find(agent => !existing.has(agent.id))).toBeDefined() + const child = scaffold.ctx.agents.list().find(agent => !existing.has(agent.id))! + expect(child.session.header.parentSession).toBeUndefined() const childRow = page.getByRole('treeitem').filter({ has: page.getByText('First turn (1)', { exact: true }) }) await childRow.waitFor() expect(await childRow.getAttribute('aria-selected')).toBe('false') diff --git a/apps/web/tests/sidebar-right.e2e.ts b/apps/web/tests/sidebar-right.e2e.ts index 79fc706ec9..307e1adf12 100644 --- a/apps/web/tests/sidebar-right.e2e.ts +++ b/apps/web/tests/sidebar-right.e2e.ts @@ -1046,6 +1046,54 @@ describe('web e2e: shipped right Sidebar', () => { expect(tripwire.warnings).toEqual([]) }, 90_000) + it('resists a floating panel dragged past the viewport edges and springs it back inside', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-sidebar-right-float-edge')) + const column = await resetSidebar(page) + const floats = page.locator('[data-sidebar-right-session]:not([hidden]) [data-dockkit-float]') + await proseChip(page).click() + await expect.poll(async () => await tabTitles(paneAt(column, 0))).toEqual(['Files', SAMPLE_NAME]) + await floatByDrag(page, paneAt(column, 0).locator('[data-dockkit-tab]').filter({ hasText: SAMPLE_NAME })) + await expect.poll(async () => await floats.count()).toBe(1) + const panel = floats.first() + const viewport = page.viewportSize() + if (viewport === null) throw new Error('page has no viewport') + + // Carrying the grip to the bottom-right corner asks for the panel well past both edges. + const grip = await centre(panel.locator('[data-dockkit-float-grip]')) + await page.mouse.move(grip.x, grip.y) + await page.mouse.down() + await page.mouse.move(viewport.width - 2, viewport.height - 2, { steps: 8 }) + const pushed = await panel.boundingBox() + if (pushed === null) throw new Error('float is not rendered') + expect(pushed.x + pushed.width).toBeGreaterThan(viewport.width) + expect(pushed.x + pushed.width).toBeLessThan(viewport.width + 120) + expect(pushed.y + pushed.height).toBeGreaterThan(viewport.height) + expect(pushed.y + pushed.height).toBeLessThan(viewport.height + 120) + await page.mouse.up() + + // The return overshoots inward and can pass the edges before it ends, so + // wait for the resting style, which drops the inline position. + await expect.poll(async () => await panel.evaluate(node => (node as HTMLElement).style.left)).toBe('') + const rest = await panel.boundingBox() + if (rest === null) throw new Error('float is not rendered') + expect({ right: Math.round(rest.x + rest.width), bottom: Math.round(rest.y + rest.height) }) + .toEqual({ right: viewport.width, bottom: viewport.height }) + + // At rest the stylesheet clamps on its own: a rectangle published from a + // stale viewport reading, far outside and larger than the viewport, still + // draws inside it. + const clamped = await panel.evaluate((node) => { + const element = node as HTMLElement + for (const name of ['x', 'y', 'width', 'height']) element.style.setProperty(`--dsh-dockkit-float-${name}`, '5000px') + const box = element.getBoundingClientRect() + return { left: box.left, top: box.top, right: box.right, bottom: box.bottom } + }) + expect(clamped).toEqual({ left: 0, top: 0, right: viewport.width, bottom: viewport.height }) + + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }, 60_000) + it('drops a pane whose last tab closes, and follows the last-tab rule on the surface', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-sidebar-right-settle')) const column = await resetSidebar(page) diff --git a/apps/web/tests/snapshots/client-ui-stats-panel/panel.expected.md b/apps/web/tests/snapshots/client-ui-stats-panel/panel.expected.md new file mode 100644 index 0000000000..e410795800 --- /dev/null +++ b/apps/web/tests/snapshots/client-ui-stats-panel/panel.expected.md @@ -0,0 +1,43 @@ +- table "Statistics": + - rowgroup: + - row "Turn / step Trigger Execution Context Output Cache hit First token Model time Output speed Tool time Total time": + - columnheader "Turn / step" + - columnheader "Trigger" + - columnheader "Execution" + - columnheader "Context" + - columnheader "Output" + - columnheader "Cache hit" + - columnheader "First token" + - columnheader "Model time" + - columnheader "Output speed" + - columnheader "Tool time" + - columnheader "Total time" + - rowgroup: + - row "Expand or collapse turn 1 · 01-15 {{clock}} Show the measured round. read ×1 → 7 chars 5.2K 0.24K 69.23% {{ttft}} {{duration}} {{tps}} {{duration}} {{duration}}": + - cell "Expand or collapse turn 1 · 01-15 {{clock}}": + - button "Expand or collapse turn 1" [expanded]: Turn 1 + - text: · 01-15 {{clock}} + - cell "Show the measured round." + - cell "read ×1 → 7 chars" + - cell "5.2K" + - cell "0.24K" + - cell "69.23%" + - cell "{{ttft}}" + - cell "{{duration}}" + - cell "{{tps}}" + - cell "{{duration}}" + - cell "{{duration}}" + - row "Expand or collapse the tool details of step 1 · details 01-15 {{clock}} read /work/notes.md 2 lines 5.2K 0.24K 69.23% {{ttft}} {{duration}} {{tps}} {{duration}} {{duration}}": + - cell "Expand or collapse the tool details of step 1 · details": + - button "Expand or collapse the tool details of step 1": Step 1 + - text: · details + - cell "01-15 {{clock}}" + - cell "read /work/notes.md 2 lines" + - cell "5.2K" + - cell "0.24K" + - cell "69.23%" + - cell "{{ttft}}" + - cell "{{duration}}" + - cell "{{tps}}" + - cell "{{duration}}" + - cell "{{duration}}" diff --git a/apps/web/tests/stats-truncated-tooltip.e2e.ts b/apps/web/tests/stats-truncated-tooltip.e2e.ts new file mode 100644 index 0000000000..18e7d5e64c --- /dev/null +++ b/apps/web/tests/stats-truncated-tooltip.e2e.ts @@ -0,0 +1,108 @@ +// Web e2e scenario: a composer statistics pill cut off by the narrow composer +// row shows its full reading in a tooltip on hover. The seed is generated, not recorded: no line is model output. +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { createSystemMessage } from '@deepseek-ai/dsh-llm' +import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold } from './scaffold.ts' +import { newEnglishPage, saveFailureShot } from './support.ts' + +const SEED_ID = 'stats-truncated-tooltip-web-e2e' +const USAGE_READING = '5.8M tok · Cache hit 98%' + +/** + * Generate one closed single-step turn whose billed usage totals 5.8M tokens at a 98% cache hit. + * @returns session.jsonl text for {@link seedSession}. + */ +function buildSeed(): string { + const lines = [JSON.stringify({ + type: 'session', version: SESSION_FORMAT_VERSION, id: '{{sessionId}}', + createdAt: 1784974100000, cwd: '{{cwd}}/workspace', isSeeded: false, delegationDepth: 0, + })] + let seq = 0 + let time = 1784974100000 + const at = (event: Record): void => { + lines.push(JSON.stringify({ ...event, seq: seq++, time: time++ })) + } + at({ type: 'turn/start', data: { turn: 1 } }) + at({ type: 'step/start', data: { turn: 1, step: 1 } }) + at({ type: 'system/message', data: { turn: 1, step: 1, message: createSystemMessage('') }, surfaceOp: 'append' }) + at({ + type: 'user/message', + data: { + id: '00000000-0000-4000-9000-000000000001', + role: 'user', + content: [{ type: 'text', text: 'm1' }], + source: { kind: 'user' }, + }, + surfaceOp: 'append', + }) + at({ + type: 'assistant/message', + data: { + stream: [], + turn: 1, + step: 1, + message: { + id: '00000000-0000-4000-8000-000000000001', + role: 'assistant', + content: [{ type: 'text', text: 'r1' }], + source: { kind: 'model', provider: 'snapshot', model: 'snapshot-replier' }, + }, + usage: { inputTokens: 100_000, outputTokens: 20_000, cacheReadTokens: 5_680_000 }, + }, + surfaceOp: 'append', + }) + at({ type: 'step/end', data: { turn: 1, step: 1 } }) + at({ type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } } }) + return `${lines.join('\n')}\n` +} + +describe('web e2e: truncated composer statistics', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + if (webSnapshotMode() === 'record') throw new Error('stats-truncated-tooltip is a keyless assembled scenario') + scaffold = await launchWebScaffold({}) + await seedSession(scaffold, buildSeed(), SEED_ID) + browser = await chromium.launch() + page = await newEnglishPage(browser) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + }, 120_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + }) + + it('shows the full reading of a pill the narrow composer cuts off', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-stats-truncated-tooltip')) + await page.locator('[role="treeitem"]').first().click() + await page.locator('[role="treeitem"]').nth(1).click() + const usagePill = page.getByRole('button', { name: USAGE_READING, exact: true }) + await usagePill.waitFor({ timeout: 15_000 }) + const tooltip = page.getByRole('tooltip') + const label = usagePill.locator(':scope > span') + const cut = () => label.evaluate(element => element.scrollWidth > element.clientWidth) + expect(await cut()).toBe(false) + + await page.setViewportSize({ width: 390, height: 900 }) + await expect.poll(cut).toBe(true) + await usagePill.hover() + await expect.poll(() => tooltip.textContent()).toBe(USAGE_READING) + await usagePill.click() + await page.getByRole('dialog', { name: 'Token usage' }).waitFor() + expect(await tooltip.count()).toBe(0) + }, 60_000) + + it('stayed clean', () => { + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }) +}) diff --git a/apps/web/tests/submission-echo.e2e.ts b/apps/web/tests/submission-echo.e2e.ts index b8b93c4afa..a1401e9e9a 100644 --- a/apps/web/tests/submission-echo.e2e.ts +++ b/apps/web/tests/submission-echo.e2e.ts @@ -1,18 +1,17 @@ // @vitest-environment jsdom -// Local submission echo over the BUILT client graph (keyless RemoteMock -// transport): a text-plus-image send paints its echo bubble synchronously on -// the submit keystroke — before serialization, transport, or the fixture's -// durable admission — with the composer already cleared and editable, and the -// durable user/message replaces the echo without a duplicate. The fixture host -// echoes the prompt requestId as the durable source's rpcId, so the retirement -// path here is the production correlation, not a test hook. +// Submission echo over the BUILT client graph (keyless RemoteMock transport): +// a text-plus-image send stays in the read-only composer, with its image rail +// and a busy send control, until the fixture host accepts the prompt; only then +// does the composer clear, and the conversation shows the message once. The +// fixture host echoes the prompt requestId as the durable source's rpcId, so +// the reconciliation here is the production correlation, not a test hook. import { fireEvent, screen, waitFor } from '@testing-library/react' import { expect, it } from 'vitest' import { createAssembledSessionComposer, installAssembledBootEnv, mountAssembledApp } from './assembled-boot.ts' installAssembledBootEnv() -it('paints the submission echo on the send keystroke and swaps it for the durable node', async () => { +it('keeps a send in the composer until the Host accepts it and then shows the message once', async () => { const remote = mountAssembledApp() const composer = await createAssembledSessionComposer(remote) const image = new File([new Uint8Array([137, 80, 78, 71])], 'echoed.png', { type: 'image/png' }) @@ -33,30 +32,32 @@ it('paints the submission echo on the send keystroke and swaps it for the durabl await waitFor(() => { expect(composer.textContent).toBe('回显这条消息') }) fireEvent.keyDown(composer, { key: 'Enter' }) - // Synchronously after the keystroke: the echo bubble is in the flow with - // the draft text and the object-URL preview, while the prompt has not even - // been serialized yet (it starts after a paint yield). The composer is - // already cleared, editable, and free of the rail. - const echo = document.querySelector('[data-submission-echo]') - if (echo === null) throw new Error('submission echo missing on the send keystroke') - expect(echo.textContent).toContain('回显这条消息') - expect(echo.querySelector('img')?.getAttribute('src')?.split(':')[0]).toBe('blob') - expect(composer.textContent).toBe('') - expect(composer.getAttribute('contenteditable')).toBe('true') - expect(document.querySelector('[role="group"][aria-label="Pending attachments"]')).toBeNull() + // Synchronously after the keystroke, before the prompt is even serialized + // (it starts after a paint yield): the draft and its image stay in the + // read-only composer behind a busy send control, and the conversation shows + // nothing yet. + expect(document.querySelector('[data-submission-echo]')).toBeNull() + expect(composer.textContent).toBe('回显这条消息') + expect(composer.getAttribute('contenteditable')).toBe('false') + expect(document.querySelector('[role="group"][aria-label="Pending attachments"] img')).not.toBeNull() + expect(screen.getByRole('button', { name: 'Sending message' }).getAttribute('aria-busy')).toBe('true') - // The fixture's durable user/message (source.rpcId echoes the prompt - // requestId) replaces the echo: one bubble, no marker left, and the image - // now renders from the durable gallery. + // The Host accepts the prompt: the composer clears and becomes editable + // again, its rail is gone, and the durable user/message (source.rpcId + // echoes the prompt requestId) is the one bubble, its image rendering from + // the durable gallery. + await waitFor(() => { + expect(composer.textContent).toBe('') + expect(composer.getAttribute('contenteditable')).toBe('true') + expect(document.querySelector('[role="group"][aria-label="Pending attachments"]')).toBeNull() + }, { timeout: 10_000 }) await waitFor(() => { if (document.querySelector('[data-submission-echo]') !== null) { throw new Error('submission echo still present after the durable node arrived') } - }, { timeout: 10_000 }) - expect(screen.getAllByText('回显这条消息')).toHaveLength(1) - await waitFor(() => { if (document.querySelector('[data-align="end"] img') === null) { throw new Error('durable user gallery missing') } }, { timeout: 10_000 }) + expect(screen.getAllByText('回显这条消息')).toHaveLength(1) }) diff --git a/apps/web/tests/support.ts b/apps/web/tests/support.ts index ef7d3765c4..953f701fc9 100644 --- a/apps/web/tests/support.ts +++ b/apps/web/tests/support.ts @@ -1,5 +1,5 @@ // Shared plumbing for the web smoke tests (dist location, free port, failure shots). -import { existsSync, mkdirSync } from 'node:fs' +import { existsSync, mkdirSync, readFileSync } from 'node:fs' import { createServer } from 'node:net' import { createRequire } from 'node:module' import { join } from 'node:path' @@ -12,6 +12,17 @@ export const DIST_INDEX = fileURLToPath(new URL('../dist/index.html', import.met export const REPO_ROOT = fileURLToPath(new URL('../../..', import.meta.url)) +/** + * Read the `meta.description` an experimental bundle's plugin page shows for one locale. + * @param bundle - Package directory under `packages/experimental`. + * @param locale - Locale resource name, such as `en` or `zh`. + * @returns The description text from `locale/.json`. + */ +export function experimentalBundleDescription(bundle: string, locale: string): string { + const resource = JSON.parse(readFileSync(join(REPO_ROOT, 'packages/experimental', bundle, 'locale', `${locale}.json`), 'utf8')) as { meta: { description: string } } + return resource.meta.description +} + const installationRequire = createRequire(join(REPO_ROOT, 'apps/cli/package.json')) /** diff --git a/apps/web/tests/trajectory-image-display.expected.e2e.ts b/apps/web/tests/trajectory-image-display.expected.e2e.ts index 2a3ffc9aca..b8da2ed2c0 100644 --- a/apps/web/tests/trajectory-image-display.expected.e2e.ts +++ b/apps/web/tests/trajectory-image-display.expected.e2e.ts @@ -77,6 +77,7 @@ it('renders durable record images in the Trajectory details panel from the share // The virtual ledger needs a measurable viewport; jsdom reports zero // heights, so pin one and neutralize the imperative tail scroll. vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(600) + vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(1000) Object.defineProperty(HTMLElement.prototype, 'scrollTo', { configurable: true, value: () => {}, diff --git a/apps/web/tests/window-drag-coverage.e2e.ts b/apps/web/tests/window-drag-coverage.e2e.ts index b7ff2b15df..cdbb727736 100644 --- a/apps/web/tests/window-drag-coverage.e2e.ts +++ b/apps/web/tests/window-drag-coverage.e2e.ts @@ -374,7 +374,9 @@ describe('web e2e: macOS window drag coverage', () => { { row: 'conversation header', what: 'the blank run right of the view tabs, on the tab strip row', - at: () => [tabs.x + tabs.width + 8, tabs.y + tabs.height / 2], + // The last tab's press target overhangs the tablist by 10px and the + // More launcher starts 20px past it; probe the run between them. + at: () => [tabs.x + tabs.width + 15, tabs.y + tabs.height / 2], drag: true, }, { diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 057a50fbea..62e0e67a61 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -23,7 +23,10 @@ // this client-registered project must not also hold them (one program // cannot see both sides of the cordis Context merges). "exclude": [ + "tests/creation-recommendations.e2e.ts", + "tests/plugin-recommendations.e2e.ts", "tests/japanese-plugin-metadata.e2e.ts", + "tests/additional-locales.e2e.ts", "tests/rich-text-quotes.e2e.ts", "tests/hover-input.e2e.ts", "tests/collapse-timing.e2e.ts", @@ -40,6 +43,7 @@ "tests/composer-shortcuts.e2e.ts", "tests/default-product-isolation.e2e.ts", "tests/diff-context.e2e.ts", + "tests/search-empty-include.e2e.ts", "tests/code-card-layout.e2e.ts", "tests/code-language.snapshot.ts", "tests/scaffold.ts", @@ -91,6 +95,7 @@ "tests/plugin-sticky-motion.e2e.ts", "tests/entry-customization.e2e.ts", "tests/cua-optin.e2e.ts", + "tests/bundle-platform.e2e.ts", "tests/cua-permissions.e2e.ts", "tests/schedule-header.e2e.ts", "tests/schedule-phone.e2e.ts", @@ -149,6 +154,7 @@ "tests/preview-boot.e2e.ts", "tests/seeded-history.e2e.ts", "tests/stats-paged-history.e2e.ts", + "tests/stats-truncated-tooltip.e2e.ts", "tests/sidebar-scrollbar.e2e.ts", "tests/sidebar-title-hover-scroll.e2e.ts", "tests/rail-search-expand.e2e.ts", @@ -169,6 +175,7 @@ "tests/fork-mid-turn.e2e.ts", "tests/message-feedback.e2e.ts", "tests/markdown-images.e2e.ts", + "tests/markdown-image-refresh.e2e.ts", "tests/markdown-file-links.e2e.ts", "tests/user-text-secret-mask.e2e.ts", "tests/reference-composer.e2e.ts", @@ -179,6 +186,7 @@ "tests/markdown-inline-code-links.e2e.ts", "tests/clickable-links-gallery.e2e.ts", "tests/queue-actions.e2e.ts", + "tests/prompt-admission.e2e.ts", "tests/idle-submission-handoff.e2e.ts", "tests/cold-blank-session.e2e.ts", "tests/blank-writer-reuse.e2e.ts", @@ -196,6 +204,7 @@ "tests/feedback-command.e2e.ts", "tests/feedback-release.e2e.ts", "tests/agent-team-panel.e2e.ts", + "tests/client-ui-stats-panel.e2e.ts", "tests/sidebar-right.e2e.ts", "tests/sidebar-terminal.e2e.ts", "tests/startup-auto-selection.e2e.ts", @@ -222,6 +231,7 @@ "tests/chat-long-interactions.e2e.ts", "tests/chat-continuous-conversation.e2e.ts", "tests/composer-tab-geometry.e2e.ts", + "tests/conversation-view-tabs.e2e.ts", "tests/window-drag-coverage.e2e.ts", "tests/complex-history.perf.ts", "tests/pwsh-terminal.e2e.ts", diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index d0463af079..984f53cb20 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -242,8 +242,11 @@ export default defineConfig({ // through its own package.json exports from the importer's directory, and // CSS still rides Vite's pipeline because the client build preset emits it // beside the bundle. Plugin packages never enter this graph; they arrive as - // runtime bundles through the client module system. The remaining alias - // browserizes the vendored Cordis Loader's only Node import. + // runtime bundles through the client module system. The node:module alias + // supports Loader initialization; its filesystem resolver's other Node + // imports must stay default imports for Vite's browser-external stubs. + // Browser boot supplies loader.internal before importing plugin entries, + // so the filesystem resolver is never invoked in the browser. alias: [ { find: /^node:module$/, replacement: src('./src/node-module-stub.ts') }, ], diff --git a/benchmarks/session-open/session-open.worker.ts b/benchmarks/session-open/session-open.worker.ts index 5e0b163aa1..6788e3f382 100644 --- a/benchmarks/session-open/session-open.worker.ts +++ b/benchmarks/session-open/session-open.worker.ts @@ -29,7 +29,8 @@ import SessionTitleService from '@deepseek-ai/dsh-session-title' import * as SessionTurnOutlinePlugin from '@deepseek-ai/dsh-session-turn-outline' import TokenMeter from '@deepseek-ai/dsh-token-meter' // These Host-only adapters have no public Node export and are compiled into the benchmark worker. -import { SessionHistoryController } from '../../packages/api/session-controller/src/history.ts' +import { HistoryController } from '../../packages/api/session-controller/src/history/controller.ts' +import { WebController } from '../../packages/api/session-controller/src/web/controller.ts' import { assertBuiltBenchmarkRuntime } from '../support/built-worker.ts' import { SYNTHETIC_SESSION_ID } from './session-open.constants.ts' @@ -151,7 +152,7 @@ class SessionBenchmarkHost { private constructor( private readonly ctx: Context, private readonly scenario: SessionOpenBenchmarkScenario, - private readonly history: SessionHistoryController | undefined, + private readonly history: WebController | undefined, ) {} static async create(root: string, scenario: SessionOpenBenchmarkScenario): Promise { @@ -165,10 +166,10 @@ class SessionBenchmarkHost { } await installProjectionSet(ctx) await ctx.plugin(JsonlSessionPersistence, { root, compression: 'zstd' }) - let history: SessionHistoryController | undefined + let history: WebController | undefined if (scenario === 'first-history') { new BenchmarkSessionQuery(ctx) - history = new SessionHistoryController(ctx, (observation) => { + history = new WebController(ctx, new HistoryController(ctx), (observation) => { // First-history ends at snapshot delivery; Agent-resume owns live activation and retention. observation[Symbol.dispose]() }) diff --git a/benchmarks/support/scaling-report.ts b/benchmarks/support/scaling-report.ts index 876e197222..6345dde870 100644 --- a/benchmarks/support/scaling-report.ts +++ b/benchmarks/support/scaling-report.ts @@ -102,13 +102,27 @@ function appendRecords(records: readonly (TimingRecord | MemoryRecord)[]): void appendFileSync(RESULTS_PATH, records.map(record => JSON.stringify(record) + '\n').join('')) } -/** Vitest global setup: discard results of an earlier run. */ +/** + * Which invocation of a phased run this process is. + * @returns `first` for the invocation that clears earlier results, `last` for the one that renders the report, and `all` for a single-invocation run. + * @throws If the value is not a known phase. + */ +function reportPhase(): 'first' | 'last' | 'all' { + const raw = process.env.DSH_BENCH_REPORT_PHASE + if (raw === undefined || raw === '' || raw === 'all') return 'all' + if (raw === 'first' || raw === 'last') return raw + throw new Error(`DSH_BENCH_REPORT_PHASE must be "first", "last", or "all", got ${JSON.stringify(raw)}.`) +} + +/** Vitest global setup: discard results of an earlier run unless this phase continues one. */ export function setup(): void { + if (reportPhase() === 'last') return rmSync(REPORT_DIRECTORY, { recursive: true, force: true }) } -/** Vitest global teardown: render the report when any case recorded a timing. */ +/** Vitest global teardown: render the report when a case recorded a timing and this phase owns the report. */ export function teardown(): void { + if (reportPhase() === 'first') return if (!existsSync(RESULTS_PATH)) return const records = readFileSync(RESULTS_PATH, 'utf8').split('\n').filter(line => line !== '').map(line => JSON.parse(line) as TimingRecord | MemoryRecord) const cpuModel = cpus()[0]?.model.trim() ?? 'unknown CPU' diff --git a/docs/api-gateway.i18n.yaml b/docs/api-gateway.i18n.yaml index 6ea6996144..f84e67f384 100644 --- a/docs/api-gateway.i18n.yaml +++ b/docs/api-gateway.i18n.yaml @@ -6,8 +6,8 @@ en: 735eb4f22d5f6f71 zh: 697eef269b133039 /api-gateway/programming-model: - en: 78eb70d6c2ce6608 - zh: 826f0ccc206b7299 + en: 008d81750e966b5d + zh: c31ca07da77ffdcc /api-gateway/component-responsibilities: en: fe382a9bcc768cc2 zh: 78e3d50d59780c3d diff --git a/docs/api-gateway.md b/docs/api-gateway.md index 103822c4aa..e5ccfb7ca6 100644 --- a/docs/api-gateway.md +++ b/docs/api-gateway.md @@ -12,7 +12,7 @@ Business services use `@Remote` or `@RemoteScope` to select the methods exposed `@RemoteScope(key)` first resolves an identity to a scoped Context through `ctx.typert.contexts`, then obtains the service from that Context and invokes the method. It applies when the method itself depends on scoped composition and does not need to receive objects such as `Agent` explicitly. -`@Remote` accepts an export name or `{ name?, mode?, resources? }`, and `@RemoteScope(key, option?)` accepts an export name, as in `@RemoteScope('agent', 'current')` below, or `{ name?, resources? }` as its second argument. `resources` holds per-kind readers that return the identities of the resources one call touches for access control; each reader receives the method's wire arguments as its own parameters, with types inferred from the decorated method. Most methods declare no readers, because the Gateway also reads identities from lookup parameters and scoped Contexts that declare a `resource`, and from the default fields in `typert.resources`; the [Typert subsystem](subsystems/typert.md) owns that order. +`@Remote` accepts an export name or `{ name?, mode?, resources? }`, and `@RemoteScope(key, option?)` accepts an export name, as in `@RemoteScope('agent', 'current')` below, or `{ name?, resources? }` as its second argument. `resources` holds per-kind readers that return the identities of the resources one call touches for access control; each reader receives the method's wire arguments as its own parameters, with types inferred from the decorated method. Most methods declare no readers, because the Gateway also reads identities from lookup parameters and scoped Contexts that declare a `resource`, and from the default fields or resolvers in `typert.resources`; the [Typert subsystem](subsystems/typert.md) owns that order. Services normally extend `TypertRemoteService` so the constructor explicitly binds the Cordis service key and default Remote namespace. A service that already has another base class can instead declare `readonly typertRemote = bindTypertRemote(this, serviceKey)`; both forms leave an inspectable public binding and do not depend on the compiler injecting a symbol into the constructor. diff --git a/docs/api-gateway.zh.md b/docs/api-gateway.zh.md index 8e2df4acbe..fb8201be74 100644 --- a/docs/api-gateway.zh.md +++ b/docs/api-gateway.zh.md @@ -14,7 +14,7 @@ `@RemoteScope(key)` 表示先通过 `ctx.typert.contexts` 把 identity 解析为一个作用域 Context,再从该 Context 取得服务并调用方法。它适用于方法本身依赖作用域组合、而不需要显式接收 `Agent` 等对象的情形。 -`@Remote` 接受导出名或 `{ name?, mode?, resources? }`;`@RemoteScope(key, option?)` 的第二个参数接受导出名(如下文的 `@RemoteScope('agent', 'current')`)或 `{ name?, resources? }`。`resources` 按资源种类给出读取函数,返回一次调用所访问资源的身份,供访问控制使用;每个读取函数以方法的 wire 参数作为自身参数,类型从被装饰方法推断。多数方法不声明读取函数,因为 Gateway 还会从声明了 `resource` 的 lookup 参数与作用域 Context 以及 `typert.resources` 中的默认字段读取身份;[Typert 子系统](subsystems/typert.zh.md)负责该顺序。 +`@Remote` 接受导出名或 `{ name?, mode?, resources? }`;`@RemoteScope(key, option?)` 的第二个参数接受导出名(如下文的 `@RemoteScope('agent', 'current')`)或 `{ name?, resources? }`。`resources` 按资源种类给出读取函数,返回一次调用所访问资源的身份,供访问控制使用;每个读取函数以方法的 wire 参数作为自身参数,类型从被装饰方法推断。多数方法不声明读取函数,因为 Gateway 还会从声明了 `resource` 的 lookup 参数与作用域 Context 以及 `typert.resources` 中的默认字段或 resolver 读取身份;[Typert 子系统](subsystems/typert.zh.md)负责该顺序。 服务通常继承 `TypertRemoteService`,让 Cordis 服务 key 与默认 Remote namespace 在构造器中显式绑定。已有其他基类的服务可以改为声明 `readonly typertRemote = bindTypertRemote(this, serviceKey)`;两种方式都会留下可检查的公开 binding,不依赖编译器向构造函数注入 symbol。 diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index eb4a96bc94..c8543cdc36 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -33,5 +33,5 @@ en: a5bc20c3f2a1b370 zh: 91773a281410b2f4 /deepseek-harness-architecture/where-new-behavior-goes: - en: 9b2eb0539a9cd0d6 - zh: 4f575277b91d4e5c + en: ee73b1861378b099 + zh: 9a182be609485f67 diff --git a/docs/architecture.md b/docs/architecture.md index 93d431ada3..e6bede8d0e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -162,7 +162,7 @@ New behavior attaches to a documented extension point. Changing the loop itself | Add durable session state | extend `SessionEventMap`; render and replay from the log | | Generate session titles | register the sole `ctx.sessionTitle` provider | | Manage a same-session objective | use `ctx.goals`; continue through `agent/*` | -| Fork a session at a turn boundary | `ctx.agents.create({ sessionId, seed, meta: { parentSession, seedLength } })` — only agent-loop-published sessions persist | +| Fork at a turn boundary | `ctx.agents.create({ sessionId, seed, inheritedEventCount, meta: { isSeeded: true } })` — only agent-loop-published sessions persist | | Store sessions in a new backend | implement `SessionPersistence` (`create`/`open`/`stat`/`list`/`export`) over the shared handle scaffolding | | Scope a registration to one agent | use that agent's `agent.ctx` | diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 687bf69911..8863c8047c 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -166,7 +166,7 @@ seam 正是替换一个提供方就能改变整个产品的原因。文件系统 | 添加持久会话状态 | 扩展 `SessionEventMap`;从日志渲染和回放 | | 生成会话标题 | 注册唯一的 `ctx.sessionTitle` 提供方 | | 管理同会话目标 | 使用 `ctx.goals`;通过 `agent/*` 续跑 | -| 在轮次边界 fork 会话 | `ctx.agents.create({ sessionId, seed, meta: { parentSession, seedLength } })`——只有经 agent-loop 发布的会话才会持久化 | +| 在轮次边界 fork 会话 | `ctx.agents.create({ sessionId, seed, inheritedEventCount, meta: { isSeeded: true } })`——只有经 agent-loop 发布的会话才会持久化 | | 在新后端存储会话 | 基于共享的句柄脚手架实现 `SessionPersistence`(`create`/`open`/`stat`/`list`/`export`) | | 将注册项限定到单个 agent | 使用该 agent 的 `agent.ctx` | diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index e2cd201a0d..fba6972189 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: f2546ac3454d220d - zh: 642a473c0405e81f + en: 506d61dfa8c71186 + zh: 46f05c4ef2f5c322 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 07f93f002f..d28f3f3aee 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -7,6 +7,13 @@ A service can be a core spine service, a swappable capability seam, a bundle/com ```mermaid flowchart LR + pkg_action_cards["action-cards"] + svc_actionCards["ctx.actionCards
Optional action cards"] + pkg_creation_recommendations["creation-recommendations"] + pkg_client_ui_action_cards["client-ui-action-cards"] + pkg_plugin_recommendations["plugin-recommendations"] + svc_pluginRecommendations["ctx.pluginRecommendations
Explicit-need plugin recommendations"] + pkg_client_ui_plugin_recommendations["client-ui-plugin-recommendations"] pkg_headless["headless"] svc_headlessStartup["ctx.headlessStartup
Headless invocation options"] pkg_experimental_client_ui_cot_translation["experimental-client-ui-cot-translation"] @@ -298,6 +305,7 @@ flowchart LR pkg_cordis_host_runner["cordis-host-runner"] svc_dynamicCordisRunner["ctx.dynamicCordisRunner
Dynamic Cordis package host runner"] svc_cordisInspect["ctx.cordisInspect
Dynamic Cordis inspect registry"] + pkg_action_cards --> svc_actionCards pkg_agent --> svc_agents pkg_agent_default_model --> svc_agentDefaultModel pkg_agent_loop --> svc_agentLoop @@ -388,6 +396,7 @@ flowchart LR pkg_plugin_manager --> svc_pluginManager pkg_plugin_market --> svc_pluginMarket pkg_plugin_package_inventory_deepseek --> svc_deepseekLlmApiExtensions + pkg_plugin_recommendations --> svc_pluginRecommendations pkg_ptc_runtime --> svc_ptcRuntime pkg_ptc_runtime_node --> svc_ptcRuntime pkg_pwsh_local --> svc_shell @@ -457,6 +466,8 @@ flowchart LR pkg_working_directory --> svc_workingDirectory pkg_workspace --> svc_workspaceRegistry pkg_workspace_changes --> svc_workspaceChanges + svc_actionCards --> pkg_client_ui_action_cards + svc_actionCards --> pkg_creation_recommendations svc_agentDefaultModel --> pkg_api_session_controller svc_agentDefaultModel --> pkg_headless svc_agentLoop --> pkg_base @@ -515,6 +526,7 @@ flowchart LR svc_pluginManager --> pkg_ui_settings_plugin_inventory svc_pluginMarket --> pkg_client_ui_plugin_market svc_pluginMarket --> pkg_plugin_market + svc_pluginRecommendations --> pkg_client_ui_plugin_recommendations svc_pluginRegistryProbe --> pkg_client_ui_plugin_manager svc_profileContext --> pkg_plugin_manager svc_ptcRuntime --> pkg_tool_executor_ptc @@ -619,6 +631,8 @@ flowchart LR | ctx key | Role | Owner | Implementations | Direct consumers | Companion plugins | Note | | --- | --- | --- | --- | --- | --- | --- | +| `ctx.actionCards` | `service` | [`action-cards`](../packages/experimental/action-cards) | - | [`creation-recommendations`](../packages/experimental/creation-recommendations), [`client-ui-action-cards`](../packages/experimental/client-ui-action-cards) | - | Owns the card tool, card state, user actions and status notices; card kinds register their actions and handlers. | +| `ctx.pluginRecommendations` | `service` | [`plugin-recommendations`](../packages/experimental/plugin-recommendations) | - | [`client-ui-plugin-recommendations`](../packages/experimental/client-ui-plugin-recommendations) | - | Reads the current catalog text of an official plugin card and enables the plugin through the profile plugin manager after a click. | | `ctx.headlessStartup` | `core` | [`headless`](../packages/bundle/headless) | - | [`headless`](../packages/bundle/headless) | - | Supplies parsed task and run options to the headless runner and its sandbox-policy configuration. | | `ctx.cotTranslation` | `service` | [`experimental-client-ui-cot-translation`](../packages/experimental/client-ui-cot-translation) | - | - | - | Serves reasoning translations, reuses saved results, and joins ordinary Session activation for uncached inactive Sessions. | | `ctx.translator` | `service` | [`experimental-translator`](../packages/experimental/translator) | - | [`experimental-client-ui-cot-translation`](../packages/experimental/client-ui-cot-translation) | - | Resolves Google or Bing requests and retains shared experimental records through the active Session writer. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index 1b10ace20d..8a2963f3cc 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -9,6 +9,13 @@ ```mermaid flowchart LR + pkg_action_cards["action-cards"] + svc_actionCards["ctx.actionCards
Optional action cards"] + pkg_creation_recommendations["creation-recommendations"] + pkg_client_ui_action_cards["client-ui-action-cards"] + pkg_plugin_recommendations["plugin-recommendations"] + svc_pluginRecommendations["ctx.pluginRecommendations
Explicit-need plugin recommendations"] + pkg_client_ui_plugin_recommendations["client-ui-plugin-recommendations"] pkg_headless["headless"] svc_headlessStartup["ctx.headlessStartup
Headless invocation options"] pkg_experimental_client_ui_cot_translation["experimental-client-ui-cot-translation"] @@ -300,6 +307,7 @@ flowchart LR pkg_cordis_host_runner["cordis-host-runner"] svc_dynamicCordisRunner["ctx.dynamicCordisRunner
Dynamic Cordis package host runner"] svc_cordisInspect["ctx.cordisInspect
Dynamic Cordis inspect registry"] + pkg_action_cards --> svc_actionCards pkg_agent --> svc_agents pkg_agent_default_model --> svc_agentDefaultModel pkg_agent_loop --> svc_agentLoop @@ -390,6 +398,7 @@ flowchart LR pkg_plugin_manager --> svc_pluginManager pkg_plugin_market --> svc_pluginMarket pkg_plugin_package_inventory_deepseek --> svc_deepseekLlmApiExtensions + pkg_plugin_recommendations --> svc_pluginRecommendations pkg_ptc_runtime --> svc_ptcRuntime pkg_ptc_runtime_node --> svc_ptcRuntime pkg_pwsh_local --> svc_shell @@ -459,6 +468,8 @@ flowchart LR pkg_working_directory --> svc_workingDirectory pkg_workspace --> svc_workspaceRegistry pkg_workspace_changes --> svc_workspaceChanges + svc_actionCards --> pkg_client_ui_action_cards + svc_actionCards --> pkg_creation_recommendations svc_agentDefaultModel --> pkg_api_session_controller svc_agentDefaultModel --> pkg_headless svc_agentLoop --> pkg_base @@ -517,6 +528,7 @@ flowchart LR svc_pluginManager --> pkg_ui_settings_plugin_inventory svc_pluginMarket --> pkg_client_ui_plugin_market svc_pluginMarket --> pkg_plugin_market + svc_pluginRecommendations --> pkg_client_ui_plugin_recommendations svc_pluginRegistryProbe --> pkg_client_ui_plugin_manager svc_profileContext --> pkg_plugin_manager svc_ptcRuntime --> pkg_tool_executor_ptc @@ -621,6 +633,8 @@ flowchart LR | ctx 键 | 角色 | 所属包 | 实现 | 直接消费方 | 配套插件 | 说明 | | --- | --- | --- | --- | --- | --- | --- | +| `ctx.actionCards` | `service` | [`action-cards`](../packages/experimental/action-cards) | - | [`creation-recommendations`](../packages/experimental/creation-recommendations), [`client-ui-action-cards`](../packages/experimental/client-ui-action-cards) | - | 负责卡片工具、卡片状态、用户操作和状态通知;各卡片种类注册自己的动作和处理器。 | +| `ctx.pluginRecommendations` | `service` | [`plugin-recommendations`](../packages/experimental/plugin-recommendations) | - | [`client-ui-plugin-recommendations`](../packages/experimental/client-ui-plugin-recommendations) | - | 读取官方插件卡片的当前目录文本,并在用户点击后通过配置插件管理器启用该插件。 | | `ctx.headlessStartup` | `core` | [`headless`](../packages/bundle/headless) | - | [`headless`](../packages/bundle/headless) | - | 将解析后的任务和运行选项提供给无界面运行器及其 sandbox-policy 配置。 | | `ctx.cotTranslation` | `service` | [`experimental-client-ui-cot-translation`](../packages/experimental/client-ui-cot-translation) | - | - | - | 为展开的思考内容提供有界的 Session 翻译请求,不改变模型可见历史。 | | `ctx.translator` | `service` | [`experimental-translator`](../packages/experimental/translator) | - | [`experimental-client-ui-cot-translation`](../packages/experimental/client-ui-cot-translation) | - | 解析 Google 或 Bing 请求,并可选保留统一的实验性 Session 记录。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index c63ec5617e..3f9f9f8e80 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -33,6 +33,21 @@ export interface AcpConfig { ``` + + + +## `@deepseek-ai/dsh-action-cards` + +- `inject`: `tools` · `agents` · `sessionProjections` · `remoteAccess` +- `refs`: `z` (`zod`) +- `source`: [`packages/experimental/action-cards/src/index.ts:23`](../packages/experimental/action-cards/src/index.ts) + +```ts config-catalog +/** Validated card limits after schema defaults. */ +export type Config = z.infer +``` + + @@ -188,7 +203,7 @@ export interface Config { ## `@deepseek-ai/dsh-api-gateway` - `inject`: `typert` · `remoteAccess` -- `source`: [`packages/api/gateway/src/index.ts:156`](../packages/api/gateway/src/index.ts) +- `source`: [`packages/api/gateway/src/index.ts:158`](../packages/api/gateway/src/index.ts) ```ts config-catalog /** Gateway transport configuration. */ @@ -227,8 +242,8 @@ export interface Config { ## `@deepseek-ai/dsh-api-session-controller` -- `inject`: `agentDefaultModel` · `agents` · `attachments` · `fileUploads` · `fs` · `llm` · `remoteAccess` · `sessions` · `sessionProjections` · `sessionQuery` · `typert` · `workspaceRegistry` -- `source`: [`packages/api/session-controller/src/index.ts:93`](../packages/api/session-controller/src/index.ts) +- `inject`: `agentDefaultModel` · `agents` · `attachments` · `fileUploads` · `fs` · `llm` · `remoteAccess` · `sessions` · `sessionProjections` · `sessionQuery` · `typert` · `typertGateway` · `workspaceRegistry` +- `source`: [`packages/api/session-controller/src/index.ts:110`](../packages/api/session-controller/src/index.ts) ```ts config-catalog /** Session Controller deployment policy. */ @@ -1791,25 +1806,15 @@ export interface Config { ## `@deepseek-ai/dsh-llm-deepseek-account` - `inject`: `llm` -- `refs`: [`DeepSeekCatalogModel`](../packages/llm/llm-deepseek/src/index.ts) · [`ProtocolConfig`](../packages/llm/llm-deepseek/src/index.ts) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/llm/llm-deepseek-account/src/config.ts:19`](../packages/llm/llm-deepseek-account/src/config.ts) +- `refs`: [`ModelListingConfig`](../packages/llm/llm-deepseek/src/index.ts) · [`ModelOverride`](../packages/llm/llm-deepseek/src/index.ts) · [`ProtocolConfig`](../packages/llm/llm-deepseek/src/index.ts) · `Volatile` (`@deepseek-ai/cordis`) +- `source`: [`packages/llm/llm-deepseek-account/src/config.ts:15`](../packages/llm/llm-deepseek-account/src/config.ts) ```ts config-catalog /** Account route configuration; authentication comes exclusively from the account service. */ -export interface Config extends Omit { - /** Deadline of one listing request, which also bounds a first-use wait (default five seconds). */ - modelsTimeoutMs: Volatile - /** - * Listing age after which the next access refreshes it in the background; - * a failed load retries after the same age (default ten minutes). - */ - modelsMaxAgeMs: Volatile +export interface Config extends Omit, ModelListingConfig { /** Field overrides by model id, layered over the account listing and the built-in catalog. */ modelOverrides: Volatile> } - -/** Field overrides for one model; unset fields and empty lists inherit the underlying entry. */ -export type ModelOverride = Omit ``` @@ -1819,12 +1824,12 @@ export type ModelOverride = Omit ## `@deepseek-ai/dsh-llm-deepseek-api-key` - `inject`: `llm` -- `refs`: [`ProtocolConfig`](../packages/llm/llm-deepseek/src/index.ts) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/llm/llm-deepseek-api-key/src/config.ts:10`](../packages/llm/llm-deepseek-api-key/src/config.ts) +- `refs`: [`ModelListingConfig`](../packages/llm/llm-deepseek/src/index.ts) · [`ProtocolConfig`](../packages/llm/llm-deepseek/src/index.ts) · `Volatile` (`@deepseek-ai/cordis`) +- `source`: [`packages/llm/llm-deepseek-api-key/src/config.ts:18`](../packages/llm/llm-deepseek-api-key/src/config.ts) ```ts config-catalog /** Messages configuration with a per-request API-key reference. */ -export interface Config extends ProtocolConfig { +export interface Config extends ProtocolConfig, ModelListingConfig { /** Credential reference resolved per request; defaults to DEEPSEEK_API_KEY. */ apiKeyEnv: Volatile } @@ -2485,7 +2490,7 @@ export interface PlanModeConfig { - `inject`: `loader` · `profileContext` - `refs`: [`NpmFileSource`](subsystems/boot.md) -- `source`: [`packages/boot/plugin-manager/src/index.ts:52`](../packages/boot/plugin-manager/src/index.ts) +- `source`: [`packages/boot/plugin-manager/src/index.ts:54`](../packages/boot/plugin-manager/src/index.ts) ```ts config-catalog /** The pnpm executable, registries, and limits for diagnostics, lookups and connection checks. */ @@ -2598,8 +2603,10 @@ export interface Config { export interface Config { /** Worker invocation in the subprocess world; omitted selects the local carrier. */ launch?: LaunchConfig - /** per-call starts fresh processes; persistent-in-memory retains a REPL per owner under the same file policy. */ - executionMode?: 'per-call' | 'persistent-in-memory' + /** per-call uses fresh async function bodies; vm-script uses VM contexts; persistent-in-memory retains a REPL per owner. */ + executionMode?: 'per-call' | 'persistent-in-memory' | 'vm-script' + /** Retain a Script process and context per stateOwner; only supported with executionMode: vm-script. */ + scriptPersistence?: boolean /** Default elapsed deadline, including nested tool and approval waits. */ timeoutMs?: number /** Maximum numeric elapsed budget accepted by resolve. */ @@ -3737,7 +3744,7 @@ export type ShellDialect = 'bash' | 'pwsh' ## `@deepseek-ai/dsh-time-context` - `inject`: `agents` · `sessionProjections` -- `source`: [`packages/context/time-context/src/index.ts:47`](../packages/context/time-context/src/index.ts) +- `source`: [`packages/context/time-context/src/index.ts:52`](../packages/context/time-context/src/index.ts) ```ts config-catalog /** Request-preparation clock formatting and append scheduling. Invalid values fail plugin load. */ @@ -3836,7 +3843,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-bash-persistent` - `inject`: `tools` · `terminals` · `workingDirectory` -- `source`: [`packages/shell/tool-bash-persistent/src/index.ts:445`](../packages/shell/tool-bash-persistent/src/index.ts) +- `source`: [`packages/shell/tool-bash-persistent/src/index.ts:447`](../packages/shell/tool-bash-persistent/src/index.ts) ```ts config-catalog /** Configuration for the persistent Bash tool. */ @@ -4139,7 +4146,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-skill` - `inject`: `agents` · `tools` · `skills` · `workingDirectory` -- `source`: [`packages/skill/tool-skill/src/index.ts:62`](../packages/skill/tool-skill/src/index.ts) +- `source`: [`packages/skill/tool-skill/src/index.ts:64`](../packages/skill/tool-skill/src/index.ts) ```ts config-catalog /** Model-facing skill catalog configuration. */ @@ -4372,7 +4379,8 @@ export interface Config { ## `@deepseek-ai/dsh-user-approval` -- `source`: [`packages/interaction/user-approval/src/index.ts:135`](../packages/interaction/user-approval/src/index.ts) +- `inject`: `sessionProjections` +- `source`: [`packages/interaction/user-approval/src/index.ts:152`](../packages/interaction/user-approval/src/index.ts) ```ts config-catalog /** Plugin config. All optional — `static Config` supplies the defaults. */ @@ -4700,6 +4708,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-client-locale` | — | [`packages/client/locale/src/index.ts`](../packages/client/locale/src/index.ts) | | `@deepseek-ai/dsh-client-modules` | `loader` | [`packages/client/modules/src/index.ts`](../packages/client/modules/src/index.ts) | | `@deepseek-ai/dsh-client-resources` | — | [`packages/client/resources/src/index.ts`](../packages/client/resources/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-action-cards` | — | [`packages/experimental/client-ui-action-cards/src/index.ts`](../packages/experimental/client-ui-action-cards/src/index.ts) | | `@deepseek-ai/dsh-client-ui-agent-preset` | — | [`packages/client/ui-agent-preset/src/index.ts`](../packages/client/ui-agent-preset/src/index.ts) | | `@deepseek-ai/dsh-client-ui-approval` | — | [`packages/client/ui-approval/src/index.ts`](../packages/client/ui-approval/src/index.ts) | | `@deepseek-ai/dsh-client-ui-attachment` | — | [`packages/client/ui-attachment/src/index.ts`](../packages/client/ui-attachment/src/index.ts) | @@ -4708,6 +4717,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-client-ui-commands` | — | [`packages/client/ui-commands/src/index.ts`](../packages/client/ui-commands/src/index.ts) | | `@deepseek-ai/dsh-client-ui-conversation` | — | [`packages/client/ui-conversation/src/index.ts`](../packages/client/ui-conversation/src/index.ts) | | `@deepseek-ai/dsh-client-ui-cordis` | — | [`packages/extensions/ui-cordis/src/index.ts`](../packages/extensions/ui-cordis/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-creation-recommendations` | — | [`packages/experimental/client-ui-creation-recommendations/src/index.ts`](../packages/experimental/client-ui-creation-recommendations/src/index.ts) | | `@deepseek-ai/dsh-client-ui-deepseek-model-label-1017` | — | [`packages/client/ui-deepseek-model-label-1017/src/index.ts`](../packages/client/ui-deepseek-model-label-1017/src/index.ts) | | `@deepseek-ai/dsh-client-ui-deliverables` | `connection` · `sessionQuery` · `sessionController` · `workspaceFiles` · `fs` · `sandboxPolicy` · `workspaceChanges` | [`packages/client/ui-deliverables/src/index.ts`](../packages/client/ui-deliverables/src/index.ts) | | `@deepseek-ai/dsh-client-ui-directory-picker-browse` | — | [`packages/client/ui-directory-picker-browse/src/index.ts`](../packages/client/ui-directory-picker-browse/src/index.ts) | @@ -4724,6 +4734,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-client-ui-permission-presets` | — | [`packages/client/ui-permission-presets/src/index.ts`](../packages/client/ui-permission-presets/src/index.ts) | | `@deepseek-ai/dsh-client-ui-plan` | — | [`packages/client/ui-plan/src/index.ts`](../packages/client/ui-plan/src/index.ts) | | `@deepseek-ai/dsh-client-ui-plugin-market` | — | [`packages/client/ui-plugin-market/src/index.ts`](../packages/client/ui-plugin-market/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-plugin-recommendations` | — | [`packages/experimental/client-ui-plugin-recommendations/src/index.ts`](../packages/experimental/client-ui-plugin-recommendations/src/index.ts) | | `@deepseek-ai/dsh-client-ui-reference` | — | [`packages/client/ui-reference/src/index.ts`](../packages/client/ui-reference/src/index.ts) | | `@deepseek-ai/dsh-client-ui-renderer` | — | [`packages/client/ui-renderer/src/index.ts`](../packages/client/ui-renderer/src/index.ts) | | `@deepseek-ai/dsh-client-ui-schedule` | — | [`packages/client/ui-schedule/src/index.ts`](../packages/client/ui-schedule/src/index.ts) | @@ -4759,12 +4770,14 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-computer-use` | — | [`packages/computer-use/computer-use/src/index.ts`](../packages/computer-use/computer-use/src/index.ts) | | `@deepseek-ai/dsh-config-editor` | `loader` · `profileContext` | [`packages/boot/config-editor/src/index.ts`](../packages/boot/config-editor/src/index.ts) | | `@deepseek-ai/dsh-cordis-client-runner` | — | [`packages/extensions/cordis-client-runner/src/index.ts`](../packages/extensions/cordis-client-runner/src/index.ts) | +| `@deepseek-ai/dsh-creation-recommendations` | `tools` · `pluginManager` · `agents` · `subagents` · `profileContext` · `skills` · `actionCards` | [`packages/experimental/creation-recommendations/src/index.ts`](../packages/experimental/creation-recommendations/src/index.ts) | | `@deepseek-ai/dsh-cua` | — | [`packages/experimental/cua/src/index.ts`](../packages/experimental/cua/src/index.ts) | | `@deepseek-ai/dsh-deepseek-llm-api-extensions` | — | [`packages/llm/deepseek-llm-api-extensions/src/index.ts`](../packages/llm/deepseek-llm-api-extensions/src/index.ts) | | `@deepseek-ai/dsh-deliverable-file-references` | `systemPrompt` | [`packages/deliverables/deliverable-file-references/src/index.ts`](../packages/deliverables/deliverable-file-references/src/index.ts) | | `@deepseek-ai/dsh-experimental-auto-review` | `approval` · `llm` · `permissionPresets` · `sessions` · `tools` · `workingDirectory` | [`packages/experimental/auto-review/src/index.ts`](../packages/experimental/auto-review/src/index.ts) | | `@deepseek-ai/dsh-experimental-client-ui-agent-team` | — | [`packages/experimental/client-ui-agent-team/src/index.ts`](../packages/experimental/client-ui-agent-team/src/index.ts) | | `@deepseek-ai/dsh-experimental-client-ui-claude-code-mods` | — | [`packages/experimental/client-ui-claude-code-mods/src/index.ts`](../packages/experimental/client-ui-claude-code-mods/src/index.ts) | +| `@deepseek-ai/dsh-experimental-client-ui-stats` | — | [`packages/experimental/client-ui-stats/src/index.ts`](../packages/experimental/client-ui-stats/src/index.ts) | | `@deepseek-ai/dsh-experimental-client-ui-voice-input` | — | [`packages/experimental/client-ui-voice-input/src/index.ts`](../packages/experimental/client-ui-voice-input/src/index.ts) | | `@deepseek-ai/dsh-experimental-computer-use-cua-driver-native` | `computerUse` · `tools` · `systemPrompt` | [`packages/experimental/computer-use-cua-driver-native/src/index.ts`](../packages/experimental/computer-use-cua-driver-native/src/index.ts) | | `@deepseek-ai/dsh-experimental-session-inspector` | — | [`packages/experimental/session-inspector/src/index.ts`](../packages/experimental/session-inspector/src/index.ts) | @@ -4781,6 +4794,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-mcp-resources` | `tools` | [`packages/mcp/mcp-resources/src/index.ts`](../packages/mcp/mcp-resources/src/index.ts) | | `@deepseek-ai/dsh-message-quotes` | — | [`packages/session/message-quotes/src/index.ts`](../packages/session/message-quotes/src/index.ts) | | `@deepseek-ai/dsh-otel` | — | [`packages/telemetry/otel/src/index.ts`](../packages/telemetry/otel/src/index.ts) | +| `@deepseek-ai/dsh-plugin-recommendations` | `pluginManager` · `agents` · `skills` · `actionCards` | [`packages/experimental/plugin-recommendations/src/index.ts`](../packages/experimental/plugin-recommendations/src/index.ts) | | `@deepseek-ai/dsh-sandbox-ssh` | `ssh` | [`packages/ssh/sandbox-ssh/src/index.ts`](../packages/ssh/sandbox-ssh/src/index.ts) | | `@deepseek-ai/dsh-session` | — | [`packages/core/session/src/index.ts`](../packages/core/session/src/index.ts) | | `@deepseek-ai/dsh-session-checkpoint-policy` | `llm` · `sessionPersistence` · `sessions` · `tools` | [`packages/session/session-checkpoint-policy/src/index.ts`](../packages/session/session-checkpoint-policy/src/index.ts) | @@ -4858,6 +4872,7 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them. | `@deepseek-ai/dsh-experimental-browser-use-runtime` | — | [`packages/experimental/browser-use-runtime/src/index.ts`](../packages/experimental/browser-use-runtime/src/index.ts) | | `@deepseek-ai/dsh-experimental-cot-translation-bundle` | — | [`packages/experimental/cot-translation-bundle/src/index.ts`](../packages/experimental/cot-translation-bundle/src/index.ts) | | `@deepseek-ai/dsh-experimental-inspector-profile` | — | [`packages/experimental/inspector-profile/src/index.ts`](../packages/experimental/inspector-profile/src/index.ts) | +| `@deepseek-ai/dsh-experimental-liveshare-protocol` | — | [`packages/experimental/liveshare-protocol/src/index.ts`](../packages/experimental/liveshare-protocol/src/index.ts) | | `@deepseek-ai/dsh-experimental-plugin-market-bundle` | — | [`packages/experimental/plugin-market-bundle/src/index.ts`](../packages/experimental/plugin-market-bundle/src/index.ts) | | `@deepseek-ai/dsh-experimental-ralph-bundle` | — | [`packages/experimental/ralph-bundle/src/index.ts`](../packages/experimental/ralph-bundle/src/index.ts) | | `@deepseek-ai/dsh-experimental-session-search` | — | [`packages/experimental/session-search/src/index.ts`](../packages/experimental/session-search/src/index.ts) | @@ -4876,9 +4891,10 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them. | `@deepseek-ai/dsh-llm-mock-server` | — | [`packages/test-support/llm-mock-server/src/index.ts`](../packages/test-support/llm-mock-server/src/index.ts) | | `@deepseek-ai/dsh-loader-smoke` | — | [`packages/test-support/loader-smoke/src/index.ts`](../packages/test-support/loader-smoke/src/index.ts) | | `@deepseek-ai/dsh-native-command` | — | [`packages/util/native-command/src/index.ts`](../packages/util/native-command/src/index.ts) | -| `@deepseek-ai/dsh-official-bundles` | — | [`packages/boot/official-bundles/src/index.ts`](../packages/boot/official-bundles/src/index.ts) | +| `@deepseek-ai/dsh-official-bundles` | — | [`packages/util/official-bundles/src/index.ts`](../packages/util/official-bundles/src/index.ts) | | `@deepseek-ai/dsh-output-retention` | — | [`packages/util/output-retention/src/index.ts`](../packages/util/output-retention/src/index.ts) | | `@deepseek-ai/dsh-package-manifest` | — | [`packages/util/package-manifest/src/index.ts`](../packages/util/package-manifest/src/index.ts) | +| `@deepseek-ai/dsh-personalized-recommendations` | — | [`packages/experimental/personalized-recommendations/src/index.ts`](../packages/experimental/personalized-recommendations/src/index.ts) | | `@deepseek-ai/dsh-plugin-detail` | — | [`packages/util/plugin-detail/src/index.ts`](../packages/util/plugin-detail/src/index.ts) | | `@deepseek-ai/dsh-plugin-market-index` | — | [`packages/util/plugin-market-index/src/index.ts`](../packages/util/plugin-market-index/src/index.ts) | | `@deepseek-ai/dsh-remote-mock` | — | [`packages/test-support/remote-mock/src/index.ts`](../packages/test-support/remote-mock/src/index.ts) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index e175b68f41..16859b173e 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -35,6 +35,21 @@ export interface AcpConfig { ``` + + + +## `@deepseek-ai/dsh-action-cards` + +- `inject`: `tools` · `agents` · `sessionProjections` · `remoteAccess` +- `refs`: `z` (`zod`) +- `source`: [`packages/experimental/action-cards/src/index.ts:23`](../packages/experimental/action-cards/src/index.ts) + +```ts config-catalog +/** Validated card limits after schema defaults. */ +export type Config = z.infer +``` + + @@ -190,7 +205,7 @@ export interface Config { ## `@deepseek-ai/dsh-api-gateway` - `inject`: `typert` · `remoteAccess` -- `source`: [`packages/api/gateway/src/index.ts:156`](../packages/api/gateway/src/index.ts) +- `source`: [`packages/api/gateway/src/index.ts:158`](../packages/api/gateway/src/index.ts) ```ts config-catalog /** Gateway transport configuration. */ @@ -229,8 +244,8 @@ export interface Config { ## `@deepseek-ai/dsh-api-session-controller` -- `inject`: `agentDefaultModel` · `agents` · `attachments` · `fileUploads` · `fs` · `llm` · `remoteAccess` · `sessions` · `sessionProjections` · `sessionQuery` · `typert` · `workspaceRegistry` -- `source`: [`packages/api/session-controller/src/index.ts:93`](../packages/api/session-controller/src/index.ts) +- `inject`: `agentDefaultModel` · `agents` · `attachments` · `fileUploads` · `fs` · `llm` · `remoteAccess` · `sessions` · `sessionProjections` · `sessionQuery` · `typert` · `typertGateway` · `workspaceRegistry` +- `source`: [`packages/api/session-controller/src/index.ts:110`](../packages/api/session-controller/src/index.ts) ```ts config-catalog /** Session Controller deployment policy. */ @@ -1793,25 +1808,15 @@ export interface Config { ## `@deepseek-ai/dsh-llm-deepseek-account` - `inject`: `llm` -- `refs`: [`DeepSeekCatalogModel`](../packages/llm/llm-deepseek/src/index.ts) · [`ProtocolConfig`](../packages/llm/llm-deepseek/src/index.ts) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/llm/llm-deepseek-account/src/config.ts:19`](../packages/llm/llm-deepseek-account/src/config.ts) +- `refs`: [`ModelListingConfig`](../packages/llm/llm-deepseek/src/index.ts) · [`ModelOverride`](../packages/llm/llm-deepseek/src/index.ts) · [`ProtocolConfig`](../packages/llm/llm-deepseek/src/index.ts) · `Volatile` (`@deepseek-ai/cordis`) +- `source`: [`packages/llm/llm-deepseek-account/src/config.ts:15`](../packages/llm/llm-deepseek-account/src/config.ts) ```ts config-catalog /** Account route configuration; authentication comes exclusively from the account service. */ -export interface Config extends Omit { - /** Deadline of one listing request, which also bounds a first-use wait (default five seconds). */ - modelsTimeoutMs: Volatile - /** - * Listing age after which the next access refreshes it in the background; - * a failed load retries after the same age (default ten minutes). - */ - modelsMaxAgeMs: Volatile +export interface Config extends Omit, ModelListingConfig { /** Field overrides by model id, layered over the account listing and the built-in catalog. */ modelOverrides: Volatile> } - -/** Field overrides for one model; unset fields and empty lists inherit the underlying entry. */ -export type ModelOverride = Omit ``` @@ -1821,12 +1826,12 @@ export type ModelOverride = Omit ## `@deepseek-ai/dsh-llm-deepseek-api-key` - `inject`: `llm` -- `refs`: [`ProtocolConfig`](../packages/llm/llm-deepseek/src/index.ts) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/llm/llm-deepseek-api-key/src/config.ts:10`](../packages/llm/llm-deepseek-api-key/src/config.ts) +- `refs`: [`ModelListingConfig`](../packages/llm/llm-deepseek/src/index.ts) · [`ProtocolConfig`](../packages/llm/llm-deepseek/src/index.ts) · `Volatile` (`@deepseek-ai/cordis`) +- `source`: [`packages/llm/llm-deepseek-api-key/src/config.ts:18`](../packages/llm/llm-deepseek-api-key/src/config.ts) ```ts config-catalog /** Messages configuration with a per-request API-key reference. */ -export interface Config extends ProtocolConfig { +export interface Config extends ProtocolConfig, ModelListingConfig { /** Credential reference resolved per request; defaults to DEEPSEEK_API_KEY. */ apiKeyEnv: Volatile } @@ -2487,7 +2492,7 @@ export interface PlanModeConfig { - `inject`: `loader` · `profileContext` - `refs`: [`NpmFileSource`](subsystems/boot.zh.md) -- `source`: [`packages/boot/plugin-manager/src/index.ts:52`](../packages/boot/plugin-manager/src/index.ts) +- `source`: [`packages/boot/plugin-manager/src/index.ts:54`](../packages/boot/plugin-manager/src/index.ts) ```ts config-catalog /** The pnpm executable, registries, and limits for diagnostics, lookups and connection checks. */ @@ -2600,8 +2605,10 @@ export interface Config { export interface Config { /** Worker invocation in the subprocess world; omitted selects the local carrier. */ launch?: LaunchConfig - /** per-call starts fresh processes; persistent-in-memory retains a REPL per owner under the same file policy. */ - executionMode?: 'per-call' | 'persistent-in-memory' + /** per-call uses fresh async function bodies; vm-script uses VM contexts; persistent-in-memory retains a REPL per owner. */ + executionMode?: 'per-call' | 'persistent-in-memory' | 'vm-script' + /** Retain a Script process and context per stateOwner; only supported with executionMode: vm-script. */ + scriptPersistence?: boolean /** Default elapsed deadline, including nested tool and approval waits. */ timeoutMs?: number /** Maximum numeric elapsed budget accepted by resolve. */ @@ -3739,7 +3746,7 @@ export type ShellDialect = 'bash' | 'pwsh' ## `@deepseek-ai/dsh-time-context` - `inject`: `agents` · `sessionProjections` -- `source`: [`packages/context/time-context/src/index.ts:47`](../packages/context/time-context/src/index.ts) +- `source`: [`packages/context/time-context/src/index.ts:52`](../packages/context/time-context/src/index.ts) ```ts config-catalog /** Request-preparation clock formatting and append scheduling. Invalid values fail plugin load. */ @@ -3838,7 +3845,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-bash-persistent` - `inject`: `tools` · `terminals` · `workingDirectory` -- `source`: [`packages/shell/tool-bash-persistent/src/index.ts:445`](../packages/shell/tool-bash-persistent/src/index.ts) +- `source`: [`packages/shell/tool-bash-persistent/src/index.ts:447`](../packages/shell/tool-bash-persistent/src/index.ts) ```ts config-catalog /** Configuration for the persistent Bash tool. */ @@ -4141,7 +4148,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-skill` - `inject`: `agents` · `tools` · `skills` · `workingDirectory` -- `source`: [`packages/skill/tool-skill/src/index.ts:62`](../packages/skill/tool-skill/src/index.ts) +- `source`: [`packages/skill/tool-skill/src/index.ts:64`](../packages/skill/tool-skill/src/index.ts) ```ts config-catalog /** Model-facing skill catalog configuration. */ @@ -4374,7 +4381,8 @@ export interface Config { ## `@deepseek-ai/dsh-user-approval` -- `source`: [`packages/interaction/user-approval/src/index.ts:135`](../packages/interaction/user-approval/src/index.ts) +- `inject`: `sessionProjections` +- `source`: [`packages/interaction/user-approval/src/index.ts:152`](../packages/interaction/user-approval/src/index.ts) ```ts config-catalog /** Plugin config. All optional — `static Config` supplies the defaults. */ @@ -4702,6 +4710,7 @@ export interface Config { | `@deepseek-ai/dsh-client-locale` | — | [`packages/client/locale/src/index.ts`](../packages/client/locale/src/index.ts) | | `@deepseek-ai/dsh-client-modules` | `loader` | [`packages/client/modules/src/index.ts`](../packages/client/modules/src/index.ts) | | `@deepseek-ai/dsh-client-resources` | — | [`packages/client/resources/src/index.ts`](../packages/client/resources/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-action-cards` | — | [`packages/experimental/client-ui-action-cards/src/index.ts`](../packages/experimental/client-ui-action-cards/src/index.ts) | | `@deepseek-ai/dsh-client-ui-agent-preset` | — | [`packages/client/ui-agent-preset/src/index.ts`](../packages/client/ui-agent-preset/src/index.ts) | | `@deepseek-ai/dsh-client-ui-approval` | — | [`packages/client/ui-approval/src/index.ts`](../packages/client/ui-approval/src/index.ts) | | `@deepseek-ai/dsh-client-ui-attachment` | — | [`packages/client/ui-attachment/src/index.ts`](../packages/client/ui-attachment/src/index.ts) | @@ -4710,6 +4719,7 @@ export interface Config { | `@deepseek-ai/dsh-client-ui-commands` | — | [`packages/client/ui-commands/src/index.ts`](../packages/client/ui-commands/src/index.ts) | | `@deepseek-ai/dsh-client-ui-conversation` | — | [`packages/client/ui-conversation/src/index.ts`](../packages/client/ui-conversation/src/index.ts) | | `@deepseek-ai/dsh-client-ui-cordis` | — | [`packages/extensions/ui-cordis/src/index.ts`](../packages/extensions/ui-cordis/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-creation-recommendations` | — | [`packages/experimental/client-ui-creation-recommendations/src/index.ts`](../packages/experimental/client-ui-creation-recommendations/src/index.ts) | | `@deepseek-ai/dsh-client-ui-deepseek-model-label-1017` | — | [`packages/client/ui-deepseek-model-label-1017/src/index.ts`](../packages/client/ui-deepseek-model-label-1017/src/index.ts) | | `@deepseek-ai/dsh-client-ui-deliverables` | `connection` · `sessionQuery` · `sessionController` · `workspaceFiles` · `fs` · `sandboxPolicy` · `workspaceChanges` | [`packages/client/ui-deliverables/src/index.ts`](../packages/client/ui-deliverables/src/index.ts) | | `@deepseek-ai/dsh-client-ui-directory-picker-browse` | — | [`packages/client/ui-directory-picker-browse/src/index.ts`](../packages/client/ui-directory-picker-browse/src/index.ts) | @@ -4726,6 +4736,7 @@ export interface Config { | `@deepseek-ai/dsh-client-ui-permission-presets` | — | [`packages/client/ui-permission-presets/src/index.ts`](../packages/client/ui-permission-presets/src/index.ts) | | `@deepseek-ai/dsh-client-ui-plan` | — | [`packages/client/ui-plan/src/index.ts`](../packages/client/ui-plan/src/index.ts) | | `@deepseek-ai/dsh-client-ui-plugin-market` | — | [`packages/client/ui-plugin-market/src/index.ts`](../packages/client/ui-plugin-market/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-plugin-recommendations` | — | [`packages/experimental/client-ui-plugin-recommendations/src/index.ts`](../packages/experimental/client-ui-plugin-recommendations/src/index.ts) | | `@deepseek-ai/dsh-client-ui-reference` | — | [`packages/client/ui-reference/src/index.ts`](../packages/client/ui-reference/src/index.ts) | | `@deepseek-ai/dsh-client-ui-renderer` | — | [`packages/client/ui-renderer/src/index.ts`](../packages/client/ui-renderer/src/index.ts) | | `@deepseek-ai/dsh-client-ui-schedule` | — | [`packages/client/ui-schedule/src/index.ts`](../packages/client/ui-schedule/src/index.ts) | @@ -4761,12 +4772,14 @@ export interface Config { | `@deepseek-ai/dsh-computer-use` | — | [`packages/computer-use/computer-use/src/index.ts`](../packages/computer-use/computer-use/src/index.ts) | | `@deepseek-ai/dsh-config-editor` | `loader` · `profileContext` | [`packages/boot/config-editor/src/index.ts`](../packages/boot/config-editor/src/index.ts) | | `@deepseek-ai/dsh-cordis-client-runner` | — | [`packages/extensions/cordis-client-runner/src/index.ts`](../packages/extensions/cordis-client-runner/src/index.ts) | +| `@deepseek-ai/dsh-creation-recommendations` | `tools` · `pluginManager` · `agents` · `subagents` · `profileContext` · `skills` · `actionCards` | [`packages/experimental/creation-recommendations/src/index.ts`](../packages/experimental/creation-recommendations/src/index.ts) | | `@deepseek-ai/dsh-cua` | — | [`packages/experimental/cua/src/index.ts`](../packages/experimental/cua/src/index.ts) | | `@deepseek-ai/dsh-deepseek-llm-api-extensions` | — | [`packages/llm/deepseek-llm-api-extensions/src/index.ts`](../packages/llm/deepseek-llm-api-extensions/src/index.ts) | | `@deepseek-ai/dsh-deliverable-file-references` | `systemPrompt` | [`packages/deliverables/deliverable-file-references/src/index.ts`](../packages/deliverables/deliverable-file-references/src/index.ts) | | `@deepseek-ai/dsh-experimental-auto-review` | `approval` · `llm` · `permissionPresets` · `sessions` · `tools` · `workingDirectory` | [`packages/experimental/auto-review/src/index.ts`](../packages/experimental/auto-review/src/index.ts) | | `@deepseek-ai/dsh-experimental-client-ui-agent-team` | — | [`packages/experimental/client-ui-agent-team/src/index.ts`](../packages/experimental/client-ui-agent-team/src/index.ts) | | `@deepseek-ai/dsh-experimental-client-ui-claude-code-mods` | — | [`packages/experimental/client-ui-claude-code-mods/src/index.ts`](../packages/experimental/client-ui-claude-code-mods/src/index.ts) | +| `@deepseek-ai/dsh-experimental-client-ui-stats` | — | [`packages/experimental/client-ui-stats/src/index.ts`](../packages/experimental/client-ui-stats/src/index.ts) | | `@deepseek-ai/dsh-experimental-client-ui-voice-input` | — | [`packages/experimental/client-ui-voice-input/src/index.ts`](../packages/experimental/client-ui-voice-input/src/index.ts) | | `@deepseek-ai/dsh-experimental-computer-use-cua-driver-native` | `computerUse` · `tools` · `systemPrompt` | [`packages/experimental/computer-use-cua-driver-native/src/index.ts`](../packages/experimental/computer-use-cua-driver-native/src/index.ts) | | `@deepseek-ai/dsh-experimental-session-inspector` | — | [`packages/experimental/session-inspector/src/index.ts`](../packages/experimental/session-inspector/src/index.ts) | @@ -4783,6 +4796,7 @@ export interface Config { | `@deepseek-ai/dsh-mcp-resources` | `tools` | [`packages/mcp/mcp-resources/src/index.ts`](../packages/mcp/mcp-resources/src/index.ts) | | `@deepseek-ai/dsh-message-quotes` | — | [`packages/session/message-quotes/src/index.ts`](../packages/session/message-quotes/src/index.ts) | | `@deepseek-ai/dsh-otel` | — | [`packages/telemetry/otel/src/index.ts`](../packages/telemetry/otel/src/index.ts) | +| `@deepseek-ai/dsh-plugin-recommendations` | `pluginManager` · `agents` · `skills` · `actionCards` | [`packages/experimental/plugin-recommendations/src/index.ts`](../packages/experimental/plugin-recommendations/src/index.ts) | | `@deepseek-ai/dsh-sandbox-ssh` | `ssh` | [`packages/ssh/sandbox-ssh/src/index.ts`](../packages/ssh/sandbox-ssh/src/index.ts) | | `@deepseek-ai/dsh-session` | — | [`packages/core/session/src/index.ts`](../packages/core/session/src/index.ts) | | `@deepseek-ai/dsh-session-checkpoint-policy` | `llm` · `sessionPersistence` · `sessions` · `tools` | [`packages/session/session-checkpoint-policy/src/index.ts`](../packages/session/session-checkpoint-policy/src/index.ts) | @@ -4860,6 +4874,7 @@ export interface Config { | `@deepseek-ai/dsh-experimental-browser-use-runtime` | — | [`packages/experimental/browser-use-runtime/src/index.ts`](../packages/experimental/browser-use-runtime/src/index.ts) | | `@deepseek-ai/dsh-experimental-cot-translation-bundle` | — | [`packages/experimental/cot-translation-bundle/src/index.ts`](../packages/experimental/cot-translation-bundle/src/index.ts) | | `@deepseek-ai/dsh-experimental-inspector-profile` | — | [`packages/experimental/inspector-profile/src/index.ts`](../packages/experimental/inspector-profile/src/index.ts) | +| `@deepseek-ai/dsh-experimental-liveshare-protocol` | — | [`packages/experimental/liveshare-protocol/src/index.ts`](../packages/experimental/liveshare-protocol/src/index.ts) | | `@deepseek-ai/dsh-experimental-plugin-market-bundle` | — | [`packages/experimental/plugin-market-bundle/src/index.ts`](../packages/experimental/plugin-market-bundle/src/index.ts) | | `@deepseek-ai/dsh-experimental-ralph-bundle` | — | [`packages/experimental/ralph-bundle/src/index.ts`](../packages/experimental/ralph-bundle/src/index.ts) | | `@deepseek-ai/dsh-experimental-session-search` | — | [`packages/experimental/session-search/src/index.ts`](../packages/experimental/session-search/src/index.ts) | @@ -4878,9 +4893,10 @@ export interface Config { | `@deepseek-ai/dsh-llm-mock-server` | — | [`packages/test-support/llm-mock-server/src/index.ts`](../packages/test-support/llm-mock-server/src/index.ts) | | `@deepseek-ai/dsh-loader-smoke` | — | [`packages/test-support/loader-smoke/src/index.ts`](../packages/test-support/loader-smoke/src/index.ts) | | `@deepseek-ai/dsh-native-command` | — | [`packages/util/native-command/src/index.ts`](../packages/util/native-command/src/index.ts) | -| `@deepseek-ai/dsh-official-bundles` | — | [`packages/boot/official-bundles/src/index.ts`](../packages/boot/official-bundles/src/index.ts) | +| `@deepseek-ai/dsh-official-bundles` | — | [`packages/util/official-bundles/src/index.ts`](../packages/util/official-bundles/src/index.ts) | | `@deepseek-ai/dsh-output-retention` | — | [`packages/util/output-retention/src/index.ts`](../packages/util/output-retention/src/index.ts) | | `@deepseek-ai/dsh-package-manifest` | — | [`packages/util/package-manifest/src/index.ts`](../packages/util/package-manifest/src/index.ts) | +| `@deepseek-ai/dsh-personalized-recommendations` | — | [`packages/experimental/personalized-recommendations/src/index.ts`](../packages/experimental/personalized-recommendations/src/index.ts) | | `@deepseek-ai/dsh-plugin-detail` | — | [`packages/util/plugin-detail/src/index.ts`](../packages/util/plugin-detail/src/index.ts) | | `@deepseek-ai/dsh-plugin-market-index` | — | [`packages/util/plugin-market-index/src/index.ts`](../packages/util/plugin-market-index/src/index.ts) | | `@deepseek-ai/dsh-remote-mock` | — | [`packages/test-support/remote-mock/src/index.ts`](../packages/test-support/remote-mock/src/index.ts) | diff --git a/docs/cookbook/adding-a-package.i18n.yaml b/docs/cookbook/adding-a-package.i18n.yaml index 2f95205489..28ee60cb3d 100644 --- a/docs/cookbook/adding-a-package.i18n.yaml +++ b/docs/cookbook/adding-a-package.i18n.yaml @@ -21,8 +21,8 @@ en: 0894bd9f35430753 zh: 2d28090e71134edd /cookbook-adding-a-workspace-package/5-add-optional-plugin-display-metadata: - en: 1238eaea376391d1 - zh: c7e606f95d8980bf + en: ee71fb0a70f02550 + zh: 1f0d6936d6c2acad /cookbook-adding-a-workspace-package/6-verify: en: 80c7fb90b1175aae zh: 2ba37962dbc57299 diff --git a/docs/cookbook/adding-a-package.md b/docs/cookbook/adding-a-package.md index 2950932479..16fe3e564f 100644 --- a/docs/cookbook/adding-a-package.md +++ b/docs/cookbook/adding-a-package.md @@ -136,7 +136,7 @@ Merge these entries into `package.json`, retaining existing runtime exports and } ``` -Keep language files together in `locale/`, with `en.json` as the discovery entry. Fields are optional; present values must be non-empty strings. English `meta.title` and `meta.description` use sentence case: capitalize only the first word, proper nouns, and product names, as in `Git worktrees` ([rule](../../.agents/skills/dsh-prose-standard/SKILL.md#required-coverage-by-prose-location)). At runtime, missing files or fields permit fallback, while malformed JSON or invalid fields produce a per-plugin diagnostic. First-party packages and plugin templates must provide `ja.json` covering every field present in `en.json` or optional `zh.json`, preserving placeholders; detail paths may point to the existing English document. Subpath resources under `locale//` follow the same checks. English descriptions explain user-visible behavior and end with sentence punctuation. Run `pnpm run check:i18n` to verify JSON metadata and UI dictionary completeness; the JSON checks also run in `check:all`, CI static checks, and hygiene. +Keep language files together in `locale/`, with `en.json` as the discovery entry. Fields are optional; present values must be non-empty strings. English `meta.title` and `meta.description` use sentence case: capitalize only the first word, proper nouns, and product names, as in `Git worktrees` ([rule](../../.agents/skills/dsh-prose-standard/SKILL.md#required-coverage-by-prose-location)). At runtime, missing files or fields permit fallback, while malformed JSON or invalid fields produce a per-plugin diagnostic. First-party packages and plugin templates must provide `ja.json`, `es.json`, `fr.json`, `de.json`, `ru.json`, and `pt.json` covering every field present in `en.json` or optional `zh.json`, preserving placeholders, slash commands, and API field names; detail paths may point to the existing English document. Subpath resources under `locale//` follow the same checks. English descriptions explain user-visible behavior and end with sentence punctuation. Run `pnpm run check:i18n` to verify JSON metadata and UI dictionary completeness; the JSON checks also run in `check:all`, CI static checks, and hygiene. Fields fall back independently before view-specific name formatting, using the existing locale language chain first: @@ -147,7 +147,7 @@ Export `/locale/en.json` for locale lookup; expose ` For an image on bundle cards, details, and component rows, a package-root plugin sets top-level `"icon": "./icon.svg"` in its exported manifest, or exports `./icon` when that field is omitted. A subpath plugin exports its own icon, such as `"./search/icon": "./search.svg"`. Include each image in `files`. A manifest `icon` is relative to the manifest's directory; absolute paths, URLs, paths outside that directory, and symlinks resolving outside it are rejected. An exported icon resolves through Node exports like locale resources and must remain inside its package. SVG, PNG, JPEG (`.jpg`/`.jpeg`), and WebP files are supported up to 256 KiB. Images must be self-contained; SVG is rendered as an image, not inline HTML. The Host returns a data URL without activating the plugin. Invalid declarations or unreadable files produce a metadata diagnostic while retaining valid text, without trying the export; missing or undecodable images use the panel's default artwork. -A bundle can also set `meta.detail` to a Markdown file path relative to the package root, such as `"docs/DETAIL.md"` in `locale/en.json` and `"docs/DETAIL.zh.md"` in `locale/zh.json`; it is read from these files at the package root. The path uses `/`, stays inside the package, ends in `.md` or `.markdown`, and has no package-field fallback; keep its images beside it, and list its top-level directory, such as `docs`, in `files` right after the locale resources, as `check-workspace-constraints` requires. The named file must exist in a subdirectory of the package; a root-level document is rejected because its neighboring images would not be published. A bundle's page in **Plugins**, and its market entry page when the [custom plugin markets bundle](../../packages/experimental/plugin-market-bundle/README.md) is on, show the file for the active UI language as the plugin's detail document. Without `meta.detail` they show the package README, and a market entry page then falls back to the declared repository's README; the [document order](../../packages/util/plugin-detail/README.md#document-order) defines the rules. Write it for users, and reference images by paths relative to the file. +A bundle can also set `meta.detail` to a Markdown file path relative to the package root, such as `"docs/DETAIL.md"` in `locale/en.json` and `"docs/DETAIL.zh.md"` in `locale/zh.json`; it is read from these files at the package root. The path uses `/`, stays inside the package, ends in `.md` or `.markdown`, and has no package-field fallback; keep its images beside it, and list its top-level directory, such as `docs`, in `files` right after the locale resources, as `check-workspace-constraints` requires. The named file must exist in a subdirectory of the package; a root-level document is rejected because its neighboring images would not be published. A bundle's page in **Plugins**, and its index entry page when the [custom plugin indexes bundle](../../packages/experimental/plugin-market-bundle/README.md) is on, show the file for the active UI language as the plugin's detail document. Without `meta.detail` they show the package README, and an index entry page then falls back to the declared repository's README; the [document order](../../packages/util/plugin-detail/README.md#document-order) defines the rules. Write it for users, and reference images by paths relative to the file. Installed bundle cards and details, component lists and configuration details, and Settings' plugin inventory display this metadata, including disabled and preset plugins. Reads do not activate plugins. diff --git a/docs/cookbook/adding-a-package.zh.md b/docs/cookbook/adding-a-package.zh.md index 6ab95ce3b3..0d74f645dc 100644 --- a/docs/cookbook/adding-a-package.zh.md +++ b/docs/cookbook/adding-a-package.zh.md @@ -136,7 +136,7 @@ Append-only, prefix-stable, replacing, or independent behavior, including the ex } ``` -语言文件统一放在 `locale/`,并保留 `en.json` 作为发现入口。字段可选,填写时必须是非空字符串。英文 `meta.title` 和 `meta.description` 使用 sentence case:只大写首个单词、专有名词和产品名,例如 `Git worktrees`([rule](../../.agents/skills/dsh-prose-standard/SKILL.md#required-coverage-by-prose-location))。运行时文件或字段缺失时允许回退,JSON 损坏或字段无效时显示单插件诊断。仓库内的包和插件模板必须提供 `ja.json`,覆盖 `en.json` 或可选 `zh.json` 中的全部字段并保留占位符;详情路径可指向现有英文文档。`locale//` 下的子路径资源使用相同检查。英文描述面向产品用户说明可见行为,并以句末标点结束。运行 `pnpm run check:i18n` 检查 JSON 元数据和 UI 字典完整性;JSON 检查也接入 `check:all`、CI 静态检查和 hygiene。 +语言文件统一放在 `locale/`,并保留 `en.json` 作为发现入口。字段可选,填写时必须是非空字符串。英文 `meta.title` 和 `meta.description` 使用 sentence case:只大写首个单词、专有名词和产品名,例如 `Git worktrees`([rule](../../.agents/skills/dsh-prose-standard/SKILL.md#required-coverage-by-prose-location))。运行时文件或字段缺失时允许回退,JSON 损坏或字段无效时显示单插件诊断。仓库内的包和插件模板必须提供 `ja.json`、`es.json`、`fr.json`、`de.json`、`ru.json` 和 `pt.json`,覆盖 `en.json` 或可选 `zh.json` 中的全部字段并保留占位符、斜杠命令和 API 字段名;详情路径可指向现有英文文档。`locale//` 下的子路径资源使用相同检查。英文描述面向产品用户说明可见行为,并以句末标点结束。运行 `pnpm run check:i18n` 检查 JSON 元数据和 UI 字典完整性;JSON 检查也接入 `check:all`、CI 静态检查和 hygiene。 各字段先独立回退,再按页面规则格式化技术名称;回退优先经过现有 locale 语言链: @@ -147,7 +147,7 @@ Append-only, prefix-stable, replacing, or independent behavior, including the ex 要在组合包卡片、详情和组件行显示图片,包根插件在导出清单顶层设置 `"icon": "./icon.svg"`,或在省略该字段时导出 `./icon`。子路径插件导出自己的图标,例如 `"./search/icon": "./search.svg"`。将每张图片加入 `files`。清单 `icon` 相对于清单所在目录;绝对路径、URL、目录外路径,以及解析到目录外的符号链接均被拒绝。导出的图标像 locale 资源一样经 Node exports 解析,且必须位于所属包内。支持不超过 256 KiB 的 SVG、PNG、JPEG(`.jpg`/`.jpeg`)和 WebP 文件。图片必须自包含;SVG 作为图片渲染,不作为内联 HTML。Host 返回 data URL,不激活插件。声明无效或文件不可读时,显示元信息诊断并保留有效文本,不再尝试导出的图标;图片缺失或无法解码时使用面板的默认插画。 -组合包还可以把 `meta.detail` 设为相对于包根目录的 Markdown 文件路径,例如在 `locale/en.json` 中设为 `"docs/DETAIL.md"`,在 `locale/zh.json` 中设为 `"docs/DETAIL.zh.md"`;读取时使用包根目录下的这些文件。路径使用 `/`,必须位于包内,以 `.md` 或 `.markdown` 结尾,且没有包字段回退;图片放在该文件旁边,并按 `check-workspace-constraints` 的要求,在 `files` 中紧接语言资源之后列出该文件的顶层目录,例如 `docs`。该文件必须位于包的子目录中且已存在;包根目录下的文档会被拒绝,因为其旁边的图片不会被发布。组合包在**插件**中的页面,以及启用[自定义插件市场组合包](../../packages/experimental/plugin-market-bundle/README.zh.md)时其市场条目页面,把当前界面语言对应的该文件作为插件的详细介绍文档显示。没有 `meta.detail` 时,它们显示包 README;市场条目页面在此之后还会回退到所声明仓库的 README;规则由[文档顺序](../../packages/util/plugin-detail/README.zh.md#document-order)定义。该文档面向用户编写,图片使用相对于该文件的路径引用。 +组合包还可以把 `meta.detail` 设为相对于包根目录的 Markdown 文件路径,例如在 `locale/en.json` 中设为 `"docs/DETAIL.md"`,在 `locale/zh.json` 中设为 `"docs/DETAIL.zh.md"`;读取时使用包根目录下的这些文件。路径使用 `/`,必须位于包内,以 `.md` 或 `.markdown` 结尾,且没有包字段回退;图片放在该文件旁边,并按 `check-workspace-constraints` 的要求,在 `files` 中紧接语言资源之后列出该文件的顶层目录,例如 `docs`。该文件必须位于包的子目录中且已存在;包根目录下的文档会被拒绝,因为其旁边的图片不会被发布。组合包在**插件**中的页面,以及启用[自定义插件索引组合包](../../packages/experimental/plugin-market-bundle/README.zh.md)时其索引条目页面,把当前界面语言对应的该文件作为插件的详细介绍文档显示。没有 `meta.detail` 时,它们显示包 README;索引条目页面在此之后还会回退到所声明仓库的 README;规则由[文档顺序](../../packages/util/plugin-detail/README.zh.md#document-order)定义。该文档面向用户编写,图片使用相对于该文件的路径引用。 已安装 bundle 的卡片和详情、组件列表与配置详情、设置中的插件清单都展示这些元信息,包括禁用插件和预设内插件。读取时不激活插件。 diff --git a/docs/cookbook/adding-a-plugin-preview.i18n.yaml b/docs/cookbook/adding-a-plugin-preview.i18n.yaml index 0111677ab5..9884dce36b 100644 --- a/docs/cookbook/adding-a-plugin-preview.i18n.yaml +++ b/docs/cookbook/adding-a-plugin-preview.i18n.yaml @@ -3,17 +3,17 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/cookbook/adding-a-plugin-preview.md /cookbook-add-a-plugin-feature-preview: - en: c37096cd3cdb886c - zh: fc6850d68c638898 + en: a0db5c6e164abfa1 + zh: 792c831c20a41e5d /cookbook-add-a-plugin-feature-preview/1-decide-whether-an-image-helps: - en: ee84f52d834cbccf - zh: 7bf3a425a231b5e6 + en: 0b401d0094e3b8ae + zh: d9eaedfaf8be012e /cookbook-add-a-plugin-feature-preview/2-draw-one-fixed-size-svg: en: 3a28640aa605dce8 zh: c5336958f92b5a70 -/cookbook-add-a-plugin-feature-preview/3-put-it-at-the-top-of-the-detail-document: - en: 17e2ace32a89c419 - zh: c635a890e86a41ec +/cookbook-add-a-plugin-feature-preview/3-make-it-the-detail-document: + en: ad09702c601e05a6 + zh: ae03649d34ab08b1 /cookbook-add-a-plugin-feature-preview/4-page-behavior: en: 20ce358cb110104c zh: abb8d72fed81f3c8 diff --git a/docs/cookbook/adding-a-plugin-preview.md b/docs/cookbook/adding-a-plugin-preview.md index 1683aab10a..1a2ceb9d81 100644 --- a/docs/cookbook/adding-a-plugin-preview.md +++ b/docs/cookbook/adding-a-plugin-preview.md @@ -2,11 +2,11 @@ English | [中文](adding-a-plugin-preview.zh.md) -A feature preview is an optional illustration at the top of a bundle's detail document, the long description that its page in **Plugins** shows first. Follow this guide when drawing one for an official bundle. The detail document itself is declared through [`meta.detail`](adding-a-package.md#plugin-display-metadata). +A feature preview is an optional illustration in a bundle's detail document, the document that its page in **Plugins** shows below the description. Follow this guide when drawing one for an official bundle. The detail document itself is declared through [`meta.detail`](adding-a-package.md#plugin-display-metadata). ## 1. Decide whether an image helps -Show one concrete result or recognizable capability. Omit the image when the description is enough: no image is required. Essential instructions stay in the document's text or in configuration outside the illustration. +Show one concrete result or recognizable capability. Omit the image when the description is enough: no image is required. Essential instructions stay in the bundle's description or in configuration outside the illustration. ## 2. Draw one fixed-size SVG @@ -21,15 +21,15 @@ Show one concrete result or recognizable capability. Omit the image when the des The SVG is self-contained: no fonts, remote resources, scripts, handlers, animation, stylesheets, `text`, or `foreignObject`. An `image` element may embed an unchanged official PNG/JPEG/WebP brand asset as a base64 data URL. Small plugin icons remain geometry-only. The page renders the SVG through ``. Keep each file small; the Host refuses images above plugin-manager's `detailImageMaxBytes`, 5 MiB by default. -## 3. Put it at the top of the detail document +## 3. Make it the detail document -Save the pair as `docs/preview.svg` and `docs/preview.zh.svg` in the bundle package, beside `docs/DETAIL.md` and `docs/DETAIL.zh.md`, and make the image the first line of each document: +Save the pair as `docs/preview.svg` and `docs/preview.zh.svg` in the bundle package, beside `docs/DETAIL.md` and `docs/DETAIL.zh.md`, and make the image the only line of each document: ```markdown ![Example feature preview](preview.svg) ``` -The Chinese document references `preview.zh.svg` with Chinese alternative text. Use the [badge skill](../../packages/experimental/badge-skill-bundle/docs/DETAIL.md) and [voice input](../../packages/experimental/voice-input-bundle/docs/DETAIL.md) documents as examples. The voice transcript is explanatory sample content, not a recording result. +The Chinese document references `preview.zh.svg` with Chinese alternative text. Use the [badge skill](../../packages/experimental/badge-skill-bundle/docs/DETAIL.md) and [voice input](../../packages/experimental/voice-input-bundle/docs/DETAIL.md) documents as examples. The voice transcript is explanatory sample content, not a recording result. Describe what the bundle does and how to use it, at the level of behavior, in `meta.description`, which the page shows above the image. ## 4. Page behavior diff --git a/docs/cookbook/adding-a-plugin-preview.zh.md b/docs/cookbook/adding-a-plugin-preview.zh.md index 3d3caeb1bf..bc6d208ac3 100644 --- a/docs/cookbook/adding-a-plugin-preview.zh.md +++ b/docs/cookbook/adding-a-plugin-preview.zh.md @@ -2,11 +2,11 @@ [English](adding-a-plugin-preview.md) | 中文 -功能配图是位于组合包详细介绍文档顶部的可选插图;详细介绍文档是该组合包在**插件**中的页面最先显示的长描述。为官方组合包绘制配图时遵循本指引。详细介绍文档本身通过 [`meta.detail`](adding-a-package.zh.md#plugin-display-metadata) 声明。 +功能配图是组合包详细介绍文档中的可选插图;详细介绍文档是该组合包在**插件**中的页面显示在描述下方的文档。为官方组合包绘制配图时遵循本指引。详细介绍文档本身通过 [`meta.detail`](adding-a-package.zh.md#plugin-display-metadata) 声明。 ## 1. 判断是否需要配图 -展示一个具体结果或容易辨认的能力。文字说明足够时省略配图:配图不是必需的。必要操作说明仍放在文档文字或图外的配置中。 +展示一个具体结果或容易辨认的能力。文字说明足够时省略配图:配图不是必需的。必要操作说明仍放在组合包描述或图外的配置中。 ## 2. 绘制一张固定尺寸 SVG @@ -21,15 +21,15 @@ SVG 必须自包含:不使用字体、远程资源、脚本、事件处理器、动画、样式表、`text` 或 `foreignObject`。`image` 元素可以通过 base64 data URL 嵌入未改动的官方 PNG/JPEG/WebP 品牌素材。小插件图标仍仅使用几何图形。页面通过 `` 渲染 SVG。每个文件都应控制大小;Host 会拒绝超过 plugin-manager 的 `detailImageMaxBytes`(默认 5 MiB)的图片。 -## 3. 放在详细介绍文档顶部 +## 3. 用它作为详细介绍文档 -将这对文件保存为组合包中的 `docs/preview.svg` 和 `docs/preview.zh.svg`,与 `docs/DETAIL.md` 和 `docs/DETAIL.zh.md` 放在一起,并把图片作为每份文档的第一行: +将这对文件保存为组合包中的 `docs/preview.svg` 和 `docs/preview.zh.svg`,与 `docs/DETAIL.md` 和 `docs/DETAIL.zh.md` 放在一起,并把图片作为每份文档唯一的一行: ```markdown ![Example feature preview](preview.svg) ``` -中文文档引用 `preview.zh.svg`,并使用中文替代文字。可参考[徽章技能](../../packages/experimental/badge-skill-bundle/docs/DETAIL.md)和[语音输入](../../packages/experimental/voice-input-bundle/docs/DETAIL.md)文档。语音图中的转写文字是说明性示例,不是录音结果。 +中文文档引用 `preview.zh.svg`,并使用中文替代文字。可参考[徽章技能](../../packages/experimental/badge-skill-bundle/docs/DETAIL.md)和[语音输入](../../packages/experimental/voice-input-bundle/docs/DETAIL.md)文档。语音图中的转写文字是说明性示例,不是录音结果。组合包做什么、怎么用,按行为层面写在 `meta.description` 中,页面将其显示在配图上方。 ## 4. 页面行为 diff --git a/docs/development.i18n.yaml b/docs/development.i18n.yaml index 089970df47..999b732bc7 100644 --- a/docs/development.i18n.yaml +++ b/docs/development.i18n.yaml @@ -21,8 +21,8 @@ en: 3221d1076554001f zh: 29f166be6a5c04d9 /development-guide/contributor-reference/typescript-project-layout: - en: 1fe7b3be73b3f8f6 - zh: 9458d1b2908e4c12 + en: 12810e1c6ca8b8e4 + zh: b505d34cdf27856d /development-guide/contributor-reference/environment-variables: en: dba2c72ee6ffa930 zh: b65c27fbb9129ec8 diff --git a/docs/development.md b/docs/development.md index 8b7c6a8e46..76e34201cb 100644 --- a/docs/development.md +++ b/docs/development.md @@ -66,15 +66,17 @@ The repository uses isolated Host and Client aggregates. An ordinary package is | `tsconfig.base.json` | Shared compilerOptions and the source `paths` map. Also the resolution facade the vitest configs point vite-tsconfig-paths at: it has no `include`, so its `paths` apply to every importer. | No | | `tsconfig.base.client.json` | Browser compiler settings (`jsx`, DOM libs, `types: []`) extended by the Client aggregate and every `packages/client/*` package. | No | +Host aggregate type checks run with a 8 GiB Node old-space limit across build, release, and Windows diagnostic commands. This is a per-compiler limit; concurrent build steps need additional memory. + Host and Client stay two aggregate programs because both sides declaration-merge the cordis `Context` interface under the same keys with different services; one program seeing both merges reports a collision. The collision exists only inside a `ts.Program` — module resolution never triggers it — which is why the solution may reference both aggregates and one paths facade may span both sides. Three disciplines follow: - `tsconfig.base.json` never gains `include` or `files`: they would leak into every extending package project and narrow the facade's match-all scope. - A script that builds a repo-wide `ts.Program` seeds `tsconfig.host.json` or `tsconfig.client.json` explicitly — never the root solution, because flattening both aggregates into one program collides the `Context` merges. - A new package is registered in exactly one aggregate; only the split packages above carry both leaf configs, and the shared leaves are registered in both aggregates because each side must type-check the same source. Having both a Node loader entry and a browser entry is not a reason to split a package; an ordinary Client plugin produces both runtime artifacts during the Client build phase. -Six packages split Host and Client tsconfigs: `api/remotes`, `api/gateway`, `api/session-controller`, `api/workspace-controller`, `client/connection`, and `session-query/session-log-export`. `api/remotes`' Host entry participates in the Host Typert graph while its Client entry imports generated `/remote` declarations; `session-log-export` keeps Node archive production out of its browser controller. Each split package-root `tsconfig.json` is therefore only a solution, and the two aggregates and direct consumers reference `tsconfig.host.json` or `tsconfig.client.json` respectively. The workspace `constraints` gate walks the reachable Project Reference graph and checks each referencing project's own compiler face: a single-config target remains valid from either face, while a split target must name the matching leaf rather than its solution root or opposite leaf; it discovers split packages from the presence of both leaf configs, so a new split joins the gate automatically. The [`api-remotes` README](../packages/api/remotes/README.md) and [`session-log-export` README](../packages/session-query/session-log-export/README.md) explain their splits. +Seven packages split Host and Client tsconfigs: `api/remotes`, `api/gateway`, `api/session-controller`, `api/workspace-controller`, `client/connection`, `session-query/session-log-export`, and `experimental/liveshare-protocol`. `api/remotes`' Host entry participates in the Host Typert graph while its Client entry imports generated `/remote` declarations; `session-log-export` keeps Node archive production out of its browser controller; `liveshare-protocol` keeps the Node wire codecs on its Host leaf and the browser viewer carrier on its Client leaf. Each split package-root `tsconfig.json` is therefore only a solution, and the two aggregates and direct consumers reference `tsconfig.host.json` or `tsconfig.client.json` respectively. The workspace `constraints` gate walks the reachable Project Reference graph and checks each referencing project's own compiler face: a single-config target remains valid from either face, while a split target must name the matching leaf rather than its solution root or opposite leaf; it discovers split packages from the presence of both leaf configs, so a new split joins the gate automatically. The [`api-remotes` README](../packages/api/remotes/README.md) and [`session-log-export` README](../packages/session-query/session-log-export/README.md) explain their splits. -`pnpm run build:artifacts` emits every artifact in the generated dependency order, checking and compiling only the package references of each compiler face: +`pnpm run build:artifacts` emits every artifact, checking and compiling only the package references of each compiler face. Client compilation waits for Host and Desktop bundling to finish: split compiler faces rewrite shared `lib/types` files read by those bundles. Client bundling follows Client compilation. The artifact order is: ```sh pnpm run build:native-system diff --git a/docs/development.zh.md b/docs/development.zh.md index fc445f0ab0..ac61221c52 100644 --- a/docs/development.zh.md +++ b/docs/development.zh.md @@ -70,15 +70,17 @@ pnpm run typecheck | `tsconfig.base.json` | 共享 compilerOptions 与源码 `paths` 映射。同时是各 vitest 配置让 vite-tsconfig-paths 指向的解析门面:它没有 `include`,因此其 `paths` 适用于任何 importer。 | 否 | | `tsconfig.base.client.json` | 浏览器编译设置(`jsx`、DOM lib、`types: []`),由 Client aggregate 和每个 `packages/client/*` 包 extends。 | 否 | +构建、发布和 Windows 诊断命令中的 Host aggregate 类型检查为 Node 老生代堆设置 8 GiB 上限。这是单个编译进程的上限;并发构建步骤还需要额外内存。 + Host 与 Client 保持两个 aggregate program,是因为两侧在相同键下以不同服务对 cordis `Context` 接口做声明合并;单一 program 同时看到两份合并会报冲突。这种冲突只存在于 `ts.Program` 内部——模块解析永远不会触发它——所以 solution 可以同时引用两个 aggregate,一个 paths 门面也可以横跨两侧。由此推出三条纪律: - `tsconfig.base.json` 永不添加 `include` 或 `files`:它们会泄漏进每个 extends 它的包项目,并收窄门面的全匹配范围。 - 构造全仓 `ts.Program` 的脚本显式以 `tsconfig.host.json` 或 `tsconfig.client.json` 为种子——根 solution 永不作为种子,因为把两个 aggregate 展平进一个 program 会撞上 `Context` 合并冲突。 - 新包只登记进一个 aggregate;只有上述拆分包同时携带两个 leaf 配置,共享 leaf 因两侧需要对同一份源码做类型检查而登记进两个 aggregate。包同时具有 Node loader 入口和 browser 入口并不构成拆分理由;普通 Client 插件的两份运行时产物都在 Client 构建阶段生成。 -拆分 Host/Client tsconfig 的包有六个:`api/remotes`、`api/gateway`、`api/session-controller`、`api/workspace-controller`、`client/connection` 与 `session-query/session-log-export`。`api/remotes` 的 Host 入口进入 Host Typert 图,而 Client 入口导入生成的 `/remote` 声明;`session-log-export` 则让 Node archive 生产代码不进入浏览器 controller。每个拆分包根 `tsconfig.json` 因此只作为 solution,两个 aggregate 和直接消费方分别引用 `tsconfig.host.json` 或 `tsconfig.client.json`。workspace `constraints` 门禁遍历可达的 Project Reference 图,并按各引用 project 自身的 compiler face 检查:只有单一配置的目标可由任一 face 引用,拆分配置的目标则必须引用匹配的 leaf,不得引用 solution 根或另一侧 leaf;该门禁按「两个 leaf 配置同时存在」自动发现拆分包,所以新拆分的包会自动纳入管辖。[`api-remotes` README](../packages/api/remotes/README.zh.md) 与 [`session-log-export` README](../packages/session-query/session-log-export/README.zh.md)分别说明其拆分。 +拆分 Host/Client tsconfig 的包有七个:`api/remotes`、`api/gateway`、`api/session-controller`、`api/workspace-controller`、`client/connection`、`session-query/session-log-export` 与 `experimental/liveshare-protocol`。`api/remotes` 的 Host 入口进入 Host Typert 图,而 Client 入口导入生成的 `/remote` 声明;`session-log-export` 则让 Node archive 生产代码不进入浏览器 controller;`liveshare-protocol` 把 Node 线路编解码放在 Host leaf、浏览器查看页载体放在 Client leaf。每个拆分包根 `tsconfig.json` 因此只作为 solution,两个 aggregate 和直接消费方分别引用 `tsconfig.host.json` 或 `tsconfig.client.json`。workspace `constraints` 门禁遍历可达的 Project Reference 图,并按各引用 project 自身的 compiler face 检查:只有单一配置的目标可由任一 face 引用,拆分配置的目标则必须引用匹配的 leaf,不得引用 solution 根或另一侧 leaf;该门禁按「两个 leaf 配置同时存在」自动发现拆分包,所以新拆分的包会自动纳入管辖。[`api-remotes` README](../packages/api/remotes/README.zh.md) 与 [`session-log-export` README](../packages/session-query/session-log-export/README.zh.md)分别说明其拆分。 -`pnpm run build:artifacts` 按生成依赖顺序产出全部产物,只检查并编译各 compiler face 的包 reference: +`pnpm run build:artifacts` 产出全部产物,只检查并编译各 compiler face 的包 reference。Client 编译等待 Host 和 Desktop 的 bundle 完成:拆分 compiler face 会重写这些 bundle 步骤读取的共享 `lib/types` 文件。Client bundle 在 Client 编译后执行。产物步骤顺序为: ```sh pnpm run build:native-system diff --git a/docs/event-producer-consumer.i18n.yaml b/docs/event-producer-consumer.i18n.yaml index f419955c56..9defd245a7 100644 --- a/docs/event-producer-consumer.i18n.yaml +++ b/docs/event-producer-consumer.i18n.yaml @@ -6,8 +6,8 @@ en: 41d772192075e133 zh: dda91c6c670cfd9d /event-producer-and-consumer-matrix: - en: 19f30fda81e73345 - zh: a8505006244f5619 + en: 2fac23d1dcc1fd3d + zh: 5fb06020a810adbf /event-producer-and-consumer-matrix/non-harness-or-undeclared-event-strings-seen-in-package-source: en: 96dc0ff1580e5741 zh: 96dc0ff1580e5741 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 9334d7b6c8..f451a58c4b 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -5,28 +5,30 @@ This matrix shows which packages dispatch each harness-owned event and which packages listen to it. Events are many-to-many, so the dense relation data is presented as a table rather than one large graph. Receiver and event-name types also cover contained dispatch sites that deliberately bypass `ctx.emit`, such as subagent lifecycle containment. +Application listeners are outside this package matrix. Desktop Host subscribes to `plugin-manager/operation` through [`installOperationDiagnostics`](../apps/desktop-host/src/operation-diagnostics.ts) and forwards bounded records to the shell. + | Event | Mode | Declared in | Dispatchers | Listeners | | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:199`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` | | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team` | | `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:328`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:336`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:350`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:350`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:600`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:580`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:607`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:586`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:593`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:53`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | +| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:689`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:669`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:696`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:675`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:682`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:55`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | | `commands/change` | `emit` | [`packages/interaction/commands/src/types.ts:89`](../packages/interaction/commands/src/types.ts) | [`commands`](../packages/interaction/commands) (`events.dispatch`) | `remotes` | @@ -56,12 +58,13 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:23`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:75`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | -| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:394`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:400`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:407`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:414`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:427`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:433`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:440`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:419`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - | +| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:447`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | | `plugin-market/changed` | `emit` | [`packages/boot/plugin-market/src/types.ts:168`](../packages/boot/plugin-market/src/types.ts) | [`plugin-market`](../packages/boot/plugin-market) (`emit`) | `remotes` | -| `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:478`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | +| `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:484`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | | `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:74`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` | | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | | `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`schedule`](../packages/schedule/schedule), `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | @@ -76,12 +79,12 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:158`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | | `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime`, [`working-directory`](../packages/session/working-directory) | | `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | -| `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `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), [`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`) | [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`subagent`](../packages/subagent/subagent), [`tool-present`](../packages/deliverables/tool-present) | +| `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`, [`subagent`](../packages/subagent/subagent), [`tool-present`](../packages/deliverables/tool-present) | | `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` | | `webserver/index-inject` | `emit` | [`packages/host/webserver/src/index.ts:44`](../packages/host/webserver/src/index.ts) | `webserver` (`emit`) | `connection`, `inspector`, `modules`, `remote-access`, `shortcuts`, `ui-sidebar-documentpreview`, `ui-theme` | | `workflow/agent-end` | `emit` | [`packages/workflow/workflow/src/index.ts:79`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | @@ -106,7 +109,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `internal/service` | - | `gateway` | | `internal/status` | - | [`agent`](../packages/core/agent), `inspector`, `translator`, [`web`](../packages/web/web) | | `internal/update` | - | [`app-boot`](../packages/boot/app-boot) | -| `loader/volatile-update` | - | [`cua`](../packages/experimental/cua), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text` | +| `loader/volatile-update` | - | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text` | | `slots/changed` | `ui-renderer` (`emit`) | - | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 20739cb0ba..c24d511061 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -7,28 +7,30 @@ 本矩阵展示哪些包会派发各个 harness 自有事件,以及哪些包会监听这些事件。事件之间存在多对多关系,因此密集的关系数据以表格而非一张大型关系图呈现。接收方和事件名称类型还涵盖有意绕过 `ctx.emit` 的内含派发位置,例如 subagent 生命周期封装。 +应用级监听者不在本包矩阵范围内。Desktop Host 通过 [`installOperationDiagnostics`](../apps/desktop-host/src/operation-diagnostics.ts) 订阅 `plugin-manager/operation`,并向壳转发有界记录。 + | Event | Mode | Declared in | Dispatchers | Listeners | | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:199`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` | | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team` | | `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:328`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:336`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:350`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:350`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:600`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:580`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:607`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:586`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:593`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:53`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | +| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:689`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:669`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:696`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:675`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:682`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:55`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | | `commands/change` | `emit` | [`packages/interaction/commands/src/types.ts:89`](../packages/interaction/commands/src/types.ts) | [`commands`](../packages/interaction/commands) (`events.dispatch`) | `remotes` | @@ -58,12 +60,13 @@ | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:23`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:75`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | -| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:394`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:400`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:407`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:414`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:427`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:433`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:440`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:419`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - | +| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:447`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | | `plugin-market/changed` | `emit` | [`packages/boot/plugin-market/src/types.ts:168`](../packages/boot/plugin-market/src/types.ts) | [`plugin-market`](../packages/boot/plugin-market) (`emit`) | `remotes` | -| `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:478`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | +| `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:484`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | | `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:74`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` | | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | | `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`schedule`](../packages/schedule/schedule), `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | @@ -78,12 +81,12 @@ | `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:158`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | | `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime`, [`working-directory`](../packages/session/working-directory) | | `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | -| `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `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), [`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`) | [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`subagent`](../packages/subagent/subagent), [`tool-present`](../packages/deliverables/tool-present) | +| `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`, [`subagent`](../packages/subagent/subagent), [`tool-present`](../packages/deliverables/tool-present) | | `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` | | `webserver/index-inject` | `emit` | [`packages/host/webserver/src/index.ts:44`](../packages/host/webserver/src/index.ts) | `webserver` (`emit`) | `connection`, `inspector`, `modules`, `remote-access`, `shortcuts`, `ui-sidebar-documentpreview`, `ui-theme` | | `workflow/agent-end` | `emit` | [`packages/workflow/workflow/src/index.ts:79`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | @@ -108,7 +111,7 @@ | `internal/service` | - | `gateway` | | `internal/status` | - | [`agent`](../packages/core/agent), `inspector`, `translator`, [`web`](../packages/web/web) | | `internal/update` | - | [`app-boot`](../packages/boot/app-boot) | -| `loader/volatile-update` | - | [`cua`](../packages/experimental/cua), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text` | +| `loader/volatile-update` | - | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text` | | `slots/changed` | `ui-renderer` (`emit`) | - | diff --git a/docs/experimental-persistence-catalog.i18n.yaml b/docs/experimental-persistence-catalog.i18n.yaml index a65825ab71..7dd24c2aa4 100644 --- a/docs/experimental-persistence-catalog.i18n.yaml +++ b/docs/experimental-persistence-catalog.i18n.yaml @@ -6,5 +6,5 @@ en: a11f106978c9dce7 zh: a11f106978c9dce7 /experimental-plugin-record-catalog: - en: 84dbc9c06ab92877 - zh: b82ef2a46292ab0e + en: cb931db3b4bcbe33 + zh: aca9cfecfdee34c0 diff --git a/docs/experimental-persistence-catalog.md b/docs/experimental-persistence-catalog.md index 0868849c51..b6d3a73de4 100644 --- a/docs/experimental-persistence-catalog.md +++ b/docs/experimental-persistence-catalog.md @@ -13,5 +13,6 @@ Shared Session event declarations and resolved schemas appear in the [Session pe | Record | Owner | Purpose | Payload and source | |---|---|---|---| +| `plugin:action-cards/decision` | `@deepseek-ai/dsh-action-cards` | Dismissals and kind-defined progress of action cards. | ActionCardDecision · [`packages/experimental/action-cards/src/types.ts`](../packages/experimental/action-cards/src/types.ts) | | `plugin:translator/request` | `@deepseek-ai/dsh-experimental-translator` | Provider-independent translation input, retained before dispatch. | TranslationRequestRecord · [`packages/experimental/translator/src/types.ts`](../packages/experimental/translator/src/types.ts) | | `plugin:translator/result` | `@deepseek-ai/dsh-experimental-translator` | Successful translation, retained before it is returned to the consumer. | TranslationResultRecord · [`packages/experimental/translator/src/types.ts`](../packages/experimental/translator/src/types.ts) | diff --git a/docs/experimental-persistence-catalog.zh.md b/docs/experimental-persistence-catalog.zh.md index 32cb1d0533..c32cdcabd0 100644 --- a/docs/experimental-persistence-catalog.zh.md +++ b/docs/experimental-persistence-catalog.zh.md @@ -13,5 +13,6 @@ | 记录 | 所属包 | 用途 | 载荷与源码 | |---|---|---|---| +| `plugin:action-cards/decision` | `@deepseek-ai/dsh-action-cards` | Dismissals and kind-defined progress of action cards. | ActionCardDecision · [`packages/experimental/action-cards/src/types.ts`](../packages/experimental/action-cards/src/types.ts) | | `plugin:translator/request` | `@deepseek-ai/dsh-experimental-translator` | Provider-independent translation input, retained before dispatch. | TranslationRequestRecord · [`packages/experimental/translator/src/types.ts`](../packages/experimental/translator/src/types.ts) | | `plugin:translator/result` | `@deepseek-ai/dsh-experimental-translator` | Successful translation, retained before it is returned to the consumer. | TranslationResultRecord · [`packages/experimental/translator/src/types.ts`](../packages/experimental/translator/src/types.ts) | diff --git a/docs/module-graph.md b/docs/module-graph.md index 2c4fef91dd..740ff07ba2 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -17,6 +17,7 @@ flowchart TD pkg_launch_environment["launch-environment"] pkg_lazy_require["lazy-require"] pkg_native_command["native-command"] + pkg_official_bundles["official-bundles"] pkg_output_retention["output-retention"] pkg_package_manifest["package-manifest"] pkg_plugin_detail["plugin-detail"] @@ -135,7 +136,6 @@ flowchart TD pkg_cmdline["cmdline"] pkg_config_editor["config-editor"] pkg_hmr["hmr"] - pkg_official_bundles["official-bundles"] pkg_plugin_manager["plugin-manager"] pkg_plugin_market["plugin-market"] end @@ -255,6 +255,11 @@ flowchart TD pkg_office_to_pdf["office-to-pdf"] end subgraph group_experimental["packages/experimental"] + pkg_action_cards["action-cards"] + pkg_client_ui_action_cards["client-ui-action-cards"] + pkg_client_ui_creation_recommendations["client-ui-creation-recommendations"] + pkg_client_ui_plugin_recommendations["client-ui-plugin-recommendations"] + pkg_creation_recommendations["creation-recommendations"] pkg_cua["cua"] pkg_cua_bundle["cua-bundle"] pkg_experimental_agent_team["experimental-agent-team"] @@ -270,6 +275,7 @@ flowchart TD pkg_experimental_client_ui_agent_team["experimental-client-ui-agent-team"] pkg_experimental_client_ui_claude_code_mods["experimental-client-ui-claude-code-mods"] pkg_experimental_client_ui_cot_translation["experimental-client-ui-cot-translation"] + pkg_experimental_client_ui_stats["experimental-client-ui-stats"] pkg_experimental_client_ui_voice_input["experimental-client-ui-voice-input"] pkg_experimental_computer_use_cua_driver_mcp["experimental-computer-use-cua-driver-mcp"] pkg_experimental_computer_use_cua_driver_native["experimental-computer-use-cua-driver-native"] @@ -277,6 +283,7 @@ flowchart TD pkg_experimental_cua_macos["experimental-cua-macos"] pkg_experimental_inspector["experimental-inspector"] pkg_experimental_inspector_profile["experimental-inspector-profile"] + pkg_experimental_liveshare_protocol["experimental-liveshare-protocol"] pkg_experimental_plugin_market_bundle["experimental-plugin-market-bundle"] pkg_experimental_ptc_runtime_python["experimental-ptc-runtime-python"] pkg_experimental_ralph_bundle["experimental-ralph-bundle"] @@ -298,6 +305,8 @@ flowchart TD pkg_hook_protocol["hook-protocol"] pkg_hooks_claude_code["hooks-claude-code"] pkg_hooks_codex["hooks-codex"] + pkg_personalized_recommendations["personalized-recommendations"] + pkg_plugin_recommendations["plugin-recommendations"] pkg_session_title_all_prompts_llm["session-title-all-prompts-llm"] pkg_skill_badge["skill-badge"] pkg_tool_ralph["tool-ralph"] @@ -516,6 +525,9 @@ flowchart TD pkg_experimental_webworker_runtime --> pkg_client_connection pkg_experimental_webworker_runtime --> pkg_client_modules pkg_experimental_webworker_runtime --> pkg_host_webserver + pkg_plugin_recommendations --> pkg_llm + pkg_plugin_recommendations --> pkg_skill + pkg_plugin_recommendations --> pkg_typert_protocol pkg_skill_badge --> pkg_skill pkg_host_directory_picker_auto --> pkg_client_connection pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_browse @@ -687,6 +699,7 @@ flowchart TD pkg_user_approval --> pkg_llm pkg_user_approval --> pkg_scope pkg_user_approval --> pkg_session + pkg_user_approval --> pkg_session_projection pkg_user_approval --> pkg_system_prompt pkg_user_questions --> pkg_agent pkg_user_questions --> pkg_llm @@ -730,7 +743,6 @@ flowchart TD pkg_llm_deepseek_account --> pkg_launch_environment pkg_llm_deepseek_account --> pkg_llm pkg_llm_deepseek_account --> pkg_llm_deepseek - pkg_llm_deepseek_account --> pkg_timeout pkg_tools --> pkg_agent pkg_tools --> pkg_llm pkg_tools --> pkg_scope @@ -767,9 +779,6 @@ flowchart TD pkg_deepseek_account_platform --> pkg_credentials pkg_deepseek_account_platform --> pkg_deepseek_account pkg_deepseek_account_platform --> pkg_host_webserver - pkg_cua --> pkg_attachment - pkg_cua --> pkg_scope - pkg_cua --> pkg_user_questions pkg_experimental_ptc_runtime_python --> pkg_ptc_runtime pkg_experimental_ptc_runtime_python --> pkg_sandbox pkg_experimental_ptc_runtime_python --> pkg_sandbox_policy @@ -925,6 +934,18 @@ flowchart TD pkg_workspace_changes --> pkg_session pkg_workspace_changes --> pkg_subprocess pkg_workspace_changes --> pkg_tools + pkg_action_cards --> pkg_llm + pkg_action_cards --> pkg_session + pkg_action_cards --> pkg_tools + pkg_action_cards --> pkg_typert_protocol + pkg_creation_recommendations --> pkg_llm + pkg_creation_recommendations --> pkg_session + pkg_creation_recommendations --> pkg_skill + pkg_creation_recommendations --> pkg_tools + pkg_cua --> pkg_attachment + pkg_cua --> pkg_ptc_runtime_node + pkg_cua --> pkg_scope + pkg_cua --> pkg_user_questions pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_agent pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_browser_use pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_system_prompt @@ -1277,7 +1298,6 @@ flowchart TD pkg_tool_subagent --> pkg_agent pkg_tool_subagent --> pkg_agent_preset_registry pkg_tool_subagent --> pkg_llm - pkg_tool_subagent --> pkg_scope pkg_tool_subagent --> pkg_session pkg_tool_subagent --> pkg_session_projection pkg_tool_subagent --> pkg_subagent @@ -1468,6 +1488,7 @@ flowchart TD | [`launch-environment`](../packages/util/launch-environment) | `util` | — | | [`lazy-require`](../packages/util/lazy-require) | `util` | — | | [`native-command`](../packages/util/native-command) | `util` | — | +| [`official-bundles`](../packages/util/official-bundles) | `util` | — | | [`output-retention`](../packages/util/output-retention) | `util` | — | | [`package-manifest`](../packages/util/package-manifest) | `util` | — | | [`plugin-detail`](../packages/util/plugin-detail) | `util` | — | @@ -1488,7 +1509,6 @@ flowchart TD | [`api-remote-access`](../packages/api/remote-access) | `api` | — | | [`api-workspace-files`](../packages/api/workspace-files) | `api` | — | | [`cmdline`](../packages/boot/cmdline) | `boot` | — | -| [`official-bundles`](../packages/boot/official-bundles) | `boot` | — | | [`acp-app`](../packages/bundle/acp-app) | `bundle` | — | | [`base`](../packages/bundle/base) | `bundle` | — | | [`sdk-app`](../packages/bundle/sdk-app) | `bundle` | — | @@ -1562,15 +1582,20 @@ flowchart TD | [`client-web`](../packages/client/web) | `client` | — | | [`credentials`](../packages/credentials/credentials) | `credentials` | — | | [`office-to-pdf`](../packages/document/office-to-pdf) | `document` | — | +| [`client-ui-action-cards`](../packages/experimental/client-ui-action-cards) | `experimental` | — | +| [`client-ui-creation-recommendations`](../packages/experimental/client-ui-creation-recommendations) | `experimental` | — | +| [`client-ui-plugin-recommendations`](../packages/experimental/client-ui-plugin-recommendations) | `experimental` | — | | [`cua-bundle`](../packages/experimental/cua-bundle) | `experimental` | — | | [`experimental-agent-team-profile`](../packages/experimental/agent-team-profile) | `experimental` | — | | [`experimental-badge-skill-bundle`](../packages/experimental/badge-skill-bundle) | `experimental` | — | | [`experimental-client-ui-agent-team`](../packages/experimental/client-ui-agent-team) | `experimental` | — | | [`experimental-client-ui-claude-code-mods`](../packages/experimental/client-ui-claude-code-mods) | `experimental` | — | +| [`experimental-client-ui-stats`](../packages/experimental/client-ui-stats) | `experimental` | — | | [`experimental-client-ui-voice-input`](../packages/experimental/client-ui-voice-input) | `experimental` | — | | [`experimental-cot-translation-bundle`](../packages/experimental/cot-translation-bundle) | `experimental` | — | | [`experimental-inspector`](../packages/experimental/inspector) | `experimental` | — | | [`experimental-inspector-profile`](../packages/experimental/inspector-profile) | `experimental` | — | +| [`experimental-liveshare-protocol`](../packages/experimental/liveshare-protocol) | `experimental` | — | | [`experimental-plugin-market-bundle`](../packages/experimental/plugin-market-bundle) | `experimental` | — | | [`experimental-ralph-bundle`](../packages/experimental/ralph-bundle) | `experimental` | — | | [`experimental-session-inspector`](../packages/experimental/session-inspector) | `experimental` | — | @@ -1579,6 +1604,7 @@ flowchart TD | [`experimental-terminal-bundle`](../packages/experimental/terminal-bundle) | `experimental` | — | | [`experimental-voice-input-bundle`](../packages/experimental/voice-input-bundle) | `experimental` | — | | [`experimental-webworker-packer`](../packages/experimental/webworker-packer) | `experimental` | — | +| [`personalized-recommendations`](../packages/experimental/personalized-recommendations) | `experimental` | — | | [`client-ui-cordis`](../packages/extensions/ui-cordis) | `extensions` | — | | [`cordis-client-runner`](../packages/extensions/cordis-client-runner) | `extensions` | — | | [`host-directory-picker`](../packages/host/directory-picker) | `host` | — | @@ -1630,6 +1656,7 @@ flowchart TD | [`deliverable-file-references`](../packages/deliverables/deliverable-file-references) | `deliverables` | [`system-prompt`](../packages/core/system-prompt) | | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) | | [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) | +| [`plugin-recommendations`](../packages/experimental/plugin-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`skill`](../packages/skill/skill), [`typert-protocol`](../packages/typert/protocol) | | [`skill-badge`](../packages/experimental/skill-badge) | `experimental` | [`skill`](../packages/skill/skill) | | [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-connection`](../packages/client/connection), [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) | | [`host-frontend-static`](../packages/host/frontend-static) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver) | @@ -1683,7 +1710,7 @@ flowchart TD | [`tmux-context`](../packages/context/tmux-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell) | | [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`util-values`](../packages/util/values) | | [`commands`](../packages/interaction/commands) | `interaction` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | -| [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt) | +| [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`user-questions`](../packages/interaction/user-questions) | `interaction` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | | [`jobs`](../packages/jobs/jobs) | `jobs` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`session`](../packages/core/session), [`workspace`](../packages/workspace/workspace) | | [`sandbox-policy`](../packages/sandbox/sandbox-policy) | `sandbox` | [`agent`](../packages/core/agent), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | @@ -1693,7 +1720,7 @@ flowchart TD | [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand) | | [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`http-proxy`](../packages/util/http-proxy), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`timeout`](../packages/util/timeout) | +| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | | [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | | [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | @@ -1702,7 +1729,6 @@ flowchart TD | [`api-account-controller`](../packages/api/account-controller) | `api` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/credentials/deepseek-account), [`typert-protocol`](../packages/typert/protocol) | | [`compaction`](../packages/compaction/compaction) | `compaction` | [`brand`](../packages/util/brand), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) | `credentials` | [`authorization`](../packages/credentials/authorization), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`host-webserver`](../packages/host/webserver) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory) | | [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | @@ -1732,6 +1758,9 @@ flowchart TD | [`file-reference-local`](../packages/context/file-reference-local) | `context` | [`agent`](../packages/core/agent), [`file-reference`](../packages/context/file-reference), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-present`](../packages/deliverables/tool-present) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | +| [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | +| [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | @@ -1794,7 +1823,7 @@ flowchart TD | [`subagent-codex`](../packages/subagent/subagent-codex) | `subagent` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process) | `subagent` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process) | `subagent` | [`subagent`](../packages/subagent/subagent) | -| [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`api-session-controller`](../packages/api/session-controller) | `api` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`api-gateway`](../packages/api/gateway), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-file-upload`](../packages/client/file-upload), [`commands`](../packages/interaction/commands), [`credentials`](../packages/credentials/credentials), [`file-reference`](../packages/context/file-reference), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`native-command`](../packages/util/native-command), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`settings`](../packages/settings/settings), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol), [`typert-registry`](../packages/typert/registry), [`util-time`](../packages/util/time), [`util-values`](../packages/util/values), [`util-workspace-path`](../packages/util/workspace-path), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`plugin-market`](../packages/boot/plugin-market) | `boot` | [`plugin-manager`](../packages/boot/plugin-manager), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 1002dd9c32..e52ff4e21c 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -19,6 +19,7 @@ flowchart TD pkg_launch_environment["launch-environment"] pkg_lazy_require["lazy-require"] pkg_native_command["native-command"] + pkg_official_bundles["official-bundles"] pkg_output_retention["output-retention"] pkg_package_manifest["package-manifest"] pkg_plugin_detail["plugin-detail"] @@ -137,7 +138,6 @@ flowchart TD pkg_cmdline["cmdline"] pkg_config_editor["config-editor"] pkg_hmr["hmr"] - pkg_official_bundles["official-bundles"] pkg_plugin_manager["plugin-manager"] pkg_plugin_market["plugin-market"] end @@ -257,6 +257,11 @@ flowchart TD pkg_office_to_pdf["office-to-pdf"] end subgraph group_experimental["packages/experimental"] + pkg_action_cards["action-cards"] + pkg_client_ui_action_cards["client-ui-action-cards"] + pkg_client_ui_creation_recommendations["client-ui-creation-recommendations"] + pkg_client_ui_plugin_recommendations["client-ui-plugin-recommendations"] + pkg_creation_recommendations["creation-recommendations"] pkg_cua["cua"] pkg_cua_bundle["cua-bundle"] pkg_experimental_agent_team["experimental-agent-team"] @@ -272,6 +277,7 @@ flowchart TD pkg_experimental_client_ui_agent_team["experimental-client-ui-agent-team"] pkg_experimental_client_ui_claude_code_mods["experimental-client-ui-claude-code-mods"] pkg_experimental_client_ui_cot_translation["experimental-client-ui-cot-translation"] + pkg_experimental_client_ui_stats["experimental-client-ui-stats"] pkg_experimental_client_ui_voice_input["experimental-client-ui-voice-input"] pkg_experimental_computer_use_cua_driver_mcp["experimental-computer-use-cua-driver-mcp"] pkg_experimental_computer_use_cua_driver_native["experimental-computer-use-cua-driver-native"] @@ -279,6 +285,7 @@ flowchart TD pkg_experimental_cua_macos["experimental-cua-macos"] pkg_experimental_inspector["experimental-inspector"] pkg_experimental_inspector_profile["experimental-inspector-profile"] + pkg_experimental_liveshare_protocol["experimental-liveshare-protocol"] pkg_experimental_plugin_market_bundle["experimental-plugin-market-bundle"] pkg_experimental_ptc_runtime_python["experimental-ptc-runtime-python"] pkg_experimental_ralph_bundle["experimental-ralph-bundle"] @@ -300,6 +307,8 @@ flowchart TD pkg_hook_protocol["hook-protocol"] pkg_hooks_claude_code["hooks-claude-code"] pkg_hooks_codex["hooks-codex"] + pkg_personalized_recommendations["personalized-recommendations"] + pkg_plugin_recommendations["plugin-recommendations"] pkg_session_title_all_prompts_llm["session-title-all-prompts-llm"] pkg_skill_badge["skill-badge"] pkg_tool_ralph["tool-ralph"] @@ -518,6 +527,9 @@ flowchart TD pkg_experimental_webworker_runtime --> pkg_client_connection pkg_experimental_webworker_runtime --> pkg_client_modules pkg_experimental_webworker_runtime --> pkg_host_webserver + pkg_plugin_recommendations --> pkg_llm + pkg_plugin_recommendations --> pkg_skill + pkg_plugin_recommendations --> pkg_typert_protocol pkg_skill_badge --> pkg_skill pkg_host_directory_picker_auto --> pkg_client_connection pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_browse @@ -689,6 +701,7 @@ flowchart TD pkg_user_approval --> pkg_llm pkg_user_approval --> pkg_scope pkg_user_approval --> pkg_session + pkg_user_approval --> pkg_session_projection pkg_user_approval --> pkg_system_prompt pkg_user_questions --> pkg_agent pkg_user_questions --> pkg_llm @@ -732,7 +745,6 @@ flowchart TD pkg_llm_deepseek_account --> pkg_launch_environment pkg_llm_deepseek_account --> pkg_llm pkg_llm_deepseek_account --> pkg_llm_deepseek - pkg_llm_deepseek_account --> pkg_timeout pkg_tools --> pkg_agent pkg_tools --> pkg_llm pkg_tools --> pkg_scope @@ -769,9 +781,6 @@ flowchart TD pkg_deepseek_account_platform --> pkg_credentials pkg_deepseek_account_platform --> pkg_deepseek_account pkg_deepseek_account_platform --> pkg_host_webserver - pkg_cua --> pkg_attachment - pkg_cua --> pkg_scope - pkg_cua --> pkg_user_questions pkg_experimental_ptc_runtime_python --> pkg_ptc_runtime pkg_experimental_ptc_runtime_python --> pkg_sandbox pkg_experimental_ptc_runtime_python --> pkg_sandbox_policy @@ -927,6 +936,18 @@ flowchart TD pkg_workspace_changes --> pkg_session pkg_workspace_changes --> pkg_subprocess pkg_workspace_changes --> pkg_tools + pkg_action_cards --> pkg_llm + pkg_action_cards --> pkg_session + pkg_action_cards --> pkg_tools + pkg_action_cards --> pkg_typert_protocol + pkg_creation_recommendations --> pkg_llm + pkg_creation_recommendations --> pkg_session + pkg_creation_recommendations --> pkg_skill + pkg_creation_recommendations --> pkg_tools + pkg_cua --> pkg_attachment + pkg_cua --> pkg_ptc_runtime_node + pkg_cua --> pkg_scope + pkg_cua --> pkg_user_questions pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_agent pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_browser_use pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_system_prompt @@ -1279,7 +1300,6 @@ flowchart TD pkg_tool_subagent --> pkg_agent pkg_tool_subagent --> pkg_agent_preset_registry pkg_tool_subagent --> pkg_llm - pkg_tool_subagent --> pkg_scope pkg_tool_subagent --> pkg_session pkg_tool_subagent --> pkg_session_projection pkg_tool_subagent --> pkg_subagent @@ -1470,6 +1490,7 @@ flowchart TD | [`launch-environment`](../packages/util/launch-environment) | `util` | — | | [`lazy-require`](../packages/util/lazy-require) | `util` | — | | [`native-command`](../packages/util/native-command) | `util` | — | +| [`official-bundles`](../packages/util/official-bundles) | `util` | — | | [`output-retention`](../packages/util/output-retention) | `util` | — | | [`package-manifest`](../packages/util/package-manifest) | `util` | — | | [`plugin-detail`](../packages/util/plugin-detail) | `util` | — | @@ -1490,7 +1511,6 @@ flowchart TD | [`api-remote-access`](../packages/api/remote-access) | `api` | — | | [`api-workspace-files`](../packages/api/workspace-files) | `api` | — | | [`cmdline`](../packages/boot/cmdline) | `boot` | — | -| [`official-bundles`](../packages/boot/official-bundles) | `boot` | — | | [`acp-app`](../packages/bundle/acp-app) | `bundle` | — | | [`base`](../packages/bundle/base) | `bundle` | — | | [`sdk-app`](../packages/bundle/sdk-app) | `bundle` | — | @@ -1564,15 +1584,20 @@ flowchart TD | [`client-web`](../packages/client/web) | `client` | — | | [`credentials`](../packages/credentials/credentials) | `credentials` | — | | [`office-to-pdf`](../packages/document/office-to-pdf) | `document` | — | +| [`client-ui-action-cards`](../packages/experimental/client-ui-action-cards) | `experimental` | — | +| [`client-ui-creation-recommendations`](../packages/experimental/client-ui-creation-recommendations) | `experimental` | — | +| [`client-ui-plugin-recommendations`](../packages/experimental/client-ui-plugin-recommendations) | `experimental` | — | | [`cua-bundle`](../packages/experimental/cua-bundle) | `experimental` | — | | [`experimental-agent-team-profile`](../packages/experimental/agent-team-profile) | `experimental` | — | | [`experimental-badge-skill-bundle`](../packages/experimental/badge-skill-bundle) | `experimental` | — | | [`experimental-client-ui-agent-team`](../packages/experimental/client-ui-agent-team) | `experimental` | — | | [`experimental-client-ui-claude-code-mods`](../packages/experimental/client-ui-claude-code-mods) | `experimental` | — | +| [`experimental-client-ui-stats`](../packages/experimental/client-ui-stats) | `experimental` | — | | [`experimental-client-ui-voice-input`](../packages/experimental/client-ui-voice-input) | `experimental` | — | | [`experimental-cot-translation-bundle`](../packages/experimental/cot-translation-bundle) | `experimental` | — | | [`experimental-inspector`](../packages/experimental/inspector) | `experimental` | — | | [`experimental-inspector-profile`](../packages/experimental/inspector-profile) | `experimental` | — | +| [`experimental-liveshare-protocol`](../packages/experimental/liveshare-protocol) | `experimental` | — | | [`experimental-plugin-market-bundle`](../packages/experimental/plugin-market-bundle) | `experimental` | — | | [`experimental-ralph-bundle`](../packages/experimental/ralph-bundle) | `experimental` | — | | [`experimental-session-inspector`](../packages/experimental/session-inspector) | `experimental` | — | @@ -1581,6 +1606,7 @@ flowchart TD | [`experimental-terminal-bundle`](../packages/experimental/terminal-bundle) | `experimental` | — | | [`experimental-voice-input-bundle`](../packages/experimental/voice-input-bundle) | `experimental` | — | | [`experimental-webworker-packer`](../packages/experimental/webworker-packer) | `experimental` | — | +| [`personalized-recommendations`](../packages/experimental/personalized-recommendations) | `experimental` | — | | [`client-ui-cordis`](../packages/extensions/ui-cordis) | `extensions` | — | | [`cordis-client-runner`](../packages/extensions/cordis-client-runner) | `extensions` | — | | [`host-directory-picker`](../packages/host/directory-picker) | `host` | — | @@ -1632,6 +1658,7 @@ flowchart TD | [`deliverable-file-references`](../packages/deliverables/deliverable-file-references) | `deliverables` | [`system-prompt`](../packages/core/system-prompt) | | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) | | [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) | +| [`plugin-recommendations`](../packages/experimental/plugin-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`skill`](../packages/skill/skill), [`typert-protocol`](../packages/typert/protocol) | | [`skill-badge`](../packages/experimental/skill-badge) | `experimental` | [`skill`](../packages/skill/skill) | | [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-connection`](../packages/client/connection), [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) | | [`host-frontend-static`](../packages/host/frontend-static) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver) | @@ -1685,7 +1712,7 @@ flowchart TD | [`tmux-context`](../packages/context/tmux-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell) | | [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`util-values`](../packages/util/values) | | [`commands`](../packages/interaction/commands) | `interaction` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | -| [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt) | +| [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`user-questions`](../packages/interaction/user-questions) | `interaction` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | | [`jobs`](../packages/jobs/jobs) | `jobs` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`session`](../packages/core/session), [`workspace`](../packages/workspace/workspace) | | [`sandbox-policy`](../packages/sandbox/sandbox-policy) | `sandbox` | [`agent`](../packages/core/agent), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | @@ -1695,7 +1722,7 @@ flowchart TD | [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand) | | [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`http-proxy`](../packages/util/http-proxy), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`timeout`](../packages/util/timeout) | +| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | | [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | | [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | @@ -1704,7 +1731,6 @@ flowchart TD | [`api-account-controller`](../packages/api/account-controller) | `api` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/credentials/deepseek-account), [`typert-protocol`](../packages/typert/protocol) | | [`compaction`](../packages/compaction/compaction) | `compaction` | [`brand`](../packages/util/brand), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) | `credentials` | [`authorization`](../packages/credentials/authorization), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`host-webserver`](../packages/host/webserver) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory) | | [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | @@ -1734,6 +1760,9 @@ flowchart TD | [`file-reference-local`](../packages/context/file-reference-local) | `context` | [`agent`](../packages/core/agent), [`file-reference`](../packages/context/file-reference), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-present`](../packages/deliverables/tool-present) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | +| [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | +| [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | @@ -1796,7 +1825,7 @@ flowchart TD | [`subagent-codex`](../packages/subagent/subagent-codex) | `subagent` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process) | `subagent` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process) | `subagent` | [`subagent`](../packages/subagent/subagent) | -| [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`api-session-controller`](../packages/api/session-controller) | `api` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`api-gateway`](../packages/api/gateway), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-file-upload`](../packages/client/file-upload), [`commands`](../packages/interaction/commands), [`credentials`](../packages/credentials/credentials), [`file-reference`](../packages/context/file-reference), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`native-command`](../packages/util/native-command), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`settings`](../packages/settings/settings), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol), [`typert-registry`](../packages/typert/registry), [`util-time`](../packages/util/time), [`util-values`](../packages/util/values), [`util-workspace-path`](../packages/util/workspace-path), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`plugin-market`](../packages/boot/plugin-market) | `boot` | [`plugin-manager`](../packages/boot/plugin-manager), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index 291a298c66..280eda500e 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -9,11 +9,11 @@ en: 1387c4505dde2faf zh: 48570fa1c13d6910 /session-persistence-event-catalog/persistence-type-fingerprints: - en: bcff48893d904af8 - zh: f82e75c91c39adb1 + en: 519d46d6078d3f68 + zh: ec9aec262312c573 /session-persistence-event-catalog/event-envelope: - en: 981db6b1928eda50 - zh: d77bc66cf678099d + en: 56414ffd00cdc32a + zh: 6dc11eb013e95e41 /session-persistence-event-catalog/events: en: f4776ba3d0fd53ce zh: e86769f50a69055a @@ -39,17 +39,17 @@ en: 1e65aa4c24a595ee zh: fe7f527c5e45d6a6 /session-persistence-event-catalog/events/approval/approval-policy-log-only: - en: d520080fbb669b54 - zh: a4459a534c1c96c5 + en: 13ecb3c4d92a39e2 + zh: 98ca36fea1b799ec /session-persistence-event-catalog/events/assistant: en: 44426b6cd0dc01cf zh: 44426b6cd0dc01cf /session-persistence-event-catalog/events/assistant/assistant-attempt-log-only: - en: 4e684124f71bd73b - zh: 445ad50a3a4fb635 + en: f330b2521ca12383 + zh: cdc6912a9244677d /session-persistence-event-catalog/events/assistant/assistant-message-surface: - en: 87d9bb62e2aea4b9 - zh: 68ef3b05d4aad7d3 + en: 95916897e677eee6 + zh: e1ea8b17e5af9f35 /session-persistence-event-catalog/events/command: en: 2cecb5b0ee955732 zh: 2cecb5b0ee955732 @@ -84,8 +84,8 @@ en: 3344204b1858edb1 zh: 3344204b1858edb1 /session-persistence-event-catalog/events/developer/developer-message-surface: - en: 927f25c5dbd69c82 - zh: 9c0331f6e61d7e2b + en: fd716cfc669a05a0 + zh: 8693a334958ab3cf /session-persistence-event-catalog/events/feedback: en: f50dbac6867fa64d zh: f50dbac6867fa64d @@ -159,11 +159,11 @@ en: a8df82440ebdf5f8 zh: a8df82440ebdf5f8 /session-persistence-event-catalog/events/request/request-context-log-only: - en: 9167d83823675b3e - zh: dfe9095419cf76f4 + en: 22abf9a3f69d498f + zh: 94055a136b641207 /session-persistence-event-catalog/events/request/request-header-log-only: - en: 6d9e26081d1e3aec - zh: 36d30d0bff197d1e + en: 6c506b420662b60e + zh: 823513802c2cc394 /session-persistence-event-catalog/events/sandbox: en: ec841ab8439335b0 zh: ec841ab8439335b0 @@ -174,14 +174,14 @@ en: e5b55405bd2b69f5 zh: e5b55405bd2b69f5 /session-persistence-event-catalog/events/schedule/schedule-change-log-only: - en: 162584304e006c72 - zh: d8a6bacf60777aa9 + en: e73c202fb99159b6 + zh: b1f43bbd116f83da /session-persistence-event-catalog/events/session: en: a1ac8f2660a4f61e zh: a1ac8f2660a4f61e /session-persistence-event-catalog/events/session/session-end-seed-log-only: - en: f285c670d1bf0e71 - zh: 14ec5689a5943156 + en: 20645a60e921f012 + zh: 7141cafe3a0e71d7 /session-persistence-event-catalog/events/session/session-title-log-only: en: 6c6a27578dff5828 zh: 9a5add2bc0df2d0a @@ -198,11 +198,11 @@ en: bd0dcbbc352b771a zh: bd0dcbbc352b771a /session-persistence-event-catalog/events/step/step-end-log-only: - en: 24bc99ca25809609 - zh: 420384e753feba64 + en: b30d8571ba611386 + zh: 42e45b49142c306c /session-persistence-event-catalog/events/step/step-start-log-only: - en: 269a493d00348184 - zh: 80feab63a0431c60 + en: 161a661514649037 + zh: 5a2e3ec5af378746 /session-persistence-event-catalog/events/subagent: en: 9630752e97ddbfbc zh: 9630752e97ddbfbc @@ -219,8 +219,8 @@ en: 8cac41d2fb575975 zh: 8cac41d2fb575975 /session-persistence-event-catalog/events/system/system-message-surface: - en: 23aedcadb0c95a51 - zh: f58e5195075ddb21 + en: f08085060f967358 + zh: 4d77a8636d9bfef5 /session-persistence-event-catalog/events/team: en: a640800a38b3c874 zh: a640800a38b3c874 @@ -246,8 +246,8 @@ en: 28a24430609494b2 zh: 28a24430609494b2 /session-persistence-event-catalog/events/tool/tool-call-log-only: - en: b5dfd3b4c54281c3 - zh: 3ac01ceab4a36d06 + en: 2edbe249bcd484fc + zh: fa838ad8325507b4 /session-persistence-event-catalog/events/tool/tool-ptc-dispatch-log-only: en: a62b38c00afed655 zh: 793bef93e856eafa @@ -255,8 +255,8 @@ en: da841b1ed3b22c87 zh: 4c9a4d4bc5bd76b6 /session-persistence-event-catalog/events/tool/tool-result-surface: - en: 722a3bf051b384eb - zh: 01e1258be37a82ce + en: e5fdf9592ffa86b4 + zh: 7455727a8f208a1c /session-persistence-event-catalog/events/tool-workflow: en: 1eac7deac6af15f3 zh: 1eac7deac6af15f3 @@ -276,17 +276,17 @@ en: d7e8c999a0851a0c zh: d7e8c999a0851a0c /session-persistence-event-catalog/events/turn/turn-end-log-only: - en: 38d2280f449d3112 - zh: 0f7f05475ea514a3 + en: 7d5bacee7392ed18 + zh: 65b8eb8ab9b10ccd /session-persistence-event-catalog/events/turn/turn-start-log-only: - en: 853b7f23d092c48a - zh: 53e312793b609198 + en: 1b5d3369f6178575 + zh: 34550bedca73336a /session-persistence-event-catalog/events/user: en: d864a88c03e8971c zh: d864a88c03e8971c /session-persistence-event-catalog/events/user/user-message-surface: - en: ba681b5ec685d6e8 - zh: e4b14b585d2b5804 + en: 836d2e0de5f33816 + zh: 67055e83e820f5f5 /session-persistence-event-catalog/events/web: en: d278748103cf1640 zh: d278748103cf1640 @@ -309,8 +309,11 @@ en: 3493ecf0993e5397 zh: ec95688f593a4ed4 /session-persistence-event-catalog/resolved-persistence-types/aborted: - en: d716fb9ee9baa564 - zh: d716fb9ee9baa564 + en: 40049fd36471e4b2 + zh: 40049fd36471e4b2 +/session-persistence-event-catalog/resolved-persistence-types/action-cards: + en: 629f821b50a38bc6 + zh: 629f821b50a38bc6 /session-persistence-event-catalog/resolved-persistence-types/active: en: 6b343e390ae7d7a7 zh: 6b343e390ae7d7a7 @@ -969,8 +972,8 @@ en: bb7b3652609ac651 zh: bdde4e652413c5eb /session-persistence-event-catalog/resolved-persistence-types/approvalpolicy: - en: 670f484e05d50fa7 - zh: 7c107f338ea6cf81 + en: c78bdd273133a02f + zh: 2cbbc4d9c7e0a726 /session-persistence-event-catalog/resolved-persistence-types/assistantmessage: en: 2a8bc13a30855b26 zh: 87f1f5fd2882a411 @@ -981,8 +984,8 @@ en: e393deed01de3665 zh: 0fa98ad93c22ce79 /session-persistence-event-catalog/resolved-persistence-types/commandsource: - en: 53feeeb70547e7df - zh: 99d9e901d9b4afe5 + en: 459a6f8c8800d3e5 + zh: f1b2626c08c62b4d /session-persistence-event-catalog/resolved-persistence-types/compactioncheckpointsource: en: 87f2aaf2b23a5249 zh: 3d6c5ed6603bee31 @@ -1005,14 +1008,14 @@ en: a6a2e38fdd6d127a zh: 1fe82356d89f5769 /session-persistence-event-catalog/resolved-persistence-types/deepseeksearchllmrequest: - en: 128c0ecc1897eb68 - zh: e4c67c92752bcc2a + en: cf3979c698e2b2ac + zh: 6252c8b668faa706 /session-persistence-event-catalog/resolved-persistence-types/developermessage: - en: 997b5db27df00446 - zh: 07e5197ddd7bd59b + en: 16992572a6919e52 + zh: 853f4873fd520444 /session-persistence-event-catalog/resolved-persistence-types/epochheader: - en: c804cb9e2e31c5ec - zh: 3ed7ac59cd1441b7 + en: 3bdc8ecd0bdf0c9c + zh: 0fe5b75c174ebab4 /session-persistence-event-catalog/resolved-persistence-types/everyscheduledispatchchange: en: 54c487394ce0db1d zh: 48d7c9affbe841cb @@ -1119,11 +1122,11 @@ en: 6dbe099c62f7c226 zh: 6fd788f63c038c91 /session-persistence-event-catalog/resolved-persistence-types/llmretrystartedeventdata: - en: c2d9edd8d9f492b7 - zh: f59c687ac691f7ce + en: 5d61649043e317aa + zh: bdf9b9d553d291cf /session-persistence-event-catalog/resolved-persistence-types/message: - en: 594707e4894819a8 - zh: 268c4bfd5c4c28f2 + en: 56953b055da0dc2b + zh: dcaa193ddb2fece0 /session-persistence-event-catalog/resolved-persistence-types/messagefeedbackdelete: en: c582953270d4ca44 zh: 966ccfe2e7660a2a @@ -1134,14 +1137,14 @@ en: f58575a1fc96df42 zh: 9f0c6ed9033e5c9d /session-persistence-event-catalog/resolved-persistence-types/messagefeedbackrating: - en: 674296d54c1914d0 - zh: 3d71ab319514be25 + en: 70ade19513d0070f + zh: ff9acb50974a32ae /session-persistence-event-catalog/resolved-persistence-types/messagesource: - en: 3fab179fe8d58c31 - zh: 5328c9161ff908a9 + en: b1bd7c8bd2309d45 + zh: d434e41517c3620d /session-persistence-event-catalog/resolved-persistence-types/message~2: - en: 8bd12543fcdcda5f - zh: d4c6b17083948856 + en: dcd71b3190faff96 + zh: b2c07224705aa52e /session-persistence-event-catalog/resolved-persistence-types/modelmessagesource: en: 5f9154ca34235ab9 zh: a833105910ebfa82 @@ -1179,11 +1182,11 @@ en: 488050ba0b6438b4 zh: 2bf607b5ad51e39d /session-persistence-event-catalog/resolved-persistence-types/requestcontext: - en: 00058b6c2220cdcb - zh: a3426a8c69123e2e + en: 544039047a28b6bb + zh: c691f0bb1e23db08 /session-persistence-event-catalog/resolved-persistence-types/requestheaderreason: - en: 8e563a11c123255f - zh: ebf891f6a3cb93d3 + en: 1f691c223f54ab2c + zh: f88fef3ee9745c91 /session-persistence-event-catalog/resolved-persistence-types/sandboxmode: en: c9fa5343ea99733b zh: d6de41351c57a73f @@ -1203,11 +1206,11 @@ en: 9a54c4478ad3b620 zh: 02c4c1fd7e252770 /session-persistence-event-catalog/resolved-persistence-types/sessiontitleeventdata: - en: bf7325029c9338d6 - zh: e5f98271511e5318 + en: 46baac9dcdfb1b63 + zh: 30a357bb8405c147 /session-persistence-event-catalog/resolved-persistence-types/sessiontitlellmrequesteventdata: - en: 89dcb9a9b957c126 - zh: 132aeb7dfd435290 + en: 035b656ba6500174 + zh: fc9d4d7cd154ca78 /session-persistence-event-catalog/resolved-persistence-types/sessiontitlemodelidentity: en: 9531468264499498 zh: 9da23c0ad2776563 @@ -1215,11 +1218,11 @@ en: 13de8e35b749db45 zh: 01e4f3bcb6784fc8 /session-persistence-event-catalog/resolved-persistence-types/sessiontitlesource: - en: 2642015fb4518c8c - zh: 152b294f41fbdcca + en: d842f1883e1b97d1 + zh: 41356f94354511ce /session-persistence-event-catalog/resolved-persistence-types/skillcatalogsource: - en: de04d42a8b0004df - zh: db64863dd7da1e26 + en: 2c3148e4a9f0c8f9 + zh: dab42cb485067bcd /session-persistence-event-catalog/resolved-persistence-types/skillinvocationsource: en: ecc15ebadb77afdf zh: 97ac27d6a4175f6f @@ -1236,8 +1239,8 @@ en: d34acab659e74957 zh: 25cabc6c9fb44a7e /session-persistence-event-catalog/resolved-persistence-types/surfaceop: - en: a62be7c2cb8a4af7 - zh: 616fd1ac4bd3995a + en: 737806b6ec54263d + zh: b4e44293950ddf8c /session-persistence-event-catalog/resolved-persistence-types/systemmessage: en: 94876079d6696df9 zh: d25c7ad9f5054eb7 @@ -1311,17 +1314,17 @@ en: 54090e169899c573 zh: 530ea8d0d0f8cf68 /session-persistence-event-catalog/resolved-persistence-types/turnendcancelcause: - en: 4dc89c072fe5d0d1 - zh: 4ed2c9e9e8b4f7e2 + en: 778debd61e0284a2 + zh: 2cc82ad9e80f18b1 /session-persistence-event-catalog/resolved-persistence-types/turnendreason: - en: 344a7207a4199a32 - zh: d500af39e83289cf + en: 3cbc1b5ae251451f + zh: a95ff0555e368432 /session-persistence-event-catalog/resolved-persistence-types/usermessage: - en: bd3aedd570ded4d2 - zh: f020d0816d3a6c1a + en: 1b30ae0450f156bd + zh: 00bb0efae7ac741e /session-persistence-event-catalog/resolved-persistence-types/usermessage~2: - en: b99d66ffe277f0bc - zh: eacc9c1f62ae66c1 + en: 1f242f48a3c8c230 + zh: 2516be50ce573b0c /session-persistence-event-catalog/resolved-persistence-types/workflowagentoutcome: en: d0a3f9aab18c3de5 zh: 76ac69a835ca4e29 @@ -1347,8 +1350,8 @@ en: 2786fef560851bb4 zh: 5d787475356b2606 /session-persistence-event-catalog/resolved-persistence-types/string: - en: a9d7dc010ada133d - zh: 9bd682adee72d04e + en: 1e12d380c4988d40 + zh: 14a781104e00f360 /session-persistence-event-catalog/resolved-persistence-types/string~2: en: 0089620bf4638263 zh: 1922bef1713094bb @@ -1410,8 +1413,8 @@ en: a117573a5d58cb3c zh: d5ad59e17a3a815d /session-persistence-event-catalog/resolved-persistence-types/arguments-callid-name-step: - en: 036101ee99efbf72 - zh: a324d7f9f671bab0 + en: 1cd530a4f45fcb4f + zh: 0bf7c0f53d10a5ec /session-persistence-event-catalog/resolved-persistence-types/callid-files-turn: en: 5f4d3f66ed86a14d zh: 7c729360fa1279e6 @@ -1443,8 +1446,8 @@ en: a1f188c9058cf621 zh: eb43c0f045fb9afb /session-persistence-event-catalog/resolved-persistence-types/code-name-reason: - en: 17649d71411cb827 - zh: abb3138d38c76459 + en: 25df2af19bc9c46d + zh: ebb6ecbeee25c9be /session-persistence-event-catalog/resolved-persistence-types/commandid-kind-sourceeventseq-text: en: 87b03e1c73d2a326 zh: d7b9f06863cad891 @@ -1473,8 +1476,8 @@ en: 10a2d594b106f6fe zh: 8408379e744ad987 /session-persistence-event-catalog/resolved-persistence-types/description-name: - en: e501ab0e92f12d77 - zh: 087fb91a04f85398 + en: 26072d80c066a334 + zh: 48deed5b57fecba4 /session-persistence-event-catalog/resolved-persistence-types/description-name~2: en: a07969828eed2e6f zh: e06893743af544b5 @@ -1485,14 +1488,14 @@ en: 4b7a8793663d3fef zh: 249459c825d330c3 /session-persistence-event-catalog/resolved-persistence-types/endseq-op-startseq: - en: 1a533265eb56a8b8 - zh: 57480f4b53713570 + en: 766772dfbbb2e164 + zh: 09973d26e68004cb /session-persistence-event-catalog/resolved-persistence-types/error-kind-error: - en: 8d0448ef77e0da08 - zh: 25770329c9db129a + en: e0833e1b1cdb29d0 + zh: 6244880c79509016 /session-persistence-event-catalog/resolved-persistence-types/error-message-meta-step: - en: 9ffa836bf88fd7b4 - zh: 7ca8bc7ebefeadb8 + en: d019b2909673d2a7 + zh: cc16e9c055ea603d /session-persistence-event-catalog/resolved-persistence-types/failure-kind-aborted: en: 349cd90f2598fd12 zh: 1eda02d520ad5d76 @@ -1500,11 +1503,11 @@ en: 51af619ed8532a43 zh: a5ad878c63d0e046 /session-persistence-event-catalog/resolved-persistence-types/header-reason-startsseries: - en: 0b1ca5c765d716d1 - zh: dd939095c250c4eb + en: 27f5b76003ac1ead + zh: 2a5a0490cc22512b /session-persistence-event-catalog/resolved-persistence-types/headerseq-message-step-turn: - en: 3d16abb7b9581429 - zh: dc959157864261d8 + en: 598021cdfe2a8687 + zh: 02e63a8b453f2f4e /session-persistence-event-catalog/resolved-persistence-types/height-width: en: a5df50710083ac25 zh: aad3ccf6f6de70e4 @@ -1521,29 +1524,50 @@ en: 41f73c58a77dfa28 zh: af77f4aee3cb4a40 /session-persistence-event-catalog/resolved-persistence-types/inherited: - en: 6ce6ddac6d815805 - zh: f7196176e902c965 + en: 7e64cae3bd1b71e9 + zh: 7451c0639044c59a /session-persistence-event-catalog/resolved-persistence-types/inserted-outcome-removedcount-start: - en: 346d884a7a74e48d - zh: 646ac1021f9ca920 + en: df2dd98c35b34bd2 + zh: ee25992a3f29d561 /session-persistence-event-catalog/resolved-persistence-types/interrupted-message-step-stream: - en: 89fb3f919d181c86 - zh: 4380624236500687 + en: 8e86cd838e3e4a49 + zh: f5fec2a8adf1f3cc /session-persistence-event-catalog/resolved-persistence-types/kind-aborted-reason: - en: 48424cbed3fbc269 - zh: 2ce88c04ad002104 + en: d2b0ef9a4e2b9be5 + zh: 44ad13fbbf836ac7 +/session-persistence-event-catalog/resolved-persistence-types/kind-action-cards: + en: 8d057f0bd0b88fc6 + zh: 500d1e3d54e6d7c4 +/session-persistence-event-catalog/resolved-persistence-types/kind-action-cards-form-catalog: + en: 14e9dd01c49f91e0 + zh: 4a7e4e4aeeb15982 +/session-persistence-event-catalog/resolved-persistence-types/kind-action-cards-form-instructions: + en: f59ec0c37dc8f9b6 + zh: debc915ed98581fb +/session-persistence-event-catalog/resolved-persistence-types/kind-action-cards-form-notice: + en: ef0a456530698cca + zh: 23f2ace5345eb847 +/session-persistence-event-catalog/resolved-persistence-types/kind-action-cards-form-recall: + en: 0b607f9577e3a3c5 + zh: 237ed72b7a4154df +/session-persistence-event-catalog/resolved-persistence-types/kind-action-cards-form-relay: + en: 712bc9ad7c51a8fe + zh: f230dc9c09bdbf3c +/session-persistence-event-catalog/resolved-persistence-types/kind-action-cards-form-snapshot: + en: 4e030b06ef900819 + zh: 27532bbabe118206 /session-persistence-event-catalog/resolved-persistence-types/kind-blocked: - en: 2fad818b19823c48 - zh: a6b33dee21c3fdc9 + en: 9db831e991ef17ce + zh: 332002f65d191b68 /session-persistence-event-catalog/resolved-persistence-types/kind-completed: - en: e8f76b61a39ebeb0 - zh: e61a304be00b4490 + en: 9affe5d5dac75c57 + zh: 8db62dcb41e804c8 /session-persistence-event-catalog/resolved-persistence-types/kind-cordis-host-runner: en: fb7b8207a6ef3b81 zh: 9d6f112181d90701 /session-persistence-event-catalog/resolved-persistence-types/kind-disposed: - en: e3c9527803bc6de3 - zh: 375c82ce2ac5282b + en: 9a3ce668c21d6c90 + zh: f661c7ce62c44a60 /session-persistence-event-catalog/resolved-persistence-types/kind-dsh-session-title-llm: en: 428529e5dedc761d zh: 3ca0b54c9c521ea0 @@ -1569,11 +1593,11 @@ en: 78e34e6d0d70339e zh: 072127e40cfb9686 /session-persistence-event-catalog/resolved-persistence-types/kind-forked: - en: e2588043ee1a8d50 - zh: d87a5bff12b9190f + en: 4663f6c1a2634822 + zh: 3a2e4f61195759a0 /session-persistence-event-catalog/resolved-persistence-types/kind-hook: - en: 78278a869370695f - zh: 6cdc47f1876f3b23 + en: 669685ab52bb7b68 + zh: 94325f99ba96dec5 /session-persistence-event-catalog/resolved-persistence-types/kind-hooks-claude-code: en: 5eb383a67f11ac4d zh: 1943747cb4995dbc @@ -1617,14 +1641,14 @@ en: a8a338be3b91008f zh: c7632c42c869c2f6 /session-persistence-event-catalog/resolved-persistence-types/kind-interrupted: - en: 452b4a96d072a9b9 - zh: d63c8ab84bd37dbb + en: 8f5585c1e90d6ca3 + zh: 78329cf995882344 /session-persistence-event-catalog/resolved-persistence-types/kind-legacy: - en: c6f68741f8631d4f - zh: 090b58f2b86c02d0 + en: 673110c18ee48238 + zh: e8dd81d68e1a4ee0 /session-persistence-event-catalog/resolved-persistence-types/kind-max-tokens: - en: f85b7a64a6a5f1f7 - zh: 3f4ad5183e1020fd + en: 337ebe760096729a + zh: bd35a401103a3071 /session-persistence-event-catalog/resolved-persistence-types/kind-model-selection: en: a5165486dca91116 zh: b7051ca8167806ef @@ -1647,8 +1671,8 @@ en: 509f9a91aedb2da1 zh: db1071678bfb98d1 /session-persistence-event-catalog/resolved-persistence-types/kind-parent: - en: 7a3ac2238405913d - zh: b249a4d6d0508d40 + en: 5ab43c283829de53 + zh: 5ed4e90922a3a88b /session-persistence-event-catalog/resolved-persistence-types/kind-plan-mode: en: 9758304800b717df zh: dccf14f3a5d0d861 @@ -1833,8 +1857,8 @@ en: 5a0bbf4c76266ac5 zh: 0b20854f90f9d74d /session-persistence-event-catalog/resolved-persistence-types/kind-user: - en: 81620af099525ee9 - zh: 812db2fdf9e5d309 + en: e98b716228feb157 + zh: 2bb593ae9cd0ce0d /session-persistence-event-catalog/resolved-persistence-types/kind-user-approval: en: a52d2dfbaf844127 zh: 4c5306ca40f20873 @@ -1872,8 +1896,8 @@ en: 82b0989dad6bbfc0 zh: 0789b63f1d59b2ed /session-persistence-event-catalog/resolved-persistence-types/message-step-turn: - en: 762219ab10a2d9b1 - zh: ce31f3b385595b96 + en: 86fe91fe83eeb08a + zh: 2ebf2f1904829753 /session-persistence-event-catalog/resolved-persistence-types/message-teamid-version: en: f778769acb264dd5 zh: eba9b81d04e9f57b @@ -1884,14 +1908,14 @@ en: 3028b222670ce5ad zh: cae4c9437e560d61 /session-persistence-event-catalog/resolved-persistence-types/policy-source: - en: 00f1d435f82d2753 - zh: c2ab108ad2748a6c + en: 88fd92dff7aa505f + zh: b400712b3ef749aa /session-persistence-event-catalog/resolved-persistence-types/preset: en: 8ebd37343b638773 zh: bf7ffa9a60ca42a8 /session-persistence-event-catalog/resolved-persistence-types/reason-turn: - en: 2d45d5c5e3959d12 - zh: df4d0d7fca4e26bc + en: b8d80b4b1e6441ad + zh: d5c52e1bfe560297 /session-persistence-event-catalog/resolved-persistence-types/role-user: en: 04b34b8ffe7e7764 zh: a792d5371516fd9d @@ -1902,11 +1926,11 @@ en: 7a2ab7b62244f43b zh: 1084e3f8876feebc /session-persistence-event-catalog/resolved-persistence-types/step-stream-turn: - en: d911fd8591d66386 - zh: cba2966a909b9293 + en: 59f11c6d124335cb + zh: 5bbdd6c88612fcff /session-persistence-event-catalog/resolved-persistence-types/step-turn: - en: 4bbf63488cce88c9 - zh: 46b40433a749c133 + en: 8f9e774f89087efa + zh: 72474e7e556e2469 /session-persistence-event-catalog/resolved-persistence-types/targets: en: 5360af614fe753e3 zh: 96427c489cc71de6 @@ -1917,14 +1941,14 @@ en: 8ab873d30e062fd5 zh: a138832c6e299ebb /session-persistence-event-catalog/resolved-persistence-types/turn: - en: ea32b4165dbfb182 - zh: 57f48af06cfa201c + en: 374b8adee8d571fa + zh: b21057efc58e6490 /session-persistence-event-catalog/resolved-persistence-types/type-agent-preset-selected: - en: c8c731ee23bed85a - zh: f4ffc80f7828701d + en: a990181189cf77ac + zh: 70198727356d1ad3 /session-persistence-event-catalog/resolved-persistence-types/type-agent-inbox-spliced: - en: 62dfe9447efaceb1 - zh: 076454de19b5d7d7 + en: f3b491e65c79b3a0 + zh: 2d3e53ceb67a55a3 /session-persistence-event-catalog/resolved-persistence-types/type-approval-asked: en: 9c77f18b0dad22f0 zh: 8894cf2878fe90db @@ -1968,11 +1992,11 @@ en: ba73fb10b7e2ffc9 zh: 8d5c97e63e5f16da /session-persistence-event-catalog/resolved-persistence-types/type-deliverables-presented: - en: a4d9eab2928e9b30 - zh: b36702c866518273 + en: 17956f440c284ea3 + zh: 5dbfd68d50483047 /session-persistence-event-catalog/resolved-persistence-types/type-developer-message: - en: a9e6e24b98390923 - zh: 65addae898d8aaec + en: ded2f3b02f776800 + zh: 4d6619c283a18e3c /session-persistence-event-catalog/resolved-persistence-types/type-disabled: en: 585627a50ece4e5f zh: 157837aee3da0ac3 @@ -2046,11 +2070,11 @@ en: acf7e21e4d21ebff zh: fb83a853634d204a /session-persistence-event-catalog/resolved-persistence-types/type-session-title: - en: b99fbacda0db1abd - zh: 9e75ce6b1d174d48 + en: f0acf1c873cd9e2a + zh: b8e175e14306afd4 /session-persistence-event-catalog/resolved-persistence-types/type-session-title-llm-request: - en: 7ba30b98d8e3f653 - zh: ca68b01ab4b6ba3d + en: ab4f20d890eed5e5 + zh: 6e4035a166821157 /session-persistence-event-catalog/resolved-persistence-types/type-step-end: en: 7fc233c4a569dae2 zh: bc2b3fed4a397c00 @@ -2127,11 +2151,11 @@ en: 1b045de96172be4b zh: 8a15c6f35b576b37 /session-persistence-event-catalog/resolved-persistence-types/type-usage: - en: 8eec3bb6eee5085b - zh: 04bb3281fd7bd95c + en: 4ed36e4498f5f203 + zh: 7b3fcddec14c306b /session-persistence-event-catalog/resolved-persistence-types/type-user-message: - en: d6d9401f19a66ee8 - zh: 569fdddf887660a2 + en: 5b8341a673284ec1 + zh: e3264a827babffeb /session-persistence-event-catalog/resolved-persistence-types/type-web-deepseek-search-llm-request: en: 99c8837344178a47 zh: bf746f5678346596 diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index e98ae23f5c..97cfa4bd63 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -23,7 +23,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `JsonlHeaderLine` | header | `18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f` | [`HeaderLine`](#persistence-type-sha256-18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f) | | `SessionEventEnvelope` | envelope | `5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc` | [`union (3 variants)`](#persistence-type-sha256-5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc) | | `event:agent-preset/selected` | event | `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | [`{ type: "agent-preset/selected" }`](#persistence-type-sha256-a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b) | -| `event:agent/inbox/spliced` | event | `0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034) | +| `event:agent/inbox/spliced` | event | `9e8043098fb89db6d7c92a92c70146c5c8d24fa88f733c687fa29e5e7a58ab30` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-9e8043098fb89db6d7c92a92c70146c5c8d24fa88f733c687fa29e5e7a58ab30) | | `event:approval/asked` | event | `3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1` | [`{ type: "approval/asked" }`](#persistence-type-sha256-3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1) | | `event:approval/decided` | event | `bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3` | [`{ type: "approval/decided" }`](#persistence-type-sha256-bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3) | | `event:approval/policy` | event | `26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78` | [`{ type: "approval/policy" }`](#persistence-type-sha256-26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78) | @@ -36,7 +36,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:compaction/start` | event | `db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965` | [`{ type: "compaction/start" }`](#persistence-type-sha256-db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965) | | `event:compaction/summary` | event | `e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602` | [`{ type: "compaction/summary" }`](#persistence-type-sha256-e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602) | | `event:deliverables/presented` | event | `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | [`{ type: "deliverables/presented" }`](#persistence-type-sha256-13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176) | -| `event:developer/message` | event | `97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c` | [`{ type: "developer/message" }`](#persistence-type-sha256-97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c) | +| `event:developer/message` | event | `95acdbd066cf445d37092e5fdfe2e8717ef6ca1aed50f70e2e6037a6989a1f2f` | [`{ type: "developer/message" }`](#persistence-type-sha256-95acdbd066cf445d37092e5fdfe2e8717ef6ca1aed50f70e2e6037a6989a1f2f) | | `event:feedback/message-delete` | event | `3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796` | [`{ type: "feedback/message-delete" }`](#persistence-type-sha256-3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796) | | `event:feedback/message-put` | event | `b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf` | [`{ type: "feedback/message-put" }`](#persistence-type-sha256-b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf) | | `event:feedback/record` | event | `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` | [`{ type: "feedback/record" }`](#persistence-type-sha256-b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8) | @@ -58,7 +58,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:session-log-deepseek/delivery-accepted` | event | `d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9` | [`{ type: "session-log-deepseek/delivery-accepted" }`](#persistence-type-sha256-d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9) | | `event:session/end-seed` | event | `5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e` | [`{ type: "session/end-seed" }`](#persistence-type-sha256-5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e) | | `event:session/title` | event | `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | [`{ type: "session/title" }`](#persistence-type-sha256-1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5) | -| `event:session/title-llm-request` | event | `79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056) | +| `event:session/title-llm-request` | event | `eaa9125aec0fb28478096c46e73e21bf512ab0d84d826bfb41e7308707734cb5` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-eaa9125aec0fb28478096c46e73e21bf512ab0d84d826bfb41e7308707734cb5) | | `event:step/end` | event | `e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05` | [`{ type: "step/end" }`](#persistence-type-sha256-e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05) | | `event:step/start` | event | `4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986` | [`{ type: "step/start" }`](#persistence-type-sha256-4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986) | | `event:subagent/catalog` | event | `53750b9abf61efb7992b0aadc3e247ec927449c63266df28230fd1139f5590ac` | [`{ type: "subagent/catalog" }`](#persistence-type-sha256-53750b9abf61efb7992b0aadc3e247ec927449c63266df28230fd1139f5590ac) | @@ -80,7 +80,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:tool/result` | event | `7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397` | [`{ type: "tool/result" }`](#persistence-type-sha256-7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397) | | `event:turn/end` | event | `0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce` | [`{ type: "turn/end" }`](#persistence-type-sha256-0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce) | | `event:turn/start` | event | `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` | [`{ type: "turn/start" }`](#persistence-type-sha256-aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8) | -| `event:user/message` | event | `2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8` | [`{ type: "user/message" }`](#persistence-type-sha256-2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8) | +| `event:user/message` | event | `39adb7fce8475af6402acd925ea79697b3341c22422ac32833d71217d84e987f` | [`{ type: "user/message" }`](#persistence-type-sha256-39adb7fce8475af6402acd925ea79697b3341c22422ac32833d71217d84e987f) | | `event:web/deepseek-search-llm-request` | event | `0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52` | [`{ type: "web/deepseek-search-llm-request" }`](#persistence-type-sha256-0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52) | | `event:working-directory/change` | event | `124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3` | [`{ type: "working-directory/change" }`](#persistence-type-sha256-124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3) | | `event:workspace/changes` | event | `e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72` | [`{ type: "workspace/changes" }`](#persistence-type-sha256-e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72) | @@ -160,7 +160,7 @@ export type SessionEvent = { }[T] ``` -Sources: [`packages/core/session/src/types.ts:433`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:441`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:464`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:495`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:439`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:447`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:470`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:501`](../packages/core/session/src/types.ts) ## Events @@ -273,7 +273,7 @@ Source: [`packages/interaction/user-approval/src/types.ts:55`](../packages/inter } ``` -Source: [`packages/interaction/user-approval/src/index.ts:40`](../packages/interaction/user-approval/src/index.ts) +Source: [`packages/interaction/user-approval/src/index.ts:41`](../packages/interaction/user-approval/src/index.ts) ### `assistant/*` @@ -290,7 +290,7 @@ Source: [`packages/interaction/user-approval/src/index.ts:40`](../packages/inter 'assistant/attempt': { turn: number; step: number; stream: AssistantStreamRecord[] } ``` -Source: [`packages/core/session/src/types.ts:357`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:363`](../packages/core/session/src/types.ts) @@ -320,7 +320,7 @@ Source: [`packages/core/session/src/types.ts:357`](../packages/core/session/src/ Types: [TokenUsage](subsystems/llm-streaming.md) -Source: [`packages/core/session/src/types.ts:343`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:349`](../packages/core/session/src/types.ts) ### `command/*` @@ -508,7 +508,7 @@ Source: [`packages/deliverables/tool-present/src/types.ts:15`](../packages/deliv } ``` -Source: [`packages/core/session/src/types.ts:313`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:317`](../packages/core/session/src/types.ts) ### `feedback/*` @@ -753,7 +753,7 @@ Source: [`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/s 'request/context': RequestContext ``` -Source: [`packages/core/session/src/types.ts:404`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:410`](../packages/core/session/src/types.ts) @@ -772,7 +772,7 @@ Source: [`packages/core/session/src/types.ts:404`](../packages/core/session/src/ } ``` -Source: [`packages/core/session/src/types.ts:392`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:398`](../packages/core/session/src/types.ts) ### `sandbox/*` @@ -813,7 +813,7 @@ Source: [`packages/sandbox/sandbox-policy/src/session-mode.ts:33`](../packages/s Types: [ScheduleChange](subsystems/schedule.md) -Source: [`packages/schedule/schedule/src/types.ts:365`](../packages/schedule/schedule/src/types.ts) +Source: [`packages/schedule/schedule/src/types.ts:371`](../packages/schedule/schedule/src/types.ts) ### `session/*` @@ -849,7 +849,7 @@ Source: [`packages/schedule/schedule/src/types.ts:365`](../packages/schedule/sch 'session/end-seed': { inherited?: true } ``` -Source: [`packages/core/session/src/types.ts:429`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:435`](../packages/core/session/src/types.ts) @@ -911,7 +911,7 @@ Source: [`packages/session/session-log-deepseek/src/types.ts:81`](../packages/se 'step/end': { turn: number; step: number } ``` -Source: [`packages/core/session/src/types.ts:303`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:307`](../packages/core/session/src/types.ts) @@ -922,7 +922,7 @@ Source: [`packages/core/session/src/types.ts:303`](../packages/core/session/src/ 'step/start': { turn: number; step: number } ``` -Source: [`packages/core/session/src/types.ts:301`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:305`](../packages/core/session/src/types.ts) ### `subagent/*` @@ -987,8 +987,10 @@ Source: [`packages/subagent/tool-subagent/src/model-selection-state.ts:17`](../p * The rendered system prompt on the model-visible surface. The loop appends * the first one as surface node 0 before the step's first `user/message`. * A prepared in-history route can append nonempty changes in a continuing - * series. An incapable route or new series normalizes text to the first system - * node. Normalization empties nonempty later nodes, then rewrites the head if + * series. An incapable route, or a new series whose effective text differs, + * normalizes text to the first system node; a series start whose latest + * surviving node already holds the rendering leaves it in place. + * Normalization empties nonempty later nodes, then rewrites the head if * needed, through logged per-node replacements. An empty rendering always * clears all active system nodes, leaving no older instructions model-visible. * Empty later nodes are dormant and project to no message; an empty head with @@ -998,7 +1000,7 @@ Source: [`packages/subagent/tool-subagent/src/model-selection-state.ts:17`](../p 'system/message': { turn: number; step: number; message: SystemMessage } ``` -Source: [`packages/core/session/src/types.ts:332`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:338`](../packages/core/session/src/types.ts) ### `team/*` @@ -1091,7 +1093,7 @@ Source: [`packages/todo/tool-todo/src/types.ts:33`](../packages/todo/tool-todo/s Types: [ToolCallId](subsystems/core.md) -Source: [`packages/core/session/src/types.ts:363`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:369`](../packages/core/session/src/types.ts) @@ -1172,7 +1174,7 @@ Source: [`packages/core/tool-executor-ptc/src/types.ts:45`](../packages/core/too } ``` -Source: [`packages/core/session/src/types.ts:377`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:383`](../packages/core/session/src/types.ts) ### `tool-workflow/*` @@ -1252,7 +1254,7 @@ Source: [`packages/workflow/tool-workflow/src/types.ts:47`](../packages/workflow Types: [TurnEndReason](subsystems/session.md) -Source: [`packages/core/session/src/types.ts:299`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:303`](../packages/core/session/src/types.ts) @@ -1268,7 +1270,7 @@ Source: [`packages/core/session/src/types.ts:299`](../packages/core/session/src/ 'turn/start': { turn: number } ``` -Source: [`packages/core/session/src/types.ts:290`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:294`](../packages/core/session/src/types.ts) ### `user/*` @@ -1287,7 +1289,7 @@ Source: [`packages/core/session/src/types.ts:290`](../packages/core/session/src/ 'user/message': UserMessage ``` -Source: [`packages/core/session/src/types.ts:311`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:315`](../packages/core/session/src/types.ts) ### `web/*` @@ -1347,6 +1349,14 @@ SHA-256: `1e0b0b66b6f0c53fc72e52289d06b4708d776f1ca9df4c86a22bff621d403cf0` `"aborted"` + + +### `"action-cards"` + +SHA-256: `05205074b24d8340cfd7995f6cb64779c7f1241490954700115601e264178877` + +`"action-cards"` + ### `"active"` @@ -3159,7 +3169,7 @@ One of: SHA-256: `05d2ae1e0c7f8770f83f9a09047afb39a335d8ac986df3193659aa1e581472cf` -Sources: [`packages/interaction/user-approval/src/index.ts:67`](../packages/interaction/user-approval/src/index.ts) +Sources: [`packages/interaction/user-approval/src/index.ts:68`](../packages/interaction/user-approval/src/index.ts) One of: @@ -3222,7 +3232,7 @@ Array of [`AssistantStreamRecord`](#persistence-type-sha256-33341aac09312300de5a SHA-256: `ada310bf0bdb8fed51f3b56ea63f6ea6b18bbd587f04fccb63a14ab0b2a24e05` -Sources: [`packages/core/session/src/types.ts:191`](../packages/core/session/src/types.ts) · [`packages/interaction/commands/src/types.ts:75`](../packages/interaction/commands/src/types.ts) · [`packages/interaction/commands/src/types.ts:79`](../packages/interaction/commands/src/types.ts) · [`packages/llm/llm/src/message.ts:111`](../packages/llm/llm/src/message.ts) · [`packages/session/session-title/src/types.ts:35`](../packages/session/session-title/src/types.ts) +Sources: [`packages/core/session/src/types.ts:195`](../packages/core/session/src/types.ts) · [`packages/interaction/commands/src/types.ts:75`](../packages/interaction/commands/src/types.ts) · [`packages/interaction/commands/src/types.ts:79`](../packages/interaction/commands/src/types.ts) · [`packages/llm/llm/src/message.ts:111`](../packages/llm/llm/src/message.ts) · [`packages/session/session-title/src/types.ts:35`](../packages/session/session-title/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -3365,7 +3375,7 @@ Sources: [`packages/web/web-search-deepseek/src/provider.ts:55`](../packages/web | `body` | required | [`{ max_tokens, messages, model, thinking?, … }`](#persistence-type-sha256-9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee) | | `endpoint` | required | `string` | - + @@ -3373,7 +3383,7 @@ Sources: [`packages/web/web-search-deepseek/src/provider.ts:55`](../packages/web ### `DeveloperMessage` -SHA-256: `0f6265188dae7ba6faa26830a180bb4deb0760561f97ee0c9d399ccf6c9cf1f7` +SHA-256: `cebb7e9f3f663e660a531d9764ecfb9fa7fc73c22bf8d628f888e9ecf18c5cf0` Sources: [`packages/llm/llm/src/message.ts:157`](../packages/llm/llm/src/message.ts) @@ -3382,11 +3392,11 @@ Sources: [`packages/llm/llm/src/message.ts:157`](../packages/llm/llm/src/message | `content` | required | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | required | `string` | | `role` | required | `"developer"` | -| `source` | required | [`MessageSource`](#persistence-type-sha256-5bc2d7f02503fc6b3e1bb7e0b7fa22c0b9e4b9841fa3175b2ad8e607ae3525a8) | +| `source` | required | [`MessageSource`](#persistence-type-sha256-b112459dcb0686091c31ce6d213b2a4934b5ad19d37cc5b599e46f5a9d715591) | Source compatibility: `source` — `session-source-attribution` v1; `session.developer-message.source`; `kind`; `preserve`. -Attribution-only additions: `tmux-context`, `user-question-reply`, `working-directory`. +Attribution-only additions: `action-cards`, `tmux-context`, `user-question-reply`, `working-directory`. @@ -3398,7 +3408,7 @@ Attribution-only additions: `tmux-context`, `user-question-reply`, `working-dire SHA-256: `9a930283b91d493d6347146f2475bb107294b379415ca02162354f46a64164f7` -Sources: [`packages/core/session/src/types.ts:242`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:246`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4081,7 +4091,7 @@ Sources: [`packages/llm/llm-retry/src/types.ts:43`](../packages/llm/llm-retry/sr | `step` | required | `number` | | `turn` | required | `number` | - + @@ -4089,17 +4099,17 @@ Sources: [`packages/llm/llm-retry/src/types.ts:43`](../packages/llm/llm-retry/sr ### `Message` -SHA-256: `040cd65423bd64264d225504f1c572d239eeb1793d0c2856ad8e42bb6e1e148b` +SHA-256: `4f9125fa028a56286fac70176ecc670d12f4402d8cbe112e14f0639f5e8e5c9d` Sources: [`packages/llm/llm/src/message.ts:196`](../packages/llm/llm/src/message.ts) One of: - [`ToolResultMessage`](#persistence-type-sha256-4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731) -- [`DeveloperMessage`](#persistence-type-sha256-0f6265188dae7ba6faa26830a180bb4deb0760561f97ee0c9d399ccf6c9cf1f7) -- [`UserMessage`](#persistence-type-sha256-2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711) -- [`AssistantMessage`](#persistence-type-sha256-fa87537f4a9c1e25602990a8bf686b383e9e00352ec8946e16ae24ba7c1625be) +- [`DeveloperMessage`](#persistence-type-sha256-cebb7e9f3f663e660a531d9764ecfb9fa7fc73c22bf8d628f888e9ecf18c5cf0) +- [`UserMessage`](#persistence-type-sha256-8bca2b4f53ec7745b0484c6e7d3a6beb2ddd6cea82fc81786eaa3c0d065bbc14) - [`SystemMessage`](#persistence-type-sha256-09f3f8dc417f278257202714132f98ba7b52957d7b558c4a04456603890eb363) +- [`AssistantMessage`](#persistence-type-sha256-fa87537f4a9c1e25602990a8bf686b383e9e00352ec8946e16ae24ba7c1625be) @@ -4174,7 +4184,7 @@ One of: - `"negative"` - `"positive"` - + @@ -4182,12 +4192,19 @@ One of: ### `MessageSource` -SHA-256: `5bc2d7f02503fc6b3e1bb7e0b7fa22c0b9e4b9841fa3175b2ad8e607ae3525a8` +SHA-256: `b112459dcb0686091c31ce6d213b2a4934b5ad19d37cc5b599e46f5a9d715591` Sources: [`packages/llm/llm/src/message.ts:136`](../packages/llm/llm/src/message.ts) | kind | Form property | Other required fields | Full definition | |---|---|---|---| +| `action-cards` | `"catalog"` | `through`: `number` | [`{ kind: "action-cards", form: "catalog" }`](#persistence-type-sha256-dd00cdccd0ba487b92362ef67db58cd264f48c1bfd368291424a1da9a899489a) | +| `action-cards` | `"instructions"` | `through`: `number` | [`{ kind: "action-cards", form: "instructions" }`](#persistence-type-sha256-ba2a1a8f194b1bb21f270713398f6643e206e8ff5f7f26f6d36a88e3f0f0ab10) | +| `action-cards` | `"notice"` | `summary`: `string`; `through`: `number` | [`{ kind: "action-cards", form: "notice" }`](#persistence-type-sha256-e7f4cbb3a57f4cbdb61ea41e95bcba626ad1fff6bb9b1e063b1d50a32da6e864) | +| `action-cards` | `"recall"` | `through`: `number` | [`{ kind: "action-cards", form: "recall" }`](#persistence-type-sha256-b613f83572fe2fbf7259c72308cafd008f4fceea897749128a48bcd158f290aa) | +| `action-cards` | `"relay"` | `through`: `number` | [`{ kind: "action-cards", form: "relay" }`](#persistence-type-sha256-45f005e6bbb7645248be792b715a74bc7fdf5a67f5381655d3a75dcc7aa2112e) | +| `action-cards` | `"snapshot"` | `sections`: [`ContextSnapshotSection[]`](#persistence-type-sha256-c748fb42c80a120038a8c587af80ec39924803c401364db11c8974d5bf6d0262); `through`: `number` | [`{ kind: "action-cards", form: "snapshot" }`](#persistence-type-sha256-3247e566f4340029325b70e4366b56fa9719977f1e39033b769a2ec221ab22a9) | +| `action-cards` | not declared | `through`: `number` | [`{ kind: "action-cards" }`](#persistence-type-sha256-dde0cdf9d426768b649b5a9783d2144e7f900c35ef65229cd89036dbf411d1b0) | | `agent-instructions` | `"instructions"` | `changes`: [`AgentInstructionChange[]`](#persistence-type-sha256-2ab12a0e345658f9342816d773fe610f049982bcad82631f43b9205abe43e5ee) | [`AgentInstructionSource`](#persistence-type-sha256-6f22a9d02b9a1f1157f3b0e7bdccd7e7b12b085c4efdb709dfc74a465cd4e590) | | `agent-message` | `"relay"` | `senderSessionId`: `string` | [`AgentMessageSource`](#persistence-type-sha256-4a9bef9f27a942520cc2279ca7dd3082556e4bff543f66b5c0333e1bbed1cd86) | | `compact-checkpoint` | not declared | `compactionId`: `string` | [`CompactionCheckpointSource`](#persistence-type-sha256-31907de9563751822af6d9be02bafaf26faa098bbd1cb412524134d577cc1648) | @@ -4252,7 +4269,7 @@ Sources: [`packages/llm/llm/src/message.ts:136`](../packages/llm/llm/src/message | `schedule` | `"snapshot"` | `sections`: [`ContextSnapshotSection[]`](#persistence-type-sha256-c748fb42c80a120038a8c587af80ec39924803c401364db11c8974d5bf6d0262) | [`{ kind: "schedule", form: "snapshot" }`](#persistence-type-sha256-28936c614bd4e7e2774806edcbb3cbfd3ee643ac1cbf0bbdff43d915505a8fe3) | | `schedule` | not declared | none | [`{ kind: "schedule" }`](#persistence-type-sha256-f29d63336e8266d80dd7baeab219436db86341304f6be1cd0edb36f5134c4a47) | | `session-reference` | `"recall"` | `references`: [`{ capturedFormatVersion?, capturedThroughSeq, compacted, inputIndex, … }[]`](#persistence-type-sha256-df843efd87c78cf8de98f8e0d0216956cd568d0d0e56a22c853663e274aa1a18); `version`: `1` | [`SessionReferenceSource`](#persistence-type-sha256-f56c5b59ca0161310c338d31dd16cf14287ccd602ff4181058df178c1c286d7f) | -| `skill-catalog` | `"catalog"` | `entries`: [`{ description, name }[]`](#persistence-type-sha256-aba175fb20ffc71112c55efe70458ff5d7dbfb83501892b4ba8d077f0ea5d7ba) | [`SkillCatalogSource`](#persistence-type-sha256-fc2ae6962f9f8801c2b1e414668e1e17cbb7544c4f39381198977a38bd10c093) | +| `skill-catalog` | `"catalog"` | `entries`: [`{ description, name }[]`](#persistence-type-sha256-aba175fb20ffc71112c55efe70458ff5d7dbfb83501892b4ba8d077f0ea5d7ba) | [`SkillCatalogSource`](#persistence-type-sha256-65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099) | | `skill-invocation` | `"instructions"` | `name`: `string` | [`SkillInvocationSource`](#persistence-type-sha256-672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db) | | `subagent-settled` | `"notice"` | `senderSessionId`: `string`; `summary`: `string` | [`SubagentSettledMessageSource`](#persistence-type-sha256-4e97c3d85c0fc817ee58873c38c25a2474abaaa0af4839311b50b68db3b8cf1a) | | `system-prompt` | not declared | none | [`SystemPromptMessageSource`](#persistence-type-sha256-65a8400e451e667e5b6e34df72ceb81fca8c12330330fa72083ad40279b189ad) | @@ -4300,13 +4317,13 @@ Sources: [`packages/llm/llm/src/message.ts:136`](../packages/llm/llm/src/message | `webhook` | `"notice"` | `deliveryId`: `string`; `provider`: `string`; `ruleId`: `string`; `source`: `string`; `summary`: `string` | [`{ kind: "webhook", form: "notice" }`](#persistence-type-sha256-9edc162949abf93bd5ff049191b345454ba104f583937ce5580fb50f067d2b94) | | `working-directory` | not declared | none | [`{ kind: "working-directory" }`](#persistence-type-sha256-2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5) | - + ### `Message[]` -SHA-256: `a927d444c928ac0efd9dd8b2e7d7d04d711c264cb71578d81e0e2fd143ff669f` +SHA-256: `d2b617d9dfcc4e0a4b60732d8ba1effc632e3b75124b93b064c07814a0a716bc` -Array of [`Message`](#persistence-type-sha256-040cd65423bd64264d225504f1c572d239eeb1793d0c2856ad8e42bb6e1e148b). +Array of [`Message`](#persistence-type-sha256-4f9125fa028a56286fac70176ecc670d12f4402d8cbe112e14f0639f5e8e5c9d). @@ -4528,7 +4545,7 @@ Sources: [`packages/llm/llm/src/types.ts:448`](../packages/llm/llm/src/types.ts) SHA-256: `b158f3ff6923714807c0d73882f0b05dc87f8fa85c9e90814852d48bbc866081` -Sources: [`packages/core/session/src/types.ts:256`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:260`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4547,7 +4564,7 @@ Sources: [`packages/core/session/src/types.ts:256`](../packages/core/session/src SHA-256: `530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6` -Sources: [`packages/core/session/src/types.ts:275`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:279`](../packages/core/session/src/types.ts) One of: @@ -4690,7 +4707,7 @@ Sources: [`packages/session/session-title/src/types.ts:41`](../packages/session/ | `source` | required | [`SessionTitleSource`](#persistence-type-sha256-30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f) | | `title` | required | `string` | - + @@ -4698,7 +4715,7 @@ Sources: [`packages/session/session-title/src/types.ts:41`](../packages/session/ ### `SessionTitleLlmRequestEventData` -SHA-256: `00c054d3018c198d92f459563331edd1385e58345c677bb499791df2da0ade9f` +SHA-256: `9808c3d0f0a1be8fe313b4148ba22c691c4d59bd2c67aef3c63cfe8043148c5f` Sources: [`packages/session/session-title-llm/src/index.ts:37`](../packages/session/session-title-llm/src/index.ts) @@ -4706,7 +4723,7 @@ Sources: [`packages/session/session-title-llm/src/index.ts:37`](../packages/sess |---|---|---| | `maxTokens` | required | `number` | | `messageSeqs` | required | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | -| `messages` | required | [`Message[]`](#persistence-type-sha256-a927d444c928ac0efd9dd8b2e7d7d04d711c264cb71578d81e0e2fd143ff669f) | +| `messages` | required | [`Message[]`](#persistence-type-sha256-d2b617d9dfcc4e0a4b60732d8ba1effc632e3b75124b93b064c07814a0a716bc) | | `reasoningEffort` | optional | `string` | | `route` | required | [`SessionTitleModelIdentity`](#persistence-type-sha256-07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235) | | `system` | required | `string` | @@ -4759,7 +4776,7 @@ Sources: [`packages/session/session-title/src/types.ts:28`](../packages/session/ | `provider` | not declared | `provider`: `string` | [`{ kind: "provider" }`](#persistence-type-sha256-b81e9de81a481b24e1e1f9adf038bfc59e57b4f35ce62f8f1e45284186f4f812) | | `user` | not declared | none | [`CommandSource`](#persistence-type-sha256-ada310bf0bdb8fed51f3b56ea63f6ea6b18bbd587f04fccb63a14ab0b2a24e05) | - + @@ -4767,7 +4784,7 @@ Sources: [`packages/session/session-title/src/types.ts:28`](../packages/session/ ### `SkillCatalogSource` -SHA-256: `fc2ae6962f9f8801c2b1e414668e1e17cbb7544c4f39381198977a38bd10c093` +SHA-256: `65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099` Sources: [`packages/skill/tool-skill/src/index.ts:35`](../packages/skill/tool-skill/src/index.ts) @@ -4775,6 +4792,7 @@ Sources: [`packages/skill/tool-skill/src/index.ts:35`](../packages/skill/tool-sk |---|---|---| | `entries` | required | [`{ description, name }[]`](#persistence-type-sha256-aba175fb20ffc71112c55efe70458ff5d7dbfb83501892b4ba8d077f0ea5d7ba) | | `form` | required | `"catalog"` | +| `incomplete` | optional | `true` | | `kind` | required | `"skill-catalog"` | | `update` | optional | `true` | @@ -4885,7 +4903,7 @@ Sources: [`packages/subagent/subagent/src/continuation-messages.ts:29`](../packa SHA-256: `335e242de1fcc17b6ca920fc420d71bec2d76e53e37955c00948b65ab77f05c5` -Sources: [`packages/core/session/src/types.ts:464`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:470`](../packages/core/session/src/types.ts) One of: @@ -5330,7 +5348,7 @@ Sources: [`packages/workflow/tool-workflow/src/types.ts:14`](../packages/workflo SHA-256: `1f8c126cfab3df812cd115cfc23e3256f0fa2383400f4ce91ecad313577e59b0` -Sources: [`packages/core/session/src/types.ts:197`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:201`](../packages/core/session/src/types.ts) | kind | Form property | Other required fields | Full definition | |---|---|---|---| @@ -5350,7 +5368,7 @@ Sources: [`packages/core/session/src/types.ts:197`](../packages/core/session/src SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` -Sources: [`packages/core/session/src/types.ts:234`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:238`](../packages/core/session/src/types.ts) | kind | Form property | Other required fields | Full definition | |---|---|---|---| @@ -5362,7 +5380,7 @@ Sources: [`packages/core/session/src/types.ts:234`](../packages/core/session/src | `interrupted` | not declared | none | [`{ kind: "interrupted" }`](#persistence-type-sha256-56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23) | | `max-tokens` | not declared | none | [`{ kind: "max-tokens" }`](#persistence-type-sha256-ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7) | - + @@ -5370,7 +5388,7 @@ Sources: [`packages/core/session/src/types.ts:234`](../packages/core/session/src ### `UserMessage` -SHA-256: `2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711` +SHA-256: `8bca2b4f53ec7745b0484c6e7d3a6beb2ddd6cea82fc81786eaa3c0d065bbc14` Sources: [`packages/llm/llm/src/message.ts:162`](../packages/llm/llm/src/message.ts) @@ -5379,19 +5397,19 @@ Sources: [`packages/llm/llm/src/message.ts:162`](../packages/llm/llm/src/message | `content` | required | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | required | `string` | | `role` | required | `"user"` | -| `source` | required | [`MessageSource`](#persistence-type-sha256-5bc2d7f02503fc6b3e1bb7e0b7fa22c0b9e4b9841fa3175b2ad8e607ae3525a8) | +| `source` | required | [`MessageSource`](#persistence-type-sha256-b112459dcb0686091c31ce6d213b2a4934b5ad19d37cc5b599e46f5a9d715591) | Source compatibility: `source` — `session-source-attribution` v1; `session.user-message.source`; `kind`; `preserve`. -Attribution-only additions: `tmux-context`, `user-question-reply`, `working-directory`. +Attribution-only additions: `action-cards`, `tmux-context`, `user-question-reply`, `working-directory`. - + ### `UserMessage[]` -SHA-256: `454a0fa879e38076bdcdbd87ef561cd67d7e43e58a287cf7dbaa7b6cf7847020` +SHA-256: `aada2771a250136cc3a839b0507e9c6502622a2897716903942297bcb6661292` -Array of [`UserMessage`](#persistence-type-sha256-2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711). +Array of [`UserMessage`](#persistence-type-sha256-8bca2b4f53ec7745b0484c6e7d3a6beb2ddd6cea82fc81786eaa3c0d065bbc14). @@ -5583,7 +5601,7 @@ Array of `number`. SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -Sources: [`packages/api/session-controller/src/types.ts:380`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:386`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` @@ -5820,7 +5838,7 @@ Sources: [`packages/interaction/commands/src/types.ts:105`](../packages/interact SHA-256: `e4c18e294232c3ba6c9f1999f168263cc55956147cfe4121720899be8e52edd1` -Sources: [`packages/core/session/src/types.ts:363`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:369`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -5979,7 +5997,7 @@ SHA-256: `cbbe8377ee744964537dbafd83607219e58ba79a13f6db0d0645c7ad3d5e8a09` SHA-256: `a81059ca06999da1e712414520c2c65e491d052fcf9640fae20aa38f0a5dc735` -Sources: [`packages/core/session/src/types.ts:385`](../packages/core/session/src/types.ts) · [`packages/core/tool-executor-ptc/src/types.ts:27`](../packages/core/tool-executor-ptc/src/types.ts) +Sources: [`packages/core/session/src/types.ts:391`](../packages/core/session/src/types.ts) · [`packages/core/tool-executor-ptc/src/types.ts:27`](../packages/core/tool-executor-ptc/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6149,7 +6167,7 @@ Sources: [`packages/llm/llm-retry/src/types.ts:30`](../packages/llm/llm-retry/sr SHA-256: `83079c8a3f733ac3fa603eefa0fbb4737ca4d8b69e7e2e7298b60f9ac4098693` -Sources: [`packages/skill/tool-skill/src/index.ts:41`](../packages/skill/tool-skill/src/index.ts) +Sources: [`packages/skill/tool-skill/src/index.ts:43`](../packages/skill/tool-skill/src/index.ts) | Property | Presence | Type | |---|---|---| @@ -6199,7 +6217,7 @@ Sources: [`packages/compaction/compaction/src/types.ts:38`](../packages/compacti SHA-256: `bcf0caf62d964b2fcf5404bd5c909cfa9a21c3f3c96e6b7e36d9e33565223825` -Sources: [`packages/core/session/src/types.ts:466`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:472`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6213,7 +6231,7 @@ Sources: [`packages/core/session/src/types.ts:466`](../packages/core/session/src SHA-256: `79650cfa10aa3c52440328d85e8a25f0ffadc8d7efd784e3c0819d8bb74a1985` -Sources: [`packages/core/session/src/types.ts:214`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:218`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6226,7 +6244,7 @@ Sources: [`packages/core/session/src/types.ts:214`](../packages/core/session/src SHA-256: `5302e763151277614b97e77f00e3b326694c6c1247b916a20503c344dc970777` -Sources: [`packages/core/session/src/types.ts:377`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:383`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6268,7 +6286,7 @@ Sources: [`packages/llm/llm/src/types.ts:161`](../packages/llm/llm/src/types.ts) SHA-256: `ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585` -Sources: [`packages/core/session/src/types.ts:392`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:398`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6276,18 +6294,18 @@ Sources: [`packages/core/session/src/types.ts:392`](../packages/core/session/src | `reason` | required | [`RequestHeaderReason`](#persistence-type-sha256-530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6) | | `startsSeries` | optional | `true` | - + ### `{ headerSeq?, message, step, turn }` -SHA-256: `f4ed4717b4c259e933b550a8dcd90dc93628cda8a3c7affcaa53b9c13c1d53eb` +SHA-256: `12f9a5a7506bca46d6ef8e3c71826c4bf40e1389bfe0236cfffaea0c3fb367d2` -Sources: [`packages/core/session/src/types.ts:313`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:317`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| | `headerSeq` | optional | `number` | -| `message` | required | [`DeveloperMessage`](#persistence-type-sha256-0f6265188dae7ba6faa26830a180bb4deb0760561f97ee0c9d399ccf6c9cf1f7) | +| `message` | required | [`DeveloperMessage`](#persistence-type-sha256-cebb7e9f3f663e660a531d9764ecfb9fa7fc73c22bf8d628f888e9ecf18c5cf0) | | `step` | required | `number` | | `turn` | required | `number` | @@ -6365,23 +6383,23 @@ SHA-256: `e3e77b26f0148755a505f5b8ea843a3be117827d4703bb5754d9dc8ddbef521f` SHA-256: `17d1afb770d9941936130996da00dc86782cfef731d8d6526162c301256a4ac3` -Sources: [`packages/core/session/src/types.ts:429`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:435`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| | `inherited` | optional | `true` | - + ### `{ inserted, outcome?, removedCount?, start, … }` -SHA-256: `fa106c5b33b657e8ef16e8cbf39f3b7d44e5cbcdf4f9303d9db6410f28951e42` +SHA-256: `c433ef580a5b229bbe68274a7164aa3a8e8040d7217f010b610ca0696a84253c` Sources: [`packages/core/agent/src/types.ts:110`](../packages/core/agent/src/types.ts) | Property | Presence | Type | |---|---|---| -| `inserted` | required | [`UserMessage[]`](#persistence-type-sha256-454a0fa879e38076bdcdbd87ef561cd67d7e43e58a287cf7dbaa7b6cf7847020) | +| `inserted` | required | [`UserMessage[]`](#persistence-type-sha256-aada2771a250136cc3a839b0507e9c6502622a2897716903942297bcb6661292) | | `outcome` | optional | `"canceled"` | | `removedCount` | optional | `number` | | `start` | required | `number` | @@ -6393,7 +6411,7 @@ Sources: [`packages/core/agent/src/types.ts:110`](../packages/core/agent/src/typ SHA-256: `1ccb56061942f5ccb0d30c9e4f2883b9d115ff906560029de637b61d3cde896d` -Sources: [`packages/core/session/src/types.ts:343`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:349`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6410,20 +6428,105 @@ Sources: [`packages/core/session/src/types.ts:343`](../packages/core/session/src SHA-256: `0a30c3be336cdd4f8f34e66543a3d46d611c43986edd9b3ce6cbb9b721d3b5d3` -Sources: [`packages/core/session/src/types.ts:205`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:209`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| | `kind` | required | `"aborted"` | | `reason` | required | [`TurnEndCancelCause`](#persistence-type-sha256-1f8c126cfab3df812cd115cfc23e3256f0fa2383400f4ce91ecad313577e59b0) | + + +### `{ kind: "action-cards" }` + +SHA-256: `dde0cdf9d426768b649b5a9783d2144e7f900c35ef65229cd89036dbf411d1b0` + +| Property | Presence | Type | +|---|---|---| +| `kind` | required | `"action-cards"` | +| `through` | required | `number` | + + + +### `{ kind: "action-cards", form: "catalog" }` + +SHA-256: `dd00cdccd0ba487b92362ef67db58cd264f48c1bfd368291424a1da9a899489a` + +| Property | Presence | Type | +|---|---|---| +| `form` | required | `"catalog"` | +| `kind` | required | `"action-cards"` | +| `through` | required | `number` | + + + +### `{ kind: "action-cards", form: "instructions" }` + +SHA-256: `ba2a1a8f194b1bb21f270713398f6643e206e8ff5f7f26f6d36a88e3f0f0ab10` + +| Property | Presence | Type | +|---|---|---| +| `form` | required | `"instructions"` | +| `kind` | required | `"action-cards"` | +| `through` | required | `number` | + + + +### `{ kind: "action-cards", form: "notice" }` + +SHA-256: `e7f4cbb3a57f4cbdb61ea41e95bcba626ad1fff6bb9b1e063b1d50a32da6e864` + +| Property | Presence | Type | +|---|---|---| +| `form` | required | `"notice"` | +| `kind` | required | `"action-cards"` | +| `summary` | required | `string` | +| `through` | required | `number` | + + + +### `{ kind: "action-cards", form: "recall" }` + +SHA-256: `b613f83572fe2fbf7259c72308cafd008f4fceea897749128a48bcd158f290aa` + +| Property | Presence | Type | +|---|---|---| +| `form` | required | `"recall"` | +| `kind` | required | `"action-cards"` | +| `through` | required | `number` | + + + +### `{ kind: "action-cards", form: "relay" }` + +SHA-256: `45f005e6bbb7645248be792b715a74bc7fdf5a67f5381655d3a75dcc7aa2112e` + +| Property | Presence | Type | +|---|---|---| +| `form` | required | `"relay"` | +| `kind` | required | `"action-cards"` | +| `through` | required | `number` | + + + +### `{ kind: "action-cards", form: "snapshot" }` + +SHA-256: `3247e566f4340029325b70e4366b56fa9719977f1e39033b769a2ec221ab22a9` + +| Property | Presence | Type | +|---|---|---| +| `form` | required | `"snapshot"` | +| `kind` | required | `"action-cards"` | +| `sections` | required | [`ContextSnapshotSection[]`](#persistence-type-sha256-c748fb42c80a120038a8c587af80ec39924803c401364db11c8974d5bf6d0262) | +| `through` | required | `number` | + ### `{ kind: "blocked" }` SHA-256: `023a355b2be0d688fb6e4df8388dadb942761d46cfe96d0f499aae9631a159d4` -Sources: [`packages/core/session/src/types.ts:207`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:211`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6435,7 +6538,7 @@ Sources: [`packages/core/session/src/types.ts:207`](../packages/core/session/src SHA-256: `b6ef9c6210be8350cd465f485cf520031fffa6bf3809c61a1e713e834c5982d0` -Sources: [`packages/core/session/src/types.ts:203`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:207`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6459,7 +6562,7 @@ Sources: [`packages/extensions/cordis-host-runner/src/index.ts:14`](../packages/ SHA-256: `4bb451330ff699f36b45539ceb0eb2606ead72084e2c5bb637c36cc80e2252db` -Sources: [`packages/core/session/src/types.ts:194`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:198`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6561,7 +6664,7 @@ Sources: [`packages/session/session-title/src/types.ts:29`](../packages/session/ SHA-256: `ec8b5ff7c77ca6893ac7ba5a0c5b2aefeb52f12c64450b7359660c2a7e8a53d7` -Sources: [`packages/core/session/src/types.ts:230`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:234`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6573,7 +6676,7 @@ Sources: [`packages/core/session/src/types.ts:230`](../packages/core/session/src SHA-256: `6c5a37d42ebdb12db4410699259335f1e149e3a0260425684c00b153afc8990d` -Sources: [`packages/core/session/src/types.ts:193`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:197`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6742,7 +6845,7 @@ SHA-256: `88841202942c7683b3b7e5ea6a796047ec326b6701ac23e58cc236d85613b9fa` SHA-256: `56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23` -Sources: [`packages/core/session/src/types.ts:223`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:227`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6754,7 +6857,7 @@ Sources: [`packages/core/session/src/types.ts:223`](../packages/core/session/src SHA-256: `eaa71be0fbf0f702df8ea6c11d0aa2f9782263d45a10d0fb14eda662f4bfe04c` -Sources: [`packages/core/session/src/types.ts:197`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:201`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6766,7 +6869,7 @@ Sources: [`packages/core/session/src/types.ts:197`](../packages/core/session/src SHA-256: `ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7` -Sources: [`packages/core/session/src/types.ts:216`](../packages/core/session/src/types.ts) · [`packages/llm/llm/src/types.ts:159`](../packages/llm/llm/src/types.ts) +Sources: [`packages/core/session/src/types.ts:220`](../packages/core/session/src/types.ts) · [`packages/llm/llm/src/types.ts:159`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6856,7 +6959,7 @@ SHA-256: `52c6113cb0e53f345324bf84f01928bea5d5df57ee80bc0dd65407b8bc5a3734` SHA-256: `6c03546143cdf6ae88f1745ac98c5139efa1588d1415249bbc5f3104d32ab800` -Sources: [`packages/core/session/src/types.ts:192`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:196`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7554,7 +7657,7 @@ Sources: [`packages/core/tools/src/index.ts:28`](../packages/core/tools/src/inde SHA-256: `6dacb1584f2bfbe209dc6b6f578d51da6d55595f64d0e63c727c98f359278def` -Sources: [`packages/api/session-controller/src/types.ts:389`](../packages/api/session-controller/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:395`](../packages/api/session-controller/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7721,7 +7824,7 @@ Sources: [`packages/experimental/agent-team/src/types.ts:230`](../packages/exper SHA-256: `6bc8e51124d0874bc89e1d0ceff381a9c3cd0fc240667d69f841ce4f60f65fe5` -Sources: [`packages/core/session/src/types.ts:332`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:338`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7777,7 +7880,7 @@ Sources: [`packages/sandbox/sandbox-policy/src/session-mode.ts:33`](../packages/ SHA-256: `11f70b595aa76897fc4e25a352bfa718c659f44b799e5aa14e84e5a38fe72912` -Sources: [`packages/interaction/user-approval/src/index.ts:40`](../packages/interaction/user-approval/src/index.ts) +Sources: [`packages/interaction/user-approval/src/index.ts:41`](../packages/interaction/user-approval/src/index.ts) | Property | Presence | Type | |---|---|---| @@ -7802,7 +7905,7 @@ Sources: [`packages/interaction/permission-presets/src/index.ts:53`](../packages SHA-256: `e481c46af3813e0010558e93f578b2986acd658404cec2d1679e3ac2a6c48654` -Sources: [`packages/core/session/src/types.ts:299`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:303`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7856,7 +7959,7 @@ Sources: [`packages/compaction/compaction/src/types.ts:82`](../packages/compacti SHA-256: `54f9276a1617d7c12594722c89cfe864bcbe4517e9a6f9c98bab14f199a135e0` -Sources: [`packages/core/session/src/types.ts:357`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:363`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7870,7 +7973,7 @@ Sources: [`packages/core/session/src/types.ts:357`](../packages/core/session/src SHA-256: `ef11a3b7fa2033ae4279545ff8a8a2ee4e301b9b73e5b91654c48e6d08283545` -Sources: [`packages/core/session/src/types.ts:301`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:303`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:305`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:307`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7921,7 +8024,7 @@ Sources: [`packages/todo/tool-todo/src/types.ts:33`](../packages/todo/tool-todo/ SHA-256: `f90eb4ab2d3897bc20c521a038e3119d581f791ec974b1a0004f63a8ab9e232d` -Sources: [`packages/core/session/src/types.ts:290`](../packages/core/session/src/types.ts) · [`packages/deliverables/workspace-changes/src/types.ts:106`](../packages/deliverables/workspace-changes/src/types.ts) +Sources: [`packages/core/session/src/types.ts:294`](../packages/core/session/src/types.ts) · [`packages/deliverables/workspace-changes/src/types.ts:106`](../packages/deliverables/workspace-changes/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7943,17 +8046,17 @@ SHA-256: `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | `time` | required | `number` | | `type` | required | `"agent-preset/selected"` | - + ### `{ type: "agent/inbox/spliced" }` -SHA-256: `0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034` +SHA-256: `9e8043098fb89db6d7c92a92c70146c5c8d24fa88f733c687fa29e5e7a58ab30` | Property | Presence | Type | |---|---|---| -| `data` | required | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-fa106c5b33b657e8ef16e8cbf39f3b7d44e5cbcdf4f9303d9db6410f28951e42) | +| `data` | required | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-c433ef580a5b229bbe68274a7164aa3a8e8040d7217f010b610ca0696a84253c) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `time` | required | `number` | @@ -8194,17 +8297,17 @@ SHA-256: `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | `time` | required | `number` | | `type` | required | `"deliverables/presented"` | - + ### `{ type: "developer/message" }` -SHA-256: `97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c` +SHA-256: `95acdbd066cf445d37092e5fdfe2e8717ef6ca1aed50f70e2e6037a6989a1f2f` | Property | Presence | Type | |---|---|---| -| `data` | required | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-f4ed4717b4c259e933b550a8dcd90dc93628cda8a3c7affcaa53b9c13c1d53eb) | +| `data` | required | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-12f9a5a7506bca46d6ef8e3c71826c4bf40e1389bfe0236cfffaea0c3fb367d2) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `sourceEventSeqs` | optional | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | @@ -8604,17 +8707,17 @@ SHA-256: `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | `time` | required | `number` | | `type` | required | `"session/title"` | - + ### `{ type: "session/title-llm-request" }` -SHA-256: `79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056` +SHA-256: `eaa9125aec0fb28478096c46e73e21bf512ab0d84d826bfb41e7308707734cb5` | Property | Presence | Type | |---|---|---| -| `data` | required | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-00c054d3018c198d92f459563331edd1385e58345c677bb499791df2da0ade9f) | +| `data` | required | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-9808c3d0f0a1be8fe313b4148ba22c691c4d59bd2c67aef3c63cfe8043148c5f) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `time` | required | `number` | @@ -9037,17 +9140,17 @@ Sources: [`packages/llm/llm/src/types.ts:476`](../packages/llm/llm/src/types.ts) | `type` | required | `"usage"` | | `usage` | required | [`TokenUsage`](#persistence-type-sha256-fec5442b9ee4122e10514d81d5a43648003fe8bfb7ee2ba50c0cdbdd383ed394) | - + ### `{ type: "user/message" }` -SHA-256: `2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8` +SHA-256: `39adb7fce8475af6402acd925ea79697b3341c22422ac32833d71217d84e987f` | Property | Presence | Type | |---|---|---| -| `data` | required | [`UserMessage`](#persistence-type-sha256-2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711) | +| `data` | required | [`UserMessage`](#persistence-type-sha256-8bca2b4f53ec7745b0484c6e7d3a6beb2ddd6cea82fc81786eaa3c0d065bbc14) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `sourceEventSeqs` | optional | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 9004bc4b21..c1dc641ae7 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -25,7 +25,7 @@ | `JsonlHeaderLine` | header | `18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f` | [`HeaderLine`](#persistence-type-sha256-18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f) | | `SessionEventEnvelope` | envelope | `5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc` | [`union (3 variants)`](#persistence-type-sha256-5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc) | | `event:agent-preset/selected` | event | `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | [`{ type: "agent-preset/selected" }`](#persistence-type-sha256-a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b) | -| `event:agent/inbox/spliced` | event | `0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034) | +| `event:agent/inbox/spliced` | event | `9e8043098fb89db6d7c92a92c70146c5c8d24fa88f733c687fa29e5e7a58ab30` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-9e8043098fb89db6d7c92a92c70146c5c8d24fa88f733c687fa29e5e7a58ab30) | | `event:approval/asked` | event | `3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1` | [`{ type: "approval/asked" }`](#persistence-type-sha256-3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1) | | `event:approval/decided` | event | `bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3` | [`{ type: "approval/decided" }`](#persistence-type-sha256-bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3) | | `event:approval/policy` | event | `26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78` | [`{ type: "approval/policy" }`](#persistence-type-sha256-26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78) | @@ -38,7 +38,7 @@ | `event:compaction/start` | event | `db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965` | [`{ type: "compaction/start" }`](#persistence-type-sha256-db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965) | | `event:compaction/summary` | event | `e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602` | [`{ type: "compaction/summary" }`](#persistence-type-sha256-e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602) | | `event:deliverables/presented` | event | `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | [`{ type: "deliverables/presented" }`](#persistence-type-sha256-13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176) | -| `event:developer/message` | event | `97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c` | [`{ type: "developer/message" }`](#persistence-type-sha256-97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c) | +| `event:developer/message` | event | `95acdbd066cf445d37092e5fdfe2e8717ef6ca1aed50f70e2e6037a6989a1f2f` | [`{ type: "developer/message" }`](#persistence-type-sha256-95acdbd066cf445d37092e5fdfe2e8717ef6ca1aed50f70e2e6037a6989a1f2f) | | `event:feedback/message-delete` | event | `3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796` | [`{ type: "feedback/message-delete" }`](#persistence-type-sha256-3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796) | | `event:feedback/message-put` | event | `b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf` | [`{ type: "feedback/message-put" }`](#persistence-type-sha256-b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf) | | `event:feedback/record` | event | `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` | [`{ type: "feedback/record" }`](#persistence-type-sha256-b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8) | @@ -60,7 +60,7 @@ | `event:session-log-deepseek/delivery-accepted` | event | `d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9` | [`{ type: "session-log-deepseek/delivery-accepted" }`](#persistence-type-sha256-d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9) | | `event:session/end-seed` | event | `5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e` | [`{ type: "session/end-seed" }`](#persistence-type-sha256-5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e) | | `event:session/title` | event | `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | [`{ type: "session/title" }`](#persistence-type-sha256-1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5) | -| `event:session/title-llm-request` | event | `79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056) | +| `event:session/title-llm-request` | event | `eaa9125aec0fb28478096c46e73e21bf512ab0d84d826bfb41e7308707734cb5` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-eaa9125aec0fb28478096c46e73e21bf512ab0d84d826bfb41e7308707734cb5) | | `event:step/end` | event | `e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05` | [`{ type: "step/end" }`](#persistence-type-sha256-e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05) | | `event:step/start` | event | `4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986` | [`{ type: "step/start" }`](#persistence-type-sha256-4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986) | | `event:subagent/catalog` | event | `53750b9abf61efb7992b0aadc3e247ec927449c63266df28230fd1139f5590ac` | [`{ type: "subagent/catalog" }`](#persistence-type-sha256-53750b9abf61efb7992b0aadc3e247ec927449c63266df28230fd1139f5590ac) | @@ -82,7 +82,7 @@ | `event:tool/result` | event | `7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397` | [`{ type: "tool/result" }`](#persistence-type-sha256-7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397) | | `event:turn/end` | event | `0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce` | [`{ type: "turn/end" }`](#persistence-type-sha256-0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce) | | `event:turn/start` | event | `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` | [`{ type: "turn/start" }`](#persistence-type-sha256-aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8) | -| `event:user/message` | event | `2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8` | [`{ type: "user/message" }`](#persistence-type-sha256-2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8) | +| `event:user/message` | event | `39adb7fce8475af6402acd925ea79697b3341c22422ac32833d71217d84e987f` | [`{ type: "user/message" }`](#persistence-type-sha256-39adb7fce8475af6402acd925ea79697b3341c22422ac32833d71217d84e987f) | | `event:web/deepseek-search-llm-request` | event | `0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52` | [`{ type: "web/deepseek-search-llm-request" }`](#persistence-type-sha256-0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52) | | `event:working-directory/change` | event | `124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3` | [`{ type: "working-directory/change" }`](#persistence-type-sha256-124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3) | | `event:workspace/changes` | event | `e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72` | [`{ type: "workspace/changes" }`](#persistence-type-sha256-e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72) | @@ -162,7 +162,7 @@ export type SessionEvent = { }[T] ``` -来源:[`packages/core/session/src/types.ts:433`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:441`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:464`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:495`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:439`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:447`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:470`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:501`](../packages/core/session/src/types.ts) ## 事件 @@ -275,7 +275,7 @@ export type SessionEvent = { } ``` -来源:[`packages/interaction/user-approval/src/index.ts:40`](../packages/interaction/user-approval/src/index.ts) +来源:[`packages/interaction/user-approval/src/index.ts:41`](../packages/interaction/user-approval/src/index.ts) ### `assistant/*` @@ -292,7 +292,7 @@ export type SessionEvent = { 'assistant/attempt': { turn: number; step: number; stream: AssistantStreamRecord[] } ``` -来源:[`packages/core/session/src/types.ts:357`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:363`](../packages/core/session/src/types.ts) @@ -322,7 +322,7 @@ export type SessionEvent = { 类型:[TokenUsage](subsystems/llm-streaming.zh.md) -来源:[`packages/core/session/src/types.ts:343`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:349`](../packages/core/session/src/types.ts) ### `command/*` @@ -510,7 +510,7 @@ export type SessionEvent = { } ``` -来源:[`packages/core/session/src/types.ts:313`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:317`](../packages/core/session/src/types.ts) ### `feedback/*` @@ -755,7 +755,7 @@ export type SessionEvent = { 'request/context': RequestContext ``` -来源:[`packages/core/session/src/types.ts:404`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:410`](../packages/core/session/src/types.ts) @@ -774,7 +774,7 @@ export type SessionEvent = { } ``` -来源:[`packages/core/session/src/types.ts:392`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:398`](../packages/core/session/src/types.ts) ### `sandbox/*` @@ -815,7 +815,7 @@ export type SessionEvent = { 类型:[ScheduleChange](subsystems/schedule.zh.md) -来源:[`packages/schedule/schedule/src/types.ts:365`](../packages/schedule/schedule/src/types.ts) +来源:[`packages/schedule/schedule/src/types.ts:371`](../packages/schedule/schedule/src/types.ts) ### `session/*` @@ -851,7 +851,7 @@ export type SessionEvent = { 'session/end-seed': { inherited?: true } ``` -来源:[`packages/core/session/src/types.ts:429`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:435`](../packages/core/session/src/types.ts) @@ -913,7 +913,7 @@ export type SessionEvent = { 'step/end': { turn: number; step: number } ``` -来源:[`packages/core/session/src/types.ts:303`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:307`](../packages/core/session/src/types.ts) @@ -924,7 +924,7 @@ export type SessionEvent = { 'step/start': { turn: number; step: number } ``` -来源:[`packages/core/session/src/types.ts:301`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:305`](../packages/core/session/src/types.ts) ### `subagent/*` @@ -989,8 +989,10 @@ export type SessionEvent = { * The rendered system prompt on the model-visible surface. The loop appends * the first one as surface node 0 before the step's first `user/message`. * A prepared in-history route can append nonempty changes in a continuing - * series. An incapable route or new series normalizes text to the first system - * node. Normalization empties nonempty later nodes, then rewrites the head if + * series. An incapable route, or a new series whose effective text differs, + * normalizes text to the first system node; a series start whose latest + * surviving node already holds the rendering leaves it in place. + * Normalization empties nonempty later nodes, then rewrites the head if * needed, through logged per-node replacements. An empty rendering always * clears all active system nodes, leaving no older instructions model-visible. * Empty later nodes are dormant and project to no message; an empty head with @@ -1000,7 +1002,7 @@ export type SessionEvent = { 'system/message': { turn: number; step: number; message: SystemMessage } ``` -来源:[`packages/core/session/src/types.ts:332`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:338`](../packages/core/session/src/types.ts) ### `team/*` @@ -1093,7 +1095,7 @@ export type SessionEvent = { 类型:[ToolCallId](subsystems/core.zh.md) -来源:[`packages/core/session/src/types.ts:363`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:369`](../packages/core/session/src/types.ts) @@ -1174,7 +1176,7 @@ export type SessionEvent = { } ``` -来源:[`packages/core/session/src/types.ts:377`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:383`](../packages/core/session/src/types.ts) ### `tool-workflow/*` @@ -1254,7 +1256,7 @@ export type SessionEvent = { 类型:[TurnEndReason](subsystems/session.zh.md) -来源:[`packages/core/session/src/types.ts:299`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:303`](../packages/core/session/src/types.ts) @@ -1270,7 +1272,7 @@ export type SessionEvent = { 'turn/start': { turn: number } ``` -来源:[`packages/core/session/src/types.ts:290`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:294`](../packages/core/session/src/types.ts) ### `user/*` @@ -1289,7 +1291,7 @@ export type SessionEvent = { 'user/message': UserMessage ``` -来源:[`packages/core/session/src/types.ts:311`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:315`](../packages/core/session/src/types.ts) ### `web/*` @@ -1349,6 +1351,14 @@ SHA-256: `1e0b0b66b6f0c53fc72e52289d06b4708d776f1ca9df4c86a22bff621d403cf0` `"aborted"` + + +### `"action-cards"` + +SHA-256: `05205074b24d8340cfd7995f6cb64779c7f1241490954700115601e264178877` + +`"action-cards"` + ### `"active"` @@ -3161,7 +3171,7 @@ SHA-256: `930c1cd289def119d443e19dd90008916bf035f0a4d23e07241e7f050f2b89b7` SHA-256: `05d2ae1e0c7f8770f83f9a09047afb39a335d8ac986df3193659aa1e581472cf` -来源:[`packages/interaction/user-approval/src/index.ts:67`](../packages/interaction/user-approval/src/index.ts) +来源:[`packages/interaction/user-approval/src/index.ts:68`](../packages/interaction/user-approval/src/index.ts) 以下类型之一: @@ -3224,7 +3234,7 @@ SHA-256: `84bbfdce7d2eab5b0c53e72ff7406db856c8bfd621b965b72fd86598ba493bf7` SHA-256: `ada310bf0bdb8fed51f3b56ea63f6ea6b18bbd587f04fccb63a14ab0b2a24e05` -来源:[`packages/core/session/src/types.ts:191`](../packages/core/session/src/types.ts) · [`packages/interaction/commands/src/types.ts:75`](../packages/interaction/commands/src/types.ts) · [`packages/interaction/commands/src/types.ts:79`](../packages/interaction/commands/src/types.ts) · [`packages/llm/llm/src/message.ts:111`](../packages/llm/llm/src/message.ts) · [`packages/session/session-title/src/types.ts:35`](../packages/session/session-title/src/types.ts) +来源:[`packages/core/session/src/types.ts:195`](../packages/core/session/src/types.ts) · [`packages/interaction/commands/src/types.ts:75`](../packages/interaction/commands/src/types.ts) · [`packages/interaction/commands/src/types.ts:79`](../packages/interaction/commands/src/types.ts) · [`packages/llm/llm/src/message.ts:111`](../packages/llm/llm/src/message.ts) · [`packages/session/session-title/src/types.ts:35`](../packages/session/session-title/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -3367,7 +3377,7 @@ SHA-256: `abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c` | `body` | 必需 | [`{ max_tokens, messages, model, thinking?, … }`](#persistence-type-sha256-9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee) | | `endpoint` | 必需 | `string` | - + @@ -3375,7 +3385,7 @@ SHA-256: `abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c` ### `DeveloperMessage` -SHA-256: `0f6265188dae7ba6faa26830a180bb4deb0760561f97ee0c9d399ccf6c9cf1f7` +SHA-256: `cebb7e9f3f663e660a531d9764ecfb9fa7fc73c22bf8d628f888e9ecf18c5cf0` 来源:[`packages/llm/llm/src/message.ts:157`](../packages/llm/llm/src/message.ts) @@ -3384,11 +3394,11 @@ SHA-256: `0f6265188dae7ba6faa26830a180bb4deb0760561f97ee0c9d399ccf6c9cf1f7` | `content` | 必需 | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | 必需 | `string` | | `role` | 必需 | `"developer"` | -| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-5bc2d7f02503fc6b3e1bb7e0b7fa22c0b9e4b9841fa3175b2ad8e607ae3525a8) | +| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-b112459dcb0686091c31ce6d213b2a4934b5ad19d37cc5b599e46f5a9d715591) | 消息源兼容策略:`source` — `session-source-attribution` v1; `session.developer-message.source`; `kind`; `preserve`. -仅表示归属的新增 kind:`tmux-context`, `user-question-reply`, `working-directory`. +仅表示归属的新增 kind:`action-cards`, `tmux-context`, `user-question-reply`, `working-directory`. @@ -3400,7 +3410,7 @@ SHA-256: `0f6265188dae7ba6faa26830a180bb4deb0760561f97ee0c9d399ccf6c9cf1f7` SHA-256: `9a930283b91d493d6347146f2475bb107294b379415ca02162354f46a64164f7` -来源:[`packages/core/session/src/types.ts:242`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:246`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4083,7 +4093,7 @@ SHA-256: `6f72ece8f317cd080c4f20a93f1bf709965f5b81ac4669528f5a023191cfcf20` | `step` | 必需 | `number` | | `turn` | 必需 | `number` | - + @@ -4091,17 +4101,17 @@ SHA-256: `6f72ece8f317cd080c4f20a93f1bf709965f5b81ac4669528f5a023191cfcf20` ### `Message` -SHA-256: `040cd65423bd64264d225504f1c572d239eeb1793d0c2856ad8e42bb6e1e148b` +SHA-256: `4f9125fa028a56286fac70176ecc670d12f4402d8cbe112e14f0639f5e8e5c9d` 来源:[`packages/llm/llm/src/message.ts:196`](../packages/llm/llm/src/message.ts) 以下类型之一: - [`ToolResultMessage`](#persistence-type-sha256-4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731) -- [`DeveloperMessage`](#persistence-type-sha256-0f6265188dae7ba6faa26830a180bb4deb0760561f97ee0c9d399ccf6c9cf1f7) -- [`UserMessage`](#persistence-type-sha256-2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711) -- [`AssistantMessage`](#persistence-type-sha256-fa87537f4a9c1e25602990a8bf686b383e9e00352ec8946e16ae24ba7c1625be) +- [`DeveloperMessage`](#persistence-type-sha256-cebb7e9f3f663e660a531d9764ecfb9fa7fc73c22bf8d628f888e9ecf18c5cf0) +- [`UserMessage`](#persistence-type-sha256-8bca2b4f53ec7745b0484c6e7d3a6beb2ddd6cea82fc81786eaa3c0d065bbc14) - [`SystemMessage`](#persistence-type-sha256-09f3f8dc417f278257202714132f98ba7b52957d7b558c4a04456603890eb363) +- [`AssistantMessage`](#persistence-type-sha256-fa87537f4a9c1e25602990a8bf686b383e9e00352ec8946e16ae24ba7c1625be) @@ -4176,7 +4186,7 @@ SHA-256: `390eed1028aba02774f14408647acec10ec5516e97d4f15ecde2b9989d5a69f2` - `"negative"` - `"positive"` - + @@ -4184,12 +4194,19 @@ SHA-256: `390eed1028aba02774f14408647acec10ec5516e97d4f15ecde2b9989d5a69f2` ### `MessageSource` -SHA-256: `5bc2d7f02503fc6b3e1bb7e0b7fa22c0b9e4b9841fa3175b2ad8e607ae3525a8` +SHA-256: `b112459dcb0686091c31ce6d213b2a4934b5ad19d37cc5b599e46f5a9d715591` 来源:[`packages/llm/llm/src/message.ts:136`](../packages/llm/llm/src/message.ts) | kind | form 属性 | 其他必需字段 | 完整定义 | |---|---|---|---| +| `action-cards` | `"catalog"` | `through`: `number` | [`{ kind: "action-cards", form: "catalog" }`](#persistence-type-sha256-dd00cdccd0ba487b92362ef67db58cd264f48c1bfd368291424a1da9a899489a) | +| `action-cards` | `"instructions"` | `through`: `number` | [`{ kind: "action-cards", form: "instructions" }`](#persistence-type-sha256-ba2a1a8f194b1bb21f270713398f6643e206e8ff5f7f26f6d36a88e3f0f0ab10) | +| `action-cards` | `"notice"` | `summary`: `string`; `through`: `number` | [`{ kind: "action-cards", form: "notice" }`](#persistence-type-sha256-e7f4cbb3a57f4cbdb61ea41e95bcba626ad1fff6bb9b1e063b1d50a32da6e864) | +| `action-cards` | `"recall"` | `through`: `number` | [`{ kind: "action-cards", form: "recall" }`](#persistence-type-sha256-b613f83572fe2fbf7259c72308cafd008f4fceea897749128a48bcd158f290aa) | +| `action-cards` | `"relay"` | `through`: `number` | [`{ kind: "action-cards", form: "relay" }`](#persistence-type-sha256-45f005e6bbb7645248be792b715a74bc7fdf5a67f5381655d3a75dcc7aa2112e) | +| `action-cards` | `"snapshot"` | `sections`: [`ContextSnapshotSection[]`](#persistence-type-sha256-c748fb42c80a120038a8c587af80ec39924803c401364db11c8974d5bf6d0262); `through`: `number` | [`{ kind: "action-cards", form: "snapshot" }`](#persistence-type-sha256-3247e566f4340029325b70e4366b56fa9719977f1e39033b769a2ec221ab22a9) | +| `action-cards` | 未声明 | `through`: `number` | [`{ kind: "action-cards" }`](#persistence-type-sha256-dde0cdf9d426768b649b5a9783d2144e7f900c35ef65229cd89036dbf411d1b0) | | `agent-instructions` | `"instructions"` | `changes`: [`AgentInstructionChange[]`](#persistence-type-sha256-2ab12a0e345658f9342816d773fe610f049982bcad82631f43b9205abe43e5ee) | [`AgentInstructionSource`](#persistence-type-sha256-6f22a9d02b9a1f1157f3b0e7bdccd7e7b12b085c4efdb709dfc74a465cd4e590) | | `agent-message` | `"relay"` | `senderSessionId`: `string` | [`AgentMessageSource`](#persistence-type-sha256-4a9bef9f27a942520cc2279ca7dd3082556e4bff543f66b5c0333e1bbed1cd86) | | `compact-checkpoint` | 未声明 | `compactionId`: `string` | [`CompactionCheckpointSource`](#persistence-type-sha256-31907de9563751822af6d9be02bafaf26faa098bbd1cb412524134d577cc1648) | @@ -4254,7 +4271,7 @@ SHA-256: `5bc2d7f02503fc6b3e1bb7e0b7fa22c0b9e4b9841fa3175b2ad8e607ae3525a8` | `schedule` | `"snapshot"` | `sections`: [`ContextSnapshotSection[]`](#persistence-type-sha256-c748fb42c80a120038a8c587af80ec39924803c401364db11c8974d5bf6d0262) | [`{ kind: "schedule", form: "snapshot" }`](#persistence-type-sha256-28936c614bd4e7e2774806edcbb3cbfd3ee643ac1cbf0bbdff43d915505a8fe3) | | `schedule` | 未声明 | 无 | [`{ kind: "schedule" }`](#persistence-type-sha256-f29d63336e8266d80dd7baeab219436db86341304f6be1cd0edb36f5134c4a47) | | `session-reference` | `"recall"` | `references`: [`{ capturedFormatVersion?, capturedThroughSeq, compacted, inputIndex, … }[]`](#persistence-type-sha256-df843efd87c78cf8de98f8e0d0216956cd568d0d0e56a22c853663e274aa1a18); `version`: `1` | [`SessionReferenceSource`](#persistence-type-sha256-f56c5b59ca0161310c338d31dd16cf14287ccd602ff4181058df178c1c286d7f) | -| `skill-catalog` | `"catalog"` | `entries`: [`{ description, name }[]`](#persistence-type-sha256-aba175fb20ffc71112c55efe70458ff5d7dbfb83501892b4ba8d077f0ea5d7ba) | [`SkillCatalogSource`](#persistence-type-sha256-fc2ae6962f9f8801c2b1e414668e1e17cbb7544c4f39381198977a38bd10c093) | +| `skill-catalog` | `"catalog"` | `entries`: [`{ description, name }[]`](#persistence-type-sha256-aba175fb20ffc71112c55efe70458ff5d7dbfb83501892b4ba8d077f0ea5d7ba) | [`SkillCatalogSource`](#persistence-type-sha256-65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099) | | `skill-invocation` | `"instructions"` | `name`: `string` | [`SkillInvocationSource`](#persistence-type-sha256-672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db) | | `subagent-settled` | `"notice"` | `senderSessionId`: `string`; `summary`: `string` | [`SubagentSettledMessageSource`](#persistence-type-sha256-4e97c3d85c0fc817ee58873c38c25a2474abaaa0af4839311b50b68db3b8cf1a) | | `system-prompt` | 未声明 | 无 | [`SystemPromptMessageSource`](#persistence-type-sha256-65a8400e451e667e5b6e34df72ceb81fca8c12330330fa72083ad40279b189ad) | @@ -4302,13 +4319,13 @@ SHA-256: `5bc2d7f02503fc6b3e1bb7e0b7fa22c0b9e4b9841fa3175b2ad8e607ae3525a8` | `webhook` | `"notice"` | `deliveryId`: `string`; `provider`: `string`; `ruleId`: `string`; `source`: `string`; `summary`: `string` | [`{ kind: "webhook", form: "notice" }`](#persistence-type-sha256-9edc162949abf93bd5ff049191b345454ba104f583937ce5580fb50f067d2b94) | | `working-directory` | 未声明 | 无 | [`{ kind: "working-directory" }`](#persistence-type-sha256-2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5) | - + ### `Message[]` -SHA-256: `a927d444c928ac0efd9dd8b2e7d7d04d711c264cb71578d81e0e2fd143ff669f` +SHA-256: `d2b617d9dfcc4e0a4b60732d8ba1effc632e3b75124b93b064c07814a0a716bc` -[`Message`](#persistence-type-sha256-040cd65423bd64264d225504f1c572d239eeb1793d0c2856ad8e42bb6e1e148b) 的数组。 +[`Message`](#persistence-type-sha256-4f9125fa028a56286fac70176ecc670d12f4402d8cbe112e14f0639f5e8e5c9d) 的数组。 @@ -4530,7 +4547,7 @@ SHA-256: `0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555` SHA-256: `b158f3ff6923714807c0d73882f0b05dc87f8fa85c9e90814852d48bbc866081` -来源:[`packages/core/session/src/types.ts:256`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:260`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4549,7 +4566,7 @@ SHA-256: `b158f3ff6923714807c0d73882f0b05dc87f8fa85c9e90814852d48bbc866081` SHA-256: `530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6` -来源:[`packages/core/session/src/types.ts:275`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:279`](../packages/core/session/src/types.ts) 以下类型之一: @@ -4692,7 +4709,7 @@ SHA-256: `b56f6a885da3dc394c69a3e3cc5c0cfc4da15601b63fda4989eee8f40efc5be4` | `source` | 必需 | [`SessionTitleSource`](#persistence-type-sha256-30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f) | | `title` | 必需 | `string` | - + @@ -4700,7 +4717,7 @@ SHA-256: `b56f6a885da3dc394c69a3e3cc5c0cfc4da15601b63fda4989eee8f40efc5be4` ### `SessionTitleLlmRequestEventData` -SHA-256: `00c054d3018c198d92f459563331edd1385e58345c677bb499791df2da0ade9f` +SHA-256: `9808c3d0f0a1be8fe313b4148ba22c691c4d59bd2c67aef3c63cfe8043148c5f` 来源:[`packages/session/session-title-llm/src/index.ts:37`](../packages/session/session-title-llm/src/index.ts) @@ -4708,7 +4725,7 @@ SHA-256: `00c054d3018c198d92f459563331edd1385e58345c677bb499791df2da0ade9f` |---|---|---| | `maxTokens` | 必需 | `number` | | `messageSeqs` | 必需 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | -| `messages` | 必需 | [`Message[]`](#persistence-type-sha256-a927d444c928ac0efd9dd8b2e7d7d04d711c264cb71578d81e0e2fd143ff669f) | +| `messages` | 必需 | [`Message[]`](#persistence-type-sha256-d2b617d9dfcc4e0a4b60732d8ba1effc632e3b75124b93b064c07814a0a716bc) | | `reasoningEffort` | 可选 | `string` | | `route` | 必需 | [`SessionTitleModelIdentity`](#persistence-type-sha256-07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235) | | `system` | 必需 | `string` | @@ -4761,7 +4778,7 @@ SHA-256: `30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f` | `provider` | 未声明 | `provider`: `string` | [`{ kind: "provider" }`](#persistence-type-sha256-b81e9de81a481b24e1e1f9adf038bfc59e57b4f35ce62f8f1e45284186f4f812) | | `user` | 未声明 | 无 | [`CommandSource`](#persistence-type-sha256-ada310bf0bdb8fed51f3b56ea63f6ea6b18bbd587f04fccb63a14ab0b2a24e05) | - + @@ -4769,7 +4786,7 @@ SHA-256: `30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f` ### `SkillCatalogSource` -SHA-256: `fc2ae6962f9f8801c2b1e414668e1e17cbb7544c4f39381198977a38bd10c093` +SHA-256: `65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099` 来源:[`packages/skill/tool-skill/src/index.ts:35`](../packages/skill/tool-skill/src/index.ts) @@ -4777,6 +4794,7 @@ SHA-256: `fc2ae6962f9f8801c2b1e414668e1e17cbb7544c4f39381198977a38bd10c093` |---|---|---| | `entries` | 必需 | [`{ description, name }[]`](#persistence-type-sha256-aba175fb20ffc71112c55efe70458ff5d7dbfb83501892b4ba8d077f0ea5d7ba) | | `form` | 必需 | `"catalog"` | +| `incomplete` | 可选 | `true` | | `kind` | 必需 | `"skill-catalog"` | | `update` | 可选 | `true` | @@ -4887,7 +4905,7 @@ SHA-256: `4e97c3d85c0fc817ee58873c38c25a2474abaaa0af4839311b50b68db3b8cf1a` SHA-256: `335e242de1fcc17b6ca920fc420d71bec2d76e53e37955c00948b65ab77f05c5` -来源:[`packages/core/session/src/types.ts:464`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:470`](../packages/core/session/src/types.ts) 以下类型之一: @@ -5332,7 +5350,7 @@ SHA-256: `a6da9ad5d42ae83a6833a8288b076688e8e0801633ea36cbdd8a30a6d9f3160c` SHA-256: `1f8c126cfab3df812cd115cfc23e3256f0fa2383400f4ce91ecad313577e59b0` -来源:[`packages/core/session/src/types.ts:197`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:201`](../packages/core/session/src/types.ts) | kind | form 属性 | 其他必需字段 | 完整定义 | |---|---|---|---| @@ -5352,7 +5370,7 @@ SHA-256: `1f8c126cfab3df812cd115cfc23e3256f0fa2383400f4ce91ecad313577e59b0` SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` -来源:[`packages/core/session/src/types.ts:234`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:238`](../packages/core/session/src/types.ts) | kind | form 属性 | 其他必需字段 | 完整定义 | |---|---|---|---| @@ -5364,7 +5382,7 @@ SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` | `interrupted` | 未声明 | 无 | [`{ kind: "interrupted" }`](#persistence-type-sha256-56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23) | | `max-tokens` | 未声明 | 无 | [`{ kind: "max-tokens" }`](#persistence-type-sha256-ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7) | - + @@ -5372,7 +5390,7 @@ SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` ### `UserMessage` -SHA-256: `2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711` +SHA-256: `8bca2b4f53ec7745b0484c6e7d3a6beb2ddd6cea82fc81786eaa3c0d065bbc14` 来源:[`packages/llm/llm/src/message.ts:162`](../packages/llm/llm/src/message.ts) @@ -5381,19 +5399,19 @@ SHA-256: `2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711` | `content` | 必需 | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | 必需 | `string` | | `role` | 必需 | `"user"` | -| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-5bc2d7f02503fc6b3e1bb7e0b7fa22c0b9e4b9841fa3175b2ad8e607ae3525a8) | +| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-b112459dcb0686091c31ce6d213b2a4934b5ad19d37cc5b599e46f5a9d715591) | 消息源兼容策略:`source` — `session-source-attribution` v1; `session.user-message.source`; `kind`; `preserve`. -仅表示归属的新增 kind:`tmux-context`, `user-question-reply`, `working-directory`. +仅表示归属的新增 kind:`action-cards`, `tmux-context`, `user-question-reply`, `working-directory`. - + ### `UserMessage[]` -SHA-256: `454a0fa879e38076bdcdbd87ef561cd67d7e43e58a287cf7dbaa7b6cf7847020` +SHA-256: `aada2771a250136cc3a839b0507e9c6502622a2897716903942297bcb6661292` -[`UserMessage`](#persistence-type-sha256-2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711) 的数组。 +[`UserMessage`](#persistence-type-sha256-8bca2b4f53ec7745b0484c6e7d3a6beb2ddd6cea82fc81786eaa3c0d065bbc14) 的数组。 @@ -5585,7 +5603,7 @@ SHA-256: `5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78` SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -来源:[`packages/api/session-controller/src/types.ts:380`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:386`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` @@ -5822,7 +5840,7 @@ SHA-256: `a853902cfab417b8f08aa51ad6855fea46f34ed4588a74e47403035111d0fb86` SHA-256: `e4c18e294232c3ba6c9f1999f168263cc55956147cfe4121720899be8e52edd1` -来源:[`packages/core/session/src/types.ts:363`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:369`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5981,7 +5999,7 @@ SHA-256: `cbbe8377ee744964537dbafd83607219e58ba79a13f6db0d0645c7ad3d5e8a09` SHA-256: `a81059ca06999da1e712414520c2c65e491d052fcf9640fae20aa38f0a5dc735` -来源:[`packages/core/session/src/types.ts:385`](../packages/core/session/src/types.ts) · [`packages/core/tool-executor-ptc/src/types.ts:27`](../packages/core/tool-executor-ptc/src/types.ts) +来源:[`packages/core/session/src/types.ts:391`](../packages/core/session/src/types.ts) · [`packages/core/tool-executor-ptc/src/types.ts:27`](../packages/core/tool-executor-ptc/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6151,7 +6169,7 @@ SHA-256: `374fdd68aee5ff844e378c0cbdd961d247a0f22e4ade0bb03d800cd2a46a2b8b` SHA-256: `83079c8a3f733ac3fa603eefa0fbb4737ca4d8b69e7e2e7298b60f9ac4098693` -来源:[`packages/skill/tool-skill/src/index.ts:41`](../packages/skill/tool-skill/src/index.ts) +来源:[`packages/skill/tool-skill/src/index.ts:43`](../packages/skill/tool-skill/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6201,7 +6219,7 @@ SHA-256: `9e41386b3a0c9572b0d63078492ebb3997da7d3a830d44e0259418bd02f4bcb2` SHA-256: `bcf0caf62d964b2fcf5404bd5c909cfa9a21c3f3c96e6b7e36d9e33565223825` -来源:[`packages/core/session/src/types.ts:466`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:472`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6215,7 +6233,7 @@ SHA-256: `bcf0caf62d964b2fcf5404bd5c909cfa9a21c3f3c96e6b7e36d9e33565223825` SHA-256: `79650cfa10aa3c52440328d85e8a25f0ffadc8d7efd784e3c0819d8bb74a1985` -来源:[`packages/core/session/src/types.ts:214`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:218`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6228,7 +6246,7 @@ SHA-256: `79650cfa10aa3c52440328d85e8a25f0ffadc8d7efd784e3c0819d8bb74a1985` SHA-256: `5302e763151277614b97e77f00e3b326694c6c1247b916a20503c344dc970777` -来源:[`packages/core/session/src/types.ts:377`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:383`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6270,7 +6288,7 @@ SHA-256: `693f4952fb5565da96c06bace8924b098ac2fbc915fde0ff8019701183abc057` SHA-256: `ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585` -来源:[`packages/core/session/src/types.ts:392`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:398`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6278,18 +6296,18 @@ SHA-256: `ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585` | `reason` | 必需 | [`RequestHeaderReason`](#persistence-type-sha256-530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6) | | `startsSeries` | 可选 | `true` | - + ### `{ headerSeq?, message, step, turn }` -SHA-256: `f4ed4717b4c259e933b550a8dcd90dc93628cda8a3c7affcaa53b9c13c1d53eb` +SHA-256: `12f9a5a7506bca46d6ef8e3c71826c4bf40e1389bfe0236cfffaea0c3fb367d2` -来源:[`packages/core/session/src/types.ts:313`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:317`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| | `headerSeq` | 可选 | `number` | -| `message` | 必需 | [`DeveloperMessage`](#persistence-type-sha256-0f6265188dae7ba6faa26830a180bb4deb0760561f97ee0c9d399ccf6c9cf1f7) | +| `message` | 必需 | [`DeveloperMessage`](#persistence-type-sha256-cebb7e9f3f663e660a531d9764ecfb9fa7fc73c22bf8d628f888e9ecf18c5cf0) | | `step` | 必需 | `number` | | `turn` | 必需 | `number` | @@ -6367,23 +6385,23 @@ SHA-256: `e3e77b26f0148755a505f5b8ea843a3be117827d4703bb5754d9dc8ddbef521f` SHA-256: `17d1afb770d9941936130996da00dc86782cfef731d8d6526162c301256a4ac3` -来源:[`packages/core/session/src/types.ts:429`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:435`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| | `inherited` | 可选 | `true` | - + ### `{ inserted, outcome?, removedCount?, start, … }` -SHA-256: `fa106c5b33b657e8ef16e8cbf39f3b7d44e5cbcdf4f9303d9db6410f28951e42` +SHA-256: `c433ef580a5b229bbe68274a7164aa3a8e8040d7217f010b610ca0696a84253c` 来源:[`packages/core/agent/src/types.ts:110`](../packages/core/agent/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| -| `inserted` | 必需 | [`UserMessage[]`](#persistence-type-sha256-454a0fa879e38076bdcdbd87ef561cd67d7e43e58a287cf7dbaa7b6cf7847020) | +| `inserted` | 必需 | [`UserMessage[]`](#persistence-type-sha256-aada2771a250136cc3a839b0507e9c6502622a2897716903942297bcb6661292) | | `outcome` | 可选 | `"canceled"` | | `removedCount` | 可选 | `number` | | `start` | 必需 | `number` | @@ -6395,7 +6413,7 @@ SHA-256: `fa106c5b33b657e8ef16e8cbf39f3b7d44e5cbcdf4f9303d9db6410f28951e42` SHA-256: `1ccb56061942f5ccb0d30c9e4f2883b9d115ff906560029de637b61d3cde896d` -来源:[`packages/core/session/src/types.ts:343`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:349`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6412,20 +6430,105 @@ SHA-256: `1ccb56061942f5ccb0d30c9e4f2883b9d115ff906560029de637b61d3cde896d` SHA-256: `0a30c3be336cdd4f8f34e66543a3d46d611c43986edd9b3ce6cbb9b721d3b5d3` -来源:[`packages/core/session/src/types.ts:205`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:209`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| | `kind` | 必需 | `"aborted"` | | `reason` | 必需 | [`TurnEndCancelCause`](#persistence-type-sha256-1f8c126cfab3df812cd115cfc23e3256f0fa2383400f4ce91ecad313577e59b0) | + + +### `{ kind: "action-cards" }` + +SHA-256: `dde0cdf9d426768b649b5a9783d2144e7f900c35ef65229cd89036dbf411d1b0` + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `kind` | 必需 | `"action-cards"` | +| `through` | 必需 | `number` | + + + +### `{ kind: "action-cards", form: "catalog" }` + +SHA-256: `dd00cdccd0ba487b92362ef67db58cd264f48c1bfd368291424a1da9a899489a` + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `form` | 必需 | `"catalog"` | +| `kind` | 必需 | `"action-cards"` | +| `through` | 必需 | `number` | + + + +### `{ kind: "action-cards", form: "instructions" }` + +SHA-256: `ba2a1a8f194b1bb21f270713398f6643e206e8ff5f7f26f6d36a88e3f0f0ab10` + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `form` | 必需 | `"instructions"` | +| `kind` | 必需 | `"action-cards"` | +| `through` | 必需 | `number` | + + + +### `{ kind: "action-cards", form: "notice" }` + +SHA-256: `e7f4cbb3a57f4cbdb61ea41e95bcba626ad1fff6bb9b1e063b1d50a32da6e864` + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `form` | 必需 | `"notice"` | +| `kind` | 必需 | `"action-cards"` | +| `summary` | 必需 | `string` | +| `through` | 必需 | `number` | + + + +### `{ kind: "action-cards", form: "recall" }` + +SHA-256: `b613f83572fe2fbf7259c72308cafd008f4fceea897749128a48bcd158f290aa` + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `form` | 必需 | `"recall"` | +| `kind` | 必需 | `"action-cards"` | +| `through` | 必需 | `number` | + + + +### `{ kind: "action-cards", form: "relay" }` + +SHA-256: `45f005e6bbb7645248be792b715a74bc7fdf5a67f5381655d3a75dcc7aa2112e` + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `form` | 必需 | `"relay"` | +| `kind` | 必需 | `"action-cards"` | +| `through` | 必需 | `number` | + + + +### `{ kind: "action-cards", form: "snapshot" }` + +SHA-256: `3247e566f4340029325b70e4366b56fa9719977f1e39033b769a2ec221ab22a9` + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `form` | 必需 | `"snapshot"` | +| `kind` | 必需 | `"action-cards"` | +| `sections` | 必需 | [`ContextSnapshotSection[]`](#persistence-type-sha256-c748fb42c80a120038a8c587af80ec39924803c401364db11c8974d5bf6d0262) | +| `through` | 必需 | `number` | + ### `{ kind: "blocked" }` SHA-256: `023a355b2be0d688fb6e4df8388dadb942761d46cfe96d0f499aae9631a159d4` -来源:[`packages/core/session/src/types.ts:207`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:211`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6437,7 +6540,7 @@ SHA-256: `023a355b2be0d688fb6e4df8388dadb942761d46cfe96d0f499aae9631a159d4` SHA-256: `b6ef9c6210be8350cd465f485cf520031fffa6bf3809c61a1e713e834c5982d0` -来源:[`packages/core/session/src/types.ts:203`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:207`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6461,7 +6564,7 @@ SHA-256: `02b2c23f2d94b028c9588a8faace3fce1217405db346da3389368b495457bf79` SHA-256: `4bb451330ff699f36b45539ceb0eb2606ead72084e2c5bb637c36cc80e2252db` -来源:[`packages/core/session/src/types.ts:194`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:198`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6563,7 +6666,7 @@ SHA-256: `1b5649238876e28811e80f10ec67a00c197ad3babd4ecc61a22b09064b88c597` SHA-256: `ec8b5ff7c77ca6893ac7ba5a0c5b2aefeb52f12c64450b7359660c2a7e8a53d7` -来源:[`packages/core/session/src/types.ts:230`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:234`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6575,7 +6678,7 @@ SHA-256: `ec8b5ff7c77ca6893ac7ba5a0c5b2aefeb52f12c64450b7359660c2a7e8a53d7` SHA-256: `6c5a37d42ebdb12db4410699259335f1e149e3a0260425684c00b153afc8990d` -来源:[`packages/core/session/src/types.ts:193`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:197`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6744,7 +6847,7 @@ SHA-256: `88841202942c7683b3b7e5ea6a796047ec326b6701ac23e58cc236d85613b9fa` SHA-256: `56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23` -来源:[`packages/core/session/src/types.ts:223`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:227`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6756,7 +6859,7 @@ SHA-256: `56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23` SHA-256: `eaa71be0fbf0f702df8ea6c11d0aa2f9782263d45a10d0fb14eda662f4bfe04c` -来源:[`packages/core/session/src/types.ts:197`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:201`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6768,7 +6871,7 @@ SHA-256: `eaa71be0fbf0f702df8ea6c11d0aa2f9782263d45a10d0fb14eda662f4bfe04c` SHA-256: `ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7` -来源:[`packages/core/session/src/types.ts:216`](../packages/core/session/src/types.ts) · [`packages/llm/llm/src/types.ts:159`](../packages/llm/llm/src/types.ts) +来源:[`packages/core/session/src/types.ts:220`](../packages/core/session/src/types.ts) · [`packages/llm/llm/src/types.ts:159`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6858,7 +6961,7 @@ SHA-256: `52c6113cb0e53f345324bf84f01928bea5d5df57ee80bc0dd65407b8bc5a3734` SHA-256: `6c03546143cdf6ae88f1745ac98c5139efa1588d1415249bbc5f3104d32ab800` -来源:[`packages/core/session/src/types.ts:192`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:196`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7556,7 +7659,7 @@ SHA-256: `8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543` SHA-256: `6dacb1584f2bfbe209dc6b6f578d51da6d55595f64d0e63c727c98f359278def` -来源:[`packages/api/session-controller/src/types.ts:389`](../packages/api/session-controller/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:395`](../packages/api/session-controller/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7723,7 +7826,7 @@ SHA-256: `b1ebd5cda47d90d980bb05bffc3f970c51537b9aff15b3bc3d639811727741b1` SHA-256: `6bc8e51124d0874bc89e1d0ceff381a9c3cd0fc240667d69f841ce4f60f65fe5` -来源:[`packages/core/session/src/types.ts:332`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:338`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7779,7 +7882,7 @@ SHA-256: `9890113e97dd3541787bfe6704f2b223d3a890b5325ca0acae2b0398909b413e` SHA-256: `11f70b595aa76897fc4e25a352bfa718c659f44b799e5aa14e84e5a38fe72912` -来源:[`packages/interaction/user-approval/src/index.ts:40`](../packages/interaction/user-approval/src/index.ts) +来源:[`packages/interaction/user-approval/src/index.ts:41`](../packages/interaction/user-approval/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7804,7 +7907,7 @@ SHA-256: `8a9c990773f798eac10ca8878e6bcc531ee080bc589cac956730e462cc6a09ad` SHA-256: `e481c46af3813e0010558e93f578b2986acd658404cec2d1679e3ac2a6c48654` -来源:[`packages/core/session/src/types.ts:299`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:303`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7858,7 +7961,7 @@ SHA-256: `5dd766ccd1702a1142ad8b4bd44f2242f8e8a6752669ad3de0a5d224329b1438` SHA-256: `54f9276a1617d7c12594722c89cfe864bcbe4517e9a6f9c98bab14f199a135e0` -来源:[`packages/core/session/src/types.ts:357`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:363`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7872,7 +7975,7 @@ SHA-256: `54f9276a1617d7c12594722c89cfe864bcbe4517e9a6f9c98bab14f199a135e0` SHA-256: `ef11a3b7fa2033ae4279545ff8a8a2ee4e301b9b73e5b91654c48e6d08283545` -来源:[`packages/core/session/src/types.ts:301`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:303`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:305`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:307`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7923,7 +8026,7 @@ SHA-256: `79ddc907312f97cf9553d4841e8b3fc937097bd8d97900a790efad3c05255e99` SHA-256: `f90eb4ab2d3897bc20c521a038e3119d581f791ec974b1a0004f63a8ab9e232d` -来源:[`packages/core/session/src/types.ts:290`](../packages/core/session/src/types.ts) · [`packages/deliverables/workspace-changes/src/types.ts:106`](../packages/deliverables/workspace-changes/src/types.ts) +来源:[`packages/core/session/src/types.ts:294`](../packages/core/session/src/types.ts) · [`packages/deliverables/workspace-changes/src/types.ts:106`](../packages/deliverables/workspace-changes/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7945,17 +8048,17 @@ SHA-256: `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | `time` | 必需 | `number` | | `type` | 必需 | `"agent-preset/selected"` | - + ### `{ type: "agent/inbox/spliced" }` -SHA-256: `0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034` +SHA-256: `9e8043098fb89db6d7c92a92c70146c5c8d24fa88f733c687fa29e5e7a58ab30` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-fa106c5b33b657e8ef16e8cbf39f3b7d44e5cbcdf4f9303d9db6410f28951e42) | +| `data` | 必需 | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-c433ef580a5b229bbe68274a7164aa3a8e8040d7217f010b610ca0696a84253c) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `time` | 必需 | `number` | @@ -8196,17 +8299,17 @@ SHA-256: `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | `time` | 必需 | `number` | | `type` | 必需 | `"deliverables/presented"` | - + ### `{ type: "developer/message" }` -SHA-256: `97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c` +SHA-256: `95acdbd066cf445d37092e5fdfe2e8717ef6ca1aed50f70e2e6037a6989a1f2f` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-f4ed4717b4c259e933b550a8dcd90dc93628cda8a3c7affcaa53b9c13c1d53eb) | +| `data` | 必需 | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-12f9a5a7506bca46d6ef8e3c71826c4bf40e1389bfe0236cfffaea0c3fb367d2) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `sourceEventSeqs` | 可选 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | @@ -8606,17 +8709,17 @@ SHA-256: `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | `time` | 必需 | `number` | | `type` | 必需 | `"session/title"` | - + ### `{ type: "session/title-llm-request" }` -SHA-256: `79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056` +SHA-256: `eaa9125aec0fb28478096c46e73e21bf512ab0d84d826bfb41e7308707734cb5` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-00c054d3018c198d92f459563331edd1385e58345c677bb499791df2da0ade9f) | +| `data` | 必需 | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-9808c3d0f0a1be8fe313b4148ba22c691c4d59bd2c67aef3c63cfe8043148c5f) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `time` | 必需 | `number` | @@ -9039,17 +9142,17 @@ SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515` | `type` | 必需 | `"usage"` | | `usage` | 必需 | [`TokenUsage`](#persistence-type-sha256-fec5442b9ee4122e10514d81d5a43648003fe8bfb7ee2ba50c0cdbdd383ed394) | - + ### `{ type: "user/message" }` -SHA-256: `2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8` +SHA-256: `39adb7fce8475af6402acd925ea79697b3341c22422ac32833d71217d84e987f` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`UserMessage`](#persistence-type-sha256-2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711) | +| `data` | 必需 | [`UserMessage`](#persistence-type-sha256-8bca2b4f53ec7745b0484c6e7d3a6beb2ddd6cea82fc81786eaa3c0d065bbc14) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `sourceEventSeqs` | 可选 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | diff --git a/docs/persistence-changes/2026-10-22-action-card-status.i18n.yaml b/docs/persistence-changes/2026-10-22-action-card-status.i18n.yaml new file mode 100644 index 0000000000..80b7c81132 --- /dev/null +++ b/docs/persistence-changes/2026-10-22-action-card-status.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for 2026-10-22-action-card-status.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/persistence-changes/2026-10-22-action-card-status.md +/: + en: 3d5a424ae7d7e46b + zh: c22a8e4a62d8cc1a +/2026-10-22-action-card-status: + en: f580a2fb64e941db + zh: 0e34217155210da6 +/2026-10-22-action-card-status/summary: + en: 3da2594bf2891e0e + zh: 5bc7d279d99400aa +/2026-10-22-action-card-status/table-of-contents: + en: 6cf314a069ceb451 + zh: 9adff678e9ecab3b +/2026-10-22-action-card-status/declaration: + en: 6907136f28e48c90 + zh: 02f8298485f3d8e7 +/2026-10-22-action-card-status/compatibility: + en: fbf4d1ada55f35fe + zh: bd5ce9a23c55fac6 +/2026-10-22-action-card-status/verification: + en: 91043c4f0b19e7bc + zh: ee1c541133475bb8 +/2026-10-22-action-card-status/dev-note: + en: b75c8458928b72b9 + zh: 003ba4e17b4b5269 diff --git a/docs/persistence-changes/2026-10-22-action-card-status.md b/docs/persistence-changes/2026-10-22-action-card-status.md new file mode 100644 index 0000000000..4c62efb5ce --- /dev/null +++ b/docs/persistence-changes/2026-10-22-action-card-status.md @@ -0,0 +1,60 @@ +--- +description: "Records a persistence type transition and its compatibility acknowledgement." +kind: persistence-change +--- + +# 2026-10-22-action-card-status + +English | [中文](2026-10-22-action-card-status.zh.md) + +## Summary + +Adds action-card status attribution to logged model context. + +## Table of Contents + +- [Declaration](#declaration) +- [Compatibility](#compatibility) +- [Verification](#verification) +- [Dev Note](#dev-note) + + +## Declaration + +```yaml persistence-change +schemaVersion: 1 +id: 2026-10-22-action-card-status +baseline: false +changes: + - root: "event:agent/inbox/spliced" + previous: "2026-10-13-user-rpc-principal" + after: "b36fd842cd004b532ce96fd5d6f5be28e017eda043131aa3cf5e69edc436108e" + decision: same-version + - root: "event:developer/message" + previous: "2026-10-13-user-rpc-principal" + after: "5ef58f2a1bdc576c1f12fa1f4da1920ece020b13c0f991a578cddcbeb28bc5be" + decision: same-version + - root: "event:session/title-llm-request" + previous: "2026-10-13-user-rpc-principal" + after: "efa1a091017ce533e38b0ef3e14d11a5c102ff1793229b18dad719a4268d9adc" + decision: same-version + - root: "event:user/message" + previous: "2026-10-13-user-rpc-principal" + after: "58b122df513aeaf7ddc5783dbb1fd844e2979bb273964e30ae351a8db6510019" + decision: same-version +``` + + +## Compatibility + +Existing messages and records are unchanged. Readers without the action-card plugin preserve the new action-cards source kind and its JSON metadata and derive the recorded text as ordinary context. Only the producer uses the through sequence, to acknowledge delivered decisions; it grants no authority and does not change replay interpretation. + + +## Verification + +pnpm exec vitest run on the action-cards, creation-recommendations, client-ui-action-cards and client-ui-creation-recommendations tests: 120 tests passed with 100% coverage of their sources. The Web creation-recommendations replay logs the status notice of a dismissed card before the next answer. + + +## Dev Note + +None. diff --git a/docs/persistence-changes/2026-10-22-action-card-status.schema.json b/docs/persistence-changes/2026-10-22-action-card-status.schema.json new file mode 100644 index 0000000000..9aa642699a --- /dev/null +++ b/docs/persistence-changes/2026-10-22-action-card-status.schema.json @@ -0,0 +1,249 @@ +{ + "formatVersion": 2, + "roots": [ + {"key":"event:agent/inbox/spliced","kind":"event","event":"agent/inbox/spliced","surface":false,"digest":"b36fd842cd004b532ce96fd5d6f5be28e017eda043131aa3cf5e69edc436108e"}, + {"key":"event:developer/message","kind":"event","event":"developer/message","surface":true,"digest":"5ef58f2a1bdc576c1f12fa1f4da1920ece020b13c0f991a578cddcbeb28bc5be"}, + {"key":"event:session/title-llm-request","kind":"event","event":"session/title-llm-request","surface":false,"digest":"efa1a091017ce533e38b0ef3e14d11a5c102ff1793229b18dad719a4268d9adc"}, + {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"58b122df513aeaf7ddc5783dbb1fd844e2979bb273964e30ae351a8db6510019"} + ], + "types": [], + "nodes": { + "0203243b72fc867a": {"kind":"object","properties":[{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "022623b9ef98ec47": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "02b2c23f2d94b028": {"kind":"object","properties":[{"name":"kind","type":"c5687b1313206a6f","optional":false}],"indices":[]}, + "05205074b24d8340": {"kind":"literal","value":"action-cards"}, + "0657d3ca5ac4e7bf": {"kind":"primitive","type":"number"}, + "07e1a58c58b593f5": {"kind":"object","properties":[{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "09655b34d7f3cf1e": {"kind":"literal","value":"system-prompt"}, + "09f3f8dc417f2782": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"8af841fc9b265ade","optional":false},{"name":"source","type":"65a8400e451e667e","optional":false}],"indices":[]}, + "0ed8d1108fe7a5e1": {"kind":"object","properties":[{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "0eeb17e1df89b1eb": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "0f46153645c29784": {"kind":"object","properties":[{"name":"height","type":"0657d3ca5ac4e7bf","optional":false},{"name":"width","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "0fe52387f6505270": {"kind":"literal","value":"plan-mode"}, + "11638dc58a31496f": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "12d5808fac1996b9": {"kind":"object","properties":[{"name":"attachment","type":"b0b0eb1b16490f6b","optional":false},{"name":"offloaded","type":"dacf3d5f3e4ff619","optional":true},{"name":"type","type":"fb8b6a2e53cb9cf4","optional":false}],"indices":[]}, + "1379f0b72275994d": {"kind":"literal","value":"developer/message"}, + "16d0507cb94b4cfc": {"kind":"literal","value":"relay"}, + "1922cd79a70806c1": {"kind":"literal","value":"skill-invocation"}, + "1938c8c20f1cba7c": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "1e709346005826eb": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "1f0133217eeeffd8": {"kind":"literal","value":"tool-call"}, + "1f1385dbc3e875c0": {"kind":"literal","value":"repeat-tool-reminder"}, + "1fdad624334d3548": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "2152caf1a71e588e": {"kind":"object","properties":[{"name":"kind","type":"2e4debca12f2c449","optional":false},{"name":"messageId","type":"4cd48f3e5108bd6e","optional":false},{"name":"senderId","type":"4cd48f3e5108bd6e","optional":false},{"name":"senderName","type":"4cd48f3e5108bd6e","optional":false},{"name":"teamId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "2235d957bf4b7c6c": {"kind":"object","properties":[{"name":"kind","type":"7b1ce60193fa8b69","optional":false}],"indices":[]}, + "224aa11d4d5f88c4": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "23af3759678a30de": {"kind":"literal","value":"dsh-session-title-llm"}, + "24b10f7cdae64928": {"kind":"literal","value":"runtime-context"}, + "24ce31aa528272e5": {"kind":"object","properties":[{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "260523b412c19ad8": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "2765e9119edf5816": {"kind":"literal","value":"model"}, + "277b61f9c6f81704": {"kind":"literal","value":"file"}, + "28936c614bd4e7e2": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "290f32bfd81ff85a": {"kind":"object","properties":[{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "297fbd8067d7815a": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "2aad1179f9576314": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "2ab12a0e345658f9": {"kind":"array","element":"83da72c6857601c7"}, + "2e4debca12f2c449": {"kind":"literal","value":"team-message"}, + "2f1e6a7ebace43d7": {"kind":"union","types":["3f74ba74acd10644","58f94390b982f8a5","de30b1fa12c75f81","ebb768d85ec87fb6"]}, + "2f3f201c8846e19c": {"kind":"literal","value":"tool-goal"}, + "312aee2f0c42aabb": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "31907de956375182": {"kind":"object","properties":[{"name":"compactionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"6b23ed9ce1b397e6","optional":false},{"name":"sourceCommandId","type":"4cd48f3e5108bd6e","optional":true}],"indices":[]}, + "3247e566f4340029": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "335e242de1fcc17b": {"kind":"union","types":["bcf0caf62d964b2f","e438a9d4fb883b3e"]}, + "383cf73ae4748e5b": {"kind":"literal","value":"recall"}, + "3b04790e08b35241": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "3b4f2c9ef2c1217e": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "3bd652ebfa8726b3": {"kind":"union","types":["0657d3ca5ac4e7bf","938f7c7357bc403e"]}, + "3bdb8dc6989655b0": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "3c2535ca0a2062f1": {"kind":"literal","value":"reasoning"}, + "3e2ece4967cfebe9": {"kind":"literal","value":"next-step"}, + "3f74ba74acd10644": {"kind":"literal","value":"image/jpeg"}, + "408927267422a7b2": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "43e311235aa537df": {"kind":"object","properties":[{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"83d6916021eede8f","optional":false}],"indices":[]}, + "45f005e6bbb76452": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "4991dfc415c9efeb": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "49dab019d00e8c26": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "4a9bef9f27a94252": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"82470020b5bfcb1a","optional":false},{"name":"senderSessionId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "4b259f7f8f0a44ad": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"isError","type":"aa93010d0e521ad7","optional":true},{"name":"role","type":"a13d8f379222ece8","optional":false},{"name":"source","type":"d9c462b9f62fdd3e","optional":false},{"name":"toolCallId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "4cd48f3e5108bd6e": {"kind":"primitive","type":"string"}, + "4e44c9118152f682": {"kind":"literal","value":"text"}, + "4e88776858652856": {"kind":"object","properties":[{"name":"text","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"4e44c9118152f682","optional":false}],"indices":[]}, + "4e97c3d85c0fc817": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"bf16d2e98a7f1389","optional":false},{"name":"senderSessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "4edec1b770e8ec4c": {"kind":"literal","value":"ptc-mode"}, + "4f91f187baeabef5": {"kind":"object","properties":[{"name":"capturedFormatVersion","type":"0657d3ca5ac4e7bf","optional":true},{"name":"capturedThroughSeq","type":"3bd652ebfa8726b3","optional":false},{"name":"compacted","type":"aa93010d0e521ad7","optional":false},{"name":"inputIndex","type":"0657d3ca5ac4e7bf","optional":false},{"name":"label","type":"4cd48f3e5108bd6e","optional":false},{"name":"omittedBytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"omittedMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"originalMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"retainedMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"truncated","type":"aa93010d0e521ad7","optional":false}],"indices":[]}, + "52c6113cb0e53f34": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "53cf1704ae0709c7": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "5654685d7557ec74": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "58015da1c1950a66": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "587bb11da730e06a": {"kind":"literal","value":"session/title-llm-request"}, + "589d0d91239681f8": {"kind":"literal","value":"developer"}, + "58b122df513aeaf7": {"kind":"object","properties":[{"name":"data","type":"b782058cef83caf3","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"de25352d2dc41963","optional":false}],"indices":[]}, + "58f94390b982f8a5": {"kind":"literal","value":"image/png"}, + "5bb69b88517f6214": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "5bc66269cfaf614c": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "5cdbf342b7748d15": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "5d00abf938272f22": {"kind":"array","element":"b782058cef83caf3"}, + "5d03ba38734809bc": {"kind":"array","element":"0657d3ca5ac4e7bf"}, + "5d7a64ed6aac5551": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "5ef58f2a1bdc576c": {"kind":"object","properties":[{"name":"data","type":"7404c6123fdaa591","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1379f0b72275994d","optional":false}],"indices":[]}, + "6085488d223aeffd": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "6292bcbedaa97fea": {"kind":"object","properties":[{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "62ecb62dc0fe1b5e": {"kind":"literal","value":"next-turn"}, + "65a8400e451e667e": {"kind":"object","properties":[{"name":"kind","type":"09655b34d7f3cf1e","optional":false}],"indices":[]}, + "672c4aa2a9b736e3": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"1922cd79a70806c1","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "68f44f59e91c4139": {"kind":"literal","value":"user"}, + "6b23ed9ce1b397e6": {"kind":"literal","value":"compact-checkpoint"}, + "6ccb6bc423fb3952": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "6dacb1584f2bfbe2": {"kind":"object","properties":[{"name":"clientTimeZone","type":"4cd48f3e5108bd6e","optional":true},{"name":"kind","type":"68f44f59e91c4139","optional":false},{"name":"principal","type":"deebfc7c62177ea8","optional":true},{"name":"rpcId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "6ea608bdc8a7a63d": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "6ebcc2dbec9f2dab": {"kind":"literal","value":"skill-catalog"}, + "6f22a9d02b9a1f11": {"kind":"object","properties":[{"name":"baseline","type":"dacf3d5f3e4ff619","optional":true},{"name":"baselineIdentity","type":"4cd48f3e5108bd6e","optional":true},{"name":"changes","type":"2ab12a0e345658f9","optional":false},{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"fbd2c74b346a1595","optional":false}],"indices":[]}, + "6f44f32be9bcd9a8": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "6f9e00383836275e": {"kind":"literal","value":"snapshot"}, + "719c51f67074f970": {"kind":"object","properties":[{"name":"kind","type":"2765e9119edf5816","optional":false},{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"replayState","type":"bbc5696e3f13c758","optional":true}],"indices":[]}, + "7382c4fc95fe8c5d": {"kind":"literal","value":"remove"}, + "7404c6123fdaa591": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"7580e7d96dc8475f","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "7554565be416b034": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "756b5e23a5cb2c7f": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "7580e7d96dc8475f": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"7a5b68bd1a5118c8","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.developer-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, + "78a9be340090b735": {"kind":"literal","value":"tmux-context"}, + "78b9204976ab9faa": {"kind":"array","element":"cda79b839d8cc0c7"}, + "7a5b68bd1a5118c8": {"kind":"union","types":["0203243b72fc867a","022623b9ef98ec47","02b2c23f2d94b028","0ed8d1108fe7a5e1","0eeb17e1df89b1eb","11638dc58a31496f","1938c8c20f1cba7c","1e709346005826eb","1fdad624334d3548","2152caf1a71e588e","2235d957bf4b7c6c","224aa11d4d5f88c4","24ce31aa528272e5","260523b412c19ad8","28936c614bd4e7e2","290f32bfd81ff85a","297fbd8067d7815a","2aad1179f9576314","312aee2f0c42aabb","31907de956375182","3247e566f4340029","3b04790e08b35241","3b4f2c9ef2c1217e","3bdb8dc6989655b0","408927267422a7b2","45f005e6bbb76452","4991dfc415c9efeb","49dab019d00e8c26","4a9bef9f27a94252","4e97c3d85c0fc817","52c6113cb0e53f34","53cf1704ae0709c7","5654685d7557ec74","58015da1c1950a66","5bb69b88517f6214","5bc66269cfaf614c","5cdbf342b7748d15","5d7a64ed6aac5551","6085488d223aeffd","6292bcbedaa97fea","65a8400e451e667e","672c4aa2a9b736e3","6ccb6bc423fb3952","6dacb1584f2bfbe2","6ea608bdc8a7a63d","6f22a9d02b9a1f11","6f44f32be9bcd9a8","719c51f67074f970","7554565be416b034","756b5e23a5cb2c7f","7df62978a2b7de85","7eaef7a763ba5b94","7f959241c24128b4","80677c8c8b804189","825ca23416b1ea9d","8338ee303e2bd448","854db3efdfb0cd39","85fe96bf15d5c755","8620189c8e335827","87b1a33564b9a4d6","88841202942c7683","8a046b52331959aa","8c1c4f72755a78ea","8c627d7a45fa406c","8f324cea3916c051","8fcb0b44a575e998","96bfb916a727cd44","99135d8a39379779","99f0e98184709ad1","9edc162949abf93b","9f65c43e340bba31","a15a19ef63cf5d1b","a16e567c8cd2c55c","a2066bd52f61218b","a3c6f1ea38e9a61d","aa2bf9e82b9fdeb9","aae343bc3d663c83","ada310bf0bdb8fed","ade057f4fdc387ae","b062078e899958f9","b2a5c8c008a31e3d","b3681c026a0b98e9","b4ec0af39fd52ed9","b613f83572fe2fbf","b6f94c17dd9bbd7c","b70f3e81fe11b7a5","b79641a9d25e7566","ba2a1a8f194b1bb2","ba4c40b4381e0dcd","baccc97ec34be6c4","c5228b7a55498d84","c55827fba7018198","cb1c8959e1726f82","cda2345a9be9d139","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd00cdccd0ba487b","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","dde0cdf9d426768b","deaae5cd30987d4f","e7f4cbb3a57f4cbd","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fc2ae6962f9f8801","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, + "7b1ce60193fa8b69": {"kind":"literal","value":"working-directory"}, + "7df62978a2b7de85": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "7eaef7a763ba5b94": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "7f13860ee89a2d35": {"kind":"literal","value":"session-reference"}, + "7f959241c24128b4": {"kind":"object","properties":[{"name":"goalId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"b815d7b91cdd9fc6","optional":false},{"name":"revision","type":"0657d3ca5ac4e7bf","optional":false},{"name":"round","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "8064c03c87c357fd": {"kind":"union","types":["12d5808fac1996b9","43e311235aa537df","4e88776858652856","814d9434e1ddf907","8e611bf46821e500","c1f0f17b6493b85d","f2da0f27c1e6add5"]}, + "80677c8c8b804189": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "8067b0d232c350f1": {"kind":"literal","value":"time-context"}, + "814d9434e1ddf907": {"kind":"object","properties":[{"name":"text","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"3c2535ca0a2062f1","optional":false}],"indices":[]}, + "82470020b5bfcb1a": {"kind":"literal","value":"agent-message"}, + "825ca23416b1ea9d": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "829a2fb3be6efd4b": {"kind":"literal","value":"agent/inbox/spliced"}, + "83079c8a3f733ac3": {"kind":"object","properties":[{"name":"description","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "8338ee303e2bd448": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "83d6916021eede8f": {"kind":"literal","value":"tool-removal"}, + "83da72c6857601c7": {"kind":"object","properties":[{"name":"action","type":"904bf499d98be4a3","optional":false},{"name":"digest","type":"4cd48f3e5108bd6e","optional":true},{"name":"path","type":"4cd48f3e5108bd6e","optional":false},{"name":"scope","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "854db3efdfb0cd39": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "85d6d96ff8842974": {"kind":"literal","value":"answered"}, + "85f9b505b7bdff1f": {"kind":"literal","value":"tool-addition"}, + "85fe96bf15d5c755": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "8620189c8e335827": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "86e1e384495ee09a": {"kind":"object","properties":[{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"text","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "87b1a33564b9a4d6": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "88841202942c7683": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "8a046b52331959aa": {"kind":"object","properties":[{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "8af841fc9b265ade": {"kind":"literal","value":"system"}, + "8c1c4f72755a78ea": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "8c627d7a45fa406c": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "8e611bf46821e500": {"kind":"object","properties":[{"name":"tool","type":"fcf427290c6213c2","optional":true},{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"85f9b505b7bdff1f","optional":false}],"indices":[]}, + "8f324cea3916c051": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "8fcb0b44a575e998": {"kind":"object","properties":[{"name":"kind","type":"a720757f704a2512","optional":false}],"indices":[]}, + "904bf499d98be4a3": {"kind":"union","types":["7382c4fc95fe8c5d","b765ee31033cea46","f6cb462f808309e3"]}, + "938f7c7357bc403e": {"kind":"primitive","type":"null"}, + "95a3ffccbf3c8afc": {"kind":"literal","value":"owner"}, + "95c0e88fcf0bafb2": {"kind":"literal","value":"assistant"}, + "9645cf93769a6dfb": {"kind":"literal","value":"user-question-reply"}, + "96bfb916a727cd44": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "96f4a9c81fc0f940": {"kind":"union","types":["3e2ece4967cfebe9","62ecb62dc0fe1b5e"]}, + "99135d8a39379779": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "99e7e7d7fed55ae6": {"kind":"literal","value":"tool-jobs"}, + "99f0e98184709ad1": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "9ac52f0f84fec2eb": {"kind":"literal","value":"model-selection"}, + "9edc162949abf93b": {"kind":"object","properties":[{"name":"deliveryId","type":"4cd48f3e5108bd6e","optional":false},{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"db6c5246911d47a7","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"ruleId","type":"4cd48f3e5108bd6e","optional":false},{"name":"source","type":"4cd48f3e5108bd6e","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "9f65c43e340bba31": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "a13d8f379222ece8": {"kind":"literal","value":"tool"}, + "a15a19ef63cf5d1b": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "a16e567c8cd2c55c": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "a2066bd52f61218b": {"kind":"object","properties":[{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "a3c6f1ea38e9a61d": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "a3e299483348f27a": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"78b9204976ab9faa","optional":false},{"name":"reasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"route","type":"07e1a58c58b593f5","optional":false},{"name":"system","type":"4cd48f3e5108bd6e","optional":false},{"name":"titleProvider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "a720757f704a2512": {"kind":"literal","value":"tool-registry"}, + "a9059a81430b3207": {"kind":"literal","value":"hooks-claude-code"}, + "aa2bf9e82b9fdeb9": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "aa93010d0e521ad7": {"kind":"primitive","type":"boolean"}, + "aae343bc3d663c83": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "aba175fb20ffc711": {"kind":"array","element":"83079c8a3f733ac3"}, + "ada310bf0bdb8fed": {"kind":"object","properties":[{"name":"kind","type":"68f44f59e91c4139","optional":false}],"indices":[]}, + "ade057f4fdc387ae": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "aec150797b655c5f": {"kind":"literal","value":"catalog"}, + "b062078e899958f9": {"kind":"object","properties":[{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "b0b0eb1b16490f6b": {"kind":"object","properties":[{"name":"attachmentId","type":"4cd48f3e5108bd6e","optional":false},{"name":"bytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"height","type":"0657d3ca5ac4e7bf","optional":false},{"name":"mediaType","type":"2f1e6a7ebace43d7","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":true},{"name":"originalDimensions","type":"0f46153645c29784","optional":true},{"name":"width","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "b2a5c8c008a31e3d": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "b2a948a5340a9341": {"kind":"object","properties":[{"name":"inserted","type":"5d00abf938272f22","optional":false},{"name":"outcome","type":"d4e4d575abeb4b72","optional":true},{"name":"removedCount","type":"0657d3ca5ac4e7bf","optional":true},{"name":"start","type":"0657d3ca5ac4e7bf","optional":false},{"name":"target","type":"96f4a9c81fc0f940","optional":false}],"indices":[]}, + "b3681c026a0b98e9": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "b36fd842cd004b53": {"kind":"object","properties":[{"name":"data","type":"b2a948a5340a9341","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"829a2fb3be6efd4b","optional":false}],"indices":[]}, + "b4ec0af39fd52ed9": {"kind":"object","properties":[{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "b52f215a6cd69105": {"kind":"array","element":"8064c03c87c357fd"}, + "b613f83572fe2fbf": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "b6f94c17dd9bbd7c": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "b70f3e81fe11b7a5": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "b765ee31033cea46": {"kind":"literal","value":"set"}, + "b782058cef83caf3": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"7a5b68bd1a5118c8","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.user-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, + "b79641a9d25e7566": {"kind":"object","properties":[{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "b815d7b91cdd9fc6": {"kind":"literal","value":"goal"}, + "ba2a1a8f194b1bb2": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "ba4c40b4381e0dcd": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "baccc97ec34be6c4": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "bb94f3217aa56c88": {"kind":"literal","value":"hooks-codex"}, + "bbc5696e3f13c758": {"kind":"opaque","reason":"unknown"}, + "bcf0caf62d964b2f": {"kind":"object","properties":[{"name":"endSeq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"op","type":"f6cb462f808309e3","optional":false},{"name":"startSeq","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "bf16d2e98a7f1389": {"kind":"literal","value":"subagent-settled"}, + "c1f0f17b6493b85d": {"kind":"object","properties":[{"name":"arguments","type":"4cd48f3e5108bd6e","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"1f0133217eeeffd8","optional":false}],"indices":[]}, + "c5228b7a55498d84": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "c55827fba7018198": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"9645cf93769a6dfb","optional":false},{"name":"outcome","type":"85d6d96ff8842974","optional":false}],"indices":[]}, + "c5687b1313206a6f": {"kind":"literal","value":"cordis-host-runner"}, + "c748fb42c80a1200": {"kind":"array","element":"86e1e384495ee09a"}, + "cb1c8959e1726f82": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "cda2345a9be9d139": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "cda79b839d8cc0c7": {"kind":"union","types":["09f3f8dc417f2782","4b259f7f8f0a44ad","7580e7d96dc8475f","b782058cef83caf3","fa87537f4a9c1e25"]}, + "d4e4d575abeb4b72": {"kind":"literal","value":"canceled"}, + "d85590a5675c6e2f": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "d9c462b9f62fdd3e": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"a13d8f379222ece8","optional":false}],"indices":[]}, + "d9edf1862e4471d6": {"kind":"literal","value":"schedule"}, + "dacf3d5f3e4ff619": {"kind":"literal","value":true}, + "db06ef35b27a3842": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "db6c5246911d47a7": {"kind":"literal","value":"webhook"}, + "dba54c09c6e7aafc": {"kind":"object","properties":[{"name":"kind","type":"4edec1b770e8ec4c","optional":false}],"indices":[]}, + "dd00cdccd0ba487b": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "dd5ee8762bd8a14b": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "dd6cc2bb2a8f2824": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "dde0cdf9d426768b": {"kind":"object","properties":[{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "de25352d2dc41963": {"kind":"literal","value":"user/message"}, + "de30b1fa12c75f81": {"kind":"literal","value":"image/gif"}, + "deaae5cd30987d4f": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "deebfc7c62177ea8": {"kind":"object","properties":[{"name":"kind","type":"95a3ffccbf3c8afc","optional":false}],"indices":[]}, + "df843efd87c78cf8": {"kind":"array","element":"4f91f187baeabef5"}, + "e438a9d4fb883b3e": {"kind":"literal","value":"append"}, + "e7f4cbb3a57f4cbd": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "e8de0f457fed5b9f": {"kind":"literal","value":"notice"}, + "ebb768d85ec87fb6": {"kind":"literal","value":"image/webp"}, + "edbbfff1128099fd": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "ee577a0cc18664c9": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "efa1a091017ce533": {"kind":"object","properties":[{"name":"data","type":"a3e299483348f27a","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"587bb11da730e06a","optional":false}],"indices":[]}, + "f19bee84bf3d2090": {"kind":"object","properties":[{"name":"attachmentId","type":"4cd48f3e5108bd6e","optional":false},{"name":"bytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "f230c0b583e23b25": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "f29d63336e8266d8": {"kind":"object","properties":[{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "f2da0f27c1e6add5": {"kind":"object","properties":[{"name":"attachment","type":"f19bee84bf3d2090","optional":false},{"name":"type","type":"277b61f9c6f81704","optional":false}],"indices":[]}, + "f4a66f654996c093": {"kind":"object","properties":[{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "f56c5b59ca016131": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"7f13860ee89a2d35","optional":false},{"name":"references","type":"df843efd87c78cf8","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, + "f6329fb30c7ea801": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "f6605d6c57933aea": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "f68c335306535a00": {"kind":"literal","value":"user-approval"}, + "f6afe41e3926f422": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "f6cb462f808309e3": {"kind":"literal","value":"replace"}, + "f7283223aacdc39b": {"kind":"object","properties":[{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "f88f1b7b6bb733f6": {"kind":"literal","value":1}, + "f97f47b0eb87905e": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "fa87537f4a9c1e25": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"95c0e88fcf0bafb2","optional":false},{"name":"source","type":"719c51f67074f970","optional":false}],"indices":[]}, + "fb8b6a2e53cb9cf4": {"kind":"literal","value":"image"}, + "fbd2c74b346a1595": {"kind":"literal","value":"agent-instructions"}, + "fc2ae6962f9f8801": {"kind":"object","properties":[{"name":"entries","type":"aba175fb20ffc711","optional":false},{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"6ebcc2dbec9f2dab","optional":false},{"name":"update","type":"dacf3d5f3e4ff619","optional":true}],"indices":[]}, + "fcf427290c6213c2": {"kind":"primitive","type":"never"}, + "fcf81d3c58c13593": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "fe1a7acdeed4d0f5": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "fee1caf8ab6a65c1": {"kind":"literal","value":"instructions"} + } +} diff --git a/docs/persistence-changes/2026-10-22-action-card-status.zh.md b/docs/persistence-changes/2026-10-22-action-card-status.zh.md new file mode 100644 index 0000000000..4257655568 --- /dev/null +++ b/docs/persistence-changes/2026-10-22-action-card-status.zh.md @@ -0,0 +1,60 @@ +--- +description: "记录持久化类型更改及其兼容性确认。" +kind: persistence-change +--- + +# 2026-10-22-action-card-status + +[English](2026-10-22-action-card-status.md) | 中文 + +## 概述 + +为写入日志的模型上下文新增操作卡片状态的来源标识。 + +## 目录 + +- [声明](#declaration) +- [兼容性](#compatibility) +- [验证](#verification) +- [开发备注](#dev-note) + + +## 声明 + +```yaml persistence-change +schemaVersion: 1 +id: 2026-10-22-action-card-status +baseline: false +changes: + - root: "event:agent/inbox/spliced" + previous: "2026-10-13-user-rpc-principal" + after: "b36fd842cd004b532ce96fd5d6f5be28e017eda043131aa3cf5e69edc436108e" + decision: same-version + - root: "event:developer/message" + previous: "2026-10-13-user-rpc-principal" + after: "5ef58f2a1bdc576c1f12fa1f4da1920ece020b13c0f991a578cddcbeb28bc5be" + decision: same-version + - root: "event:session/title-llm-request" + previous: "2026-10-13-user-rpc-principal" + after: "efa1a091017ce533e38b0ef3e14d11a5c102ff1793229b18dad719a4268d9adc" + decision: same-version + - root: "event:user/message" + previous: "2026-10-13-user-rpc-principal" + after: "58b122df513aeaf7ddc5783dbb1fd844e2979bb273964e30ae351a8db6510019" + decision: same-version +``` + + +## 兼容性 + +已有消息和记录不变。没有操作卡片插件的读取方保留新的 action-cards 来源类型及其 JSON 元数据,并把记录的文本当作普通上下文。只有写入方使用 through 序号确认已送达的决定;它不授予任何权限,也不改变回放的解释。 + + +## 验证 + +对 action-cards、creation-recommendations、client-ui-action-cards 和 client-ui-creation-recommendations 的测试运行 pnpm exec vitest run:120 个测试通过,源码覆盖率 100%。Web creation-recommendations 回放在下一次回答之前记录了已忽略卡片的状态通知。 + + +## 开发备注 + +无。 diff --git a/docs/persistence-changes/2026-10-25-skill-catalog-incomplete.i18n.yaml b/docs/persistence-changes/2026-10-25-skill-catalog-incomplete.i18n.yaml new file mode 100644 index 0000000000..d9f830e422 --- /dev/null +++ b/docs/persistence-changes/2026-10-25-skill-catalog-incomplete.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for 2026-10-25-skill-catalog-incomplete.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/persistence-changes/2026-10-25-skill-catalog-incomplete.md +/: + en: 3d5a424ae7d7e46b + zh: c22a8e4a62d8cc1a +/2026-10-25-skill-catalog-incomplete: + en: 77f5988a4e0ad23e + zh: 7def799f40328fd9 +/2026-10-25-skill-catalog-incomplete/summary: + en: 2e5d228ea592110b + zh: 4d6a7c1fcde5e7c8 +/2026-10-25-skill-catalog-incomplete/table-of-contents: + en: 6cf314a069ceb451 + zh: 9adff678e9ecab3b +/2026-10-25-skill-catalog-incomplete/declaration: + en: 6907136f28e48c90 + zh: 02f8298485f3d8e7 +/2026-10-25-skill-catalog-incomplete/compatibility: + en: 5c837cd1fe40b2ab + zh: 7e0f980f2d2fb250 +/2026-10-25-skill-catalog-incomplete/verification: + en: f8bd4f442ccb271b + zh: 0f659a17ca577c0c +/2026-10-25-skill-catalog-incomplete/dev-note: + en: b75c8458928b72b9 + zh: 003ba4e17b4b5269 diff --git a/docs/persistence-changes/2026-10-25-skill-catalog-incomplete.md b/docs/persistence-changes/2026-10-25-skill-catalog-incomplete.md new file mode 100644 index 0000000000..5d0638e9b2 --- /dev/null +++ b/docs/persistence-changes/2026-10-25-skill-catalog-incomplete.md @@ -0,0 +1,60 @@ +--- +description: "Records a persistence type transition and its compatibility acknowledgement." +kind: persistence-change +--- + +# 2026-10-25-skill-catalog-incomplete + +English | [中文](2026-10-25-skill-catalog-incomplete.zh.md) + +## Summary + +Adds optional incomplete: true metadata to skill-catalog message sources when discovery returns only the currently readable skills. + +## Table of Contents + +- [Declaration](#declaration) +- [Compatibility](#compatibility) +- [Verification](#verification) +- [Dev Note](#dev-note) + + +## Declaration + +```yaml persistence-change +schemaVersion: 1 +id: 2026-10-25-skill-catalog-incomplete +baseline: false +changes: + - root: "event:agent/inbox/spliced" + previous: "2026-10-22-action-card-status" + after: "9e8043098fb89db6d7c92a92c70146c5c8d24fa88f733c687fa29e5e7a58ab30" + decision: same-version + - root: "event:developer/message" + previous: "2026-10-22-action-card-status" + after: "95acdbd066cf445d37092e5fdfe2e8717ef6ca1aed50f70e2e6037a6989a1f2f" + decision: same-version + - root: "event:session/title-llm-request" + previous: "2026-10-22-action-card-status" + after: "eaa9125aec0fb28478096c46e73e21bf512ab0d84d826bfb41e7308707734cb5" + decision: same-version + - root: "event:user/message" + previous: "2026-10-22-action-card-status" + after: "39adb7fce8475af6402acd925ea79697b3341c22422ac32833d71217d84e987f" + decision: same-version +``` + + +## Compatibility + +Existing catalogs omit the flag and remain complete. New readers compare both entries and completeness. Older readers accept the unchanged source discriminator and entry fields, preserve the already-rendered discovery warning in message content, and ignore the optional flag. No event discriminator, required field, or Session format version changes. + + +## Verification + +Focused skill-filesystem and tool-skill tests: 71 passed with 100% coverage for both changed source files. Keyless headless skill-root-isolation and skill-load snapshots: 2 passed; the isolation fixture logs the partial catalog and loads a readable skill despite a failing root. + + +## Dev Note + +None. diff --git a/docs/persistence-changes/2026-10-25-skill-catalog-incomplete.schema.json b/docs/persistence-changes/2026-10-25-skill-catalog-incomplete.schema.json new file mode 100644 index 0000000000..3ae2f36178 --- /dev/null +++ b/docs/persistence-changes/2026-10-25-skill-catalog-incomplete.schema.json @@ -0,0 +1,249 @@ +{ + "formatVersion": 2, + "roots": [ + {"key":"event:agent/inbox/spliced","kind":"event","event":"agent/inbox/spliced","surface":false,"digest":"9e8043098fb89db6d7c92a92c70146c5c8d24fa88f733c687fa29e5e7a58ab30"}, + {"key":"event:developer/message","kind":"event","event":"developer/message","surface":true,"digest":"95acdbd066cf445d37092e5fdfe2e8717ef6ca1aed50f70e2e6037a6989a1f2f"}, + {"key":"event:session/title-llm-request","kind":"event","event":"session/title-llm-request","surface":false,"digest":"eaa9125aec0fb28478096c46e73e21bf512ab0d84d826bfb41e7308707734cb5"}, + {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"39adb7fce8475af6402acd925ea79697b3341c22422ac32833d71217d84e987f"} + ], + "types": [], + "nodes": { + "0203243b72fc867a": {"kind":"object","properties":[{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "022623b9ef98ec47": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "02b2c23f2d94b028": {"kind":"object","properties":[{"name":"kind","type":"c5687b1313206a6f","optional":false}],"indices":[]}, + "05205074b24d8340": {"kind":"literal","value":"action-cards"}, + "0657d3ca5ac4e7bf": {"kind":"primitive","type":"number"}, + "07e1a58c58b593f5": {"kind":"object","properties":[{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "09655b34d7f3cf1e": {"kind":"literal","value":"system-prompt"}, + "09f3f8dc417f2782": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"8af841fc9b265ade","optional":false},{"name":"source","type":"65a8400e451e667e","optional":false}],"indices":[]}, + "0ed8d1108fe7a5e1": {"kind":"object","properties":[{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "0eeb17e1df89b1eb": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "0f46153645c29784": {"kind":"object","properties":[{"name":"height","type":"0657d3ca5ac4e7bf","optional":false},{"name":"width","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "0fe52387f6505270": {"kind":"literal","value":"plan-mode"}, + "11638dc58a31496f": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "12d5808fac1996b9": {"kind":"object","properties":[{"name":"attachment","type":"b0b0eb1b16490f6b","optional":false},{"name":"offloaded","type":"dacf3d5f3e4ff619","optional":true},{"name":"type","type":"fb8b6a2e53cb9cf4","optional":false}],"indices":[]}, + "12f9a5a7506bca46": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"cebb7e9f3f663e66","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "1379f0b72275994d": {"kind":"literal","value":"developer/message"}, + "16d0507cb94b4cfc": {"kind":"literal","value":"relay"}, + "1922cd79a70806c1": {"kind":"literal","value":"skill-invocation"}, + "1938c8c20f1cba7c": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "1e709346005826eb": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "1f0133217eeeffd8": {"kind":"literal","value":"tool-call"}, + "1f1385dbc3e875c0": {"kind":"literal","value":"repeat-tool-reminder"}, + "1fdad624334d3548": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "2152caf1a71e588e": {"kind":"object","properties":[{"name":"kind","type":"2e4debca12f2c449","optional":false},{"name":"messageId","type":"4cd48f3e5108bd6e","optional":false},{"name":"senderId","type":"4cd48f3e5108bd6e","optional":false},{"name":"senderName","type":"4cd48f3e5108bd6e","optional":false},{"name":"teamId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "2235d957bf4b7c6c": {"kind":"object","properties":[{"name":"kind","type":"7b1ce60193fa8b69","optional":false}],"indices":[]}, + "224aa11d4d5f88c4": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "23af3759678a30de": {"kind":"literal","value":"dsh-session-title-llm"}, + "24b10f7cdae64928": {"kind":"literal","value":"runtime-context"}, + "24ce31aa528272e5": {"kind":"object","properties":[{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "260523b412c19ad8": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "2765e9119edf5816": {"kind":"literal","value":"model"}, + "277b61f9c6f81704": {"kind":"literal","value":"file"}, + "28936c614bd4e7e2": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "290f32bfd81ff85a": {"kind":"object","properties":[{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "297fbd8067d7815a": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "2aad1179f9576314": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "2ab12a0e345658f9": {"kind":"array","element":"83da72c6857601c7"}, + "2e4debca12f2c449": {"kind":"literal","value":"team-message"}, + "2f1e6a7ebace43d7": {"kind":"union","types":["3f74ba74acd10644","58f94390b982f8a5","de30b1fa12c75f81","ebb768d85ec87fb6"]}, + "2f3f201c8846e19c": {"kind":"literal","value":"tool-goal"}, + "312aee2f0c42aabb": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "31907de956375182": {"kind":"object","properties":[{"name":"compactionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"6b23ed9ce1b397e6","optional":false},{"name":"sourceCommandId","type":"4cd48f3e5108bd6e","optional":true}],"indices":[]}, + "3247e566f4340029": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "335e242de1fcc17b": {"kind":"union","types":["bcf0caf62d964b2f","e438a9d4fb883b3e"]}, + "383cf73ae4748e5b": {"kind":"literal","value":"recall"}, + "39adb7fce8475af6": {"kind":"object","properties":[{"name":"data","type":"8bca2b4f53ec7745","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"de25352d2dc41963","optional":false}],"indices":[]}, + "3b04790e08b35241": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "3b4f2c9ef2c1217e": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "3bd652ebfa8726b3": {"kind":"union","types":["0657d3ca5ac4e7bf","938f7c7357bc403e"]}, + "3bdb8dc6989655b0": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "3c2535ca0a2062f1": {"kind":"literal","value":"reasoning"}, + "3e2ece4967cfebe9": {"kind":"literal","value":"next-step"}, + "3f74ba74acd10644": {"kind":"literal","value":"image/jpeg"}, + "408927267422a7b2": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "43e311235aa537df": {"kind":"object","properties":[{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"83d6916021eede8f","optional":false}],"indices":[]}, + "45f005e6bbb76452": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "4991dfc415c9efeb": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "49dab019d00e8c26": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "4a9bef9f27a94252": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"82470020b5bfcb1a","optional":false},{"name":"senderSessionId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "4b259f7f8f0a44ad": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"isError","type":"aa93010d0e521ad7","optional":true},{"name":"role","type":"a13d8f379222ece8","optional":false},{"name":"source","type":"d9c462b9f62fdd3e","optional":false},{"name":"toolCallId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "4cd48f3e5108bd6e": {"kind":"primitive","type":"string"}, + "4e44c9118152f682": {"kind":"literal","value":"text"}, + "4e88776858652856": {"kind":"object","properties":[{"name":"text","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"4e44c9118152f682","optional":false}],"indices":[]}, + "4e97c3d85c0fc817": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"bf16d2e98a7f1389","optional":false},{"name":"senderSessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "4edec1b770e8ec4c": {"kind":"literal","value":"ptc-mode"}, + "4f9125fa028a5628": {"kind":"union","types":["09f3f8dc417f2782","4b259f7f8f0a44ad","8bca2b4f53ec7745","cebb7e9f3f663e66","fa87537f4a9c1e25"]}, + "4f91f187baeabef5": {"kind":"object","properties":[{"name":"capturedFormatVersion","type":"0657d3ca5ac4e7bf","optional":true},{"name":"capturedThroughSeq","type":"3bd652ebfa8726b3","optional":false},{"name":"compacted","type":"aa93010d0e521ad7","optional":false},{"name":"inputIndex","type":"0657d3ca5ac4e7bf","optional":false},{"name":"label","type":"4cd48f3e5108bd6e","optional":false},{"name":"omittedBytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"omittedMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"originalMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"retainedMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"truncated","type":"aa93010d0e521ad7","optional":false}],"indices":[]}, + "52c6113cb0e53f34": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "53cf1704ae0709c7": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "5654685d7557ec74": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "58015da1c1950a66": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "587bb11da730e06a": {"kind":"literal","value":"session/title-llm-request"}, + "589d0d91239681f8": {"kind":"literal","value":"developer"}, + "58f94390b982f8a5": {"kind":"literal","value":"image/png"}, + "5bb69b88517f6214": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "5bc66269cfaf614c": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "5cdbf342b7748d15": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "5d03ba38734809bc": {"kind":"array","element":"0657d3ca5ac4e7bf"}, + "5d7a64ed6aac5551": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "6085488d223aeffd": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "6292bcbedaa97fea": {"kind":"object","properties":[{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "62ecb62dc0fe1b5e": {"kind":"literal","value":"next-turn"}, + "65a8400e451e667e": {"kind":"object","properties":[{"name":"kind","type":"09655b34d7f3cf1e","optional":false}],"indices":[]}, + "65d583e66518c523": {"kind":"object","properties":[{"name":"entries","type":"aba175fb20ffc711","optional":false},{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"incomplete","type":"dacf3d5f3e4ff619","optional":true},{"name":"kind","type":"6ebcc2dbec9f2dab","optional":false},{"name":"update","type":"dacf3d5f3e4ff619","optional":true}],"indices":[]}, + "672c4aa2a9b736e3": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"1922cd79a70806c1","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "68f44f59e91c4139": {"kind":"literal","value":"user"}, + "6b23ed9ce1b397e6": {"kind":"literal","value":"compact-checkpoint"}, + "6ccb6bc423fb3952": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "6dacb1584f2bfbe2": {"kind":"object","properties":[{"name":"clientTimeZone","type":"4cd48f3e5108bd6e","optional":true},{"name":"kind","type":"68f44f59e91c4139","optional":false},{"name":"principal","type":"deebfc7c62177ea8","optional":true},{"name":"rpcId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "6ea608bdc8a7a63d": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "6ebcc2dbec9f2dab": {"kind":"literal","value":"skill-catalog"}, + "6f22a9d02b9a1f11": {"kind":"object","properties":[{"name":"baseline","type":"dacf3d5f3e4ff619","optional":true},{"name":"baselineIdentity","type":"4cd48f3e5108bd6e","optional":true},{"name":"changes","type":"2ab12a0e345658f9","optional":false},{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"fbd2c74b346a1595","optional":false}],"indices":[]}, + "6f44f32be9bcd9a8": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "6f9e00383836275e": {"kind":"literal","value":"snapshot"}, + "719c51f67074f970": {"kind":"object","properties":[{"name":"kind","type":"2765e9119edf5816","optional":false},{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"replayState","type":"bbc5696e3f13c758","optional":true}],"indices":[]}, + "7382c4fc95fe8c5d": {"kind":"literal","value":"remove"}, + "7554565be416b034": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "756b5e23a5cb2c7f": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "78a9be340090b735": {"kind":"literal","value":"tmux-context"}, + "7b1ce60193fa8b69": {"kind":"literal","value":"working-directory"}, + "7df62978a2b7de85": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "7eaef7a763ba5b94": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "7f13860ee89a2d35": {"kind":"literal","value":"session-reference"}, + "7f959241c24128b4": {"kind":"object","properties":[{"name":"goalId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"b815d7b91cdd9fc6","optional":false},{"name":"revision","type":"0657d3ca5ac4e7bf","optional":false},{"name":"round","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "8064c03c87c357fd": {"kind":"union","types":["12d5808fac1996b9","43e311235aa537df","4e88776858652856","814d9434e1ddf907","8e611bf46821e500","c1f0f17b6493b85d","f2da0f27c1e6add5"]}, + "80677c8c8b804189": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "8067b0d232c350f1": {"kind":"literal","value":"time-context"}, + "814d9434e1ddf907": {"kind":"object","properties":[{"name":"text","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"3c2535ca0a2062f1","optional":false}],"indices":[]}, + "82470020b5bfcb1a": {"kind":"literal","value":"agent-message"}, + "825ca23416b1ea9d": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "829a2fb3be6efd4b": {"kind":"literal","value":"agent/inbox/spliced"}, + "83079c8a3f733ac3": {"kind":"object","properties":[{"name":"description","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "8338ee303e2bd448": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "83d6916021eede8f": {"kind":"literal","value":"tool-removal"}, + "83da72c6857601c7": {"kind":"object","properties":[{"name":"action","type":"904bf499d98be4a3","optional":false},{"name":"digest","type":"4cd48f3e5108bd6e","optional":true},{"name":"path","type":"4cd48f3e5108bd6e","optional":false},{"name":"scope","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "854db3efdfb0cd39": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "85d6d96ff8842974": {"kind":"literal","value":"answered"}, + "85f9b505b7bdff1f": {"kind":"literal","value":"tool-addition"}, + "85fe96bf15d5c755": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "8620189c8e335827": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "86e1e384495ee09a": {"kind":"object","properties":[{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"text","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "87b1a33564b9a4d6": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "88841202942c7683": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "8a046b52331959aa": {"kind":"object","properties":[{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "8af841fc9b265ade": {"kind":"literal","value":"system"}, + "8bca2b4f53ec7745": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"b112459dcb068609","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.user-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, + "8c1c4f72755a78ea": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "8c627d7a45fa406c": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "8e611bf46821e500": {"kind":"object","properties":[{"name":"tool","type":"fcf427290c6213c2","optional":true},{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"85f9b505b7bdff1f","optional":false}],"indices":[]}, + "8f324cea3916c051": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "8fcb0b44a575e998": {"kind":"object","properties":[{"name":"kind","type":"a720757f704a2512","optional":false}],"indices":[]}, + "904bf499d98be4a3": {"kind":"union","types":["7382c4fc95fe8c5d","b765ee31033cea46","f6cb462f808309e3"]}, + "938f7c7357bc403e": {"kind":"primitive","type":"null"}, + "95a3ffccbf3c8afc": {"kind":"literal","value":"owner"}, + "95acdbd066cf445d": {"kind":"object","properties":[{"name":"data","type":"12f9a5a7506bca46","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1379f0b72275994d","optional":false}],"indices":[]}, + "95c0e88fcf0bafb2": {"kind":"literal","value":"assistant"}, + "9645cf93769a6dfb": {"kind":"literal","value":"user-question-reply"}, + "96bfb916a727cd44": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "96f4a9c81fc0f940": {"kind":"union","types":["3e2ece4967cfebe9","62ecb62dc0fe1b5e"]}, + "9808c3d0f0a1be8f": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"d2b617d9dfcc4e0a","optional":false},{"name":"reasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"route","type":"07e1a58c58b593f5","optional":false},{"name":"system","type":"4cd48f3e5108bd6e","optional":false},{"name":"titleProvider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "99135d8a39379779": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "99e7e7d7fed55ae6": {"kind":"literal","value":"tool-jobs"}, + "99f0e98184709ad1": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "9ac52f0f84fec2eb": {"kind":"literal","value":"model-selection"}, + "9e8043098fb89db6": {"kind":"object","properties":[{"name":"data","type":"c433ef580a5b229b","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"829a2fb3be6efd4b","optional":false}],"indices":[]}, + "9edc162949abf93b": {"kind":"object","properties":[{"name":"deliveryId","type":"4cd48f3e5108bd6e","optional":false},{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"db6c5246911d47a7","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"ruleId","type":"4cd48f3e5108bd6e","optional":false},{"name":"source","type":"4cd48f3e5108bd6e","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "9f65c43e340bba31": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "a13d8f379222ece8": {"kind":"literal","value":"tool"}, + "a15a19ef63cf5d1b": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "a16e567c8cd2c55c": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "a2066bd52f61218b": {"kind":"object","properties":[{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "a3c6f1ea38e9a61d": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "a720757f704a2512": {"kind":"literal","value":"tool-registry"}, + "a9059a81430b3207": {"kind":"literal","value":"hooks-claude-code"}, + "aa2bf9e82b9fdeb9": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "aa93010d0e521ad7": {"kind":"primitive","type":"boolean"}, + "aada2771a250136c": {"kind":"array","element":"8bca2b4f53ec7745"}, + "aae343bc3d663c83": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "aba175fb20ffc711": {"kind":"array","element":"83079c8a3f733ac3"}, + "ada310bf0bdb8fed": {"kind":"object","properties":[{"name":"kind","type":"68f44f59e91c4139","optional":false}],"indices":[]}, + "ade057f4fdc387ae": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "aec150797b655c5f": {"kind":"literal","value":"catalog"}, + "b062078e899958f9": {"kind":"object","properties":[{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "b0b0eb1b16490f6b": {"kind":"object","properties":[{"name":"attachmentId","type":"4cd48f3e5108bd6e","optional":false},{"name":"bytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"height","type":"0657d3ca5ac4e7bf","optional":false},{"name":"mediaType","type":"2f1e6a7ebace43d7","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":true},{"name":"originalDimensions","type":"0f46153645c29784","optional":true},{"name":"width","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "b112459dcb068609": {"kind":"union","types":["0203243b72fc867a","022623b9ef98ec47","02b2c23f2d94b028","0ed8d1108fe7a5e1","0eeb17e1df89b1eb","11638dc58a31496f","1938c8c20f1cba7c","1e709346005826eb","1fdad624334d3548","2152caf1a71e588e","2235d957bf4b7c6c","224aa11d4d5f88c4","24ce31aa528272e5","260523b412c19ad8","28936c614bd4e7e2","290f32bfd81ff85a","297fbd8067d7815a","2aad1179f9576314","312aee2f0c42aabb","31907de956375182","3247e566f4340029","3b04790e08b35241","3b4f2c9ef2c1217e","3bdb8dc6989655b0","408927267422a7b2","45f005e6bbb76452","4991dfc415c9efeb","49dab019d00e8c26","4a9bef9f27a94252","4e97c3d85c0fc817","52c6113cb0e53f34","53cf1704ae0709c7","5654685d7557ec74","58015da1c1950a66","5bb69b88517f6214","5bc66269cfaf614c","5cdbf342b7748d15","5d7a64ed6aac5551","6085488d223aeffd","6292bcbedaa97fea","65a8400e451e667e","65d583e66518c523","672c4aa2a9b736e3","6ccb6bc423fb3952","6dacb1584f2bfbe2","6ea608bdc8a7a63d","6f22a9d02b9a1f11","6f44f32be9bcd9a8","719c51f67074f970","7554565be416b034","756b5e23a5cb2c7f","7df62978a2b7de85","7eaef7a763ba5b94","7f959241c24128b4","80677c8c8b804189","825ca23416b1ea9d","8338ee303e2bd448","854db3efdfb0cd39","85fe96bf15d5c755","8620189c8e335827","87b1a33564b9a4d6","88841202942c7683","8a046b52331959aa","8c1c4f72755a78ea","8c627d7a45fa406c","8f324cea3916c051","8fcb0b44a575e998","96bfb916a727cd44","99135d8a39379779","99f0e98184709ad1","9edc162949abf93b","9f65c43e340bba31","a15a19ef63cf5d1b","a16e567c8cd2c55c","a2066bd52f61218b","a3c6f1ea38e9a61d","aa2bf9e82b9fdeb9","aae343bc3d663c83","ada310bf0bdb8fed","ade057f4fdc387ae","b062078e899958f9","b2a5c8c008a31e3d","b3681c026a0b98e9","b4ec0af39fd52ed9","b613f83572fe2fbf","b6f94c17dd9bbd7c","b70f3e81fe11b7a5","b79641a9d25e7566","ba2a1a8f194b1bb2","ba4c40b4381e0dcd","baccc97ec34be6c4","c5228b7a55498d84","c55827fba7018198","cb1c8959e1726f82","cda2345a9be9d139","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd00cdccd0ba487b","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","dde0cdf9d426768b","deaae5cd30987d4f","e7f4cbb3a57f4cbd","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, + "b2a5c8c008a31e3d": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "b3681c026a0b98e9": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "b4ec0af39fd52ed9": {"kind":"object","properties":[{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "b52f215a6cd69105": {"kind":"array","element":"8064c03c87c357fd"}, + "b613f83572fe2fbf": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "b6f94c17dd9bbd7c": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "b70f3e81fe11b7a5": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "b765ee31033cea46": {"kind":"literal","value":"set"}, + "b79641a9d25e7566": {"kind":"object","properties":[{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "b815d7b91cdd9fc6": {"kind":"literal","value":"goal"}, + "ba2a1a8f194b1bb2": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "ba4c40b4381e0dcd": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "baccc97ec34be6c4": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "bb94f3217aa56c88": {"kind":"literal","value":"hooks-codex"}, + "bbc5696e3f13c758": {"kind":"opaque","reason":"unknown"}, + "bcf0caf62d964b2f": {"kind":"object","properties":[{"name":"endSeq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"op","type":"f6cb462f808309e3","optional":false},{"name":"startSeq","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "bf16d2e98a7f1389": {"kind":"literal","value":"subagent-settled"}, + "c1f0f17b6493b85d": {"kind":"object","properties":[{"name":"arguments","type":"4cd48f3e5108bd6e","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"1f0133217eeeffd8","optional":false}],"indices":[]}, + "c433ef580a5b229b": {"kind":"object","properties":[{"name":"inserted","type":"aada2771a250136c","optional":false},{"name":"outcome","type":"d4e4d575abeb4b72","optional":true},{"name":"removedCount","type":"0657d3ca5ac4e7bf","optional":true},{"name":"start","type":"0657d3ca5ac4e7bf","optional":false},{"name":"target","type":"96f4a9c81fc0f940","optional":false}],"indices":[]}, + "c5228b7a55498d84": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "c55827fba7018198": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"9645cf93769a6dfb","optional":false},{"name":"outcome","type":"85d6d96ff8842974","optional":false}],"indices":[]}, + "c5687b1313206a6f": {"kind":"literal","value":"cordis-host-runner"}, + "c748fb42c80a1200": {"kind":"array","element":"86e1e384495ee09a"}, + "cb1c8959e1726f82": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "cda2345a9be9d139": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "cebb7e9f3f663e66": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"b112459dcb068609","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.developer-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, + "d2b617d9dfcc4e0a": {"kind":"array","element":"4f9125fa028a5628"}, + "d4e4d575abeb4b72": {"kind":"literal","value":"canceled"}, + "d85590a5675c6e2f": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "d9c462b9f62fdd3e": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"a13d8f379222ece8","optional":false}],"indices":[]}, + "d9edf1862e4471d6": {"kind":"literal","value":"schedule"}, + "dacf3d5f3e4ff619": {"kind":"literal","value":true}, + "db06ef35b27a3842": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "db6c5246911d47a7": {"kind":"literal","value":"webhook"}, + "dba54c09c6e7aafc": {"kind":"object","properties":[{"name":"kind","type":"4edec1b770e8ec4c","optional":false}],"indices":[]}, + "dd00cdccd0ba487b": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "dd5ee8762bd8a14b": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "dd6cc2bb2a8f2824": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "dde0cdf9d426768b": {"kind":"object","properties":[{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "de25352d2dc41963": {"kind":"literal","value":"user/message"}, + "de30b1fa12c75f81": {"kind":"literal","value":"image/gif"}, + "deaae5cd30987d4f": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "deebfc7c62177ea8": {"kind":"object","properties":[{"name":"kind","type":"95a3ffccbf3c8afc","optional":false}],"indices":[]}, + "df843efd87c78cf8": {"kind":"array","element":"4f91f187baeabef5"}, + "e438a9d4fb883b3e": {"kind":"literal","value":"append"}, + "e7f4cbb3a57f4cbd": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "e8de0f457fed5b9f": {"kind":"literal","value":"notice"}, + "eaa9125aec0fb284": {"kind":"object","properties":[{"name":"data","type":"9808c3d0f0a1be8f","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"587bb11da730e06a","optional":false}],"indices":[]}, + "ebb768d85ec87fb6": {"kind":"literal","value":"image/webp"}, + "edbbfff1128099fd": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "ee577a0cc18664c9": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "f19bee84bf3d2090": {"kind":"object","properties":[{"name":"attachmentId","type":"4cd48f3e5108bd6e","optional":false},{"name":"bytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "f230c0b583e23b25": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "f29d63336e8266d8": {"kind":"object","properties":[{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "f2da0f27c1e6add5": {"kind":"object","properties":[{"name":"attachment","type":"f19bee84bf3d2090","optional":false},{"name":"type","type":"277b61f9c6f81704","optional":false}],"indices":[]}, + "f4a66f654996c093": {"kind":"object","properties":[{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "f56c5b59ca016131": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"7f13860ee89a2d35","optional":false},{"name":"references","type":"df843efd87c78cf8","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, + "f6329fb30c7ea801": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "f6605d6c57933aea": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "f68c335306535a00": {"kind":"literal","value":"user-approval"}, + "f6afe41e3926f422": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "f6cb462f808309e3": {"kind":"literal","value":"replace"}, + "f7283223aacdc39b": {"kind":"object","properties":[{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "f88f1b7b6bb733f6": {"kind":"literal","value":1}, + "f97f47b0eb87905e": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "fa87537f4a9c1e25": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"95c0e88fcf0bafb2","optional":false},{"name":"source","type":"719c51f67074f970","optional":false}],"indices":[]}, + "fb8b6a2e53cb9cf4": {"kind":"literal","value":"image"}, + "fbd2c74b346a1595": {"kind":"literal","value":"agent-instructions"}, + "fcf427290c6213c2": {"kind":"primitive","type":"never"}, + "fcf81d3c58c13593": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "fe1a7acdeed4d0f5": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "fee1caf8ab6a65c1": {"kind":"literal","value":"instructions"} + } +} diff --git a/docs/persistence-changes/2026-10-25-skill-catalog-incomplete.zh.md b/docs/persistence-changes/2026-10-25-skill-catalog-incomplete.zh.md new file mode 100644 index 0000000000..f87865566f --- /dev/null +++ b/docs/persistence-changes/2026-10-25-skill-catalog-incomplete.zh.md @@ -0,0 +1,60 @@ +--- +description: "记录持久化类型更改及其兼容性确认。" +kind: persistence-change +--- + +# 2026-10-25-skill-catalog-incomplete + +[English](2026-10-25-skill-catalog-incomplete.md) | 中文 + +## 概述 + +当技能发现仅返回当前可读技能时,为 skill-catalog 消息来源添加可选的 incomplete: true 元数据。 + +## 目录 + +- [声明](#declaration) +- [兼容性](#compatibility) +- [验证](#verification) +- [开发备注](#dev-note) + + +## 声明 + +```yaml persistence-change +schemaVersion: 1 +id: 2026-10-25-skill-catalog-incomplete +baseline: false +changes: + - root: "event:agent/inbox/spliced" + previous: "2026-10-22-action-card-status" + after: "9e8043098fb89db6d7c92a92c70146c5c8d24fa88f733c687fa29e5e7a58ab30" + decision: same-version + - root: "event:developer/message" + previous: "2026-10-22-action-card-status" + after: "95acdbd066cf445d37092e5fdfe2e8717ef6ca1aed50f70e2e6037a6989a1f2f" + decision: same-version + - root: "event:session/title-llm-request" + previous: "2026-10-22-action-card-status" + after: "eaa9125aec0fb28478096c46e73e21bf512ab0d84d826bfb41e7308707734cb5" + decision: same-version + - root: "event:user/message" + previous: "2026-10-22-action-card-status" + after: "39adb7fce8475af6402acd925ea79697b3341c22422ac32833d71217d84e987f" + decision: same-version +``` + + +## 兼容性 + +已有目录不含此标记,仍按完整目录读取。新读取方同时比较条目与完整性。旧读取方接受未变的来源判别值与条目字段,保留消息正文中已渲染的发现警告,并忽略可选标记。不改变事件判别值、必填字段或 Session 格式版本。 + + +## 验证 + +skill-filesystem 与 tool-skill 定向测试共 71 项通过,两个修改源文件覆盖率均为 100%。无密钥 headless skill-root-isolation 与 skill-load 快照共 2 项通过;隔离夹具记录部分目录,并在一个根失败时成功加载可读技能。 + + +## 开发备注 + +无。 diff --git a/docs/persistence-changes/historical-formats/README.i18n.yaml b/docs/persistence-changes/historical-formats/README.i18n.yaml index 5339de2d2b..40d842e063 100644 --- a/docs/persistence-changes/historical-formats/README.i18n.yaml +++ b/docs/persistence-changes/historical-formats/README.i18n.yaml @@ -15,8 +15,8 @@ en: 14c57f30e676f6e3 zh: b1a0ccf26fab3727 /session-persistence-formats/format-references: - en: 17ef09dfc5a89073 - zh: 59b8d60acb66c2dc + en: e3511a4ac3bc4457 + zh: 828f3c39f80d5370 /session-persistence-formats/scope-and-evidence: en: b220062139ddac1e zh: 7c4c0efe05dafa9c diff --git a/docs/persistence-changes/historical-formats/README.md b/docs/persistence-changes/historical-formats/README.md index 174c007423..74c575b300 100644 --- a/docs/persistence-changes/historical-formats/README.md +++ b/docs/persistence-changes/historical-formats/README.md @@ -32,7 +32,7 @@ The index is generated from validated snapshots and the current writer constant. | 1 | PR #3349 | [V1](v1.md) | [JSON](v1.schema.json) | 54 / 415 | | 2 | `dsh-v0.1.3-alpha.2` | [V2](v2.md) | [JSON](v2.schema.json) | 56 / 435 | | 3 | PR #4320 | [V3](v3.md) | [JSON](v3.schema.json) | 60 / 467 | -| 4 | Current checkout | [Current catalog](../../persistence-catalog.md) | [JSON](../../persistence-schema.json) | 65 / 614 | +| 4 | Current checkout | [Current catalog](../../persistence-catalog.md) | [JSON](../../persistence-schema.json) | 65 / 622 | diff --git a/docs/persistence-changes/historical-formats/README.zh.md b/docs/persistence-changes/historical-formats/README.zh.md index 055e07f954..12eb600771 100644 --- a/docs/persistence-changes/historical-formats/README.zh.md +++ b/docs/persistence-changes/historical-formats/README.zh.md @@ -32,7 +32,7 @@ description: "查找从 V0 到工作区写入器版本的每个 Session 格式 | 1 | PR #3349 | [V1](v1.zh.md) | [JSON](v1.schema.json) | 54 / 415 | | 2 | `dsh-v0.1.3-alpha.2` | [V2](v2.zh.md) | [JSON](v2.schema.json) | 56 / 435 | | 3 | PR #4320 | [V3](v3.zh.md) | [JSON](v3.schema.json) | 60 / 467 | -| 4 | 当前工作树 | [当前目录](../../persistence-catalog.zh.md) | [JSON](../../persistence-schema.json) | 65 / 614 | +| 4 | 当前工作树 | [当前目录](../../persistence-catalog.zh.md) | [JSON](../../persistence-schema.json) | 65 / 622 | diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index c668fb96cf..c6c15a7c90 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -5,7 +5,7 @@ {"key":"JsonlHeaderLine","kind":"header","digest":"18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f"}, {"key":"SessionEventEnvelope","kind":"envelope","digest":"5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc"}, {"key":"event:agent-preset/selected","kind":"event","event":"agent-preset/selected","surface":false,"digest":"a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b"}, - {"key":"event:agent/inbox/spliced","kind":"event","event":"agent/inbox/spliced","surface":false,"digest":"0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034"}, + {"key":"event:agent/inbox/spliced","kind":"event","event":"agent/inbox/spliced","surface":false,"digest":"9e8043098fb89db6d7c92a92c70146c5c8d24fa88f733c687fa29e5e7a58ab30"}, {"key":"event:approval/asked","kind":"event","event":"approval/asked","surface":false,"digest":"3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1"}, {"key":"event:approval/decided","kind":"event","event":"approval/decided","surface":false,"digest":"bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3"}, {"key":"event:approval/policy","kind":"event","event":"approval/policy","surface":false,"digest":"26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78"}, @@ -18,7 +18,7 @@ {"key":"event:compaction/start","kind":"event","event":"compaction/start","surface":false,"digest":"db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965"}, {"key":"event:compaction/summary","kind":"event","event":"compaction/summary","surface":false,"digest":"e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602"}, {"key":"event:deliverables/presented","kind":"event","event":"deliverables/presented","surface":false,"digest":"13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176"}, - {"key":"event:developer/message","kind":"event","event":"developer/message","surface":true,"digest":"97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c"}, + {"key":"event:developer/message","kind":"event","event":"developer/message","surface":true,"digest":"95acdbd066cf445d37092e5fdfe2e8717ef6ca1aed50f70e2e6037a6989a1f2f"}, {"key":"event:feedback/message-delete","kind":"event","event":"feedback/message-delete","surface":false,"digest":"3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796"}, {"key":"event:feedback/message-put","kind":"event","event":"feedback/message-put","surface":false,"digest":"b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf"}, {"key":"event:feedback/record","kind":"event","event":"feedback/record","surface":false,"digest":"b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8"}, @@ -40,7 +40,7 @@ {"key":"event:session-log-deepseek/delivery-accepted","kind":"event","event":"session-log-deepseek/delivery-accepted","surface":false,"digest":"d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9"}, {"key":"event:session/end-seed","kind":"event","event":"session/end-seed","surface":false,"digest":"5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e"}, {"key":"event:session/title","kind":"event","event":"session/title","surface":false,"digest":"1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5"}, - {"key":"event:session/title-llm-request","kind":"event","event":"session/title-llm-request","surface":false,"digest":"79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056"}, + {"key":"event:session/title-llm-request","kind":"event","event":"session/title-llm-request","surface":false,"digest":"eaa9125aec0fb28478096c46e73e21bf512ab0d84d826bfb41e7308707734cb5"}, {"key":"event:step/end","kind":"event","event":"step/end","surface":false,"digest":"e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05"}, {"key":"event:step/start","kind":"event","event":"step/start","surface":false,"digest":"4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986"}, {"key":"event:subagent/catalog","kind":"event","event":"subagent/catalog","surface":false,"digest":"53750b9abf61efb7992b0aadc3e247ec927449c63266df28230fd1139f5590ac"}, @@ -62,29 +62,27 @@ {"key":"event:tool/result","kind":"event","event":"tool/result","surface":true,"digest":"7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397"}, {"key":"event:turn/end","kind":"event","event":"turn/end","surface":false,"digest":"0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce"}, {"key":"event:turn/start","kind":"event","event":"turn/start","surface":false,"digest":"aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8"}, - {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8"}, + {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"39adb7fce8475af6402acd925ea79697b3341c22422ac32833d71217d84e987f"}, {"key":"event:web/deepseek-search-llm-request","kind":"event","event":"web/deepseek-search-llm-request","surface":false,"digest":"0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52"}, {"key":"event:working-directory/change","kind":"event","event":"working-directory/change","surface":false,"digest":"124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3"}, {"key":"event:workspace/changes","kind":"event","event":"workspace/changes","surface":false,"digest":"e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72"} ], "types": [ - {"digest":"00c054d3018c198d92f459563331edd1385e58345c677bb499791df2da0ade9f","names":["packages/session/session-title-llm/src/index.ts#SessionTitleLlmRequestEventData"],"sources":["packages/session/session-title-llm/src/index.ts:37"]}, {"digest":"0116b1f89c05221d56b0ba35c83d302bf4857bc7277d247e9bbaf74b27d2c66e","names":[],"sources":[]}, {"digest":"0203243b72fc867afc81aff5f4cf2167e564ed342534eb612fc92f295cf07789","names":[],"sources":[]}, {"digest":"022623b9ef98ec47ec3c3bae0c51027c70d2601141c5e92e26a0d83d1b4cef06","names":[],"sources":[]}, - {"digest":"023a355b2be0d688fb6e4df8388dadb942761d46cfe96d0f499aae9631a159d4","names":[],"sources":["packages/core/session/src/types.ts:207"]}, + {"digest":"023a355b2be0d688fb6e4df8388dadb942761d46cfe96d0f499aae9631a159d4","names":[],"sources":["packages/core/session/src/types.ts:211"]}, {"digest":"02b2c23f2d94b028c9588a8faace3fce1217405db346da3389368b495457bf79","names":[],"sources":["packages/extensions/cordis-host-runner/src/index.ts:14"]}, {"digest":"0341d4c3dfcd53253cdc1e789d9130d3cd848b6f8b0706bf92f313a68b39ff23","names":[],"sources":[]}, - {"digest":"040cd65423bd64264d225504f1c572d239eeb1793d0c2856ad8e42bb6e1e148b","names":["packages/llm/llm/src/message.ts#Message"],"sources":["packages/llm/llm/src/message.ts:196"]}, + {"digest":"05205074b24d8340cfd7995f6cb64779c7f1241490954700115601e264178877","names":[],"sources":[]}, {"digest":"05a2796621b1ee6c03ef7abe560b25116bb4da4d592312117242a78415a32b04","names":[],"sources":[]}, - {"digest":"05d2ae1e0c7f8770f83f9a09047afb39a335d8ac986df3193659aa1e581472cf","names":["packages/interaction/user-approval/src/index.ts#ApprovalPolicy"],"sources":["packages/interaction/user-approval/src/index.ts:67"]}, + {"digest":"05d2ae1e0c7f8770f83f9a09047afb39a335d8ac986df3193659aa1e581472cf","names":["packages/interaction/user-approval/src/index.ts#ApprovalPolicy"],"sources":["packages/interaction/user-approval/src/index.ts:68"]}, {"digest":"0657d3ca5ac4e7bf79b00bcf860b1c7159d01a9da137497221ec2f1776e365f7","names":["packages/core/session/src/types.ts#SessionSeq"],"sources":["packages/core/session/src/types.ts:33"]}, - {"digest":"0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034","names":[],"sources":[]}, {"digest":"07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235","names":["packages/session/session-title/src/types.ts#SessionTitleModelIdentity","packages/subagent/tool-subagent/src/model-selection.ts#AllowedModelRoute"],"sources":["packages/session/session-title/src/types.ts:20","packages/subagent/tool-subagent/src/model-selection.ts:9"]}, {"digest":"07eccc9ea2f9b5439d76cc77d5e062936677d43f07a23da749819b0a22ee36b7","names":[],"sources":[]}, {"digest":"09655b34d7f3cf1e9005974de2357de2d4a60deea165d16dac1eadaa6ec539a8","names":[],"sources":[]}, {"digest":"09f3f8dc417f278257202714132f98ba7b52957d7b558c4a04456603890eb363","names":["packages/llm/llm/src/message.ts#SystemMessage"],"sources":["packages/llm/llm/src/message.ts:151"]}, - {"digest":"0a30c3be336cdd4f8f34e66543a3d46d611c43986edd9b3ce6cbb9b721d3b5d3","names":[],"sources":["packages/core/session/src/types.ts:205"]}, + {"digest":"0a30c3be336cdd4f8f34e66543a3d46d611c43986edd9b3ce6cbb9b721d3b5d3","names":[],"sources":["packages/core/session/src/types.ts:209"]}, {"digest":"0a8a062bc9c3c0d97fd97742262f2ea53dd32297f834e81114870d38ac3dc6da","names":[],"sources":[]}, {"digest":"0aa62ab51b36c0e64b134bd03ba8725d758744180a1a447da49beaad194f219f","names":[],"sources":[]}, {"digest":"0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555","names":["packages/llm/llm/src/types.ts#ReplayEnvelope"],"sources":["packages/llm/llm/src/types.ts:448"]}, @@ -101,17 +99,17 @@ {"digest":"0ed8d1108fe7a5e1c3078ef1faea12199a56b6b1216ccaceb0f6103b0c9a7691","names":[],"sources":[]}, {"digest":"0eeb17e1df89b1ebc2902116fe7145e0d321ef0db26e6bdebc802cb8513a01c1","names":[],"sources":[]}, {"digest":"0f46153645c297846a3fad3911636659ca4717a5e7d71c9f50bffacd312115ef","names":[],"sources":["packages/attachment/attachment/src/types.ts:28"]}, - {"digest":"0f6265188dae7ba6faa26830a180bb4deb0760561f97ee0c9d399ccf6c9cf1f7","names":["packages/llm/llm/src/message.ts#DeveloperMessage"],"sources":["packages/llm/llm/src/message.ts:157"]}, {"digest":"0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce","names":[],"sources":[]}, {"digest":"0fe52387f65052702ed9d7cd59db826468936595d1b3eec207e7a823adc719db","names":[],"sources":[]}, {"digest":"1033093edd0db80ff410e00830b523405e00bb0c7684948e531ff65095799625","names":[],"sources":[]}, {"digest":"10e386801903f9d424602c31d3ff837a94aef623c8b391376d8d9e253525fabe","names":[],"sources":[]}, {"digest":"11638dc58a31496fb6706ced3e23e3a2db1f3b2a8845968c810827a72b5fc811","names":[],"sources":[]}, {"digest":"119abe2b9c0b2f46ecb31d82b9acba4d4b30e049f655e2475e8b4ae12d5a9e25","names":[],"sources":["packages/experimental/hook-protocol/src/types.ts:19"]}, - {"digest":"11f70b595aa76897fc4e25a352bfa718c659f44b799e5aa14e84e5a38fe72912","names":[],"sources":["packages/interaction/user-approval/src/index.ts:40"]}, + {"digest":"11f70b595aa76897fc4e25a352bfa718c659f44b799e5aa14e84e5a38fe72912","names":[],"sources":["packages/interaction/user-approval/src/index.ts:41"]}, {"digest":"124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3","names":[],"sources":[]}, {"digest":"12a0cfa619ac4a5fc6c3e8e359c8dae15769edc61497a575935c78d5842f8e42","names":[],"sources":[]}, {"digest":"12d5808fac1996b9b3c2afa806e03022252ba2d7b88f835862ae1896591f60c7","names":["packages/llm/llm/src/types.ts#ImageBlock"],"sources":["packages/llm/llm/src/types.ts:79"]}, + {"digest":"12f9a5a7506bca46d6ef8e3c71826c4bf40e1389bfe0236cfffaea0c3fb367d2","names":[],"sources":["packages/core/session/src/types.ts:317"]}, {"digest":"1379f0b72275994d20f1ddca2d60a96ab16ec80397ca9f1af21bdc67ba5c269c","names":[],"sources":[]}, {"digest":"13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176","names":[],"sources":[]}, {"digest":"14230f9b8b5797bb7e8c621fa636531cfbde2ffba1ef5f1fd058216ff21952a0","names":[],"sources":[]}, @@ -123,7 +121,7 @@ {"digest":"15d5dfdd822aa35e115afd74a8982825a493880457774e6850bc1520b50875e4","names":[],"sources":[]}, {"digest":"16d0507cb94b4cfc84a87446b1ba7652d6ec1d65ee1684789e747e30d542800e","names":[],"sources":[]}, {"digest":"17aae616ef020b8b9f011ec398ec935450fb06d3e2a0722c456f63aeaf5ff728","names":[],"sources":[]}, - {"digest":"17d1afb770d9941936130996da00dc86782cfef731d8d6526162c301256a4ac3","names":[],"sources":["packages/core/session/src/types.ts:429"]}, + {"digest":"17d1afb770d9941936130996da00dc86782cfef731d8d6526162c301256a4ac3","names":[],"sources":["packages/core/session/src/types.ts:435"]}, {"digest":"18dc21f12bbac8ade8377e6fbb54179e20c3d955d73fba3244c57fb6bf001df0","names":["packages/schedule/schedule/src/types.ts#ScheduleDeleteChange"],"sources":["packages/schedule/schedule/src/types.ts:230"]}, {"digest":"18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f","names":["packages/session/session-persistence-jsonl/src/format.ts#HeaderLine"],"sources":["packages/session/session-persistence-jsonl/src/format.ts:83"]}, {"digest":"18fcdd273a2f2f9d813a3be5e71df5903a963a5c88e46b90b14de6e2db890da0","names":[],"sources":[]}, @@ -138,7 +136,7 @@ {"digest":"1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5","names":[],"sources":[]}, {"digest":"1c2686c0682e7bc51d61117b2652bd4a80707e331aa276d6ef915ae32534a330","names":[],"sources":[]}, {"digest":"1c5a58f4599bd4a9711712551ffe2442a5e5fcd0758bafe630cc4ead850bdaa7","names":[],"sources":[]}, - {"digest":"1ccb56061942f5ccb0d30c9e4f2883b9d115ff906560029de637b61d3cde896d","names":[],"sources":["packages/core/session/src/types.ts:343"]}, + {"digest":"1ccb56061942f5ccb0d30c9e4f2883b9d115ff906560029de637b61d3cde896d","names":[],"sources":["packages/core/session/src/types.ts:349"]}, {"digest":"1cde1bedde79c5e8a56aee9c05c8e0a579cf5bc611deb85b93fa331a16ca978f","names":["packages/compaction/compaction-image-offload/src/projection.ts#ImageOffloadTarget"],"sources":["packages/compaction/compaction-image-offload/src/projection.ts:9"]}, {"digest":"1d5f04a03ea75fc8eeece544129eba0f49f0c82046e9c404461920390135c7b2","names":[],"sources":[]}, {"digest":"1d76406cbb2ddadb0dbbb51e9d8bc6cf678fed455cf8eb512f36f7c86d37a62f","names":[],"sources":["packages/llm/llm/src/types.ts:157"]}, @@ -151,7 +149,7 @@ {"digest":"1ebc6f9ff3aa9e3a38f8695f49bacdab1f8b7a3832741853ca46f40af56ccd01","names":[],"sources":[]}, {"digest":"1f0133217eeeffd8d387baf1ec8ed9856e719bcd999dc08e48624cba96d75fd7","names":[],"sources":[]}, {"digest":"1f1385dbc3e875c021e387c7096d671d606f22daec51b25c80348735b6bbfa10","names":[],"sources":[]}, - {"digest":"1f8c126cfab3df812cd115cfc23e3256f0fa2383400f4ce91ecad313577e59b0","names":["packages/core/session/src/types.ts#TurnEndCancelCause"],"sources":["packages/core/session/src/types.ts:197"]}, + {"digest":"1f8c126cfab3df812cd115cfc23e3256f0fa2383400f4ce91ecad313577e59b0","names":["packages/core/session/src/types.ts#TurnEndCancelCause"],"sources":["packages/core/session/src/types.ts:201"]}, {"digest":"1fdad624334d354820dfb3a26e28d0bc9fc1b62a33f87bab63f715b3f4391bfd","names":[],"sources":[]}, {"digest":"20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5","names":[],"sources":["packages/plan/plan-mode/src/index.ts:53"]}, {"digest":"2142e391b9ccb60d487afcf373ce74db98d952f69e8289eddb352a7e16e996c5","names":[],"sources":[]}, @@ -178,11 +176,9 @@ {"digest":"2aad1179f957631477b582e57cd8f538cb82618fc3fb816bde1171154235b065","names":[],"sources":[]}, {"digest":"2ab12a0e345658f9342816d773fe610f049982bcad82631f43b9205abe43e5ee","names":[],"sources":[]}, {"digest":"2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095","names":[],"sources":["packages/llm/llm/src/types.ts:473"]}, - {"digest":"2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8","names":[],"sources":[]}, {"digest":"2aed07493b1c65b6d00de5586da1e743cf501684b9ad43a1765fb4007d4ea456","names":[],"sources":[]}, {"digest":"2c4c21f19f426a58f2dac914e34313aa43f8408972de857a486d1f086d5adb6c","names":[],"sources":[]}, {"digest":"2c64d4bc7264fd3f8bed47e96ab8a593bce05a1e4e1c436dcd244a3b7e0c2a9d","names":[],"sources":[]}, - {"digest":"2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711","names":["packages/llm/llm/src/message.ts#UserMessage"],"sources":["packages/llm/llm/src/message.ts:162"]}, {"digest":"2d11ca7b0d4493e244b74eba093227866b33249841e59a1e9bf56afed38604c3","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:71"]}, {"digest":"2da725e554cd89301d829ed9dc45a572c3cd1b93b5e91d0d71f007976d8a0863","names":[],"sources":[]}, {"digest":"2e3523541e942ef6cc9fbc5b91f242e0ca4c6ada479b79b96025b797f6e41f3f","names":["packages/schedule/schedule/src/types.ts#ScheduleChange"],"sources":["packages/schedule/schedule/src/types.ts:256"]}, @@ -194,10 +190,11 @@ {"digest":"30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f","names":["packages/session/session-title/src/types.ts#SessionTitleSource"],"sources":["packages/session/session-title/src/types.ts:28"]}, {"digest":"312aee2f0c42aabbae6cc60d92d596d8453c0aeb061c5868d1755a69ef49e69a","names":[],"sources":[]}, {"digest":"31907de9563751822af6d9be02bafaf26faa098bbd1cb412524134d577cc1648","names":["packages/compaction/compaction/src/checkpoint.ts#CompactionCheckpointSource"],"sources":["packages/compaction/compaction/src/checkpoint.ts:22"]}, + {"digest":"3247e566f4340029325b70e4366b56fa9719977f1e39033b769a2ec221ab22a9","names":[],"sources":[]}, {"digest":"326a9bfda27dda5882fb3cbe6e715df41dae2298fdae3d66437457268a665693","names":["packages/llm/llm/src/call-config.ts#LlmCallConfigAdapterDefaults"],"sources":["packages/llm/llm/src/call-config.ts:54"]}, {"digest":"3305a4bb6b6c29b482ba91d59c60b47e8f98282d3dacc8c29e4a4c2712209bdd","names":[],"sources":[]}, {"digest":"33341aac09312300de5a178e6cc6f6544a4876f7f710cfea55eda473c8d329ef","names":["packages/llm/llm/src/assistant-stream.ts#AssistantStreamRecord"],"sources":["packages/llm/llm/src/assistant-stream.ts:20"]}, - {"digest":"335e242de1fcc17b6ca920fc420d71bec2d76e53e37955c00948b65ab77f05c5","names":["packages/core/session/src/types.ts#SurfaceOp"],"sources":["packages/core/session/src/types.ts:464"]}, + {"digest":"335e242de1fcc17b6ca920fc420d71bec2d76e53e37955c00948b65ab77f05c5","names":["packages/core/session/src/types.ts#SurfaceOp"],"sources":["packages/core/session/src/types.ts:470"]}, {"digest":"347de3380f2da308d0c74e08821f9e85559f55af4c5010795b110d00f7fc9dbd","names":[],"sources":[]}, {"digest":"34d1ab5c5df378186d6054b1a1beea9a41e41965d6f336f0bc0025c441a82e66","names":[],"sources":[]}, {"digest":"35203ba7ad5ef6f97d556b85df20ae98f04f09c65748cecdf8eefdb8b6405ffc","names":[],"sources":[]}, @@ -210,6 +207,7 @@ {"digest":"383cf73ae4748e5beb281ae74857ba1ffb92ae01075b9fbf51af78b666007a8f","names":[],"sources":[]}, {"digest":"3860b4757d512a2869be833acb0faf834335b1b056bf3f83df5474dce95f8fa6","names":[],"sources":["packages/llm/llm/src/assistant-stream.ts:35"]}, {"digest":"390eed1028aba02774f14408647acec10ec5516e97d4f15ecde2b9989d5a69f2","names":["packages/feedback/message-feedback/src/types.ts#MessageFeedbackRating"],"sources":["packages/feedback/message-feedback/src/types.ts:17"]}, + {"digest":"39adb7fce8475af6402acd925ea79697b3341c22422ac32833d71217d84e987f","names":[],"sources":[]}, {"digest":"39cf2d3ff8bac81c62d49ac2ba38a095b18e80f3ad700819fa1f650a4e60197f","names":["packages/jobs/jobs/src/types.ts#JobToolCall"],"sources":["packages/jobs/jobs/src/types.ts:16"]}, {"digest":"3b04790e08b35241ffa0d38f6d7e4f8788aa921341f6c0d7574a329397c59408","names":[],"sources":[]}, {"digest":"3b1be838223869fe0a08210db85bf773796ed3f2373ac16555dff227cade0c48","names":[],"sources":[]}, @@ -236,7 +234,7 @@ {"digest":"44818000e56acb97afdb5045ce235eb55e3fb1ccabc9fc7d0750bb38f36a7f8e","names":[],"sources":[]}, {"digest":"44c8c77aa9aa100b0d74d2deee85474b29faa6eee0ac0f662f7abe9931ddd7f2","names":[],"sources":[]}, {"digest":"4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986","names":[],"sources":[]}, - {"digest":"454a0fa879e38076bdcdbd87ef561cd67d7e43e58a287cf7dbaa7b6cf7847020","names":[],"sources":[]}, + {"digest":"45f005e6bbb7645248be792b715a74bc7fdf5a67f5381655d3a75dcc7aa2112e","names":[],"sources":[]}, {"digest":"45f2a07ea94573123b6ae14db787a40062dec3834f36d8be92c523d40ba28448","names":[],"sources":["packages/interaction/user-approval/src/types.ts:44"]}, {"digest":"477614bca595a9e7adb5a1870be446b9a8684f3ba8950259d6289f2d3b74f028","names":[],"sources":["packages/compaction/compaction-image-offload/src/projection.ts:25"]}, {"digest":"47e5d84f1a93450a78c7f3954b43990d0f629af7c034a56313e5deb63e772c1b","names":[],"sources":[]}, @@ -252,14 +250,15 @@ {"digest":"4b1e632e05776982a2d21c25a50c7c04c199d311c5675218fa73ff9fe30d22cd","names":["packages/schedule/schedule/src/types.ts#LegacyScheduleRecord"],"sources":["packages/schedule/schedule/src/types.ts:185"]}, {"digest":"4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731","names":["packages/llm/llm/src/message.ts#ToolResultMessage"],"sources":["packages/llm/llm/src/message.ts:173"]}, {"digest":"4b7ddaf3710b88ff9b8df66304f5f97bf03688fd19730eedc2e9535203c820ea","names":[],"sources":[]}, - {"digest":"4bb451330ff699f36b45539ceb0eb2606ead72084e2c5bb637c36cc80e2252db","names":[],"sources":["packages/core/session/src/types.ts:194"]}, - {"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/agent-team/src/types.ts#TeamId","packages/experimental/agent-team/src/types.ts#TeamMessageId","packages/experimental/agent-team/src/types.ts#TeamTaskId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/index.ts#SessionTitleProviderId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:380","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/agent-team/src/types.ts:21","packages/experimental/agent-team/src/types.ts:33","packages/experimental/agent-team/src/types.ts:9","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:31","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:19","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/index.ts:42","packages/session/session-title/src/types.ts:17","packages/workflow/workflow/src/types.ts:13"]}, + {"digest":"4bb451330ff699f36b45539ceb0eb2606ead72084e2c5bb637c36cc80e2252db","names":[],"sources":["packages/core/session/src/types.ts:198"]}, + {"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/agent-team/src/types.ts#TeamId","packages/experimental/agent-team/src/types.ts#TeamMessageId","packages/experimental/agent-team/src/types.ts#TeamTaskId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/index.ts#SessionTitleProviderId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:386","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/agent-team/src/types.ts:21","packages/experimental/agent-team/src/types.ts:33","packages/experimental/agent-team/src/types.ts:9","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:31","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:19","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/index.ts:42","packages/session/session-title/src/types.ts:17","packages/workflow/workflow/src/types.ts:13"]}, {"digest":"4e011753f8263f436efaabfbb3b4db53a98fc55342c5ded2daf7208b217be159","names":[],"sources":[]}, {"digest":"4e44c9118152f6829634bfd508e47669ab0497caffa380c94b4be91f9390d35d","names":[],"sources":[]}, {"digest":"4e887768586528565381dadbddee6cef555874148089f4579e0b4b1ad096fc9c","names":["packages/llm/llm/src/types.ts#TextBlock"],"sources":["packages/llm/llm/src/types.ts:62","packages/web/web-search-deepseek/src/provider.ts:66"]}, {"digest":"4e97c3d85c0fc817ee58873c38c25a2474abaaa0af4839311b50b68db3b8cf1a","names":["packages/subagent/subagent/src/continuation-messages.ts#SubagentSettledMessageSource"],"sources":["packages/subagent/subagent/src/continuation-messages.ts:29"]}, {"digest":"4edec1b770e8ec4ce1220bf42edc5ac46713a1b48d4caa778dcfc98bad1f28a3","names":[],"sources":[]}, {"digest":"4f507598cf476214aa7646ce7841a7064a9dcb05d0a1eaaefaf79c2b738f160f","names":[],"sources":[]}, + {"digest":"4f9125fa028a56286fac70176ecc670d12f4402d8cbe112e14f0639f5e8e5c9d","names":["packages/llm/llm/src/message.ts#Message"],"sources":["packages/llm/llm/src/message.ts:196"]}, {"digest":"4f91f187baeabef5c7950c4780d31bbe39f3345dff591a6cf26ac7e135ac1cf4","names":[],"sources":["packages/context/session-reference/src/types.ts:18"]}, {"digest":"4fb59762612c3e3ac3a3bd4f84c9c148d3c3893bd422ba2b201cc039fabd49bc","names":[],"sources":[]}, {"digest":"50cf02d875f8a1f1411f4a6fbcffab9120ccef5f74a47331fbf29480e5f68f48","names":[],"sources":[]}, @@ -269,14 +268,14 @@ {"digest":"525254db03b1d1e6b74cf55aced52817568331ac1f96c0818728910b6692e336","names":[],"sources":[]}, {"digest":"529e0ccd0e34079ab4ff21ed87f810cee0388246263bf22e8aba5986b56fae05","names":[],"sources":["packages/util/values/src/index.ts:4"]}, {"digest":"52c6113cb0e53f345324bf84f01928bea5d5df57ee80bc0dd65407b8bc5a3734","names":[],"sources":[]}, - {"digest":"5302e763151277614b97e77f00e3b326694c6c1247b916a20503c344dc970777","names":[],"sources":["packages/core/session/src/types.ts:377"]}, - {"digest":"530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6","names":["packages/core/session/src/types.ts#RequestHeaderReason"],"sources":["packages/core/session/src/types.ts:275"]}, + {"digest":"5302e763151277614b97e77f00e3b326694c6c1247b916a20503c344dc970777","names":[],"sources":["packages/core/session/src/types.ts:383"]}, + {"digest":"530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6","names":["packages/core/session/src/types.ts#RequestHeaderReason"],"sources":["packages/core/session/src/types.ts:279"]}, {"digest":"53750b9abf61efb7992b0aadc3e247ec927449c63266df28230fd1139f5590ac","names":[],"sources":[]}, {"digest":"53cf1704ae0709c7678bcf070c83c619fc48ca1b5c173b74cfa8702f22a8e492","names":[],"sources":[]}, - {"digest":"54f9276a1617d7c12594722c89cfe864bcbe4517e9a6f9c98bab14f199a135e0","names":[],"sources":["packages/core/session/src/types.ts:357"]}, + {"digest":"54f9276a1617d7c12594722c89cfe864bcbe4517e9a6f9c98bab14f199a135e0","names":[],"sources":["packages/core/session/src/types.ts:363"]}, {"digest":"557e148d30b79ee48645850832b30c717d7c3b64641deb5d6133b8b4e91ee0b8","names":[],"sources":[]}, {"digest":"5654685d7557ec747e74887237065e626a5bdfa426ca43f7fbb0b6fee9b0916c","names":[],"sources":[]}, - {"digest":"56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23","names":[],"sources":["packages/core/session/src/types.ts:223"]}, + {"digest":"56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23","names":[],"sources":["packages/core/session/src/types.ts:227"]}, {"digest":"570e85022434613394418ad33e77e9f1f7a05699b33d0b62eae0677a638c3833","names":[],"sources":[]}, {"digest":"576a2de8355eb09850963ff5953420b172e274d9283666eb7d889097db120796","names":[],"sources":[]}, {"digest":"5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc","names":[],"sources":[]}, @@ -290,7 +289,6 @@ {"digest":"5b232a9b9bfcc0fc6794dab7865bcf203a65785c5de5aa647a51228bff628413","names":[],"sources":[]}, {"digest":"5b6fb1f226ff56402db08a6aae82af76100b14056271875f69ec526a1ae05d51","names":[],"sources":["packages/interaction/commands/src/types.ts:112"]}, {"digest":"5bb69b88517f6214f2af4d1a6d2b771e271ad3ad695cc9c2c272069ae698c9bc","names":[],"sources":[]}, - {"digest":"5bc2d7f02503fc6b3e1bb7e0b7fa22c0b9e4b9841fa3175b2ad8e607ae3525a8","names":["packages/llm/llm/src/message.ts#MessageSource"],"sources":["packages/llm/llm/src/message.ts:136"]}, {"digest":"5bc66269cfaf614c0ecda8ecb469f23101a7609793fc2b693ac23c4aecdb575e","names":[],"sources":[]}, {"digest":"5bd310104cfe448e530beb11422d2f791e2e32e8e95fdc528a15f9ca693dae75","names":[],"sources":[]}, {"digest":"5c45bf4c544a7211dcd8ba6ba7e5f1bc39b49e7a9df9d5cbdc8e87c22771b37b","names":[],"sources":[]}, @@ -316,6 +314,7 @@ {"digest":"6487b10ba7542f3c447b1e41a1c6a590b7bfafe0b9b66b49f34028da85bb970f","names":["packages/subagent/subagent/src/descriptor.ts#ContinuableSubagentDescriptorData"],"sources":["packages/subagent/subagent/src/descriptor.ts:72"]}, {"digest":"6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25","names":["packages/experimental/agent-team/src/types.ts#TeamMemberSnapshot"],"sources":["packages/experimental/agent-team/src/types.ts:48"]}, {"digest":"65a8400e451e667e5b6e34df72ceb81fca8c12330330fa72083ad40279b189ad","names":["packages/llm/llm/src/message.ts#SystemPromptMessageSource"],"sources":["packages/llm/llm/src/message.ts:35"]}, + {"digest":"65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099","names":["packages/skill/tool-skill/src/index.ts#SkillCatalogSource"],"sources":["packages/skill/tool-skill/src/index.ts:35"]}, {"digest":"66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2","names":["packages/llm/llm/src/types.ts#ToolSchema"],"sources":["packages/llm/llm/src/types.ts:491"]}, {"digest":"672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db","names":["packages/skill/skill/src/index.ts#SkillInvocationSource"],"sources":["packages/skill/skill/src/index.ts:146"]}, {"digest":"67d5f73ceae82f5265258142ad6cf172de2c1fef93ba551b7f0454e0a93bffe0","names":["packages/llm/llm/src/call-config.ts#LlmCallConfig"],"sources":["packages/llm/llm/src/call-config.ts:31"]}, @@ -328,14 +327,14 @@ {"digest":"6ab45ac76839722df912f3ba50f1c6b41f2d614bde11f1aabfae04117ccdc80d","names":[],"sources":[]}, {"digest":"6b23ed9ce1b397e602788dbe033693bf97642a69e23fcab1cc45bf6f13b6d619","names":[],"sources":[]}, {"digest":"6bbe793f6a93dc8d50a4d4d3fbb6f8ed15650bcb7e151d28669628f7b7c3fc25","names":["packages/goal/goal/src/types.ts#GoalSnapshot"],"sources":["packages/goal/goal/src/types.ts:60"]}, - {"digest":"6bc8e51124d0874bc89e1d0ceff381a9c3cd0fc240667d69f841ce4f60f65fe5","names":[],"sources":["packages/core/session/src/types.ts:332"]}, - {"digest":"6c03546143cdf6ae88f1745ac98c5139efa1588d1415249bbc5f3104d32ab800","names":[],"sources":["packages/core/session/src/types.ts:192"]}, + {"digest":"6bc8e51124d0874bc89e1d0ceff381a9c3cd0fc240667d69f841ce4f60f65fe5","names":[],"sources":["packages/core/session/src/types.ts:338"]}, + {"digest":"6c03546143cdf6ae88f1745ac98c5139efa1588d1415249bbc5f3104d32ab800","names":[],"sources":["packages/core/session/src/types.ts:196"]}, {"digest":"6c1cccb433ddc153facb380c7dda956237ba5c31f8a532a69142dc277890cc9b","names":[],"sources":[]}, - {"digest":"6c5a37d42ebdb12db4410699259335f1e149e3a0260425684c00b153afc8990d","names":[],"sources":["packages/core/session/src/types.ts:193"]}, + {"digest":"6c5a37d42ebdb12db4410699259335f1e149e3a0260425684c00b153afc8990d","names":[],"sources":["packages/core/session/src/types.ts:197"]}, {"digest":"6ccb6bc423fb3952458abf9c1b1c3284208b7e660344b612cc55da773d61afe4","names":[],"sources":[]}, {"digest":"6cda0d6d3b4336d83998fe580628426df81c2afbab5d768b8813b56d569120e8","names":[],"sources":[]}, {"digest":"6cf082d0fb6034dea61636787ff0ddf43b6e59aad71e644435a479bc9b83ad65","names":[],"sources":[]}, - {"digest":"6dacb1584f2bfbe209dc6b6f578d51da6d55595f64d0e63c727c98f359278def","names":[],"sources":["packages/api/session-controller/src/types.ts:389"]}, + {"digest":"6dacb1584f2bfbe209dc6b6f578d51da6d55595f64d0e63c727c98f359278def","names":[],"sources":["packages/api/session-controller/src/types.ts:395"]}, {"digest":"6e52dd55a1d48954ed5464ec46fe34d9eb65f709baabc9561e7a279910b0c406","names":[],"sources":["packages/preset/agent-preset-registry/src/session.ts:31"]}, {"digest":"6ea608bdc8a7a63d3d23b84c49721325094db88d136482e43a820945295eee3e","names":[],"sources":[]}, {"digest":"6ebcc2dbec9f2dabca9f668ae6d39e877899b180740570f453409db339221df3","names":[],"sources":[]}, @@ -358,8 +357,7 @@ {"digest":"763c8a20af487263a0080548274f7437ef4a86e0ba8769127d1ced10a72c664d","names":[],"sources":[]}, {"digest":"76632533f67879dcb346fcae640540dbc89b2472b0bce88c59f7e48fc5c0e668","names":[],"sources":[]}, {"digest":"78a9be340090b735a39980e7222ce730c972fbcf1de7c9e0aef2125884b7caee","names":[],"sources":[]}, - {"digest":"79650cfa10aa3c52440328d85e8a25f0ffadc8d7efd784e3c0819d8bb74a1985","names":[],"sources":["packages/core/session/src/types.ts:214"]}, - {"digest":"79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056","names":[],"sources":[]}, + {"digest":"79650cfa10aa3c52440328d85e8a25f0ffadc8d7efd784e3c0819d8bb74a1985","names":[],"sources":["packages/core/session/src/types.ts:218"]}, {"digest":"79ddc907312f97cf9553d4841e8b3fc937097bd8d97900a790efad3c05255e99","names":[],"sources":["packages/todo/tool-todo/src/types.ts:33"]}, {"digest":"7a651f3b672c52fb615f22c0ce9cb3cc5b22aad92e6bbeefb0808fd7b9233a50","names":[],"sources":[]}, {"digest":"7af85bf70d4eafce63e739adae38ea85501e68df3a0e22f97f3a0be90fd9e4cb","names":[],"sources":[]}, @@ -383,7 +381,7 @@ {"digest":"82470020b5bfcb1a843e2aa05602af7d37df99e82d01f015c7c589ba054fd89d","names":[],"sources":[]}, {"digest":"825ca23416b1ea9d81442afead5cf9229a6fa05842f042135cc3aa9710a6a2d8","names":[],"sources":[]}, {"digest":"829a2fb3be6efd4ba36aef8ed2d381a4c6fb2a0aaf50c823a6f3f8290786b809","names":[],"sources":[]}, - {"digest":"83079c8a3f733ac3fa603eefa0fbb4737ca4d8b69e7e2e7298b60f9ac4098693","names":[],"sources":["packages/skill/tool-skill/src/index.ts:41"]}, + {"digest":"83079c8a3f733ac3fa603eefa0fbb4737ca4d8b69e7e2e7298b60f9ac4098693","names":[],"sources":["packages/skill/tool-skill/src/index.ts:43"]}, {"digest":"8338ee303e2bd448e9e6144069942f63e3cfd5868962bddc9347d7009e8919d6","names":[],"sources":[]}, {"digest":"83d6916021eede8f2d83a1872716caa1efdec39a3681890996c55147187fdd12","names":[],"sources":[]}, {"digest":"83da72c6857601c75da11212ef847f57d457b9c99f0a82246dcdff3e26700239","names":["packages/context/agent-instructions/src/render.ts#AgentInstructionChange"],"sources":["packages/context/agent-instructions/src/render.ts:62"]}, @@ -407,6 +405,7 @@ {"digest":"8ad45ad053b4d89f8865c17cc9ff3b8748e86045f3f0fb816269a34af2619141","names":[],"sources":["packages/experimental/hook-protocol/src/types.ts:31"]}, {"digest":"8af841fc9b265ade3441caf9fe40dd24db24226befba48150e6d0eeccc1389c3","names":[],"sources":[]}, {"digest":"8bb8c3751a6ce64b61aba1ec7ae798c00a5803c4d868a0430873216c6569ed52","names":[],"sources":["packages/session/session-log-deepseek/src/types.ts:81"]}, + {"digest":"8bca2b4f53ec7745b0484c6e7d3a6beb2ddd6cea82fc81786eaa3c0d065bbc14","names":["packages/llm/llm/src/message.ts#UserMessage"],"sources":["packages/llm/llm/src/message.ts:162"]}, {"digest":"8c1c4f72755a78ea163523a46565316e36e9b644382eb48e6635c71a6f412dd2","names":[],"sources":[]}, {"digest":"8c627d7a45fa406cea879a3922105e27ed4c3c7966e264afaf11ea7a330f2dd1","names":[],"sources":[]}, {"digest":"8cdd3fdd295cee53035de16a1b23411716f75e9f994fe9510cac5d7fef605c76","names":[],"sources":[]}, @@ -427,11 +426,12 @@ {"digest":"94c56aeb1564ad735eb773d88636b40761d063efa1610f1308004d32923f5378","names":[],"sources":[]}, {"digest":"95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65","names":[],"sources":["packages/llm/llm/src/types.ts:472"]}, {"digest":"95a3ffccbf3c8afcf9a2f3b355f724da8e07e98dc47ee741166dde7f9ea058bd","names":[],"sources":[]}, + {"digest":"95acdbd066cf445d37092e5fdfe2e8717ef6ca1aed50f70e2e6037a6989a1f2f","names":[],"sources":[]}, {"digest":"95c0e88fcf0bafb2087f912ad9e2369de6ae6530cc0c4c2772c96205b57f7f60","names":[],"sources":[]}, {"digest":"9645cf93769a6dfb227bd400bd6cb9fa7bab9140f4a851e4ae92514ade6e3114","names":[],"sources":[]}, {"digest":"96bfb916a727cd4445a594df264c523fc039749a31bfed924b8cc7bb308a5bb0","names":[],"sources":[]}, {"digest":"96f4a9c81fc0f940ef71528a8cc66731ae4cf1f40d79680c5fe3c39f96d7723c","names":["packages/core/agent/src/types.ts#InboxTarget"],"sources":["packages/core/agent/src/types.ts:40"]}, - {"digest":"97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c","names":[],"sources":[]}, + {"digest":"9808c3d0f0a1be8fe313b4148ba22c691c4d59bd2c67aef3c63cfe8043148c5f","names":["packages/session/session-title-llm/src/index.ts#SessionTitleLlmRequestEventData"],"sources":["packages/session/session-title-llm/src/index.ts:37"]}, {"digest":"9890113e97dd3541787bfe6704f2b223d3a890b5325ca0acae2b0398909b413e","names":[],"sources":["packages/sandbox/sandbox-policy/src/session-mode.ts:33"]}, {"digest":"99135d8a3937977955eaac5f8f04f930dcd1562f8450a54a51cde9b921dd59a6","names":[],"sources":[]}, {"digest":"9947aa5938fe19a895298da412917acbf9ffb5093a73ab8baa257e6ae9e63a07","names":[],"sources":[]}, @@ -440,7 +440,7 @@ {"digest":"99f0e98184709ad10f27bfdeaafb4457d9d2b413f402331764798cdb7d3cbe4d","names":[],"sources":[]}, {"digest":"9a2a9029f8d7ede05336980d8342737557f487b913bfd28853d0ab5214600ab5","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:64"]}, {"digest":"9a410ddf56792b2b7cd4a224a2e54dc4dee30a8e8e6b1c2b9a1d19992b217adc","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowAgentStartData"],"sources":["packages/workflow/tool-workflow/src/types.ts:20"]}, - {"digest":"9a930283b91d493d6347146f2475bb107294b379415ca02162354f46a64164f7","names":["packages/core/session/src/types.ts#EpochHeader"],"sources":["packages/core/session/src/types.ts:242"]}, + {"digest":"9a930283b91d493d6347146f2475bb107294b379415ca02162354f46a64164f7","names":["packages/core/session/src/types.ts#EpochHeader"],"sources":["packages/core/session/src/types.ts:246"]}, {"digest":"9ac52f0f84fec2eb9f71c2937e497d759db5ca0da4836d93a679d113684141f2","names":[],"sources":[]}, {"digest":"9acbe713f3f641921dd3333b240aa72e176d795327c24e8d9db9b68b16771b49","names":[],"sources":[]}, {"digest":"9b4fd974c124c83743efe030ba4e1250e087505f3f74588716a521fb8d453267","names":[],"sources":[]}, @@ -449,6 +449,7 @@ {"digest":"9e07693fd7cd9babe0688c22c986e4d519ae1c0e40eeea13b2dc583bed2abc86","names":[],"sources":[]}, {"digest":"9e2c06d8653585b33d72d5c1a80da79c8a24a88c284409bca15cc0f0ead5ebfb","names":[],"sources":[]}, {"digest":"9e41386b3a0c9572b0d63078492ebb3997da7d3a830d44e0259418bd02f4bcb2","names":[],"sources":["packages/compaction/compaction/src/types.ts:38","packages/compaction/compaction/src/types.ts:84"]}, + {"digest":"9e8043098fb89db6d7c92a92c70146c5c8d24fa88f733c687fa29e5e7a58ab30","names":[],"sources":[]}, {"digest":"9edc162949abf93bd5ff049191b345454ba104f583937ce5580fb50f067d2b94","names":[],"sources":["packages/experimental/webhook/src/types.ts:74"]}, {"digest":"9f65c43e340bba31cdc0fc37bd93ccb68d5e9b36f47a68c207e95a8e68620a5d","names":[],"sources":[]}, {"digest":"a0a2e5c42e1c929445ecd1cd70f49be6b66441894ec72c08e8ae332821d4a3cb","names":[],"sources":[]}, @@ -471,12 +472,11 @@ {"digest":"a6da9ad5d42ae83a6833a8288b076688e8e0801633ea36cbdd8a30a6d9f3160c","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowRunStartData"],"sources":["packages/workflow/tool-workflow/src/types.ts:14"]}, {"digest":"a720757f704a2512e9d2f20da4a093e582472176236a75ab8b8eb7aaff17d85a","names":[],"sources":[]}, {"digest":"a7cf43ce7c2a4c038feed1885cd7a00d5c6ee2d90a7e0d56b46f78a3e1ca327f","names":[],"sources":[]}, - {"digest":"a81059ca06999da1e712414520c2c65e491d052fcf9640fae20aa38f0a5dc735","names":[],"sources":["packages/core/session/src/types.ts:385","packages/core/tool-executor-ptc/src/types.ts:27"]}, + {"digest":"a81059ca06999da1e712414520c2c65e491d052fcf9640fae20aa38f0a5dc735","names":[],"sources":["packages/core/session/src/types.ts:391","packages/core/tool-executor-ptc/src/types.ts:27"]}, {"digest":"a853902cfab417b8f08aa51ad6855fea46f34ed4588a74e47403035111d0fb86","names":[],"sources":["packages/interaction/commands/src/types.ts:105"]}, {"digest":"a8a2b9011fc067862df7ce40748868467e5778283d7ac193c13f77684a914c57","names":[],"sources":[]}, {"digest":"a9059a81430b320792bbb7c2ee1f8f6c77ff71e40ee44c18aec72e157c522694","names":[],"sources":[]}, {"digest":"a926dc71814edd01a4f041eb5fc766d153db3407ef4704e98f4c1b6527309ebb","names":["packages/schedule/schedule/src/types.ts#LegacyEveryScheduleRecord"],"sources":["packages/schedule/schedule/src/types.ts:173"]}, - {"digest":"a927d444c928ac0efd9dd8b2e7d7d04d711c264cb71578d81e0e2fd143ff669f","names":[],"sources":[]}, {"digest":"a99ec0993c62c058e50af9f68922202a3b54f5e259bc2abf1915a73381d2316d","names":[],"sources":[]}, {"digest":"a99f76fd149051c363f960bfeeb5b9509587ecaf7591a42797e4bfe810d8987a","names":["packages/todo/tool-todo/src/types.ts#TodoItem"],"sources":["packages/todo/tool-todo/src/types.ts:23"]}, {"digest":"aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8","names":[],"sources":[]}, @@ -484,15 +484,16 @@ {"digest":"aa7bc2817014ca6c45719b1c193c5c131be718a0921f34345098ff250f444626","names":["packages/feedback/message-feedback/src/types.ts#MessageFeedbackPut"],"sources":["packages/feedback/message-feedback/src/types.ts:38"]}, {"digest":"aa93010d0e521ad7c42273f58d5c9b8bf1dfc94edf1b805a3971b364a35c1877","names":[],"sources":[]}, {"digest":"aacda84a69739238aa782eea902d3073017d9d74b9808de2bf5a83c9738cbdc6","names":[],"sources":[]}, + {"digest":"aada2771a250136cc3a839b0507e9c6502622a2897716903942297bcb6661292","names":[],"sources":[]}, {"digest":"aae343bc3d663c83f2e8b5e1c7eea5d509dc7a5361bc8bd8b5ac3bb8d3b1ed56","names":[],"sources":[]}, - {"digest":"ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7","names":[],"sources":["packages/core/session/src/types.ts:216","packages/llm/llm/src/types.ts:159"]}, + {"digest":"ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7","names":[],"sources":["packages/core/session/src/types.ts:220","packages/llm/llm/src/types.ts:159"]}, {"digest":"aba175fb20ffc71112c55efe70458ff5d7dbfb83501892b4ba8d077f0ea5d7ba","names":[],"sources":[]}, {"digest":"abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c","names":["packages/web/web-search-deepseek/src/provider.ts#DeepSeekSearchLlmRequest"],"sources":["packages/web/web-search-deepseek/src/provider.ts:55"]}, - {"digest":"ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585","names":[],"sources":["packages/core/session/src/types.ts:392"]}, + {"digest":"ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585","names":[],"sources":["packages/core/session/src/types.ts:398"]}, {"digest":"ad22a5ca5bbaab2e1440779cd3648e85ddfc6f73b5207394eda699555cf31430","names":[],"sources":[]}, {"digest":"ad3b56aa2fc1ad4250e7399295d34a8eae592e1907e85852e2291b2e498a30bc","names":[],"sources":[]}, {"digest":"ad92f473a03ae72599ff26c86e897c25e16269519ad2a87340f0bea946517af8","names":[],"sources":[]}, - {"digest":"ada310bf0bdb8fed51f3b56ea63f6ea6b18bbd587f04fccb63a14ab0b2a24e05","names":["packages/interaction/commands/src/types.ts#CommandSource"],"sources":["packages/core/session/src/types.ts:191","packages/interaction/commands/src/types.ts:75","packages/interaction/commands/src/types.ts:79","packages/llm/llm/src/message.ts:111","packages/session/session-title/src/types.ts:35"]}, + {"digest":"ada310bf0bdb8fed51f3b56ea63f6ea6b18bbd587f04fccb63a14ab0b2a24e05","names":["packages/interaction/commands/src/types.ts#CommandSource"],"sources":["packages/core/session/src/types.ts:195","packages/interaction/commands/src/types.ts:75","packages/interaction/commands/src/types.ts:79","packages/llm/llm/src/message.ts:111","packages/session/session-title/src/types.ts:35"]}, {"digest":"ade057f4fdc387aec6426f48704a1f9359cfc6fee13f27735b07f9b215ec16ca","names":[],"sources":[]}, {"digest":"ae63d9d1080ed8945031594d93f8d96651d7101b848719cc3e1475875cd3d649","names":[],"sources":[]}, {"digest":"aec150797b655c5f15ebb7a501454b0c208fbaccec9ace49d7de2171fc02f47d","names":[],"sources":[]}, @@ -502,7 +503,8 @@ {"digest":"b0127044ab31a702bddfd785d345f5abd7a70876746e895ce443afa3e60ddf2d","names":[],"sources":[]}, {"digest":"b062078e899958f99ae464514578b8c093924dfe34bd9a835932b420ff2150b1","names":[],"sources":[]}, {"digest":"b0b0eb1b16490f6bee135b2377e8f8c39227974c799ad7d49ff418af23ecbc35","names":["packages/attachment/attachment/src/types.ts#ImageAttachmentRef"],"sources":["packages/attachment/attachment/src/types.ts:11"]}, - {"digest":"b158f3ff6923714807c0d73882f0b05dc87f8fa85c9e90814852d48bbc866081","names":["packages/core/session/src/types.ts#RequestContext"],"sources":["packages/core/session/src/types.ts:256"]}, + {"digest":"b112459dcb0686091c31ce6d213b2a4934b5ad19d37cc5b599e46f5a9d715591","names":["packages/llm/llm/src/message.ts#MessageSource"],"sources":["packages/llm/llm/src/message.ts:136"]}, + {"digest":"b158f3ff6923714807c0d73882f0b05dc87f8fa85c9e90814852d48bbc866081","names":["packages/core/session/src/types.ts#RequestContext"],"sources":["packages/core/session/src/types.ts:260"]}, {"digest":"b1664fa89f8eab49a14e7e3168d8bc4da4aa9fd76332f6c4a053d839e5276ae7","names":[],"sources":[]}, {"digest":"b1ebd5cda47d90d980bb05bffc3f970c51537b9aff15b3bc3d639811727741b1","names":[],"sources":["packages/experimental/agent-team/src/types.ts:230"]}, {"digest":"b1f62380f6746fedd629e71065e3583cef83334875b499ac9665c2eb87acfbf5","names":[],"sources":[]}, @@ -519,9 +521,10 @@ {"digest":"b56f6a885da3dc394c69a3e3cc5c0cfc4da15601b63fda4989eee8f40efc5be4","names":["packages/session/session-title/src/types.ts#SessionTitleEventData"],"sources":["packages/session/session-title/src/types.ts:41"]}, {"digest":"b57a2889408de36e4516807194c73bdecd51a92f633ccd05db81bf049200f420","names":[],"sources":[]}, {"digest":"b57ae1b37e52bee0a21cbdace168dc6a15582bcda8c306dad962c5dcc8a8e28b","names":[],"sources":[]}, + {"digest":"b613f83572fe2fbf7259c72308cafd008f4fceea897749128a48bcd158f290aa","names":[],"sources":[]}, {"digest":"b63b089a00b3b9357675b3e0c3d3e9aa4fdbda1fba9c91a6b0c59ffdbb89f505","names":["packages/schedule/schedule/src/types.ts#LegacyAtScheduleRecord"],"sources":["packages/schedule/schedule/src/types.ts:167"]}, {"digest":"b6896938660a1dfe4ddd100fb3164d9f8fa57feeabfe37441a80106c9942697a","names":[],"sources":[]}, - {"digest":"b6ef9c6210be8350cd465f485cf520031fffa6bf3809c61a1e713e834c5982d0","names":[],"sources":["packages/core/session/src/types.ts:203"]}, + {"digest":"b6ef9c6210be8350cd465f485cf520031fffa6bf3809c61a1e713e834c5982d0","names":[],"sources":["packages/core/session/src/types.ts:207"]}, {"digest":"b6f94c17dd9bbd7cd57015198b7c7c88407f0e3b89faab176ca3c11c3d864d3e","names":[],"sources":[]}, {"digest":"b70f3e81fe11b7a5f2504fb47a4502fb8d9c8f0731fdfe8ddcaf9b41f5a6e196","names":[],"sources":[]}, {"digest":"b765ee31033cea463863faf3fc6a0a1b85c47c6a2f13fe1ce833abe56105114b","names":[],"sources":[]}, @@ -534,6 +537,7 @@ {"digest":"b9305f0ea75ccd6a6061c27fde19f2ab85534f9f3c1a717b573b077ebae0f611","names":[],"sources":[]}, {"digest":"b978cff734e62143eb56c9125423ec275405eda969802d42aaf73ecb987d3b26","names":[],"sources":[]}, {"digest":"b993441f8ce7d27b80e619e113e232ae8e62d3d5a8340f6bfe12d8c4c018e62f","names":[],"sources":[]}, + {"digest":"ba2a1a8f194b1bb21f270713398f6643e206e8ff5f7f26f6d36a88e3f0f0ab10","names":[],"sources":[]}, {"digest":"ba4c40b4381e0dcdfab8fc9fc75b5c9b3e8f09ef56deeb1bec8e703b0ef8cd6d","names":[],"sources":[]}, {"digest":"ba77b58995e36f14bb13886b0493d0a1a63d5db10b1a6cd9f6ac65a72cf832ec","names":[],"sources":[]}, {"digest":"bab68657940075483f086fffb711682a45bcc99c43d659fbe1c36af21ac05dd7","names":[],"sources":[]}, @@ -542,7 +546,7 @@ {"digest":"bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3","names":[],"sources":[]}, {"digest":"bb94f3217aa56c8876bbff0b8460d6a73cbead545659abb29e76cd0cf2cb92d6","names":[],"sources":[]}, {"digest":"bbc5696e3f13c758237b316e3cf08cda0b9fd51ffe672539883457769faa185d","names":[],"sources":[]}, - {"digest":"bcf0caf62d964b2fcf5404bd5c909cfa9a21c3f3c96e6b7e36d9e33565223825","names":[],"sources":["packages/core/session/src/types.ts:466"]}, + {"digest":"bcf0caf62d964b2fcf5404bd5c909cfa9a21c3f3c96e6b7e36d9e33565223825","names":[],"sources":["packages/core/session/src/types.ts:472"]}, {"digest":"bd499eac047efe091a4df7382eadd06d25cf0cb31fee3981e8b24d85762841cd","names":[],"sources":[]}, {"digest":"bf16d2e98a7f13894ded2cffe5ce857bf473954a0e3c0ed9bc7739e2e1c7b78a","names":[],"sources":[]}, {"digest":"c0ea97bc89dfc46fa94eab956f5c3ee6af2f964aa7db6327cb18b451f207bef7","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowAgentEndData"],"sources":["packages/workflow/tool-workflow/src/types.ts:29"]}, @@ -552,6 +556,7 @@ {"digest":"c219efbdfd53b836786202ab4532913d555798f0a8615a4e9629736e3799fb70","names":[],"sources":[]}, {"digest":"c2deb7c9183735d4e0fffddf5c623f4e34daa1c8e96b111982e957dfcbbcf896","names":["packages/workflow/workflow/src/types.ts#WorkflowAgentOutcome"],"sources":["packages/workflow/workflow/src/types.ts:110"]}, {"digest":"c2f49004d9ae38a964e80850c87bc6849d6a872091a1d43e99eedf00c641e2a3","names":[],"sources":[]}, + {"digest":"c433ef580a5b229bbe68274a7164aa3a8e8040d7217f010b610ca0696a84253c","names":[],"sources":["packages/core/agent/src/types.ts:110"]}, {"digest":"c43b119ce579b3e9983a0d3adc4ba402ebb9ba773d89738a2dab01ecf5813943","names":[],"sources":[]}, {"digest":"c5228b7a55498d84f529591744a0ab26e0b93ade18a70a26db1377a1ecfa6b49","names":[],"sources":[]}, {"digest":"c55827fba7018198772c50e37cb7d3f60a3d8bb6e94b07de72dee0d9f8968005","names":[],"sources":["packages/interaction/user-questions/src/types.ts:134"]}, @@ -570,10 +575,12 @@ {"digest":"cda2345a9be9d139df49ccbd16dcba716f3440178bf20ff8b801fda1f5eb77dc","names":[],"sources":[]}, {"digest":"cdca80b8dad24d4e7b1d5a288a8475ba8d8d46be385bd2da85f122ee836f1670","names":[],"sources":[]}, {"digest":"cdee10e87dbed8440d8b6935888624884878efc7af95402e94171b29f173dced","names":[],"sources":["packages/llm/llm-retry/src/types.ts:17"]}, + {"digest":"cebb7e9f3f663e660a531d9764ecfb9fa7fc73c22bf8d628f888e9ecf18c5cf0","names":["packages/llm/llm/src/message.ts#DeveloperMessage"],"sources":["packages/llm/llm/src/message.ts:157"]}, {"digest":"cef171adf021a1867d244618a3dbbaafc22beb17c7f3df3ee203393271c8c6f6","names":["packages/core/tool-executor-ptc/src/types.ts#PtcDispatchEventData"],"sources":["packages/core/tool-executor-ptc/src/types.ts:21"]}, {"digest":"cffcdc19881ab61ec0a9ce18743996f7ac44ac8889f34dfac36ae745574aa22f","names":["packages/goal/goal/src/domain.ts#GoalClearChangeMeta"],"sources":["packages/goal/goal/src/domain.ts:35"]}, {"digest":"d0fbb0ca1bbba059830826f33f801da1aced35a2504376d61e020bdfec8d50c0","names":[],"sources":[]}, {"digest":"d28765f87d6b6ab408e0b2f3e7e297791b004b806d8e302c49903ebae815feb2","names":[],"sources":[]}, + {"digest":"d2b617d9dfcc4e0a4b60732d8ba1effc632e3b75124b93b064c07814a0a716bc","names":[],"sources":[]}, {"digest":"d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d","names":[],"sources":["packages/llm/llm/src/types.ts:475"]}, {"digest":"d4c799e3d51cae1040362ba4968efc484739e14416c9c1df20c2f108b4ef2eb5","names":[],"sources":[]}, {"digest":"d4e4d575abeb4b72d616dc65c17ac0eaa943cc135609395044c38d5afcb10e31","names":[],"sources":[]}, @@ -592,9 +599,11 @@ {"digest":"db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965","names":[],"sources":[]}, {"digest":"dba54c09c6e7aafc9acbed7792ecc920d99f92d0784aeeed10af55f7fe0bc8cd","names":[],"sources":["packages/core/tool-executor-ptc/src/types.ts:68"]}, {"digest":"dbdafceb9a900183cccc80596498d386f3bf7bddead2b8cfde68453aa4739edc","names":[],"sources":[]}, + {"digest":"dd00cdccd0ba487b92362ef67db58cd264f48c1bfd368291424a1da9a899489a","names":[],"sources":[]}, {"digest":"dd2780e7e07684332f7a9ab047237798d260e7eaffb1321cb38eca695d184c3d","names":[],"sources":[]}, {"digest":"dd5ee8762bd8a14b6c6bffedd1753e4e78505bb0f9ea1621018d03a54eef59d5","names":[],"sources":[]}, {"digest":"dd6cc2bb2a8f28248347021ad93565360b196a042360b4cd16b569d3a2a91f2d","names":[],"sources":[]}, + {"digest":"dde0cdf9d426768b649b5a9783d2144e7f900c35ef65229cd89036dbf411d1b0","names":[],"sources":[]}, {"digest":"de25352d2dc4196309bd84b5bac6319f6d5c898ea0e82bb5ae66c5738d0d426f","names":[],"sources":[]}, {"digest":"de30b1fa12c75f81df6aa4096e1595296d2d04e2be14a7c29849cf8028b79048","names":[],"sources":[]}, {"digest":"deaae5cd30987d4f49398e8f9d994c125907e7f928300745fb1dbf15f145d0e7","names":[],"sources":[]}, @@ -613,8 +622,8 @@ {"digest":"e41bdebe246abe17154de7e7a1d81035437eee8d20e7f1edff0d91e2598ad828","names":[],"sources":[]}, {"digest":"e42b0f40b5d0b628c6e1c44a8fb9eda0780037a81959e1b93d2dfb47b46b0e87","names":[],"sources":[]}, {"digest":"e438a9d4fb883b3e4a8d9fc8913aa1550ed50eb384bfbf943100a5605b537498","names":[],"sources":[]}, - {"digest":"e481c46af3813e0010558e93f578b2986acd658404cec2d1679e3ac2a6c48654","names":[],"sources":["packages/core/session/src/types.ts:299"]}, - {"digest":"e4c18e294232c3ba6c9f1999f168263cc55956147cfe4121720899be8e52edd1","names":[],"sources":["packages/core/session/src/types.ts:363"]}, + {"digest":"e481c46af3813e0010558e93f578b2986acd658404cec2d1679e3ac2a6c48654","names":[],"sources":["packages/core/session/src/types.ts:303"]}, + {"digest":"e4c18e294232c3ba6c9f1999f168263cc55956147cfe4121720899be8e52edd1","names":[],"sources":["packages/core/session/src/types.ts:369"]}, {"digest":"e4cac694f8b6e1d52e48c699464f1c4c26111ef87e558f7931040d00fdc8d486","names":[],"sources":[]}, {"digest":"e5d3828df1ec3e2a66879de0659e0f4866d9cfffc00825ee731a66f8a0c03d98","names":[],"sources":[]}, {"digest":"e6063d0451dc02026fd9b54ad3f77c7b1b6392ad3e872a7737ac84e13ca72344","names":["packages/schedule/schedule/src/types.ts#EveryScheduleDispatchChange"],"sources":["packages/schedule/schedule/src/types.ts:244"]}, @@ -624,24 +633,26 @@ {"digest":"e7ce49f12953583fad217bf80fb9f1463acff2c3e9471a823782661675fb124c","names":[],"sources":[]}, {"digest":"e7e154d47d5fbc5366330fb4dade1f108c6dfe4335044d21ded14b7bf1dce084","names":[],"sources":[]}, {"digest":"e7e8f1318170b8284f16ab45a557afd4675c96071c0f2a456636481dab20b427","names":[],"sources":[]}, + {"digest":"e7f4cbb3a57f4cbdb61ea41e95bcba626ad1fff6bb9b1e063b1d50a32da6e864","names":[],"sources":[]}, {"digest":"e8de0f457fed5b9ff94dc4950b59ef75fd8ba8af665cc7899485924a62653367","names":[],"sources":[]}, {"digest":"e95f957154b2b1b58692af53d4131180b6dd19e2264869f876dbaa959991494e","names":[],"sources":[]}, {"digest":"ea08ec1df0c33108fd03345b9af199cf04dea450aa045d3c683f216311403403","names":[],"sources":["packages/experimental/agent-team/src/types.ts:234"]}, - {"digest":"eaa71be0fbf0f702df8ea6c11d0aa2f9782263d45a10d0fb14eda662f4bfe04c","names":[],"sources":["packages/core/session/src/types.ts:197"]}, + {"digest":"eaa71be0fbf0f702df8ea6c11d0aa2f9782263d45a10d0fb14eda662f4bfe04c","names":[],"sources":["packages/core/session/src/types.ts:201"]}, + {"digest":"eaa9125aec0fb28478096c46e73e21bf512ab0d84d826bfb41e7308707734cb5","names":[],"sources":[]}, {"digest":"ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8","names":[],"sources":[]}, {"digest":"ec38b5949af8eacaf00df002f4acbe344f934f8a061e9cdc65a52a48e5f6dd93","names":[],"sources":[]}, - {"digest":"ec8b5ff7c77ca6893ac7ba5a0c5b2aefeb52f12c64450b7359660c2a7e8a53d7","names":[],"sources":["packages/core/session/src/types.ts:230"]}, + {"digest":"ec8b5ff7c77ca6893ac7ba5a0c5b2aefeb52f12c64450b7359660c2a7e8a53d7","names":[],"sources":["packages/core/session/src/types.ts:234"]}, {"digest":"edbbfff1128099fda7b792c56330d2cb04debc9790988e66d1c3f4026e813e0e","names":[],"sources":[]}, {"digest":"edd37b1e4974af648633014435572089b1e8fb71910468a0767a7e28fdd22abf","names":[],"sources":[]}, {"digest":"ee577a0cc18664c9daee50e9455153321155604f8f1817362f8f4a4b6fb9e1ad","names":[],"sources":[]}, {"digest":"eea687d437880bd5f55fb447a561112800ca34334c0724d9cecb98493059d9e4","names":["packages/schedule/schedule/src/types.ts#ScheduleCreateChange"],"sources":["packages/schedule/schedule/src/types.ts:223"]}, {"digest":"eefbea819caeeea91ccb02dfafc16c68dd7f961cf9c1b2be25a2084509cf5c5a","names":[],"sources":[]}, - {"digest":"ef11a3b7fa2033ae4279545ff8a8a2ee4e301b9b73e5b91654c48e6d08283545","names":[],"sources":["packages/core/session/src/types.ts:301","packages/core/session/src/types.ts:303"]}, + {"digest":"ef11a3b7fa2033ae4279545ff8a8a2ee4e301b9b73e5b91654c48e6d08283545","names":[],"sources":["packages/core/session/src/types.ts:305","packages/core/session/src/types.ts:307"]}, {"digest":"ef226a90ddac6cd8e631a3a337a3a3e27f9494be92befb7c718b404681d75e21","names":[],"sources":[]}, {"digest":"ef4f00923b9edbae15c7ef05320280bf61147ca17146cf59690359bfd5e5da45","names":[],"sources":[]}, {"digest":"f05fb85e715af4ab4de0b6ba111166dd0435bd8bb74a0fa0f32b9d174113fc7c","names":[],"sources":[]}, {"digest":"f09e5e7acf5ff5ccd193ff2eeec015fa2ff7c29d98bc465f8c3302058d47e29b","names":["packages/core/agent/src/types.ts#ModelSelection"],"sources":["packages/core/agent/src/types.ts:79"]}, - {"digest":"f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402","names":["packages/core/session/src/types.ts#TurnEndReason"],"sources":["packages/core/session/src/types.ts:234"]}, + {"digest":"f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402","names":["packages/core/session/src/types.ts#TurnEndReason"],"sources":["packages/core/session/src/types.ts:238"]}, {"digest":"f1996af2602e6f62b5ab179ca5c4af00d8753938b74cc6ef102de09e99e74a7e","names":[],"sources":[]}, {"digest":"f19bee84bf3d20904553cdcd57465232bc1c2a194f54c4d195292ba0487223a6","names":["packages/attachment/attachment/src/types.ts#FileAttachmentRef"],"sources":["packages/attachment/attachment/src/types.ts:39"]}, {"digest":"f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515","names":[],"sources":["packages/llm/llm/src/types.ts:476"]}, @@ -650,7 +661,6 @@ {"digest":"f2da0f27c1e6add59982c37b15e4a4912c5b33466859cce3b13d503600e24aef","names":["packages/llm/llm/src/types.ts#FileBlock"],"sources":["packages/llm/llm/src/types.ts:98"]}, {"digest":"f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5","names":["packages/llm/llm/src/types.ts#SystemPromptUpdate"],"sources":["packages/llm/llm/src/types.ts:414"]}, {"digest":"f4a66f654996c093aae700ea4c434ff2ee3569fea9c0e5813ccf6afdccabd163","names":[],"sources":[]}, - {"digest":"f4ed4717b4c259e933b550a8dcd90dc93628cda8a3c7affcaa53b9c13c1d53eb","names":[],"sources":["packages/core/session/src/types.ts:313"]}, {"digest":"f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1","names":[],"sources":[]}, {"digest":"f56c5b59ca0161310c338d31dd16cf14287ccd602ff4181058df178c1c286d7f","names":["packages/context/session-reference/src/types.ts#SessionReferenceSource"],"sources":["packages/context/session-reference/src/types.ts:13"]}, {"digest":"f6329fb30c7ea8013e8975ca5e78284fb7685cc6bd620e8aa4e9a99bc81d45eb","names":[],"sources":[]}, @@ -663,17 +673,15 @@ {"digest":"f731ffe80810b0289b3e694d8f40af6f01865c02a622ee457be90ca808b66e87","names":["packages/subagent/subagent/src/catalog.ts#SubagentCatalogEvent"],"sources":["packages/subagent/subagent/src/catalog.ts:28"]}, {"digest":"f789af5ab844827eb5a4f357c0afae1eeed108c6c22d8ca1a56e586b349a7c85","names":[],"sources":[]}, {"digest":"f88f1b7b6bb733f685f5fb6a8744a5db9199fa53c90463ea1a33bad51153671d","names":[],"sources":[]}, - {"digest":"f90eb4ab2d3897bc20c521a038e3119d581f791ec974b1a0004f63a8ab9e232d","names":[],"sources":["packages/core/session/src/types.ts:290","packages/deliverables/workspace-changes/src/types.ts:106"]}, + {"digest":"f90eb4ab2d3897bc20c521a038e3119d581f791ec974b1a0004f63a8ab9e232d","names":[],"sources":["packages/core/session/src/types.ts:294","packages/deliverables/workspace-changes/src/types.ts:106"]}, {"digest":"f97f47b0eb87905ed77cc27c5e4ed75ef805cb372c98905253709de1aab9b63c","names":[],"sources":[]}, {"digest":"f9cfc89e8fe085b4fcc9cd32b74b6f103608c54d7d8cd97b47c01de34f252ba3","names":[],"sources":[]}, - {"digest":"fa106c5b33b657e8ef16e8cbf39f3b7d44e5cbcdf4f9303d9db6410f28951e42","names":[],"sources":["packages/core/agent/src/types.ts:110"]}, {"digest":"fa87537f4a9c1e25602990a8bf686b383e9e00352ec8946e16ae24ba7c1625be","names":["packages/llm/llm/src/message.ts#AssistantMessage"],"sources":["packages/llm/llm/src/message.ts:167"]}, {"digest":"fab2bb09bc5e3b9db0685e8f5500b029af1a2b33e70bc703c1d5d0f596fbc1fd","names":["packages/sandbox/sandbox/src/index.ts#SandboxMode"],"sources":["packages/sandbox/sandbox/src/index.ts:30"]}, {"digest":"fab35c4520883c0d69e42d079c9f543fc5ac7a2d15b537b5572fcd99059c7018","names":[],"sources":[]}, {"digest":"fb5e0517050d2c6d40e5b8145db1f7c5ca7044d5d50fada6ff80e0b22c6ca973","names":[],"sources":[]}, {"digest":"fb8b6a2e53cb9cf44c551176de0fb77d1ddc60037b99a891ff8a860b6d5c29a0","names":[],"sources":[]}, {"digest":"fbd2c74b346a1595b376139c587fadd23e4a21acc9c0abce342975b6cfc60986","names":[],"sources":[]}, - {"digest":"fc2ae6962f9f8801c2b1e414668e1e17cbb7544c4f39381198977a38bd10c093","names":["packages/skill/tool-skill/src/index.ts#SkillCatalogSource"],"sources":["packages/skill/tool-skill/src/index.ts:35"]}, {"digest":"fc351843b8ecbd05d739c4ca4fcd4bc7cfad6c0beacbbd48389959bb1bf06cf3","names":[],"sources":[]}, {"digest":"fcf427290c6213c2a7feb57492d832ce324f5b9737a759f424dab69e6bd101a0","names":[],"sources":[]}, {"digest":"fcf81d3c58c13593bf2594e342e31734f4ab2d24938dc610875194c6079749c7","names":[],"sources":[]}, @@ -684,18 +692,16 @@ {"digest":"fee1caf8ab6a65c1bc981f5a1730164490f22a2a89ffa3d0b76f1f432c44c8b5","names":[],"sources":[]} ], "nodes": { - "00c054d3018c198d": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"a927d444c928ac0e","optional":false},{"name":"reasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"route","type":"07e1a58c58b593f5","optional":false},{"name":"system","type":"4cd48f3e5108bd6e","optional":false},{"name":"titleProvider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "0116b1f89c05221d": {"kind":"literal","value":"web_search_20250305"}, "0203243b72fc867a": {"kind":"object","properties":[{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, "022623b9ef98ec47": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, "023a355b2be0d688": {"kind":"object","properties":[{"name":"kind","type":"254dce209e735f9c","optional":false}],"indices":[]}, "02b2c23f2d94b028": {"kind":"object","properties":[{"name":"kind","type":"c5687b1313206a6f","optional":false}],"indices":[]}, "0341d4c3dfcd5325": {"kind":"literal","value":"product-interaction"}, - "040cd65423bd6426": {"kind":"union","types":["09f3f8dc417f2782","0f6265188dae7ba6","2cf075b013d363ad","4b259f7f8f0a44ad","fa87537f4a9c1e25"]}, + "05205074b24d8340": {"kind":"literal","value":"action-cards"}, "05a2796621b1ee6c": {"kind":"literal","value":"unknown"}, "05d2ae1e0c7f8770": {"kind":"union","types":["1571525adc95a24e","9e07693fd7cd9bab"]}, "0657d3ca5ac4e7bf": {"kind":"primitive","type":"number"}, - "0755b7d1128319ba": {"kind":"object","properties":[{"name":"data","type":"fa106c5b33b657e8","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"829a2fb3be6efd4b","optional":false}],"indices":[]}, "07e1a58c58b593f5": {"kind":"object","properties":[{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "07eccc9ea2f9b543": {"kind":"literal","value":"security-privacy-permission"}, "09655b34d7f3cf1e": {"kind":"literal","value":"system-prompt"}, @@ -717,7 +723,6 @@ "0ed8d1108fe7a5e1": {"kind":"object","properties":[{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, "0eeb17e1df89b1eb": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, "0f46153645c29784": {"kind":"object","properties":[{"name":"height","type":"0657d3ca5ac4e7bf","optional":false},{"name":"width","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, - "0f6265188dae7ba6": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"5bc2d7f02503fc6b","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.developer-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "0f8512903d94f57a": {"kind":"object","properties":[{"name":"data","type":"e481c46af3813e00","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"4312134fc6f9cad5","optional":false}],"indices":[]}, "0fe52387f6505270": {"kind":"literal","value":"plan-mode"}, "1033093edd0db80f": {"kind":"object","properties":[{"name":"data","type":"1ccb56061942f5cc","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"6ab45ac76839722d","optional":false}],"indices":[]}, @@ -728,6 +733,7 @@ "124aa62078ca3311": {"kind":"object","properties":[{"name":"data","type":"da60ed58a8fa23d7","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"d4c799e3d51cae10","optional":false}],"indices":[]}, "12a0cfa619ac4a5f": {"kind":"literal","value":"read-only"}, "12d5808fac1996b9": {"kind":"object","properties":[{"name":"attachment","type":"b0b0eb1b16490f6b","optional":false},{"name":"offloaded","type":"dacf3d5f3e4ff619","optional":true},{"name":"type","type":"fb8b6a2e53cb9cf4","optional":false}],"indices":[]}, + "12f9a5a7506bca46": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"cebb7e9f3f663e66","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "1379f0b72275994d": {"kind":"literal","value":"developer/message"}, "13d3d180f977bf78": {"kind":"object","properties":[{"name":"data","type":"1528539c63db8b23","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1a2718b00937b236","optional":false}],"indices":[]}, "14230f9b8b5797bb": {"kind":"literal","value":"chunk"}, @@ -794,11 +800,9 @@ "2aad1179f9576314": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "2ab12a0e345658f9": {"kind":"array","element":"83da72c6857601c7"}, "2abb711460e6238d": {"kind":"object","properties":[{"name":"index","type":"0657d3ca5ac4e7bf","optional":false},{"name":"text","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"6f091fe32ab24407","optional":false}],"indices":[]}, - "2ae8594a998c9862": {"kind":"object","properties":[{"name":"data","type":"2cf075b013d363ad","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"de25352d2dc41963","optional":false}],"indices":[]}, "2aed07493b1c65b6": {"kind":"literal","value":"tool/ptc-dispatch-start"}, "2c4c21f19f426a58": {"kind":"literal","value":"unavailable"}, "2c64d4bc7264fd3f": {"kind":"literal","value":"step/start"}, - "2cf075b013d363ad": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"5bc2d7f02503fc6b","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.user-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "2d11ca7b0d4493e2": {"kind":"object","properties":[{"name":"max_uses","type":"0657d3ca5ac4e7bf","optional":false},{"name":"name","type":"935c8d486292b13c","optional":false},{"name":"type","type":"0116b1f89c05221d","optional":false}],"indices":[]}, "2da725e554cd8930": {"kind":"literal","value":"fork"}, "2e3523541e942ef6": {"kind":"union","types":["18dc21f12bbac8ad","8e8e91646a5cae3f","e6063d0451dc0202","eea687d437880bd5"]}, @@ -810,6 +814,7 @@ "30d5a537b2966857": {"kind":"union","types":["1b5649238876e288","ada310bf0bdb8fed","b81e9de81a481b24"]}, "312aee2f0c42aabb": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "31907de956375182": {"kind":"object","properties":[{"name":"compactionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"6b23ed9ce1b397e6","optional":false},{"name":"sourceCommandId","type":"4cd48f3e5108bd6e","optional":true}],"indices":[]}, + "3247e566f4340029": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "326a9bfda27dda58": {"kind":"object","properties":[{"name":"maxTokens","type":"dacf3d5f3e4ff619","optional":true},{"name":"reasoningEffort","type":"dacf3d5f3e4ff619","optional":true}],"indices":[]}, "3305a4bb6b6c29b4": {"kind":"union","types":["0341d4c3dfcd5325","07eccc9ea2f9b543","5bd310104cfe448e","7180844e1066230c","9d80129e13edfb6f","e4cac694f8b6e1d5","f05fb85e715af4ab"]}, "33341aac09312300": {"kind":"union","types":["3860b4757d512a28","487b65c37bfedb8b","71bb3254ec8f1e49","e72269f931559e90"]}, @@ -826,6 +831,7 @@ "383cf73ae4748e5b": {"kind":"literal","value":"recall"}, "3860b4757d512a28": {"kind":"object","properties":[{"name":"args","type":"93c33d9687613293","optional":false},{"name":"dt","type":"5d03ba38734809bc","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"index","type":"0657d3ca5ac4e7bf","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":true},{"name":"time0","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"616f93a5047de668","optional":false}],"indices":[]}, "390eed1028aba027": {"kind":"union","types":["b1f62380f6746fed","df5d9709b7db2a72"]}, + "39adb7fce8475af6": {"kind":"object","properties":[{"name":"data","type":"8bca2b4f53ec7745","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"de25352d2dc41963","optional":false}],"indices":[]}, "39cf2d3ff8bac81c": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"rootCallId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "3b04790e08b35241": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, "3b1be838223869fe": {"kind":"object","properties":[{"name":"data","type":"e4c18e294232c3ba","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"c589e938cc0e4989","optional":false}],"indices":[]}, @@ -852,7 +858,7 @@ "44818000e56acb97": {"kind":"literal","value":"feedback/message-delete"}, "44c8c77aa9aa100b": {"kind":"literal","value":"subagent/catalog"}, "4513e088d43e6c68": {"kind":"object","properties":[{"name":"data","type":"ef11a3b7fa2033ae","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"2c64d4bc7264fd3f","optional":false}],"indices":[]}, - "454a0fa879e38076": {"kind":"array","element":"2cf075b013d363ad"}, + "45f005e6bbb76452": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "45f2a07ea9457312": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":true},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"reason","type":"4cd48f3e5108bd6e","optional":true},{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "477614bca595a9e7": {"kind":"object","properties":[{"name":"targets","type":"9e2c06d8653585b3","optional":false}],"indices":[]}, "47e5d84f1a93450a": {"kind":"literal","value":"session-log-deepseek/delivery-accepted"}, @@ -876,6 +882,7 @@ "4e97c3d85c0fc817": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"bf16d2e98a7f1389","optional":false},{"name":"senderSessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "4edec1b770e8ec4c": {"kind":"literal","value":"ptc-mode"}, "4f507598cf476214": {"kind":"literal","value":"series"}, + "4f9125fa028a5628": {"kind":"union","types":["09f3f8dc417f2782","4b259f7f8f0a44ad","8bca2b4f53ec7745","cebb7e9f3f663e66","fa87537f4a9c1e25"]}, "4f91f187baeabef5": {"kind":"object","properties":[{"name":"capturedFormatVersion","type":"0657d3ca5ac4e7bf","optional":true},{"name":"capturedThroughSeq","type":"3bd652ebfa8726b3","optional":false},{"name":"compacted","type":"aa93010d0e521ad7","optional":false},{"name":"inputIndex","type":"0657d3ca5ac4e7bf","optional":false},{"name":"label","type":"4cd48f3e5108bd6e","optional":false},{"name":"omittedBytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"omittedMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"originalMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"retainedMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"truncated","type":"aa93010d0e521ad7","optional":false}],"indices":[]}, "4fb59762612c3e3a": {"kind":"object","properties":[{"name":"data","type":"b1ebd5cda47d90d9","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"18fcdd273a2f2f9d","optional":false}],"indices":[]}, "50cf02d875f8a1f1": {"kind":"union","types":["2da725e554cd8930","dd2780e7e0768433"]}, @@ -906,7 +913,6 @@ "5b232a9b9bfcc0fc": {"kind":"literal","value":"after"}, "5b6fb1f226ff5640": {"kind":"object","properties":[{"name":"commandId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"1ab2ef1296f157ba","optional":false},{"name":"sourceEventSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"text","type":"4cd48f3e5108bd6e","optional":true}],"indices":[]}, "5bb69b88517f6214": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, - "5bc2d7f02503fc6b": {"kind":"union","types":["0203243b72fc867a","022623b9ef98ec47","02b2c23f2d94b028","0ed8d1108fe7a5e1","0eeb17e1df89b1eb","11638dc58a31496f","1938c8c20f1cba7c","1e709346005826eb","1fdad624334d3548","2152caf1a71e588e","2235d957bf4b7c6c","224aa11d4d5f88c4","24ce31aa528272e5","260523b412c19ad8","28936c614bd4e7e2","290f32bfd81ff85a","297fbd8067d7815a","2aad1179f9576314","312aee2f0c42aabb","31907de956375182","3b04790e08b35241","3b4f2c9ef2c1217e","3bdb8dc6989655b0","408927267422a7b2","4991dfc415c9efeb","49dab019d00e8c26","4a9bef9f27a94252","4e97c3d85c0fc817","52c6113cb0e53f34","53cf1704ae0709c7","5654685d7557ec74","58015da1c1950a66","5bb69b88517f6214","5bc66269cfaf614c","5cdbf342b7748d15","5d7a64ed6aac5551","6085488d223aeffd","6292bcbedaa97fea","65a8400e451e667e","672c4aa2a9b736e3","6ccb6bc423fb3952","6dacb1584f2bfbe2","6ea608bdc8a7a63d","6f22a9d02b9a1f11","6f44f32be9bcd9a8","719c51f67074f970","7554565be416b034","756b5e23a5cb2c7f","7df62978a2b7de85","7eaef7a763ba5b94","7f959241c24128b4","80677c8c8b804189","825ca23416b1ea9d","8338ee303e2bd448","854db3efdfb0cd39","85fe96bf15d5c755","8620189c8e335827","87b1a33564b9a4d6","88841202942c7683","8a046b52331959aa","8c1c4f72755a78ea","8c627d7a45fa406c","8f324cea3916c051","8fcb0b44a575e998","96bfb916a727cd44","99135d8a39379779","99f0e98184709ad1","9edc162949abf93b","9f65c43e340bba31","a15a19ef63cf5d1b","a16e567c8cd2c55c","a2066bd52f61218b","a3c6f1ea38e9a61d","aa2bf9e82b9fdeb9","aae343bc3d663c83","ada310bf0bdb8fed","ade057f4fdc387ae","b062078e899958f9","b2a5c8c008a31e3d","b3681c026a0b98e9","b4ec0af39fd52ed9","b6f94c17dd9bbd7c","b70f3e81fe11b7a5","b79641a9d25e7566","ba4c40b4381e0dcd","baccc97ec34be6c4","c5228b7a55498d84","c55827fba7018198","cb1c8959e1726f82","cda2345a9be9d139","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","deaae5cd30987d4f","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fc2ae6962f9f8801","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, "5bc66269cfaf614c": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, "5bd310104cfe448e": {"kind":"literal","value":"resource-cost"}, "5c45bf4c544a7211": {"kind":"object","properties":[{"name":"data","type":"8a9c990773f798ea","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"ae63d9d1080ed894","optional":false}],"indices":[]}, @@ -932,6 +938,7 @@ "6487b10ba7542f3c": {"kind":"object","properties":[{"name":"agentModel","type":"4cd48f3e5108bd6e","optional":true},{"name":"agentProvider","type":"4cd48f3e5108bd6e","optional":true},{"name":"agentReasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"label","type":"4cd48f3e5108bd6e","optional":false},{"name":"mode","type":"e5d3828df1ec3e2a","optional":false},{"name":"persona","type":"4cd48f3e5108bd6e","optional":true},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"toolFilter","type":"3cfc3a56502da1f8","optional":true},{"name":"version","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "6598cd6da253948d": {"kind":"object","properties":[{"name":"context","type":"50cf02d875f8a1f1","optional":false},{"name":"description","type":"4cd48f3e5108bd6e","optional":false},{"name":"error","type":"4cd48f3e5108bd6e","optional":true},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"phase","type":"dfce5db4aa42b7eb","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "65a8400e451e667e": {"kind":"object","properties":[{"name":"kind","type":"09655b34d7f3cf1e","optional":false}],"indices":[]}, + "65d583e66518c523": {"kind":"object","properties":[{"name":"entries","type":"aba175fb20ffc711","optional":false},{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"incomplete","type":"dacf3d5f3e4ff619","optional":true},{"name":"kind","type":"6ebcc2dbec9f2dab","optional":false},{"name":"update","type":"dacf3d5f3e4ff619","optional":true}],"indices":[]}, "66ba70f6f068da44": {"kind":"object","properties":[{"name":"deferLoading","type":"dacf3d5f3e4ff619","optional":true},{"name":"description","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"parameters","type":"0aa62ab51b36c0e6","optional":false}],"indices":[]}, "672c4aa2a9b736e3": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"1922cd79a70806c1","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "67d5f73ceae82f52": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":true},{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"reasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"stop","type":"93c33d9687613293","optional":true},{"name":"temperature","type":"0657d3ca5ac4e7bf","optional":true}],"indices":[]}, @@ -975,7 +982,6 @@ "76632533f67879dc": {"kind":"literal","value":"delegation"}, "78a9be340090b735": {"kind":"literal","value":"tmux-context"}, "79650cfa10aa3c52": {"kind":"object","properties":[{"name":"error","type":"5f2117d1856a5ab4","optional":false},{"name":"kind","type":"a2be0f0cb59f0d4a","optional":false}],"indices":[]}, - "79a4c87f8bfb4d6d": {"kind":"object","properties":[{"name":"data","type":"00c054d3018c198d","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"587bb11da730e06a","optional":false}],"indices":[]}, "79ddc907312f97cf": {"kind":"object","properties":[{"name":"todos","type":"4b7ddaf3710b88ff","optional":false}],"indices":[]}, "7a651f3b672c52fb": {"kind":"literal","value":"session/title"}, "7af85bf70d4eafce": {"kind":"object","properties":[{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, @@ -1023,6 +1029,7 @@ "8ad45ad053b4d89f": {"kind":"object","properties":[{"name":"decision","type":"4cd48f3e5108bd6e","optional":false},{"name":"durationMs","type":"0657d3ca5ac4e7bf","optional":false},{"name":"exitCode","type":"0657d3ca5ac4e7bf","optional":true},{"name":"handlerId","type":"4cd48f3e5108bd6e","optional":false},{"name":"point","type":"4cd48f3e5108bd6e","optional":false},{"name":"stderrSummary","type":"4cd48f3e5108bd6e","optional":true},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "8af841fc9b265ade": {"kind":"literal","value":"system"}, "8bb8c3751a6ce64b": {"kind":"object","properties":[{"name":"sessionFormatVersion","type":"0657d3ca5ac4e7bf","optional":true},{"name":"sessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"throughSeq","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "8bca2b4f53ec7745": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"b112459dcb068609","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.user-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "8c1c4f72755a78ea": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "8c627d7a45fa406c": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "8cdd3fdd295cee53": {"kind":"literal","value":"command/done"}, @@ -1043,11 +1050,12 @@ "94c56aeb1564ad73": {"kind":"literal","value":"in_progress"}, "95080295115fbd83": {"kind":"object","properties":[{"name":"index","type":"0657d3ca5ac4e7bf","optional":false},{"name":"text","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"5abab3a27fd27366","optional":false}],"indices":[]}, "95a3ffccbf3c8afc": {"kind":"literal","value":"owner"}, + "95acdbd066cf445d": {"kind":"object","properties":[{"name":"data","type":"12f9a5a7506bca46","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1379f0b72275994d","optional":false}],"indices":[]}, "95c0e88fcf0bafb2": {"kind":"literal","value":"assistant"}, "9645cf93769a6dfb": {"kind":"literal","value":"user-question-reply"}, "96bfb916a727cd44": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, "96f4a9c81fc0f940": {"kind":"union","types":["3e2ece4967cfebe9","62ecb62dc0fe1b5e"]}, - "97e0162f983c2745": {"kind":"object","properties":[{"name":"data","type":"f4ed4717b4c259e9","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1379f0b72275994d","optional":false}],"indices":[]}, + "9808c3d0f0a1be8f": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"d2b617d9dfcc4e0a","optional":false},{"name":"reasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"route","type":"07e1a58c58b593f5","optional":false},{"name":"system","type":"4cd48f3e5108bd6e","optional":false},{"name":"titleProvider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "9890113e97dd3541": {"kind":"object","properties":[{"name":"mode","type":"fab2bb09bc5e3b9d","optional":false},{"name":"source","type":"76632533f67879dc","optional":true}],"indices":[]}, "99135d8a39379779": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, "9947aa5938fe19a8": {"kind":"union","types":["576a2de8355eb098","a99ec0993c62c058"]}, @@ -1065,6 +1073,7 @@ "9e07693fd7cd9bab": {"kind":"literal","value":"ask"}, "9e2c06d8653585b3": {"kind":"array","element":"1cde1bedde79c5e8"}, "9e41386b3a0c9572": {"kind":"object","properties":[{"name":"end","type":"0657d3ca5ac4e7bf","optional":false},{"name":"start","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "9e8043098fb89db6": {"kind":"object","properties":[{"name":"data","type":"c433ef580a5b229b","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"829a2fb3be6efd4b","optional":false}],"indices":[]}, "9edc162949abf93b": {"kind":"object","properties":[{"name":"deliveryId","type":"4cd48f3e5108bd6e","optional":false},{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"db6c5246911d47a7","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"ruleId","type":"4cd48f3e5108bd6e","optional":false},{"name":"source","type":"4cd48f3e5108bd6e","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "9f65c43e340bba31": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, "a0a2e5c42e1c9294": {"kind":"object","properties":[{"name":"data","type":"2e3523541e942ef6","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"0e7b2a97f54f1afd","optional":false}],"indices":[]}, @@ -1092,7 +1101,6 @@ "a8a2b9011fc06786": {"kind":"literal","value":"team/message/delivered"}, "a9059a81430b3207": {"kind":"literal","value":"hooks-claude-code"}, "a926dc71814edd01": {"kind":"object","properties":[{"name":"everySeconds","type":"0657d3ca5ac4e7bf","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"e42b0f40b5d0b628","optional":false},{"name":"prompt","type":"4cd48f3e5108bd6e","optional":false},{"name":"scheduledAt","type":"4cd48f3e5108bd6e","optional":false},{"name":"title","type":"4cd48f3e5108bd6e","optional":true}],"indices":[]}, - "a927d444c928ac0e": {"kind":"array","element":"040cd65423bd6426"}, "a99ec0993c62c058": {"kind":"object","properties":[{"name":"compactionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"llmStreamCall","type":"dacf3d5f3e4ff619","optional":false},{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":true},{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"rawOutput","type":"b52f215a6cd69105","optional":false},{"name":"shadowedRange","type":"9e41386b3a0c9572","optional":false},{"name":"shadowedSeqs","type":"5d03ba38734809bc","optional":false},{"name":"shadowedTokenCount","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceCommandId","type":"4cd48f3e5108bd6e","optional":true},{"name":"summary","type":"b52f215a6cd69105","optional":false},{"name":"usage","type":"fec5442b9ee4122e","optional":true}],"indices":[]}, "a99f76fd149051c3": {"kind":"object","properties":[{"name":"content","type":"4cd48f3e5108bd6e","optional":false},{"name":"status","type":"fd0d91a1f9dd2efb","optional":false}],"indices":[]}, "aa0957eca50aeb28": {"kind":"object","properties":[{"name":"data","type":"f90eb4ab2d3897bc","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"0af3ecfb8c60d416","optional":false}],"indices":[]}, @@ -1100,6 +1108,7 @@ "aa7bc2817014ca6c": {"kind":"object","properties":[{"name":"item","type":"3d7d07060a7be779","optional":false},{"name":"sessionId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "aa93010d0e521ad7": {"kind":"primitive","type":"boolean"}, "aacda84a69739238": {"kind":"literal","value":"subagent"}, + "aada2771a250136c": {"kind":"array","element":"8bca2b4f53ec7745"}, "aae343bc3d663c83": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, "ab7ec5f9eb2c6dfa": {"kind":"object","properties":[{"name":"kind","type":"68141cbe3994a5ff","optional":false}],"indices":[]}, "aba175fb20ffc711": {"kind":"array","element":"83079c8a3f733ac3"}, @@ -1118,6 +1127,7 @@ "b0127044ab31a702": {"kind":"object","properties":[{"name":"data","type":"ca59530d1a4f3e19","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1986c2664009c991","optional":false}],"indices":[]}, "b062078e899958f9": {"kind":"object","properties":[{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, "b0b0eb1b16490f6b": {"kind":"object","properties":[{"name":"attachmentId","type":"4cd48f3e5108bd6e","optional":false},{"name":"bytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"height","type":"0657d3ca5ac4e7bf","optional":false},{"name":"mediaType","type":"2f1e6a7ebace43d7","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":true},{"name":"originalDimensions","type":"0f46153645c29784","optional":true},{"name":"width","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "b112459dcb068609": {"kind":"union","types":["0203243b72fc867a","022623b9ef98ec47","02b2c23f2d94b028","0ed8d1108fe7a5e1","0eeb17e1df89b1eb","11638dc58a31496f","1938c8c20f1cba7c","1e709346005826eb","1fdad624334d3548","2152caf1a71e588e","2235d957bf4b7c6c","224aa11d4d5f88c4","24ce31aa528272e5","260523b412c19ad8","28936c614bd4e7e2","290f32bfd81ff85a","297fbd8067d7815a","2aad1179f9576314","312aee2f0c42aabb","31907de956375182","3247e566f4340029","3b04790e08b35241","3b4f2c9ef2c1217e","3bdb8dc6989655b0","408927267422a7b2","45f005e6bbb76452","4991dfc415c9efeb","49dab019d00e8c26","4a9bef9f27a94252","4e97c3d85c0fc817","52c6113cb0e53f34","53cf1704ae0709c7","5654685d7557ec74","58015da1c1950a66","5bb69b88517f6214","5bc66269cfaf614c","5cdbf342b7748d15","5d7a64ed6aac5551","6085488d223aeffd","6292bcbedaa97fea","65a8400e451e667e","65d583e66518c523","672c4aa2a9b736e3","6ccb6bc423fb3952","6dacb1584f2bfbe2","6ea608bdc8a7a63d","6f22a9d02b9a1f11","6f44f32be9bcd9a8","719c51f67074f970","7554565be416b034","756b5e23a5cb2c7f","7df62978a2b7de85","7eaef7a763ba5b94","7f959241c24128b4","80677c8c8b804189","825ca23416b1ea9d","8338ee303e2bd448","854db3efdfb0cd39","85fe96bf15d5c755","8620189c8e335827","87b1a33564b9a4d6","88841202942c7683","8a046b52331959aa","8c1c4f72755a78ea","8c627d7a45fa406c","8f324cea3916c051","8fcb0b44a575e998","96bfb916a727cd44","99135d8a39379779","99f0e98184709ad1","9edc162949abf93b","9f65c43e340bba31","a15a19ef63cf5d1b","a16e567c8cd2c55c","a2066bd52f61218b","a3c6f1ea38e9a61d","aa2bf9e82b9fdeb9","aae343bc3d663c83","ada310bf0bdb8fed","ade057f4fdc387ae","b062078e899958f9","b2a5c8c008a31e3d","b3681c026a0b98e9","b4ec0af39fd52ed9","b613f83572fe2fbf","b6f94c17dd9bbd7c","b70f3e81fe11b7a5","b79641a9d25e7566","ba2a1a8f194b1bb2","ba4c40b4381e0dcd","baccc97ec34be6c4","c5228b7a55498d84","c55827fba7018198","cb1c8959e1726f82","cda2345a9be9d139","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd00cdccd0ba487b","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","dde0cdf9d426768b","deaae5cd30987d4f","e7f4cbb3a57f4cbd","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, "b158f3ff69237148": {"kind":"object","properties":[{"name":"contextWindow","type":"0657d3ca5ac4e7bf","optional":true},{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"systemPromptUpdate","type":"f311671e07bc7fa6","optional":true}],"indices":[]}, "b1664fa89f8eab49": {"kind":"array","element":"bbc5696e3f13c758"}, "b1ebd5cda47d90d9": {"kind":"object","properties":[{"name":"member","type":"6598cd6da253948d","optional":false},{"name":"teamId","type":"4cd48f3e5108bd6e","optional":false},{"name":"version","type":"a0f906856fc06f1c","optional":false}],"indices":[]}, @@ -1135,6 +1145,7 @@ "b56f6a885da3dc39": {"kind":"object","properties":[{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"source","type":"30d5a537b2966857","optional":false},{"name":"title","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "b57a2889408de36e": {"kind":"literal","value":"failed"}, "b57ae1b37e52bee0": {"kind":"literal","value":"team/task"}, + "b613f83572fe2fbf": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "b63b089a00b3b935": {"kind":"object","properties":[{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"17aae616ef020b8b","optional":false},{"name":"prompt","type":"4cd48f3e5108bd6e","optional":false},{"name":"scheduledAt","type":"4cd48f3e5108bd6e","optional":false},{"name":"title","type":"4cd48f3e5108bd6e","optional":true}],"indices":[]}, "b6896938660a1dfe": {"kind":"object","properties":[{"name":"childCreatedAt","type":"0657d3ca5ac4e7bf","optional":false},{"name":"childId","type":"4cd48f3e5108bd6e","optional":false},{"name":"label","type":"4cd48f3e5108bd6e","optional":true},{"name":"mode","type":"d28765f87d6b6ab4","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, "b6ef9c6210be8350": {"kind":"object","properties":[{"name":"kind","type":"1ebc6f9ff3aa9e3a","optional":false}],"indices":[]}, @@ -1150,6 +1161,7 @@ "b9305f0ea75ccd6a": {"kind":"literal","value":"hook/invoked"}, "b978cff734e62143": {"kind":"object","properties":[{"name":"data","type":"79ddc907312f97cf","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"af0750d32d97d47b","optional":false}],"indices":[]}, "b993441f8ce7d27b": {"kind":"tuple","elements":[{"type":"9a2a9029f8d7ede0","optional":false,"rest":false}]}, + "ba2a1a8f194b1bb2": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "ba4c40b4381e0dcd": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "ba77b58995e36f14": {"kind":"array","element":"07e1a58c58b593f5"}, "bab6865794007548": {"kind":"literal","value":"kill"}, @@ -1168,6 +1180,7 @@ "c219efbdfd53b836": {"kind":"literal","value":"step/end"}, "c2deb7c9183735d4": {"kind":"union","types":["1ebc6f9ff3aa9e3a","2142e391b9ccb60d","b57a2889408de36e"]}, "c2f49004d9ae38a9": {"kind":"union","types":["1ebc6f9ff3aa9e3a","b57a2889408de36e","ef226a90ddac6cd8"]}, + "c433ef580a5b229b": {"kind":"object","properties":[{"name":"inserted","type":"aada2771a250136c","optional":false},{"name":"outcome","type":"d4e4d575abeb4b72","optional":true},{"name":"removedCount","type":"0657d3ca5ac4e7bf","optional":true},{"name":"start","type":"0657d3ca5ac4e7bf","optional":false},{"name":"target","type":"96f4a9c81fc0f940","optional":false}],"indices":[]}, "c43b119ce579b3e9": {"kind":"literal","value":"paused"}, "c5228b7a55498d84": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "c55827fba7018198": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"9645cf93769a6dfb","optional":false},{"name":"outcome","type":"85d6d96ff8842974","optional":false}],"indices":[]}, @@ -1186,10 +1199,12 @@ "cda2345a9be9d139": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "cdca80b8dad24d4e": {"kind":"literal","value":"tool-workflow/run-start"}, "cdee10e87dbed844": {"kind":"object","properties":[{"name":"delayMs","type":"0657d3ca5ac4e7bf","optional":false},{"name":"failure","type":"5f2117d1856a5ab4","optional":false},{"name":"maxRetries","type":"0657d3ca5ac4e7bf","optional":false},{"name":"mode","type":"3bc287e765d58dc3","optional":false},{"name":"policyKey","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"retry","type":"0657d3ca5ac4e7bf","optional":false},{"name":"retryId","type":"4cd48f3e5108bd6e","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "cebb7e9f3f663e66": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"b112459dcb068609","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.developer-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "cef171adf021a186": {"kind":"object","properties":[{"name":"arguments","type":"bbc5696e3f13c758","optional":false},{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"error","type":"a81059ca06999da1","optional":true},{"name":"isError","type":"aa93010d0e521ad7","optional":false},{"name":"meta","type":"c592ce75aab73fca","optional":true},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"parentCallId","type":"4cd48f3e5108bd6e","optional":false},{"name":"rootCallId","type":"4cd48f3e5108bd6e","optional":false},{"name":"subCallId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "cffcdc19881ab61e": {"kind":"object","properties":[{"name":"cleared","type":"0b6d718c693fdf7f","optional":false},{"name":"clearedAt","type":"0657d3ca5ac4e7bf","optional":false},{"name":"kind","type":"237c004c73b6b288","optional":false},{"name":"operation","type":"e7e154d47d5fbc53","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, "d0fbb0ca1bbba059": {"kind":"literal","value":"delete"}, "d28765f87d6b6ab4": {"kind":"literal","value":"one-shot"}, + "d2b617d9dfcc4e0a": {"kind":"array","element":"4f9125fa028a5628"}, "d4b739491689cc6b": {"kind":"object","properties":[{"name":"block","type":"8064c03c87c357fd","optional":false},{"name":"index","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"eefbea819caeeea9","optional":false}],"indices":[]}, "d4c799e3d51cae10": {"kind":"literal","value":"working-directory/change"}, "d4e4d575abeb4b72": {"kind":"literal","value":"canceled"}, @@ -1208,9 +1223,11 @@ "db874d463b0fdec7": {"kind":"object","properties":[{"name":"data","type":"3e4e7683b0192c9f","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"e2d0367e5716bc18","optional":false}],"indices":[]}, "dba54c09c6e7aafc": {"kind":"object","properties":[{"name":"kind","type":"4edec1b770e8ec4c","optional":false}],"indices":[]}, "dbdafceb9a900183": {"kind":"literal","value":"hook"}, + "dd00cdccd0ba487b": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "dd2780e7e0768433": {"kind":"literal","value":"fresh"}, "dd5ee8762bd8a14b": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, "dd6cc2bb2a8f2824": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "dde0cdf9d426768b": {"kind":"object","properties":[{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "de25352d2dc41963": {"kind":"literal","value":"user/message"}, "de30b1fa12c75f81": {"kind":"literal","value":"image/gif"}, "deaae5cd30987d4f": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, @@ -1240,10 +1257,12 @@ "e7ce49f12953583f": {"kind":"literal","value":"initial"}, "e7e154d47d5fbc53": {"kind":"literal","value":"clear"}, "e7e8f1318170b828": {"kind":"literal","value":"deleted"}, + "e7f4cbb3a57f4cbd": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "e8de0f457fed5b9f": {"kind":"literal","value":"notice"}, "e95f957154b2b1b5": {"kind":"literal","value":"assistant/attempt"}, "ea08ec1df0c33108": {"kind":"object","properties":[{"name":"message","type":"2eafefdc6f79a492","optional":false},{"name":"teamId","type":"4cd48f3e5108bd6e","optional":false},{"name":"version","type":"a0f906856fc06f1c","optional":false}],"indices":[]}, "eaa71be0fbf0f702": {"kind":"object","properties":[{"name":"kind","type":"ad3b56aa2fc1ad42","optional":false}],"indices":[]}, + "eaa9125aec0fb284": {"kind":"object","properties":[{"name":"data","type":"9808c3d0f0a1be8f","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"587bb11da730e06a","optional":false}],"indices":[]}, "ebb768d85ec87fb6": {"kind":"literal","value":"image/webp"}, "ec38b5949af8eaca": {"kind":"object","properties":[{"name":"data","type":"2fe5026daf14bd4f","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"2aed07493b1c65b6","optional":false}],"indices":[]}, "ec8b5ff7c77ca689": {"kind":"object","properties":[{"name":"kind","type":"b2245a906e13aa94","optional":false}],"indices":[]}, @@ -1266,7 +1285,6 @@ "f2da0f27c1e6add5": {"kind":"object","properties":[{"name":"attachment","type":"f19bee84bf3d2090","optional":false},{"name":"type","type":"277b61f9c6f81704","optional":false}],"indices":[]}, "f311671e07bc7fa6": {"kind":"literal","value":"in-history"}, "f4a66f654996c093": {"kind":"object","properties":[{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, - "f4ed4717b4c259e9": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"0f6265188dae7ba6","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "f5520c1d261ca86e": {"kind":"object","properties":[{"name":"data","type":"e3056e0dda3a379e","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"24a8188c4d61b70a","optional":false}],"indices":[]}, "f56c5b59ca016131": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"7f13860ee89a2d35","optional":false},{"name":"references","type":"df843efd87c78cf8","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, "f6329fb30c7ea801": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, @@ -1282,14 +1300,12 @@ "f90eb4ab2d3897bc": {"kind":"object","properties":[{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "f97f47b0eb87905e": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, "f9cfc89e8fe085b4": {"kind":"literal","value":"text-chunks"}, - "fa106c5b33b657e8": {"kind":"object","properties":[{"name":"inserted","type":"454a0fa879e38076","optional":false},{"name":"outcome","type":"d4e4d575abeb4b72","optional":true},{"name":"removedCount","type":"0657d3ca5ac4e7bf","optional":true},{"name":"start","type":"0657d3ca5ac4e7bf","optional":false},{"name":"target","type":"96f4a9c81fc0f940","optional":false}],"indices":[]}, "fa87537f4a9c1e25": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"95c0e88fcf0bafb2","optional":false},{"name":"source","type":"719c51f67074f970","optional":false}],"indices":[]}, "fab2bb09bc5e3b9d": {"kind":"union","types":["12a0cfa619ac4a5f","18fce9540bb20897","a3edd1efd1fef21b"]}, "fab35c4520883c0d": {"kind":"literal","value":"rejected"}, "fb5e0517050d2c6d": {"kind":"literal","value":"tool/ptc-dispatch"}, "fb8b6a2e53cb9cf4": {"kind":"literal","value":"image"}, "fbd2c74b346a1595": {"kind":"literal","value":"agent-instructions"}, - "fc2ae6962f9f8801": {"kind":"object","properties":[{"name":"entries","type":"aba175fb20ffc711","optional":false},{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"6ebcc2dbec9f2dab","optional":false},{"name":"update","type":"dacf3d5f3e4ff619","optional":true}],"indices":[]}, "fc351843b8ecbd05": {"kind":"literal","value":"external"}, "fcf427290c6213c2": {"kind":"primitive","type":"never"}, "fcf81d3c58c13593": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, diff --git a/docs/subsystems/attachment.i18n.yaml b/docs/subsystems/attachment.i18n.yaml index 621444176d..856a932e75 100644 --- a/docs/subsystems/attachment.i18n.yaml +++ b/docs/subsystems/attachment.i18n.yaml @@ -6,8 +6,8 @@ en: 564dfcaaca384e23 zh: 5d215635919b5bc4 /durable-attachments/identity-and-verified-metadata: - en: 96378c208b220c6f - zh: 7af93f6a79520732 + en: 3e14f535f7587b0c + zh: cbbd513a5dff5fed /durable-attachments/commit-and-verified-read-payloads: - en: f79753272bb0ec70 - zh: 61830c41021f9274 + en: db2017cdf91e260a + zh: 6ba39bbc7cef4d8f diff --git a/docs/subsystems/attachment.md b/docs/subsystems/attachment.md index 2e330672f7..bccf3c33a3 100644 --- a/docs/subsystems/attachment.md +++ b/docs/subsystems/attachment.md @@ -58,7 +58,7 @@ interface ImageAttachmentLimits { The local backend admits at most 20 images and 200 MiB of encoded source data per message. One source may use up to 50 MiB, 64,000,000 pixels, and 65,535 pixels on either side. These source limits precede the independent normalization stage, which limits the long edge to 2048 pixels and encoded data to 4 MiB by default. -The reference records intrinsic dimensions and encoded length so clients can lay out history without decoding first, while every authoritative read still re-checks digest, media signature, dimensions, and metadata against the object. +The reference records intrinsic dimensions and encoded length so clients can lay out history without decoding first. Reads verify the stored object against the supplied reference's ID, format, byte length, width, and height. Optional display names and pre-normalization dimensions are returned unchanged as caller-supplied display information, without verification against stored bytes. ## Commit and verified-read payloads @@ -173,7 +173,7 @@ interface RequestImageAttachment { } ``` -`saveImage()` prepares and atomically commits a provider-independent normalized attachment before returning its `ImageAttachmentRef`. `saveImages()` prepares every validated attachment once before publishing the batch, so validation rejection leaves no partial objects and publication does not repeat decoding or quality selection. `admitPromptContent()` accepts the complete ordered Host prompt after upload receipt resolution, replaces base64 image uploads with durable references, passes durable file references and already stored images unchanged, and counts every image toward the per-message image count and aggregate byte limits, a stored image by the bytes of its upload. `admitEncodedImages()` supports other wire entries and delegates count, aggregate-byte, and ordered batch admission to `saveImages()`. `admitEncodedFile()` gives encoded protocol adapters the same service-owned canonical-base64 admission, and `isAttachmentError()` lets those adapters recognize stable attachment failures without importing implementation helpers. `readImage()` verifies a normalized attachment from an authorized session path. `imageHostPath()` exposes only the provider-owned host object location; it does not decide whether the current tool execution world can read it. `readImageRequest()` derives and caches one deterministic request version at an exact route-chosen target size and encoded-byte target. That version contains encoded bytes and metadata but no execution-world path. New entries are fully decoded before publication, while cache hits use a bounded metadata probe. Callers use `Promise.all` over the singular method when they need an ordered batch. The local implementation lazily encodes preferred candidates, singleflights equal request identities, lets each waiter cancel independently, stops shared work when no waiter remains, and bounds all transforms with its instance-level limiter, which defaults to two simultaneous transformations. The service is retention-neutral: resumed and forked sessions may share objects, so reference-aware garbage collection is deferred rather than tied to one session's deletion. +`saveImage()` prepares and atomically commits a provider-independent normalized attachment before returning its `ImageAttachmentRef`. `saveImages()` prepares every validated attachment once before publishing the batch, so validation rejection leaves no partial objects and publication does not repeat decoding or quality selection. `admitPromptContent()` accepts the complete ordered Host prompt after upload receipt resolution, replaces base64 image uploads with durable references, passes durable file references and already stored images unchanged, and counts every image toward the per-message image count and aggregate byte limits, a stored image by the bytes of its upload. `admitEncodedImages()` supports other wire entries and delegates count, aggregate-byte, and ordered batch admission to `saveImages()`. `admitEncodedFile()` gives encoded protocol adapters the same service-owned canonical-base64 admission, and `isAttachmentError()` lets those adapters recognize stable attachment failures without importing implementation helpers. `readImage()` verifies a normalized object against the supplied complete reference without consulting Session history, then returns that reference with the bytes. Access policy belongs to the calling API; Session Controller uses the store-level [image access rule](../../.agents/notes/implemented/architecture/2026-10-23-store-scoped-image-reads.md). `imageHostPath()` exposes only the provider-owned host object location; it does not decide whether the current tool execution world can read it. `readImageRequest()` derives and caches one deterministic request version at an exact route-chosen target size and encoded-byte target. That version contains encoded bytes and metadata but no execution-world path. New entries are fully decoded before publication, while cache hits use a bounded metadata probe. Callers use `Promise.all` over the singular method when they need an ordered batch. The local implementation lazily encodes preferred candidates, singleflights equal request identities, lets each waiter cancel independently, stops shared work when no waiter remains, and bounds all transforms with its instance-level limiter, which defaults to two simultaneous transformations. The service is retention-neutral: resumed and forked sessions may share objects, so reference-aware garbage collection is deferred rather than tied to one session's deletion. @@ -243,8 +243,8 @@ isAttachmentError(error: unknown): error is AttachmentError abstract saveImage(input: SaveImageAttachment): Promise /** - * Read one image and verify that bytes still match the recorded reference. - * @param ref - durable reference from the session log. + * Read one image and verify its ID, format, byte length, and dimensions against the supplied reference. + * @param ref - supplied image reference; name and originalDimensions are preserved without file verification. * @param signal - optional cancellation for backend read and verification work. * @returns the verified bytes and normalized attachment reference. * @throws the signal reason when aborted, or a storage error when verification fails. @@ -282,7 +282,7 @@ saveFileStream(input: SaveFileStreamAttachment): Promise * Read and verify one verbatim stored file as bounded chunks. Providers must * not collect the complete file in memory. Backends without verbatim file * reads keep this default rejection. - * @param ref - durable reference from the session log. + * @param ref - durable file reference from the session log. * @param signal - optional cancellation for backend reads and verification work. * @returns exact file bytes in order; integrity failures reject the iteration. */ diff --git a/docs/subsystems/attachment.zh.md b/docs/subsystems/attachment.zh.md index 057ed080f4..c917947b73 100644 --- a/docs/subsystems/attachment.zh.md +++ b/docs/subsystems/attachment.zh.md @@ -58,7 +58,7 @@ interface ImageAttachmentLimits { 本地后端每条消息最多准入 20 张图片,源图编码数据总量不超过 200 MiB。单张源图不得超过 50 MiB、64,000,000 像素和单边 65,535 像素。这些源文件限制先于独立的规范化阶段执行;该阶段默认把长边限制为 2048 像素,把编码数据限制为 4 MiB。 -引用记录固有尺寸和编码长度,使客户端无需先解码即可排布历史记录;每次权威读取仍会根据对象重新校验摘要、媒体签名、尺寸和元数据。 +引用记录固有尺寸和编码长度,使客户端无需先解码即可排布历史记录。读取会把存储对象与传入引用中的 ID、格式、字节数、宽度和高度比对。可选的显示名称和规范化前尺寸作为调用方提交的显示信息原样返回,不根据存储字节校验。 ## 提交与经校验读取的数据 @@ -173,7 +173,7 @@ interface RequestImageAttachment { } ``` -`saveImage()` 准备并原子提交提供方无关的规范化附件,然后直接返回 `ImageAttachmentRef`。`saveImages()` 在发布批次前为每个成员各准备一次经过验证的附件,因此校验拒绝不会留下部分对象,发布也不会重复解码或选择质量。`admitPromptContent()` 在上传凭证解析后接收完整且有序的 Host prompt,把 base64 图片上传替换为持久引用,让持久文件引用和已存储的图片原样通过,并把每张图片计入单条消息的图片数量与总字节上限,已存储的图片按其上传的字节数计入。`admitEncodedImages()` 支持其他 wire 入口,把张数、聚合字节和有序批量准入交给 `saveImages()`。`admitEncodedFile()` 让编码协议适配器使用服务拥有的规范 base64 准入,`isAttachmentError()` 让这些适配器无需导入实现辅助函数即可识别稳定的附件错误。`readImage()` 校验来自已授权会话路径的规范化附件。`imageHostPath()` 只公开提供方所持对象的宿主位置,不判断当前工具执行环境能否读取它。`readImageRequest()` 按确切的路由目标尺寸和编码字节目标派生并缓存确定性请求版本。该版本包含编码字节和元数据,不包含执行环境路径。新条目在发布前完整解码,缓存命中只做有界元数据探测。调用方需要有序批次时,对单数方法使用 `Promise.all`。本地实现按需编码首选候选、合并相同请求身份的并发任务、允许每个等待方单独取消、没有等待方时停止共享任务,并通过实例级限流器限制全部变换,默认同时执行两项。该服务不规定保留策略:恢复和 fork 后的会话可能共享对象,因此基于引用的垃圾回收会延期实现,不与单个会话的删除绑定。 +`saveImage()` 准备并原子提交提供方无关的规范化附件,然后直接返回 `ImageAttachmentRef`。`saveImages()` 在发布批次前为每个成员各准备一次经过验证的附件,因此校验拒绝不会留下部分对象,发布也不会重复解码或选择质量。`admitPromptContent()` 在上传凭证解析后接收完整且有序的 Host prompt,把 base64 图片上传替换为持久引用,让持久文件引用和已存储的图片原样通过,并把每张图片计入单条消息的图片数量与总字节上限,已存储的图片按其上传的字节数计入。`admitEncodedImages()` 支持其他 wire 入口,把张数、聚合字节和有序批量准入交给 `saveImages()`。`admitEncodedFile()` 让编码协议适配器使用服务拥有的规范 base64 准入,`isAttachmentError()` 让这些适配器无需导入实现辅助函数即可识别稳定的附件错误。`readImage()` 把规范化对象与传入的完整引用比对,无需查询 Session 历史,随后返回该引用与字节。访问规则由调用 API 负责;Session Controller 使用存储范围的[图片访问规则](../../.agents/notes/implemented/architecture/2026-10-23-store-scoped-image-reads.zh.md)。`imageHostPath()` 只公开提供方所持对象的宿主位置,不判断当前工具执行环境能否读取它。`readImageRequest()` 按确切的路由目标尺寸和编码字节目标派生并缓存确定性请求版本。该版本包含编码字节和元数据,不包含执行环境路径。新条目在发布前完整解码,缓存命中只做有界元数据探测。调用方需要有序批次时,对单数方法使用 `Promise.all`。本地实现按需编码首选候选、合并相同请求身份的并发任务、允许每个等待方单独取消、没有等待方时停止共享任务,并通过实例级限流器限制全部变换,默认同时执行两项。该服务不规定保留策略:恢复和 fork 后的会话可能共享对象,因此基于引用的垃圾回收会延期实现,不与单个会话的删除绑定。 @@ -243,8 +243,8 @@ isAttachmentError(error: unknown): error is AttachmentError abstract saveImage(input: SaveImageAttachment): Promise /** - * Read one image and verify that bytes still match the recorded reference. - * @param ref - durable reference from the session log. + * Read one image and verify its ID, format, byte length, and dimensions against the supplied reference. + * @param ref - supplied image reference; name and originalDimensions are preserved without file verification. * @param signal - optional cancellation for backend read and verification work. * @returns the verified bytes and normalized attachment reference. * @throws the signal reason when aborted, or a storage error when verification fails. @@ -282,7 +282,7 @@ saveFileStream(input: SaveFileStreamAttachment): Promise * Read and verify one verbatim stored file as bounded chunks. Providers must * not collect the complete file in memory. Backends without verbatim file * reads keep this default rejection. - * @param ref - durable reference from the session log. + * @param ref - durable file reference from the session log. * @param signal - optional cancellation for backend reads and verification work. * @returns exact file bytes in order; integrity failures reject the iteration. */ diff --git a/docs/subsystems/boot.i18n.yaml b/docs/subsystems/boot.i18n.yaml index 0d52b7d7e5..7754efcc03 100644 --- a/docs/subsystems/boot.i18n.yaml +++ b/docs/subsystems/boot.i18n.yaml @@ -6,8 +6,8 @@ en: 962b4398c9052959 zh: 14471c340a9f6e60 /profile-management/management-records: - en: 2def418f04e9fc10 - zh: af0bd1610bdc2f2b + en: 8813788cd8a86903 + zh: 3c30cb180fc1a33d /profile-management/market-records: en: 3dfc62d837d61b9b zh: ec223be315f3dc62 diff --git a/docs/subsystems/boot.md b/docs/subsystems/boot.md index ed9b5553c7..157ef5da64 100644 --- a/docs/subsystems/boot.md +++ b/docs/subsystems/boot.md @@ -10,7 +10,7 @@ The [boot package group](../../packages/boot/README.md) owns launcher-provided p `PluginInfo` carries module identity, effective enablement, fiber phase and optional display `meta`, plus a unique `patchId` or a `readOnlyReason`. -`BundleInfo.official` identifies project-maintained shipped optional bundles and on-demand catalog entries independently of installation. `availability` identifies a readable installation-provided or profile package, or `missing`; on-demand catalog entries exclude undeclared transitive copies. `installed` records the profile dependency declaration. An on-demand `installTarget` carries the host-derived exact spec and version. `BundleInfo` also carries the package name, optional installed version, selected enablement, removal availability, update eligibility (`updatable`), optional resolution error, and, for a bundle the profile's own dependency supplies and the installation does not, `source`: that dependency as a spec `pnpm add` accepts. Its optional `meta` and each `BundleRowInfo.meta` contain display text or a metadata diagnostic; Clients select a language at render time. +`BundleInfo.official` identifies project-maintained shipped optional bundles and on-demand catalog entries independently of installation. `availability` identifies a readable installation-provided or profile package, or `missing`; on-demand catalog entries exclude undeclared transitive copies. `installed` records the profile dependency declaration. An on-demand `installTarget` carries the host-derived exact spec and version. `BundleInfo` also carries the package name, optional installed version, selected enablement, removal availability, update eligibility (`updatable`), optional resolution or unsupported-platform error, and, for a bundle the profile's own dependency supplies and the installation does not, `source`: that dependency as a spec `pnpm add` accepts. Its optional `meta` and each `BundleRowInfo.meta` contain display text or a metadata diagnostic; Clients select a language at render time. `InstallBundleOptions.saveExact` passes `--save-exact` to the shared package installer. `InstallBundleOptions.enabled` defaults to true. False installs without selecting the bundle layer. `approvedBuilds` grants persistent script permission to the supplied pending package names before installation. `registry` names the registry asked first; absent, the configured one. @@ -69,6 +69,53 @@ interface PendingModule { Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md). + + +### `ctx.actionCards` — `ActionCards` + +Card tool, kind registry, Session projection, user actions and status notices. + +```ts cordis-catalog +/** + * Register one action kind for the caller's lifetime. + * @param kind - the kind's skill, details schema, verbs and handler. + * @returns disposer removing the kind; actions on its cards are then unavailable. + * @throws when another kind already registered the same action. + */ +register
(kind: ActionCardKind
): () => void + +/** + * Record a card decision in the Session log; the next model request reports it. + * @param agent - agent whose Session owns the card. + * @param decision - the card's new state. + * @throws when no kind ever registered the decision's action with this service, or its phase is one the projection derives. + */ +record(agent: Agent, decision: ActionCardDecision): void + +/** + * Read the cards of one Session. + * @param session - a Session whose projections are prepared. + * @returns proposals and decisions by call id. + */ +view(session: Session): ActionCardView + +/** + * Apply a user action to a logged card. Shared checks run first, then the kind reconciles the card; `dismiss` is + * recorded here and every other verb goes to the card's kind. `dismiss` also works on an unstarted card whose kind + * is no longer registered. Concurrent actions on one card share one operation. + * @param agent - live root resolved from the displayed Session. + * @param callId - the card's `propose_action` call id. + * @param verb - `dismiss` or one of the kind's verbs. + * @param payload - kind-defined fields such as a chosen location. + * @returns acceptance of background work, the decision in effect, or a refusal. + */ +@Remote act(agent: Agent, callId: ToolCallId, verb: string, payload?: Record): Promise +``` + +Types: [Agent](core.md) · [Session](session.md) · [ToolCallId](core.md) + +Source: [`packages/experimental/action-cards/src/index.ts`](../../packages/experimental/action-cards/src/index.ts) + ### `ctx.configEditor` — `ConfigEditor` @@ -355,6 +402,26 @@ async entry(url: string, name: string): Promise Source: [`packages/boot/plugin-market/src/index.ts`](../../packages/boot/plugin-market/src/index.ts) + + +### `ctx.pluginRecommendations` — `PluginRecommendations` + +Catalog lookups for card text and the enabling behind the `enable_official_plugin` card. + +```ts cordis-catalog +/** + * Read the current catalog text for a logged card. + * @param agent - Exact live root resolved by the Gateway from the Session id. + * @param callId - The card's `propose_action` call id, never a package supplied by the browser. + * @returns the plugin's title, description and selection, or a refusal when the card names no available official plugin. + */ +@Remote async describe(agent: Agent, callId: ToolCallId): Promise +``` + +Types: [Agent](core.md) · [ToolCallId](core.md) + +Source: [`packages/experimental/plugin-recommendations/src/index.ts`](../../packages/experimental/plugin-recommendations/src/index.ts) + ### `ctx.pluginRegistryProbe` — `PluginRegistryProbe` @@ -496,6 +563,23 @@ An installation moved between its Host phases. `installing` is announced once pe Source: [`packages/boot/plugin-manager/src/types.ts`](../../packages/boot/plugin-manager/src/types.ts) + + +#### `plugin-manager/operation` — parallel + +One manager invocation started or ended; subscribers run independently without delaying management. + +```ts cordis-catalog +/** + * One manager invocation started or ended; subscribers run independently without delaying management. + * @mode parallel + * @param operation - Correlated operation facts; a start without an end has an unknown outcome. + */ +'plugin-manager/operation'(operation: PluginOperation): void | Promise +``` + +Source: [`packages/boot/plugin-manager/src/types.ts`](../../packages/boot/plugin-manager/src/types.ts) + #### `plugin-manager/update-state` — emit diff --git a/docs/subsystems/boot.zh.md b/docs/subsystems/boot.zh.md index ee14d22335..1e5f78cf0e 100644 --- a/docs/subsystems/boot.zh.md +++ b/docs/subsystems/boot.zh.md @@ -10,7 +10,7 @@ `PluginInfo` 包含模块标识、实际启停状态、fiber 阶段和可选的展示 `meta`,以及唯一的 `patchId` 或 `readOnlyReason`。 -`BundleInfo.official` 标识项目维护的随附可选组合包和按需目录项,独立于安装状态。`availability` 表示可读取的安装随附包、profile 包或 `missing`;按需目录项不计入未声明的传递依赖副本。`installed` 记录 profile 的依赖声明。按需条目的 `installTarget` 包含 Host 生成的精确 spec 和版本。`BundleInfo` 还包含包名、可选的安装版本、组合层选择状态、删除可用性、更新资格(`updatable`)、可选的解析错误;由 profile 自身依赖提供、且安装不提供的组合包还带有 `source`,即该依赖在 `pnpm add` 中可用的 spec。它的可选 `meta` 与各行的 `BundleRowInfo.meta` 包含展示文本或元信息诊断;Client 在渲染时选择语言。 +`BundleInfo.official` 标识项目维护的随附可选组合包和按需目录项,独立于安装状态。`availability` 表示可读取的安装随附包、profile 包或 `missing`;按需目录项不计入未声明的传递依赖副本。`installed` 记录 profile 的依赖声明。按需条目的 `installTarget` 包含 Host 生成的精确 spec 和版本。`BundleInfo` 还包含包名、可选的安装版本、组合层选择状态、删除可用性、更新资格(`updatable`)、可选的解析错误或平台不支持错误;由 profile 自身依赖提供、且安装不提供的组合包还带有 `source`,即该依赖在 `pnpm add` 中可用的 spec。它的可选 `meta` 与各行的 `BundleRowInfo.meta` 包含展示文本或元信息诊断;Client 在渲染时选择语言。 `InstallBundleOptions.saveExact` 向共享包安装器传入 `--save-exact`。`InstallBundleOptions.enabled` 默认为 true,false 表示安装但不选择组合包层。`approvedBuilds` 在安装前向指定的待审批包名授予持久脚本权限。`registry` 指定首先询问的注册表;缺省为配置的那个。 @@ -69,6 +69,53 @@ interface PendingModule { Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.zh.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md). + + +### `ctx.actionCards` — `ActionCards` + +Card tool, kind registry, Session projection, user actions and status notices. + +```ts cordis-catalog +/** + * Register one action kind for the caller's lifetime. + * @param kind - the kind's skill, details schema, verbs and handler. + * @returns disposer removing the kind; actions on its cards are then unavailable. + * @throws when another kind already registered the same action. + */ +register
(kind: ActionCardKind
): () => void + +/** + * Record a card decision in the Session log; the next model request reports it. + * @param agent - agent whose Session owns the card. + * @param decision - the card's new state. + * @throws when no kind ever registered the decision's action with this service, or its phase is one the projection derives. + */ +record(agent: Agent, decision: ActionCardDecision): void + +/** + * Read the cards of one Session. + * @param session - a Session whose projections are prepared. + * @returns proposals and decisions by call id. + */ +view(session: Session): ActionCardView + +/** + * Apply a user action to a logged card. Shared checks run first, then the kind reconciles the card; `dismiss` is + * recorded here and every other verb goes to the card's kind. `dismiss` also works on an unstarted card whose kind + * is no longer registered. Concurrent actions on one card share one operation. + * @param agent - live root resolved from the displayed Session. + * @param callId - the card's `propose_action` call id. + * @param verb - `dismiss` or one of the kind's verbs. + * @param payload - kind-defined fields such as a chosen location. + * @returns acceptance of background work, the decision in effect, or a refusal. + */ +@Remote act(agent: Agent, callId: ToolCallId, verb: string, payload?: Record): Promise +``` + +Types: [Agent](core.zh.md) · [Session](session.zh.md) · [ToolCallId](core.zh.md) + +Source: [`packages/experimental/action-cards/src/index.ts`](../../packages/experimental/action-cards/src/index.ts) + ### `ctx.configEditor` — `ConfigEditor` @@ -355,6 +402,26 @@ async entry(url: string, name: string): Promise Source: [`packages/boot/plugin-market/src/index.ts`](../../packages/boot/plugin-market/src/index.ts) + + +### `ctx.pluginRecommendations` — `PluginRecommendations` + +Catalog lookups for card text and the enabling behind the `enable_official_plugin` card. + +```ts cordis-catalog +/** + * Read the current catalog text for a logged card. + * @param agent - Exact live root resolved by the Gateway from the Session id. + * @param callId - The card's `propose_action` call id, never a package supplied by the browser. + * @returns the plugin's title, description and selection, or a refusal when the card names no available official plugin. + */ +@Remote async describe(agent: Agent, callId: ToolCallId): Promise +``` + +Types: [Agent](core.zh.md) · [ToolCallId](core.zh.md) + +Source: [`packages/experimental/plugin-recommendations/src/index.ts`](../../packages/experimental/plugin-recommendations/src/index.ts) + ### `ctx.pluginRegistryProbe` — `PluginRegistryProbe` @@ -496,6 +563,23 @@ An installation moved between its Host phases. `installing` is announced once pe Source: [`packages/boot/plugin-manager/src/types.ts`](../../packages/boot/plugin-manager/src/types.ts) + + +#### `plugin-manager/operation` — parallel + +One manager invocation started or ended; subscribers run independently without delaying management. + +```ts cordis-catalog +/** + * One manager invocation started or ended; subscribers run independently without delaying management. + * @mode parallel + * @param operation - Correlated operation facts; a start without an end has an unknown outcome. + */ +'plugin-manager/operation'(operation: PluginOperation): void | Promise +``` + +Source: [`packages/boot/plugin-manager/src/types.ts`](../../packages/boot/plugin-manager/src/types.ts) + #### `plugin-manager/update-state` — emit diff --git a/docs/subsystems/computer-use.i18n.yaml b/docs/subsystems/computer-use.i18n.yaml index fc82ebf720..54d4801a17 100644 --- a/docs/subsystems/computer-use.i18n.yaml +++ b/docs/subsystems/computer-use.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/computer-use.md /computer-use: - en: aff84e3ac8c41594 - zh: bee7fc09854bfa8b + en: e78e111e0debc21b + zh: 0d218fa34c63cc32 /computer-use/choose-a-provider: en: fa2e0d7b41c0450b zh: af9a799711f901e6 diff --git a/docs/subsystems/computer-use.md b/docs/subsystems/computer-use.md index bc8f1b0491..957990b09c 100644 --- a/docs/subsystems/computer-use.md +++ b/docs/subsystems/computer-use.md @@ -12,7 +12,7 @@ The CUA provider owns `ctx.cuaAccess` for system-permission status, explicit sys | Permission type | Meaning | |---|---| -| `CuaApplicationId`, `CuaApplicationGrant` | An executable/signature identity and its displayed saved decision. | +| `CuaApplicationId`, `CuaApplicationGrant` | A platform-provided application identity and its displayed saved decision. | | `CuaSystemPermission` | Accessibility or Screen Recording, selected by the human. | | `CuaPermissionProcess`, `CuaSystemPermissionState` | Native privilege checks, observed helper/parent processes, and the application identified by macOS process responsibility at helper startup. Application metadata is absent if the optional system query or application lookup is unavailable. | | `CuaApplicationState` | Saved grants, refused applications, and whether persistence is available. Session-only grants remain internal to the provider. System observations and application icons are queried separately so the page can display each result as it arrives. | @@ -85,10 +85,10 @@ Browser controls for provider-owned native permission and application decisions. @Remote async enablePersistentPtc(): Promise /** - * Read application decisions without waiting for the native helper. - * @returns Saved grants and refused applications with their persistence owner. + * Read fresh stored application decisions without issuing a native request. + * @returns Saved grants, refused applications and durable-storage availability. */ -@Remote applications(): CuaApplicationState +@Remote applications(): Promise /** * Inspect system privileges independently of application decisions and icons. @@ -98,7 +98,7 @@ Browser controls for provider-owned native permission and application decisions. /** * Load presentation icons separately from application decisions. - * @returns Optional native PNG icons keyed by executable path for saved and blocked applications. + * @returns Optional native PNG icons keyed by executable path; applications without paths are skipped. */ @Remote async applicationIcons(): Promise> diff --git a/docs/subsystems/computer-use.zh.md b/docs/subsystems/computer-use.zh.md index 1323c6b033..30d6f91ae1 100644 --- a/docs/subsystems/computer-use.zh.md +++ b/docs/subsystems/computer-use.zh.md @@ -12,7 +12,7 @@ CUA provider 通过 `ctx.cuaAccess` 提供系统权限状态、用户主动申 | 权限类型 | 含义 | |---|---| -| `CuaApplicationId`、`CuaApplicationGrant` | 可执行文件和签名身份,以及显示给用户的已保存决定。 | +| `CuaApplicationId`、`CuaApplicationGrant` | 平台提供的应用身份,以及显示给用户的已保存决定。 | | `CuaSystemPermission` | 用户选择申请的辅助功能或屏幕录制权限。 | | `CuaPermissionProcess`、`CuaSystemPermissionState` | 观测到的 helper、父进程和原生权限状态,以及 helper 启动时由 macOS 责任进程记录识别出的应用。可选系统查询或应用查找不可用时,省略应用信息。 | | `CuaApplicationState` | 持久授权、拒绝记录,以及能否持久保存。会话授权只保留在 provider 内部。系统权限和应用图标分别查询,页面在各项结果返回后分别显示。 | @@ -85,10 +85,10 @@ Browser controls for provider-owned native permission and application decisions. @Remote async enablePersistentPtc(): Promise /** - * Read application decisions without waiting for the native helper. - * @returns Saved grants and refused applications with their persistence owner. + * Read fresh stored application decisions without issuing a native request. + * @returns Saved grants, refused applications and durable-storage availability. */ -@Remote applications(): CuaApplicationState +@Remote applications(): Promise /** * Inspect system privileges independently of application decisions and icons. @@ -98,7 +98,7 @@ Browser controls for provider-owned native permission and application decisions. /** * Load presentation icons separately from application decisions. - * @returns Optional native PNG icons keyed by executable path for saved and blocked applications. + * @returns Optional native PNG icons keyed by executable path; applications without paths are skipped. */ @Remote async applicationIcons(): Promise> diff --git a/docs/subsystems/persistence.md b/docs/subsystems/persistence.md index 8f35e17f05..2c2dedab48 100644 --- a/docs/subsystems/persistence.md +++ b/docs/subsystems/persistence.md @@ -156,7 +156,11 @@ interface SessionHeader { readonly createdAt: number /** Absolute working directory the session was created in (if any). */ readonly cwd?: string - /** The session this one was forked from (seed lineage), if any. */ + /** + * Direct creator of a subagent Session. Ordinary forks omit this field; + * historical ordinary forks may retain their source id here. Presence alone + * does not classify a Session as a subagent; use `origin` for that distinction. + */ readonly parentSession?: SessionId /** * Whether this Session contains a fork-inherited event prefix. The exact prefix diff --git a/docs/subsystems/persistence.zh.md b/docs/subsystems/persistence.zh.md index c88b884fdb..aeec8c81c0 100644 --- a/docs/subsystems/persistence.zh.md +++ b/docs/subsystems/persistence.zh.md @@ -156,7 +156,11 @@ interface SessionHeader { readonly createdAt: number /** Absolute working directory the session was created in (if any). */ readonly cwd?: string - /** The session this one was forked from (seed lineage), if any. */ + /** + * Direct creator of a subagent Session. Ordinary forks omit this field; + * historical ordinary forks may retain their source id here. Presence alone + * does not classify a Session as a subagent; use `origin` for that distinction. + */ readonly parentSession?: SessionId /** * Whether this Session contains a fork-inherited event prefix. The exact prefix diff --git a/docs/subsystems/ptc-runtime.i18n.yaml b/docs/subsystems/ptc-runtime.i18n.yaml index 7c6f634157..b9a617739e 100644 --- a/docs/subsystems/ptc-runtime.i18n.yaml +++ b/docs/subsystems/ptc-runtime.i18n.yaml @@ -6,8 +6,8 @@ en: 337a6580d7571274 zh: f4ae98899120d122 /ptc-runtime/the-run-request-in-result-out: - en: 0305ed1d4f8bc618 - zh: fcfeb156574b5779 + en: 6dfa7da8b13a4f17 + zh: 09a3c8c4922239ef /ptc-runtime/bindings-host-functions-as-program-globals: en: 182147ddf388c600 zh: c0a7d77602c78bcd diff --git a/docs/subsystems/ptc-runtime.md b/docs/subsystems/ptc-runtime.md index d9ad8138a0..b1820bc264 100644 --- a/docs/subsystems/ptc-runtime.md +++ b/docs/subsystems/ptc-runtime.md @@ -19,9 +19,11 @@ interface PtcRunRequest { /** * The program source, in the runtime's {@link ../index.ts | language}. It * follows the provider's programFormat: an async function body supports - * top-level `await` and `return`; a REPL supports top-level declarations, - * `await`, and a final expression. The completion value becomes - * {@link PtcRunResult.value}. + * top-level `await` and `return`; REPL and Script programs support top-level + * declarations, `await`, and a final expression, but not top-level `return`. + * The Script provider lowers top-level await; its executionInstructions and + * documentation define retained-binding semantics. The completion value + * becomes {@link PtcRunResult.value}. */ program: string /** @@ -84,7 +86,7 @@ interface PtcRunResult { /** Applied file policy and observed denial, when the provider enforces file policy. */ sandbox?: PtcRunSandbox /** - * The program's completion value (a return or final REPL expression), when it ran to + * The program's completion value (a return or final REPL/Script expression), when it ran to * completion and the value crossed the runtime's lossless-JSON boundary. * Invalid or over-limit completions fail the run instead of substituting a * rendered string; a failed or value-less run leaves this absent. @@ -101,7 +103,12 @@ interface PtcRunResult { } ``` -`programFormat` distinguishes async function bodies from REPL statements. `stateOwner` is an in-process object identity for optional retained memory; distinct objects remain isolated. Consumers await `release(owner)` when that owner ends; cleanup failures reject that call. Omitted owners are one-shot, and stateless providers ignore ownership. The [persistent Node provider](../../packages/ptc-runtime/ptc-runtime-node/README.md#persistent-repl) defines reset and recovery behavior; no retained object enters the durable Session format. +```ts type-equiv +/** Source evaluation form, independent of retained program state. */ +type PtcProgramFormat = 'function-body' | 'repl' | 'script' +``` + +`programFormat` distinguishes async function bodies, REPL statements, and scripts. REPL and Script programs accept top-level `await`, declarations, and a final expression; top-level `return` is not supported. The Node Script provider lowers top-level await and awaits the completion value; its [declaration limitations](../../packages/ptc-runtime/ptc-runtime-node/README.md#known-limitations-and-deferred-work) apply to transformed programs. `retainsState` reports memory retention independently of source syntax. `stateOwner` is an in-process object identity for optional retained memory; distinct objects remain isolated. Consumers await `release(owner)` when that owner ends; cleanup failures reject that call. Omitted owners are one-shot, and stateless providers ignore ownership. The [persistent Node provider](../../packages/ptc-runtime/ptc-runtime-node/README.md#persistent-repl) defines reset and recovery behavior; no retained object enters the durable Session format. ## Bindings: host functions as program globals diff --git a/docs/subsystems/ptc-runtime.zh.md b/docs/subsystems/ptc-runtime.zh.md index ba747b5369..9aee80d258 100644 --- a/docs/subsystems/ptc-runtime.zh.md +++ b/docs/subsystems/ptc-runtime.zh.md @@ -19,9 +19,11 @@ interface PtcRunRequest { /** * The program source, in the runtime's {@link ../index.ts | language}. It * follows the provider's programFormat: an async function body supports - * top-level `await` and `return`; a REPL supports top-level declarations, - * `await`, and a final expression. The completion value becomes - * {@link PtcRunResult.value}. + * top-level `await` and `return`; REPL and Script programs support top-level + * declarations, `await`, and a final expression, but not top-level `return`. + * The Script provider lowers top-level await; its executionInstructions and + * documentation define retained-binding semantics. The completion value + * becomes {@link PtcRunResult.value}. */ program: string /** @@ -84,7 +86,7 @@ interface PtcRunResult { /** Applied file policy and observed denial, when the provider enforces file policy. */ sandbox?: PtcRunSandbox /** - * The program's completion value (a return or final REPL expression), when it ran to + * The program's completion value (a return or final REPL/Script expression), when it ran to * completion and the value crossed the runtime's lossless-JSON boundary. * Invalid or over-limit completions fail the run instead of substituting a * rendered string; a failed or value-less run leaves this absent. @@ -101,7 +103,12 @@ interface PtcRunResult { } ``` -`programFormat` 区分异步函数体与 REPL 语句。`stateOwner` 是标识可选保留内存的进程内对象身份;不同对象相互隔离。消费者在所有者结束时等待 `release(owner)`;清理失败时该调用拒绝。省略所有者时仅执行一次,无状态提供方忽略所有权。[持久 Node 提供方](../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#persistent-repl)定义重置和恢复行为;保留对象不会进入持久 Session 格式。 +```ts type-equiv +/** Source evaluation form, independent of retained program state. */ +type PtcProgramFormat = 'function-body' | 'repl' | 'script' +``` + +`programFormat` 区分异步函数体、REPL 语句与脚本。REPL 与 Script 程序接受顶层 `await`、声明和末尾表达式,不支持顶层 `return`。Node Script 提供方转换顶层 await 并等待完成值;其[声明限制](../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#known-limitations-and-deferred-work)适用于转换后的程序。`retainsState` 独立于源码语法报告是否保留内存。`stateOwner` 是标识可选保留内存的进程内对象身份;不同对象相互隔离。消费者在所有者结束时等待 `release(owner)`;清理失败时该调用拒绝。省略所有者时仅执行一次,无状态提供方忽略所有权。[持久 Node 提供方](../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#persistent-repl)定义重置和恢复行为;保留对象不会进入持久 Session 格式。 ## 绑定:宿主函数作为程序全局变量 diff --git a/docs/subsystems/schedule.i18n.yaml b/docs/subsystems/schedule.i18n.yaml index a6e7893cf3..63354f0fd0 100644 --- a/docs/subsystems/schedule.i18n.yaml +++ b/docs/subsystems/schedule.i18n.yaml @@ -27,8 +27,8 @@ en: 93798ad69f74ddd5 zh: 634126ad8accc356 /host-wide-schedule/web-catalog: - en: b5e5ac8125e65f33 - zh: 9ee064d833a4f838 + en: 3377a013bf8cbfb7 + zh: c5666dc3f28b087f /host-wide-schedule/timing-edits: en: ce5d2095a3ad2e82 zh: 167b3715f8eaffc1 diff --git a/docs/subsystems/schedule.md b/docs/subsystems/schedule.md index ef24673f9b..13f1752a31 100644 --- a/docs/subsystems/schedule.md +++ b/docs/subsystems/schedule.md @@ -309,6 +309,14 @@ type ScheduleDeleteResult = | { readonly id: ScheduleId; readonly deleted: false; readonly code: 'schedule_not_found' } ``` +```ts type-equiv +/** Successful Host-wide removal of every ended task, whether or not any remained. */ +interface ScheduleDeleteInactiveResult { + /** Ended task rows this call removed; zero when the Host held none. */ + readonly deleted: number +} +``` + ## Web catalog The Remote `schedule.catalog()` method returns active and inactive Host tasks with their original Session bindings, ordered by `scheduledAt` ascending and then lexicographically by `id`. It reads only the Schedule domain, without activating Sessions or reading their history. Browser consumers receive this browser-safe type: @@ -337,7 +345,7 @@ type ScheduleCatalogEntry = ScheduleRecord & { } ``` -The Remote `schedule.list({ sessionId })`, model `schedule_list`, and Session-header catalog return only active tasks. A model view's derived timing `state` remains distinct from stored lifecycle `status`. Deletion uses `schedule.delete({ sessionId, id })` with the entry's original binding; a mismatched binding returns not found. Model tools supply the current Agent's Session, whereas the global user interface supplies the selected task's binding. The binding check alone does not establish caller authorization. The payload-free `schedule/changed` event invalidates client lists; reconnecting clients fetch current state again. +The Remote `schedule.list({ sessionId })`, model `schedule_list`, and Session-header catalog return only active tasks. A model view's derived timing `state` remains distinct from stored lifecycle `status`. Deletion uses `schedule.delete({ sessionId, id })` with the entry's original binding; a mismatched binding returns not found. Model tools supply the current Agent's Session, whereas the global user interface supplies the selected task's binding. The binding check alone does not establish caller authorization. `schedule.deleteInactive()` removes every ended (inactive) task across Sessions, with the saved delivery records each row carries; on success it answers `{ deleted }` with the count it removed; a normal failed batch rejects with nothing removed; an `unknown-state` failure may have removed rows and quarantines the Host schedule domain, so later schedule operations reject until it is reopened. Any rejection announces `schedule/changed`, and clients then re-read. The Automation tasks page's bulk cleanup uses it. An ended task never arms a timer, so the removal recomputes no target. The payload-free `schedule/changed` event invalidates client lists; reconnecting clients fetch current state again. The shipped Web composition mounts `ui-schedule` with the Host capability. The [client package](../../packages/client/ui-schedule/README.md) owns the catalog, empty state, and deletion controls. The page separately filters all, active, and inactive tasks, retains inactive details and an original-Session control in the detail tab strip, and requires explicit confirmed deletion. The Rules and Records tabs separate task settings from lazily paged saved receipts. Neither a receipt nor inactive status confirms model execution. @@ -508,6 +516,22 @@ async create(sessionId: SessionId, request: ScheduleCreateRequest, signal?: Abor */ @Remote('delete') async delete(request: ScheduleDeleteRequest, signal?: AbortSignal): Promise +/** + * Delete every ended Host task, leaving active tasks armed. + * + * Ended tasks never schedule another delivery, so the removal changes no pending + * target and no timer is recomputed. Rows are enumerated and removed in one FIFO + * slot, so a delivery ordered behind this call ends its task after the + * enumeration rather than during it. The batch is one domain write: a normal + * failure rejects with every listed row still stored, while a backend + * `unknown-state` failure may have removed rows and quarantines the Host + * domain, so later schedule operations reject until the domain is reopened. + * Every rejection announces `schedule/changed` because it does not establish + * which rows landed, and clients then re-read the catalog. + * @returns Count of removed rows; zero when the Host held no ended task. + */ +@Remote('deleteInactive') async deleteInactive(): Promise + /** * Update the name, instruction, and timing of an active task within the original Session * binding without activating the Session or changing saved deliveries. diff --git a/docs/subsystems/schedule.zh.md b/docs/subsystems/schedule.zh.md index 2d140c3821..320ae8e743 100644 --- a/docs/subsystems/schedule.zh.md +++ b/docs/subsystems/schedule.zh.md @@ -309,6 +309,14 @@ type ScheduleDeleteResult = | { readonly id: ScheduleId; readonly deleted: false; readonly code: 'schedule_not_found' } ``` +```ts type-equiv +/** Successful Host-wide removal of every ended task, whether or not any remained. */ +interface ScheduleDeleteInactiveResult { + /** Ended task rows this call removed; zero when the Host held none. */ + readonly deleted: number +} +``` + ## Web 目录 Remote 方法 `schedule.catalog()` 返回活动和未运行的宿主任务及其原始 Session 绑定,先按 `scheduledAt` 升序排列,再按 `id` 字典序排列。它只读取 Schedule domain,不激活 Session 或读取其历史。浏览器消费方接收以下可安全用于浏览器的类型: @@ -337,7 +345,7 @@ type ScheduleCatalogEntry = ScheduleRecord & { } ``` -Remote 方法 `schedule.list({ sessionId })`、模型 `schedule_list` 和 Session 页头目录仅返回活动任务。模型视图派生的时间 `state` 与存储的生命周期 `status` 仍是不同概念。删除通过 `schedule.delete({ sessionId, id })` 使用条目的原始绑定;绑定不匹配时返回未找到。模型工具传入当前 Agent 的 Session,全局用户界面则传入所选任务的绑定。仅校验绑定并不构成调用者鉴权。无 payload 的 `schedule/changed` 事件通知客户端刷新列表;重新连接后,客户端再次获取当前状态。 +Remote 方法 `schedule.list({ sessionId })`、模型 `schedule_list` 和 Session 页头目录仅返回活动任务。模型视图派生的时间 `state` 与存储的生命周期 `status` 仍是不同概念。删除通过 `schedule.delete({ sessionId, id })` 使用条目的原始绑定;绑定不匹配时返回未找到。模型工具传入当前 Agent 的 Session,全局用户界面则传入所选任务的绑定。仅校验绑定并不构成调用者鉴权。`schedule.deleteInactive()` 删除跨会话的全部未运行(已结束)任务,连同每行携带的已保存的发送记录;成功时以它移除的计数答复 `{ deleted }`;普通失败时不删除任何行;后端报告 `unknown-state` 时可能已移除部分行,并会隔离 Host 的 schedule 领域,之后该领域的操作都会拒绝,直到重新打开。任何拒绝都会先发出 `schedule/changed`,客户端重新读取。自动化任务页面的批量清理使用该方法。未运行任务从不会安排定时器,因此该删除不重算任何目标。无 payload 的 `schedule/changed` 事件通知客户端刷新列表;重新连接后,客户端再次获取当前状态。 随发行版交付的 Web 组合把 `ui-schedule` 与宿主能力一起挂载。[客户端包](../../packages/client/ui-schedule/README.zh.md) 负责目录、空状态与删除控件。页面单独筛选全部、活动和未运行任务,保留未运行任务详情及详情页签条内的原 Session 入口,并要求显式确认删除。“规则”和“任务运行记录”页签将任务设置与按需分页加载的已保存回执分开。回执与未运行状态均不确认模型执行。 @@ -508,6 +516,22 @@ async create(sessionId: SessionId, request: ScheduleCreateRequest, signal?: Abor */ @Remote('delete') async delete(request: ScheduleDeleteRequest, signal?: AbortSignal): Promise +/** + * Delete every ended Host task, leaving active tasks armed. + * + * Ended tasks never schedule another delivery, so the removal changes no pending + * target and no timer is recomputed. Rows are enumerated and removed in one FIFO + * slot, so a delivery ordered behind this call ends its task after the + * enumeration rather than during it. The batch is one domain write: a normal + * failure rejects with every listed row still stored, while a backend + * `unknown-state` failure may have removed rows and quarantines the Host + * domain, so later schedule operations reject until the domain is reopened. + * Every rejection announces `schedule/changed` because it does not establish + * which rows landed, and clients then re-read the catalog. + * @returns Count of removed rows; zero when the Host held no ended task. + */ +@Remote('deleteInactive') async deleteInactive(): Promise + /** * Update the name, instruction, and timing of an active task within the original Session * binding without activating the Session or changing saved deliveries. diff --git a/docs/subsystems/session.i18n.yaml b/docs/subsystems/session.i18n.yaml index 1a778923dc..53d89173b4 100644 --- a/docs/subsystems/session.i18n.yaml +++ b/docs/subsystems/session.i18n.yaml @@ -45,8 +45,8 @@ en: 45d1a9ee6d610ac5 zh: 79c061252fde4ceb /sessions/live-session-fork-api: - en: c72c73ce4b4c697c - zh: 8a34785a92df0ad5 + en: 06189884c62a80a1 + zh: 30121aed7a011c72 /sessions/why-a-turn-ended-turnendreasonmap: en: 966cc60273fb3911 zh: de5123ea9dbb0df2 diff --git a/docs/subsystems/session.md b/docs/subsystems/session.md index e9369b0702..7cbc91298d 100644 --- a/docs/subsystems/session.md +++ b/docs/subsystems/session.md @@ -65,8 +65,10 @@ interface SessionEventMap { * The rendered system prompt on the model-visible surface. The loop appends * the first one as surface node 0 before the step's first `user/message`. * A prepared in-history route can append nonempty changes in a continuing - * series. An incapable route or new series normalizes text to the first system - * node. Normalization empties nonempty later nodes, then rewrites the head if + * series. An incapable route, or a new series whose effective text differs, + * normalizes text to the first system node; a series start whose latest + * surviving node already holds the rendering leaves it in place. + * Normalization empties nonempty later nodes, then rewrites the head if * needed, through logged per-node replacements. An empty rendering always * clears all active system nodes, leaving no older instructions model-visible. * Empty later nodes are dormant and project to no message; an empty head with @@ -683,7 +685,7 @@ Everything else (`turn/*`, `step/*`, `assistant/attempt`, plugin-owned `llm/retr `ctx.sessions.create(id, { seed, meta })` is the low-level replay/fork primitive. For ordinary live-session forks, `SessionStore` exposes one policy API: -- `fork(source, boundary?, childSessionId?)` accepts a live `Session` object or live `SessionId`, selects source events through the inclusive `SessionSeq` boundary (default: current last event), requires the selected prefix to end outside an open turn, then creates a live child session with deep-cloned seed events, `parentSession`, `isSeeded: true`, the exact `inheritedEventCount`, and inherited `cwd`. +- `fork(source, boundary?, childSessionId?)` accepts a live `Session` object or live `SessionId`, selects source events through the inclusive `SessionSeq` boundary (default: current last event), closes any open tail, then creates an independent live session with deep-cloned seed events, `isSeeded: true`, the exact `inheritedEventCount`, and inherited `cwd`, without `parentSession`. An explicit `boundary` lets callers fork from any stable between-turn position, including a previous `turn/end` or a later standalone log-only event, even if the source has newer events or an open current turn. The API rejects a prefix that ends inside an open turn instead of clipping silently. `dsh-subagent-fork-in-process` keeps its completed-prefix clipping because tool-time delegation usually starts while the parent turn is open; ordinary session branching should make the requested boundary explicit. @@ -837,14 +839,6 @@ Host service backing the generated `ctx.remote.session` namespace. */ resolveAgent(sessionId: SessionId): Promise -/** - * Inspect one attached or persisted Session without activating its Agent. - * @param sessionId - durable Session identity. - * @param signal - optional caller cancellation for persistence reads. - * @returns the current attached state or persisted header and event prefix. - */ -inspect( sessionId: SessionId, signal?: AbortSignal, ): Promise - /** * Read all visible Session rows without resuming an Agent. * @param _request - reserved empty list request. @@ -944,8 +938,8 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | @Remote('prompt') async prompt(request: SessionPromptRequest, signal: AbortSignal): Promise /** - * Read one image proven reachable from the addressed Session log. - * @param request - Session and attachment identities used for authorization. + * Read one image from the attachment store after gateway authorization. + * @param request - image reference and gateway permission scope; Session existence is not checked. * @returns the durable attachment reference and base64-encoded bytes. */ @Remote('attachment') attachment(request: SessionAttachmentRequest): Promise @@ -966,11 +960,51 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | /** * Read one cold-safe, message-aligned Session history page. - * @param request - durable address, backward cursor, and page budget. + * @param request - durable address, optional fixed cut, backward cursor, and page budget. * @param signal - cancellation for persistence reads. - * @returns one chronological page. + * @returns one chronological page with its inclusive cursor. */ -@Remote({ name: 'page', resources: { session: addressedSession } }) page(request: SessionPageRequest, signal: AbortSignal): Promise +@Remote events(request: SessionPageRequest, signal: AbortSignal): Promise + +/** + * Subscribe to Session events without reading a snapshot. + * @param request - Session address. + * @param signal - subscription cancellation. + * @returns readiness and subsequent events, without a snapshot. + */ +@Remote({ mode: 'stream' }) observeEvent(request: SessionObserveEventRequest, signal: AbortSignal): AsyncIterable + +/** + * Subscribe to sparse Session projection changes. + * @param request - target Session. + * @param signal - subscription cancellation. + * @returns readiness and sparse projection changes. + */ +@Remote({ mode: 'stream' }) observeProjections(request: SessionProjectionsRequest, signal: AbortSignal): AsyncIterable + +/** + * Read passive Session state. + * @param request - target Session. + * @param signal - read cancellation. + * @returns current passive state. + */ +@Remote state(request: SessionStateRequest, signal: AbortSignal): Promise + +/** + * Subscribe to complete Session state replacements. + * @param request - target Session. + * @param signal - subscription cancellation. + * @returns complete passive state replacements. + */ +@Remote({ mode: 'stream' }) observeState(request: SessionStateRequest, signal: AbortSignal): AsyncIterable + +/** + * Wait for Session quiescence or pending input with bounded assistant output. + * @param request - Session, wait bounds and output window. + * @param signal - caller cancellation. + * @returns stopping state and bounded assistant output. + */ +@Remote wait(request: SessionWaitRequest, signal: AbortSignal): Promise /** * Follow one Session log from its opening or resume cursor. @@ -979,7 +1013,7 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | * @returns a complete opening snapshot followed by gap-free durable event * frames and optional cursorless assistant-stream frames. */ -@Remote({ mode: 'stream', resources: { session: addressedSession } }) follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable +@Remote({ mode: 'stream' }) follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable /** * Read exact projections, returning cached hints only when migration is required. @@ -987,7 +1021,7 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | * @param signal - cancellation for the Session read. * @returns a sequenced baseline, cached hints when migration is deferred, or null when absent. */ -@Remote('projections') async projections(request: SessionProjectionsRequest, signal: AbortSignal): Promise +@Remote('projections') projections(request: SessionProjectionsRequest, signal: AbortSignal): Promise /** * Stream a complete live-control baseline followed by replacement frames. @@ -997,7 +1031,7 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | @Remote({ mode: 'stream' }) async *control(signal: AbortSignal): AsyncIterable ``` -Types: [SessionId](core.md) · [SessionInspection](persistence.md) · [SessionSearchRequest](session-query.md) +Types: [SessionId](core.md) · [SessionSearchRequest](session-query.md) Source: [`packages/api/session-controller/src/index.ts`](../../packages/api/session-controller/src/index.ts) @@ -1128,7 +1162,7 @@ get(id: SessionId): Session | undefined list(): Session[] /** - * Create a live child session from an exact prefix of a live source. + * Create an independent live session from an exact prefix of a live source. * `boundary` is an inclusive source event seq; omitted means the source's * current last event. An open tail receives synthetic tool results and * step/turn closers with the forked cause. Closed steps and turns remain diff --git a/docs/subsystems/session.zh.md b/docs/subsystems/session.zh.md index 7971f5e7fd..1f40042967 100644 --- a/docs/subsystems/session.zh.md +++ b/docs/subsystems/session.zh.md @@ -65,8 +65,10 @@ interface SessionEventMap { * The rendered system prompt on the model-visible surface. The loop appends * the first one as surface node 0 before the step's first `user/message`. * A prepared in-history route can append nonempty changes in a continuing - * series. An incapable route or new series normalizes text to the first system - * node. Normalization empties nonempty later nodes, then rewrites the head if + * series. An incapable route, or a new series whose effective text differs, + * normalizes text to the first system node; a series start whose latest + * surviving node already holds the rendering leaves it in place. + * Normalization empties nonempty later nodes, then rewrites the head if * needed, through logged per-node replacements. An empty rendering always * clears all active system nodes, leaving no older instructions model-visible. * Empty later nodes are dormant and project to no message; an empty head with @@ -685,7 +687,7 @@ declare class Session { `ctx.sessions.create(id, { seed, meta })` 是底层的回放/fork 原语。对于普通的活跃会话 fork,`SessionStore` 暴露一个策略 API: -- `fork(source, boundary?, childSessionId?)` 接受一个活跃的 `Session` 对象或活跃的 `SessionId`,选取到 `SessionSeq` boundary(含)为止的源事件(默认为当前最后一个事件),要求所选前缀结束时没有开放轮次,然后创建一个活跃的子会话,包含深克隆的 seed event、`parentSession`、`isSeeded: true`、精确 `inheritedEventCount` 及继承的 `cwd`。 +- `fork(source, boundary?, childSessionId?)` 接受一个活跃的 `Session` 对象或活跃的 `SessionId`,选取到 `SessionSeq` boundary(含)为止的源事件(默认为当前最后一个事件),闭合任何开放尾部,然后创建一个独立的活跃会话,包含深克隆的 seed event、`isSeeded: true`、精确 `inheritedEventCount` 及继承的 `cwd`,不含 `parentSession`。 显式 `boundary` 允许调用者从任意稳定的轮次间位置 fork,包括之前的 `turn/end` 或更晚的独立纯日志事件,即使源会话有更新的事件或正在进行的轮次。API 拒绝结束于开放轮次内的前缀,而不是静默截断。`dsh-subagent-fork-in-process` 保留其已完成前缀截断逻辑,因为工具调用时的委托通常在父轮次仍然打开时启动;普通的会话分支应显式指定请求的 boundary。 @@ -841,14 +843,6 @@ Host service backing the generated `ctx.remote.session` namespace. */ resolveAgent(sessionId: SessionId): Promise -/** - * Inspect one attached or persisted Session without activating its Agent. - * @param sessionId - durable Session identity. - * @param signal - optional caller cancellation for persistence reads. - * @returns the current attached state or persisted header and event prefix. - */ -inspect( sessionId: SessionId, signal?: AbortSignal, ): Promise - /** * Read all visible Session rows without resuming an Agent. * @param _request - reserved empty list request. @@ -948,8 +942,8 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | @Remote('prompt') async prompt(request: SessionPromptRequest, signal: AbortSignal): Promise /** - * Read one image proven reachable from the addressed Session log. - * @param request - Session and attachment identities used for authorization. + * Read one image from the attachment store after gateway authorization. + * @param request - image reference and gateway permission scope; Session existence is not checked. * @returns the durable attachment reference and base64-encoded bytes. */ @Remote('attachment') attachment(request: SessionAttachmentRequest): Promise @@ -970,11 +964,51 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | /** * Read one cold-safe, message-aligned Session history page. - * @param request - durable address, backward cursor, and page budget. + * @param request - durable address, optional fixed cut, backward cursor, and page budget. * @param signal - cancellation for persistence reads. - * @returns one chronological page. + * @returns one chronological page with its inclusive cursor. */ -@Remote({ name: 'page', resources: { session: addressedSession } }) page(request: SessionPageRequest, signal: AbortSignal): Promise +@Remote events(request: SessionPageRequest, signal: AbortSignal): Promise + +/** + * Subscribe to Session events without reading a snapshot. + * @param request - Session address. + * @param signal - subscription cancellation. + * @returns readiness and subsequent events, without a snapshot. + */ +@Remote({ mode: 'stream' }) observeEvent(request: SessionObserveEventRequest, signal: AbortSignal): AsyncIterable + +/** + * Subscribe to sparse Session projection changes. + * @param request - target Session. + * @param signal - subscription cancellation. + * @returns readiness and sparse projection changes. + */ +@Remote({ mode: 'stream' }) observeProjections(request: SessionProjectionsRequest, signal: AbortSignal): AsyncIterable + +/** + * Read passive Session state. + * @param request - target Session. + * @param signal - read cancellation. + * @returns current passive state. + */ +@Remote state(request: SessionStateRequest, signal: AbortSignal): Promise + +/** + * Subscribe to complete Session state replacements. + * @param request - target Session. + * @param signal - subscription cancellation. + * @returns complete passive state replacements. + */ +@Remote({ mode: 'stream' }) observeState(request: SessionStateRequest, signal: AbortSignal): AsyncIterable + +/** + * Wait for Session quiescence or pending input with bounded assistant output. + * @param request - Session, wait bounds and output window. + * @param signal - caller cancellation. + * @returns stopping state and bounded assistant output. + */ +@Remote wait(request: SessionWaitRequest, signal: AbortSignal): Promise /** * Follow one Session log from its opening or resume cursor. @@ -983,7 +1017,7 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | * @returns a complete opening snapshot followed by gap-free durable event * frames and optional cursorless assistant-stream frames. */ -@Remote({ mode: 'stream', resources: { session: addressedSession } }) follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable +@Remote({ mode: 'stream' }) follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable /** * Read exact projections, returning cached hints only when migration is required. @@ -991,7 +1025,7 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | * @param signal - cancellation for the Session read. * @returns a sequenced baseline, cached hints when migration is deferred, or null when absent. */ -@Remote('projections') async projections(request: SessionProjectionsRequest, signal: AbortSignal): Promise +@Remote('projections') projections(request: SessionProjectionsRequest, signal: AbortSignal): Promise /** * Stream a complete live-control baseline followed by replacement frames. @@ -1001,7 +1035,7 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | @Remote({ mode: 'stream' }) async *control(signal: AbortSignal): AsyncIterable ``` -Types: [SessionId](core.zh.md) · [SessionInspection](persistence.zh.md) · [SessionSearchRequest](session-query.zh.md) +Types: [SessionId](core.zh.md) · [SessionSearchRequest](session-query.zh.md) Source: [`packages/api/session-controller/src/index.ts`](../../packages/api/session-controller/src/index.ts) @@ -1132,7 +1166,7 @@ get(id: SessionId): Session | undefined list(): Session[] /** - * Create a live child session from an exact prefix of a live source. + * Create an independent live session from an exact prefix of a live source. * `boundary` is an inclusive source event seq; omitted means the source's * current last event. An open tail receives synthetic tool results and * step/turn closers with the forked cause. Closed steps and turns remain diff --git a/docs/subsystems/skills.i18n.yaml b/docs/subsystems/skills.i18n.yaml index c4fbc992b6..b9101bbb51 100644 --- a/docs/subsystems/skills.i18n.yaml +++ b/docs/subsystems/skills.i18n.yaml @@ -9,20 +9,20 @@ en: abe338b6c6d1ebd1 zh: c604db2de10a23c4 /skills/local-discovery-priority: - en: accf8ad4c73c41ad - zh: 141294fe8dab8ecf + en: 390fc00bbccfb777 + zh: 96ff7abfbd4b911b /skills/skill-identity: en: 61295a9cf1c51588 zh: 1c4c1582688d2310 /skills/summaries-candidates-and-complete-definitions: - en: 8819c25fac497a1f - zh: 5795f0d16f09750e + en: fdc9f7c9c7f1ba0f + zh: 0ce311eb495233e6 /skills/lookup-and-configuration: en: e60215d73b0abe75 zh: a086985044324141 /skills/session-catalog-and-tool-contract: - en: 5d5c36b1843a9d7d - zh: cd92ab1545e65722 + en: 6624024d8fc01937 + zh: 79533abe482565d8 /skills/browser-session-catalog: en: 1209dc6ee65fd476 zh: af3b7ef836564d05 diff --git a/docs/subsystems/skills.md b/docs/subsystems/skills.md index 3bfdbff402..0c7ab18d2b 100644 --- a/docs/subsystems/skills.md +++ b/docs/subsystems/skills.md @@ -74,7 +74,7 @@ The shipped local provider scans roots in rank order: | 500 | `user-agents` | `/skills` | | 600 | `bundled` | `Config.bundledSkillDir` when configured | -The project root is the nearest ancestor containing `.git`; without one, the current cwd is used. When `ctx.fs` is available, the git-root walk probes `.git` through the filesystem service so remote or sandboxed workspaces do not fall back to the host filesystem boundary. The user DSH root skips its `.system` child. The local provider does not synthesize built-in system skills; deployments supply packaged skills through configured bundled roots or dedicated providers. +The project root is the nearest ancestor containing `.git`; without one, the current cwd is used. When `ctx.fs` is available, the git-root walk probes `.git` through the filesystem service so remote or sandboxed workspaces do not fall back to the host filesystem boundary. The user DSH root skips its `.system` child. The local provider does not synthesize built-in system skills; deployments supply packaged skills through configured bundled roots or dedicated providers. A failed root contributes no candidates, so a lower-priority same-name skill from another root may supply both the catalog description and loaded body until recovery. `dsh-skill-badge` registers one immutable `bundled` candidate at `BUNDLED_SKILL_RANK` and exposes its packaged asset directory through `resourceBase`. The shipped CLI declares the plugin disabled, so enabling its composition row is an explicit opt-in. @@ -127,7 +127,7 @@ interface SkillSummary { `ctx.skills.list()` preserves all four policy combinations. `isModelInvocable(skill)` and `isUserInvocable(skill)` read the corresponding required field. A model-only skill sets `{ modelInvocable: true, userInvocable: false }`, a user-only skill sets `{ modelInvocable: false, userInvocable: true }`, and setting both fields to `false` keeps the skill available only through trusted `ctx.skills.get()` callers. The local provider reads the exact kebab-case frontmatter keys `disable-model-invocation` and `user-invocable`, defaults omitted fields to `true`, and projects every parsed skill into this normalized policy. -`SkillCatalogSnapshot` distinguishes authoritative absence from transient provider failure or a catalog that kept changing during discovery. `skills` contains the sorted invocation-neutral summaries collected in that observation; `complete` is true only when every registered provider completed without a concurrent catalog revision. Incomplete snapshots are not cached, allowing each consumer to retain its last-good filtered catalog and retry. +`SkillCatalogSnapshot` distinguishes authoritative absence from transient provider failure or a catalog that kept changing during discovery. `skills` contains the sorted invocation-neutral summaries collected in that observation; `complete` is true only when every registered provider completed without a concurrent catalog revision. Incomplete snapshots are not cached, so the next lookup retries discovery; each consumer decides how to present the partial result. ```ts type-equiv /** One catalog observation plus whether discovery completed within a stable catalog revision. */ @@ -226,9 +226,9 @@ interface Config { ## Session catalog and tool contract -`dsh-tool-skill` injects the initial durable user-role `` at the first `agent/pre-step` of a live session that observes a non-empty complete view. The catalog contains sorted skill `name` and normalized, XML-escaped `description` only; it omits bodies, paths, sources, providers, and routing hints. Discovery forwards the step's abort signal through `SkillLookupOptions`. `catalogDescriptionMaxLength` is the consumer config for the description bound, with default `500` and integer minimum `3`. +`dsh-tool-skill` injects the initial durable user-role `` at the first `agent/pre-step` of a live session that observes available skills or incomplete discovery. The catalog contains sorted skill `name` and normalized, XML-escaped `description` only; it omits bodies, paths, sources, providers, and routing hints. Discovery forwards the step's abort signal through `SkillLookupOptions`. `catalogDescriptionMaxLength` is the consumer config for the description bound, with default `500` and integer minimum `3`. -Before each later model step, the consumer applies exact tool visibility and digests the exact rendered entries between the `` tags from a complete snapshot. It derives the comparison baseline from the same entries in the newest recognizable visible catalog message sourced by the plugin. A changed digest appends a durable full replacement through `agent.inject()`; deleting every skill appends an explicit empty replacement. Incomplete snapshots preserve the last-good model view. If compaction hides every historical catalog message, the next complete snapshot re-establishes the current catalog; an empty view with no prior catalog emits nothing. These catalog messages are session history, not World State. +Before each later model step, the consumer applies exact tool visibility and compares the entries and completeness with the newest recognizable visible catalog message in the session log. A changed observation contributes a durable replacement to the pre-step decision; deleting every skill appends an explicit empty replacement. Incomplete discovery publishes the available subset with a warning and optional `incomplete: true` source metadata; absence of that flag means complete. Recovery republishes the catalog even when its entries are unchanged. If compaction hides every historical catalog message, the next observation re-establishes the current catalog; a complete empty view with no prior catalog emits nothing. These catalog messages are session history, not World State. The model-facing `skill({ name })` tool validates the kebab-case name, finds the summary in the invocation-neutral catalog, rejects it before loading unless `isModelInvocable` permits access, then rereads the complete definition for the calling agent cwd and rechecks the policy before returning content. It reports an unresolved skill as unknown or no longer available and returns a tool result containing ``, ``, and ``. `resourceBase` resolves explicitly referenced scripts, references, and assets only as needed; the loaded result does not enumerate a skill directory. Body-only edits therefore change later tool calls without producing catalog messages or rewriting earlier tool results. diff --git a/docs/subsystems/skills.zh.md b/docs/subsystems/skills.zh.md index d93f8416fb..f2f84ab22d 100644 --- a/docs/subsystems/skills.zh.md +++ b/docs/subsystems/skills.zh.md @@ -74,7 +74,7 @@ interface SkillProviderControl { | 500 | `user-agents` | `/skills` | | 600 | `bundled` | 配置了 `Config.bundledSkillDir` 时使用该目录 | -项目根目录为包含 `.git` 的最近祖先目录;找不到时使用当前 cwd。当 `ctx.fs` 可用时,git-root 向上查找通过文件系统服务探测 `.git`,使远程或沙箱工作区不会回退到宿主文件系统边界。用户 DSH 根目录会跳过其 `.system` 子目录。本地提供方不会合成内置系统 skill;部署方通过已配置的 bundled 根目录或专用提供方提供随包 skill。 +项目根目录为包含 `.git` 的最近祖先目录;找不到时使用当前 cwd。当 `ctx.fs` 可用时,git-root 向上查找通过文件系统服务探测 `.git`,使远程或沙箱工作区不会回退到宿主文件系统边界。用户 DSH 根目录会跳过其 `.system` 子目录。本地提供方不会合成内置系统 skill;部署方通过已配置的 bundled 根目录或专用提供方提供随包 skill。失败的根目录不提供候选项,因此在恢复之前,其他根中较低优先级的同名 skill 可能同时提供目录描述与加载的正文。 `dsh-skill-badge` 在 `BUNDLED_SKILL_RANK` 注册一个不可变的 `bundled` 候选项,并通过 `resourceBase` 公开其随包资产目录。交付的 CLI(命令行界面)将该插件声明为禁用,因此启用其组合配置行即为显式选择加入。 @@ -127,7 +127,7 @@ interface SkillSummary { `ctx.skills.list()` 保留全部四种策略组合。`isModelInvocable(skill)` 和 `isUserInvocable(skill)` 分别读取对应的必填字段。仅供模型调用的 skill 设置 `{ modelInvocable: true, userInvocable: false }`,仅供用户调用的 skill 设置 `{ modelInvocable: false, userInvocable: true }`,两个字段均设为 `false` 后,该 skill 只能由受信的 `ctx.skills.get()` 调用方获取。本地提供方读取名称完全匹配的 kebab-case frontmatter 键 `disable-model-invocation` 和 `user-invocable`,将省略的字段默认为 `true`,并为每个解析出的 skill 生成这个规范化策略。 -`SkillCatalogSnapshot` 用于区分已确定的不存在与提供方的瞬时失败或发现期间持续变化的目录。`skills` 包含该次观测中收集、排序且与调用策略无关的摘要;只有每个已注册提供方都在没有并发目录修订时完成发现,`complete` 才为 true。不完整快照不会缓存,因此每个消费方可以保留上一份经过自身过滤的可用目录并重试。 +`SkillCatalogSnapshot` 用于区分已确定的不存在与提供方的瞬时失败或发现期间持续变化的目录。`skills` 包含该次观测中收集、排序且与调用策略无关的摘要;只有每个已注册提供方都在没有并发目录修订时完成发现,`complete` 才为 true。不完整快照不会缓存,因此下次查询会重试发现;各消费方自行决定如何呈现部分结果。 ```ts type-equiv /** One catalog observation plus whether discovery completed within a stable catalog revision. */ @@ -226,9 +226,9 @@ interface Config { ## 会话目录与工具约定 -`dsh-tool-skill` 在存活会话中第一个观察到非空完整视图的 `agent/pre-step` 注入初始的持久 user-role ``。目录只包含已排序的 skill `name` 和规范化、经 XML 转义的 `description`;不包含正文、路径、来源、提供方或路由提示。发现通过 `SkillLookupOptions` 转发该步骤的 abort signal。`catalogDescriptionMaxLength` 是消费方用于 description 上限的配置,默认值为 `500`,整数最小值为 `3`。 +`dsh-tool-skill` 在存活会话中第一个观察到可用 skill 或发现不完整的 `agent/pre-step` 注入初始的持久 user-role ``。目录只包含已排序的 skill `name` 和规范化、经 XML 转义的 `description`;不包含正文、路径、来源、提供方或路由提示。发现通过 `SkillLookupOptions` 转发该步骤的 abort signal。`catalogDescriptionMaxLength` 是消费方用于 description 上限的配置,默认值为 `500`,整数最小值为 `3`。 -在后续每个模型步骤之前,消费方都会应用精确的工具可见性,并对完整快照中 `` 标签之间精确渲染的条目计算 digest。它以该插件所发布、最新一条可识别且仍可见的目录消息中的相同条目作为比较基线。digest 发生变化时,会通过 `agent.inject()` 追加一条持久的完整目录替换;删除所有 skill 时会追加一条显式的空替换。不完整快照会保留上一份可用模型视图。如果压缩(compaction)隐藏了所有历史目录消息,下一份完整快照会重新建立当前目录;如果视图为空且从未发布目录,则不发送任何内容。这些目录消息属于会话历史,而非 World State。 +在后续每个模型步骤之前,消费方都会应用精确的工具可见性,并将条目与完整性同会话日志中最新一条可识别且仍可见的目录消息比较。观测变化时,会向 pre-step 决策提供一条持久的替换目录;删除所有 skill 时会追加显式的空替换。发现不完整时会发布可用子集,并附带警告和可选的 `incomplete: true` 来源元数据;缺少该标记表示完整。恢复后即使条目未变也会重新发布目录。如果压缩(compaction)隐藏了所有历史目录消息,下一次观测会重新建立当前目录;完整的空视图在从未发布目录时不发送任何内容。这些目录消息属于会话历史,而非 World State。 面向模型的 `skill({ name })` 工具校验 kebab-case 名称,在与调用策略无关的目录中查找摘要,并在加载前通过 `isModelInvocable` 拒绝无权访问的 skill;随后它根据调用方 agent 的 cwd 重新读取完整定义,并在返回内容前再次检查策略。该工具将无法解析的 skill 报告为未知或已不可用,并返回包含 ``、`` 和 `` 的工具结果。`resourceBase` 仅按需解析显式引用的脚本、参考资料和资产;加载结果不枚举 skill 目录。因此,仅修改正文会改变后续工具调用,而不会生成目录消息或改写先前工具结果。 diff --git a/docs/subsystems/slots.i18n.yaml b/docs/subsystems/slots.i18n.yaml index cf71b1d1af..17ae54903e 100644 --- a/docs/subsystems/slots.i18n.yaml +++ b/docs/subsystems/slots.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/slots.md /web-client-slots: - en: dd504c406c346f45 - zh: 5dadae8b00aafc5b + en: 808a284f5a4280b5 + zh: 1650d6c3a94eae6e /web-client-slots/declaration-and-lifecycle: en: f2d2c0d3b8f14ec7 zh: 441ed13ff3f81d2a diff --git a/docs/subsystems/slots.md b/docs/subsystems/slots.md index 998aebbffc..ee31122d13 100644 --- a/docs/subsystems/slots.md +++ b/docs/subsystems/slots.md @@ -10,7 +10,7 @@ This page documents slot ownership, component inputs, extension APIs, and the sh The plugin catalog declares `plugins.add.actions`, a root-scoped list for `MenuItemButton` rows after installation in the Add plugin menu. Its owner supplies `onDismiss()` to close the menu before starting an action. The slot follows the owning Plugins page declaration lifetime. -The root-scoped lists `sidebar.panellist.actions`, `conversation.session.header.views.actions`, and `sidebar.right.tab.guide.actions` supply the rows of the More menus after the panel rows, the View tabs, and the right-sidebar guide cards. A region draws its More button and menu only while its list has registrations, and passes the customizable entries with their pin state, `onOpen`, `onPinnedChange`, and `onDismiss`. Each region persists its own unpinned entry ids; [`ui-entry-customization`](../../packages/client/ui-entry-customization/README.md) registers the shipped rows. +The root-scoped lists `sidebar.panellist.actions`, `conversation.session.header.views.actions`, and `sidebar.right.tab.guide.actions` supply the rows of the More menus after the panel rows, the View tabs, and the right-sidebar guide cards. A region draws its More button and menu only while its list has registrations, and passes the customizable entries with their pin state, `onOpen`, `onPinnedChange`, and `onDismiss`. Panel and View entries also carry optional `active` state for the current selection, independently of pin state. Each region keeps its own unpinned entry ids in memory; [`ui-entry-customization`](../../packages/client/ui-entry-customization/README.md) registers the shipped rows. [ui-workspace](../../packages/client/ui-workspace/README.md#understand-the-implementation) documents Session-row extension positions, visibility, and keyboard behavior. diff --git a/docs/subsystems/slots.zh.md b/docs/subsystems/slots.zh.md index e2d9217ec6..ca13d60008 100644 --- a/docs/subsystems/slots.zh.md +++ b/docs/subsystems/slots.zh.md @@ -10,7 +10,7 @@ Slots 是 Web Client 的类型化 React 组合系统。[`dsh-client-ui-slots`](. 插件目录声明 `plugins.add.actions`,它是 root 作用域的 list,在添加插件菜单的安装项之后提供 `MenuItemButton` 行。owner 提供 `onDismiss()`,用于开始动作前关闭菜单。该 slot 遵循所属插件页面声明的生命周期。 -root 作用域的 list `sidebar.panellist.actions`、`conversation.session.header.views.actions` 和 `sidebar.right.tab.guide.actions` 提供面板行、View 标签和右侧栏引导卡片之后“更多”菜单的菜单行。区域只在其 list 有注册项时画“更多”按钮与菜单,并传入可自定义的入口及其 Pin 状态、`onOpen`、`onPinnedChange` 与 `onDismiss`。各区域自行持久化已收起的入口 id;[`ui-entry-customization`](../../packages/client/ui-entry-customization/README.zh.md) 注册随产品提供的菜单行。 +root 作用域的 list `sidebar.panellist.actions`、`conversation.session.header.views.actions` 和 `sidebar.right.tab.guide.actions` 提供面板行、View 标签和右侧栏引导卡片之后“更多”菜单的菜单行。区域只在其 list 有注册项时画“更多”按钮与菜单,并传入可自定义的入口及其 Pin 状态、`onOpen`、`onPinnedChange` 与 `onDismiss`。面板和 View 入口还通过可选的 `active` 状态标识当前选中项,该状态独立于 Pin 状态。各区域在内存中维护已收起的入口 id;[`ui-entry-customization`](../../packages/client/ui-entry-customization/README.zh.md) 注册随产品提供的菜单行。 [ui-workspace](../../packages/client/ui-workspace/README.zh.md#understand-the-implementation) 记录 Session 行的扩展位置、显示条件和键盘行为。 diff --git a/docs/subsystems/storage.i18n.yaml b/docs/subsystems/storage.i18n.yaml index 632e0788df..d58a4c2f17 100644 --- a/docs/subsystems/storage.i18n.yaml +++ b/docs/subsystems/storage.i18n.yaml @@ -9,14 +9,17 @@ en: b11e06e7c0e0fd13 zh: 4585f26ff416cb41 /storage/the-backend-contract: - en: 2316787902c6a94e - zh: e3bda06e1c33acac + en: 50afeec4e9fd3e08 + zh: e8d2892c83ad3441 /storage/declaring-a-domain: - en: 775cce941500f01f - zh: 78acbc67f48574cb + en: fa4613279da360c5 + zh: 09e7a7d63bd1774a +/storage/domain-versioning: + en: 37e40cc29f3bb898 + zh: bbd55e732bd4b83b /storage/the-open-domain: - en: 2468b5df66c49b51 - zh: 1587f460e9769db2 + en: c0787f6a496b4c46 + zh: f219b16ec96d6cb6 /storage/the-domain-facility-ctx-storagedomain: en: deed74fcd4506ef4 zh: 8e3e6e5d2dc2e989 diff --git a/docs/subsystems/storage.md b/docs/subsystems/storage.md index 674221a263..16c994d8b0 100644 --- a/docs/subsystems/storage.md +++ b/docs/subsystems/storage.md @@ -44,7 +44,7 @@ interface StorageBackend { } ``` -A backend owns one medium (a file-tree root, a database file) and exposes optional operation groups; `kv` is the only shipped group. `KvFacet.open(descriptor)` opens one named unit — `KvUnitDescriptor` carries the name, current format version, optional compatible record versions, table names, and whether a global singleton slot exists — and returns a `KvUnit` with `loadAll`, `putRecord`, `deleteRecord`, `setGlobal`, and `close`. Unit and table names must match `UNIT_NAME_RE` (safe as a file name and as a SQL identifier segment); record keys are arbitrary strings that never reach file paths. A unit does not serialize concurrent writes — ordering belongs to the caller — but each single call is atomic on the medium and durable once resolved. A `single` medium stamped with a different version rejects `version-mismatch`; a `per-record` document stamped outside the accepted set reads as absent. A medium that cannot be parsed as the unit rejects `malformed-medium`. [`backend.ts`](../../packages/storage/storage/src/backend.ts) is the normative clause-by-clause contract, and the shared conformance suite in [`tests/contract.ts`](../../packages/storage/storage/tests/contract.ts) checks every clause against each backend. The [json backend](../../packages/storage/storage-json/README.md) republishes one whole human-readable file per unit atomically; the [sqlite backend](../../packages/storage/storage-sqlite/README.md) stores one document per row in one database for frequently updated data. +A backend owns one medium (a file-tree root, a database file) and exposes optional operation groups; `kv` is the only shipped group. `KvFacet.open(descriptor)` opens one named unit — `KvUnitDescriptor` carries the name, current format version, optional compatible versions, table names, and whether a global singleton slot exists — and returns a `KvUnit` with `loadAll`, `putRecord`, `deleteRecord`, `deleteRecords`, `setGlobal`, and `close`. Unit and table names must match `UNIT_NAME_RE` (safe as a file name and as a SQL identifier segment); record keys are opaque strings in the `single` layout and match `[a-zA-Z0-9_-]+` path segments in the `per-record` layout. A unit does not serialize concurrent writes — ordering belongs to the caller — whole-document and row-store calls are atomic on the medium, while a per-record batch interrupted before resolution can be partially applied. Resolved writes are durable; per-record deletions sync directory changes on POSIX. `deleteRecords` applies a whole batch in one call: it resolves once every listed record is absent from the readable state and the backend accepted the batch, and a rejection normally leaves the batch unapplied; a backend that cannot establish or restore the batch's state rejects with `unknown-state`, after which every later operation on that unit rejects with the same error until `close()` releases it (calls after close reject `closed`). A `single`-layout failure after the atomic replacement (a directory-fsync error) can leave the new file on the medium while the caller sees a rejection; close the backend and its domains, then reopen to inspect saved state before retrying. A `single` medium stamped outside the current and declared compatible versions rejects `version-mismatch`; a `per-record` document stamped outside the accepted set reads as absent. A medium that cannot be parsed as the unit rejects `malformed-medium`. [`backend.ts`](../../packages/storage/storage/src/backend.ts) is the normative clause-by-clause contract, and the shared conformance suite in [`tests/contract.ts`](../../packages/storage/storage/tests/contract.ts) checks the shared clauses against each backend. The [json backend](../../packages/storage/storage-json/README.md) republishes one whole human-readable file per unit atomically; the [sqlite backend](../../packages/storage/storage-sqlite/README.md) stores one document per row in one database for frequently updated data. ## Declaring a domain @@ -58,20 +58,20 @@ interface DomainSpec { /** Current domain format version; reads enforce it according to the selected layout. */ readonly version: number /** - * Medium layout for the backend unit: `single` (the default) stores the + * Document layout for the backend unit: `single` (the default) stores the * whole unit as one document; `per-record` stores each record as its own * document, for units whose records are large, sparse, or individually - * disposable — the projection cache — and scopes version checks per record - * (an unaccepted record document is discarded, never migrated). + * disposable — the projection cache — with per-record version checks. + * Row stores retain unit-wide versioning for either layout request. */ readonly layout?: 'single' | 'per-record' /** * Older domain versions whose stored records the current record schemas * also accept (the declaring owner vouches for that, typically by - * declaring the fields older records lack as optional). `per-record` backends - * read documents stamped with a listed version instead of discarding them, - * and accept a legacy whole-unit file so stamped for the one-time - * bootstrap; writes always stamp {@link version}. + * declaring the fields older records lack as optional). Ordinary reads admit + * listed versions without restamping saved data; writes stamp {@link version} + * while leaving untouched records as saved. Current schemas must therefore + * accept mixed generations even under the current unit stamp. */ readonly compatibleVersions?: readonly number[] /** @@ -94,6 +94,23 @@ interface DomainSpec { `defineDomain(spec)` pins the spec's literal types and fails loud at the owner's module load, before any medium is touched: a domain or table name outside `UNIT_NAME_RE`, a version that is not a non-negative integer, or a global schema that accepts `null` all throw (`null` is the medium's "never written" sentinel, so a stored nullable global could not round-trip). `domainTable(schema)` declares one table with a phantom compile-time key type (typically a [branded id](core.md#branded-ids)); `descriptorOf(spec)` projects the backend-facing unit descriptor. + +## Domain versioning + +`version` names the current read/write format. `compatibleVersions` lists older versions whose records and global value the owner can decode with its current schemas; only nonnegative integers below `version` are allowed. Without that declaration, reads stay exact-version. Acceptance does not weaken record validation or permit a newer unknown version. Each row's saved fields must determine its meaning unambiguously; a unit stamp cannot distinguish different meanings of identical fields in mixed rows. + +Ordinary compatible opens and reads do not restamp or normalize saved values. Whole-unit JSON publishes the current stamp and changed data in one atomic file replacement; SQLite commits its first updated unit stamp and mutation in one transaction; batch deletes always use one transaction. Deleting missing records or an empty batch does not advance the stamp. The stamp identifies an accepted format, not completion of value normalization; readers must accept mixed generations. A backend with a unit-wide stamp rejects an unsupported unit version. + +Serialization failure before publication or successful SQLite rollback preserves the previous data and stamp. An I/O failure after JSON replacement, or a failure of SQLite rollback itself, can leave the saved outcome unknown despite rejection. Stop using and close the backend and its domains, then reopen to inspect saved state before deciding whether to retry. The backend READMEs define these failure cases. + +JSON's `per-record` layout checks and stamps each document independently; an unsupported document reads as absent. Its existing whole-unit bootstrap is an exception to read-only loading: it copies accepted historical values into current-stamped documents without converting them. An existing declared table directory, even when empty, or a declared global document suppresses bootstrap. SQLite retains unit-wide version checks regardless of the layout request. See the [JSON backend](../../packages/storage/storage-json/README.md) and [SQLite backend](../../packages/storage/storage-sqlite/README.md) for layout and recovery behavior. + +For a compatible successor, bump `version`, keep all still-readable stamps in `compatibleVersions`, and extend the same schema's decoding/defaults. Consumers normalize values when rewriting selected records; Storage does not assign application record versions. Verify historical and skipped upgrades, mixed values, reads without writes, failure rollback, restart, other-unit isolation, and unknown-version refusal. Table removal and layout changes require their own retention and upgrade policy; a compatible stamp alone does not define either. + +A v2 unit may contain untouched v1 values. A v3 reader accepting stamp 2 must still decode those values; accepting stamp 1 is also necessary for users who skipped v2 entirely. Removing old decoding requires rewriting and validating every affected record, including those already under a current unit stamp. An incompatible change needs an explicit, recoverable upgrade before opening with the new schema; the storage domain has no value-migration runner. + +Keep a consistent backup before writing a new format if return to an older reader is required: that reader can refuse the new stamp after the first mutation. Lowering a saved stamp by hand does not reverse value conversion. Domain compatibility does not migrate SQLite's physical schema or JSON envelope formats, and changing a backend route does not transfer stored data. Session-format migrations and SQLite physical-layout versioning have separate owners and do not migrate domain values. + ## The open domain ```ts type-equiv @@ -123,7 +140,7 @@ interface Domain { } ``` -Reads are synchronous from authoritative in-memory state: `KvTable` exposes `get`/`entries`/`keys`/`size` (snapshot iterators that stay stable while queued writes land), and the global handle's `get()` serves the spec's `initial` until the first `set` materializes the slot on the medium. Every write — `put`, `delete`, `update`, `global.set` — queues on one per-domain chain and reaches backend durability first, then mutates memory, then emits `domain/changed`; a rejected backend write leaves memory untouched, so reads never diverge from the medium. `update(key, fn)` is an atomic read-modify-write at its chain slot (a missing key rejects `missing-key`); `delete` of an absent key resolves `false` with no write and no event. Returned records are the stored objects themselves, not copies — replace via `put`/`update`, never mutate in place. +Reads are synchronous from authoritative in-memory state: `KvTable` exposes `get`/`entries`/`keys`/`size` (snapshot iterators that stay stable while queued writes land), and the global handle's `get()` serves the spec's `initial` until the first `set` materializes the slot on the medium. Every write — `put`, `delete`, `deleteMany`, `update`, `global.set` — queues on one per-domain chain and reaches backend durability first, then mutates memory, then emits `domain/changed`; a rejected backend write does not publish a domain change; an unknown durable outcome requires reopening before further use of that snapshot; a backend that reports `unknown-state` instead quarantines the domain, and its reads and later writes reject until `close()` releases it. `update(key, fn)` is an atomic read-modify-write at its chain slot (a missing key rejects `missing-key`); `delete` of an absent key resolves `false` with no write and no event. `deleteMany(keys)` removes the present keys as one backend batch in one chain slot, resolves the removed count, and emits one `domain/changed` per removed key; a rejected backend write leaves every record in place and emits nothing; an `unknown-state` rejection quarantines the domain. Returned records are the stored objects themselves, not copies — replace via `put`/`update`, never mutate in place. ## The domain facility: `ctx.storageDomain` diff --git a/docs/subsystems/storage.zh.md b/docs/subsystems/storage.zh.md index 2a4366c84e..7c44b1cc98 100644 --- a/docs/subsystems/storage.zh.md +++ b/docs/subsystems/storage.zh.md @@ -44,7 +44,7 @@ interface StorageBackend { } ``` -一个后端拥有一个介质(一棵文件树的根目录、一个数据库文件),并提供可选的操作组;`kv` 是唯一已交付的操作组。`KvFacet.open(descriptor)` 打开一个具名 unit——`KvUnitDescriptor` 携带名称、当前格式版本、可选的兼容记录版本、表名清单,以及是否存在全局单例 slot——并返回提供 `loadAll`、`putRecord`、`deleteRecord`、`setGlobal` 和 `close` 的 `KvUnit`。unit 名与表名必须匹配 `UNIT_NAME_RE`(既可安全用作文件名,也可安全用作 SQL 标识符片段);记录键是任意字符串,绝不进入文件路径。unit 不对并发写入做串行化——顺序由调用方负责——但每次单独调用在介质上都是原子的,且 resolve 后即已持久。`single` 介质上记录的版本不同时拒绝 `version-mismatch`;`per-record` 文档的版本在接受集合之外时读作不存在。无法按该 unit 解析的介质拒绝 `malformed-medium`。[`backend.ts`](../../packages/storage/storage/src/backend.ts) 是逐条款的规范性约定,[`tests/contract.ts`](../../packages/storage/storage/tests/contract.ts) 中的共享一致性套件会针对每个后端检查每项条款。[json 后端](../../packages/storage/storage-json/README.zh.md)以原子方式为每个 unit 整文件重新发布一份人类可读文件;[sqlite 后端](../../packages/storage/storage-sqlite/README.zh.md)在单个数据库中每行存储一份文档,用于频繁更新的数据。 +一个后端拥有一个介质(一棵文件树的根目录、一个数据库文件),并提供可选的操作组;`kv` 是唯一已交付的操作组。`KvFacet.open(descriptor)` 打开一个具名 unit——`KvUnitDescriptor` 携带名称、当前格式版本、可选的兼容版本、表名清单,以及是否存在全局单例 slot——并返回提供 `loadAll`、`putRecord`、`deleteRecord`、`deleteRecords`、`setGlobal` 和 `close` 的 `KvUnit`。unit 名与表名必须匹配 `UNIT_NAME_RE`(既可安全用作文件名,也可安全用作 SQL 标识符片段);记录键在 `single` 布局中是不透明字符串,在 `per-record` 布局中则是匹配 `[a-zA-Z0-9_-]+` 的路径片段。unit 不对并发写入做串行化——顺序由调用方负责——整文档与行存储调用在介质上是原子的,而逐记录批次在完成前中断时可能只应用一部分。写入完成后即已持久化;逐记录删除会在 POSIX 上同步目录变更。`deleteRecords` 以一次调用应用整批删除:所有列出的记录都从可读状态消失且后端接受该批后才 resolve,拒绝时通常整批未应用;无法建立或恢复批次状态的批量删除会以 `unknown-state` 拒绝,之后该 unit 的所有操作都以同一错误拒绝,直到 `close()` 释放它(关闭后的调用以 `closed` 拒绝)。`single` 布局在原子替换之后失败(目录 fsync 错误)时,新文件可能已落在介质上而调用方看到拒绝;必须关闭后端及其领域,再重新打开以检查已存状态,然后决定是否重试。`single` 介质上的版本不在当前版本和已声明兼容版本内时拒绝 `version-mismatch`;`per-record` 文档的版本在接受集合之外时读作不存在。无法按该 unit 解析的介质拒绝 `malformed-medium`。[`backend.ts`](../../packages/storage/storage/src/backend.ts) 是逐条款的规范性约定,[`tests/contract.ts`](../../packages/storage/storage/tests/contract.ts) 中的共享一致性套件会针对每个后端检查共享条款。[json 后端](../../packages/storage/storage-json/README.zh.md)以原子方式为每个 unit 整文件重新发布一份人类可读文件;[sqlite 后端](../../packages/storage/storage-sqlite/README.zh.md)在单个数据库中每行存储一份文档,用于频繁更新的数据。 ## 声明领域 @@ -58,20 +58,20 @@ interface DomainSpec { /** Current domain format version; reads enforce it according to the selected layout. */ readonly version: number /** - * Medium layout for the backend unit: `single` (the default) stores the + * Document layout for the backend unit: `single` (the default) stores the * whole unit as one document; `per-record` stores each record as its own * document, for units whose records are large, sparse, or individually - * disposable — the projection cache — and scopes version checks per record - * (an unaccepted record document is discarded, never migrated). + * disposable — the projection cache — with per-record version checks. + * Row stores retain unit-wide versioning for either layout request. */ readonly layout?: 'single' | 'per-record' /** * Older domain versions whose stored records the current record schemas * also accept (the declaring owner vouches for that, typically by - * declaring the fields older records lack as optional). `per-record` backends - * read documents stamped with a listed version instead of discarding them, - * and accept a legacy whole-unit file so stamped for the one-time - * bootstrap; writes always stamp {@link version}. + * declaring the fields older records lack as optional). Ordinary reads admit + * listed versions without restamping saved data; writes stamp {@link version} + * while leaving untouched records as saved. Current schemas must therefore + * accept mixed generations even under the current unit stamp. */ readonly compatibleVersions?: readonly number[] /** @@ -94,6 +94,23 @@ interface DomainSpec { `defineDomain(spec)` 固定 spec 的字面量类型,并在拥有方的模块加载时、任何介质被触碰之前就明确报错:领域名或表名不匹配 `UNIT_NAME_RE`、版本不是非负整数、global schema 接受 `null`,这些都会抛出(`null` 是介质的「从未写入」哨兵值,可空的 global 一旦存储就无法往返还原)。`domainTable(schema)` 声明一张表,其键类型是仅存在于编译期的 phantom 类型(通常是[品牌化 id](core.zh.md#branded-ids));`descriptorOf(spec)` 投影出面向后端的 unit 描述符。 + +## 领域版本 + +`version` 表示当前读写格式。`compatibleVersions` 列出拥有方可用当前 schema 解码其记录和全局值的旧版本;只允许小于 `version` 的非负整数。不声明兼容版本时,读取仍要求精确版本。接受旧版本不放宽记录校验,也不允许更新的未知版本。每行已存字段必须能无歧义地确定其含义;单元版本戳无法在混合行中区分相同字段的不同含义。 + +普通兼容打开和读取不会重新盖戳或规范化已存值。整单元 JSON 用一次原子文件替换发布当前版本戳和修改后的数据;SQLite 将首次单元版本更新与修改放在同一事务中提交;批量删除始终使用一个事务。删除不存在的记录或空批次不会推进版本戳。版本戳标识可接受格式,不代表值规范化已经完成;读取器必须接受混合代际。采用单元级版本戳的后端会拒绝不支持的单元版本。 + +发布前的序列化失败或成功的 SQLite 回滚会保留原有数据与版本戳。JSON 替换后的 I/O 失败或 SQLite 回滚本身失败时,即使操作被拒绝,已存结果也可能未知。必须停止使用并关闭后端及其领域,然后重新打开检查已存状态,再决定是否重试。各后端 README 定义了这些失败情况。 + +JSON 的 `per-record` 布局独立检查和标记每份文档;不支持的文档读取为缺失。其已有整单元引导是只读加载的例外:它将接受的历史值复制到当前版本文档中,不转换其中的值。已有的已声明表目录(即使为空)或已声明全局文档会禁止引导。SQLite 无论布局请求为何都保持单元级版本检查。布局与恢复行为见 [JSON 后端](../../packages/storage/storage-json/README.zh.md)和 [SQLite 后端](../../packages/storage/storage-sqlite/README.zh.md)。 + +兼容后继版本需提升 `version`、在 `compatibleVersions` 中保留仍可读的版本戳,并扩展同一 schema 的解码和默认规则。消费者在重写选定记录时规范化值;Storage 不分配应用记录版本。验证历史版本与跨版本升级、混合值、不写入的读取、失败回滚、重启、其他单元隔离和未知版本拒绝。删表与布局变更各自需要保留及升级策略;兼容版本戳本身不定义这些策略。 + +v2 单元可能包含未改动的 v1 值。接受版本戳 2 的 v3 读取器仍须解码这些值;对于跳过 v2 的用户,还必须接受版本戳 1。移除旧解码逻辑前必须重写并验证全部受影响记录,包括已处于当前单元版本戳下的记录。不兼容变更需要在用新 schema 打开前执行明确且可恢复的升级;存储领域没有值迁移执行器。 + +如果需要回到旧读取器,必须在写入新格式前保留一致的备份:首次修改后,旧读取器可能拒绝新的版本戳。手工降低已存版本戳不会逆转值转换。领域兼容性不迁移 SQLite 物理 schema 或 JSON 外层格式,更改后端路由也不会转移已存数据。Session 格式迁移与 SQLite 物理布局版本各有拥有方,不迁移领域值。 + ## 打开的领域 ```ts type-equiv @@ -123,7 +140,7 @@ interface Domain { } ``` -读取是同步的,来自权威的内存态:`KvTable` 暴露 `get`/`entries`/`keys`/`size`(快照迭代器,在排队写入落地期间保持稳定),global 句柄的 `get()` 在第一次 `set` 将 slot 物化到介质之前一直返回 spec 的 `initial`。每次写入——`put`、`delete`、`update`、`global.set`——都在同一条逐领域写链上排队,先在后端完成持久化,再更新内存,最后发出 `domain/changed`;后端写入被拒时内存原样不动,因此读取绝不会偏离介质。`update(key, fn)` 在其写链 slot 上是一次原子的读-改-写(键缺失时拒绝 `missing-key`);`delete` 一个不存在的键 resolve 为 `false`,不产生写入也不产生事件。返回的记录就是存储的对象本身,不是副本——请经 `put`/`update` 整体替换,绝不要就地修改。 +读取是同步的,来自权威的内存态:`KvTable` 暴露 `get`/`entries`/`keys`/`size`(快照迭代器,在排队写入落地期间保持稳定),global 句柄的 `get()` 在第一次 `set` 将 slot 物化到介质之前一直返回 spec 的 `initial`。每次写入——`put`、`delete`、`deleteMany`、`update`、`global.set`——都在同一条逐领域写链上排队,先在后端完成持久化,再更新内存,最后发出 `domain/changed`;后端写入被拒时不会发布领域变更;持久化结果未知时必须重新打开后才能继续使用该快照;若后端报告 `unknown-state`,领域会被隔离,读取与后续写入都会拒绝,直到 `close()` 释放它。`update(key, fn)` 在其写链 slot 上是一次原子的读-改-写(键缺失时拒绝 `missing-key`);`delete` 一个不存在的键 resolve 为 `false`,不产生写入也不产生事件。`deleteMany(keys)` 在一个写链 slot 内把存在的键作为一次后端批量删除移除,resolve 为移除数量,并为每个被移除的键发一次 `domain/changed`;后端写入被拒时所有记录保持原样,也不发事件;`unknown-state` 拒绝会隔离整个领域。返回的记录就是存储的对象本身,不是副本——请经 `put`/`update` 整体替换,绝不要就地修改。 ## 领域 facility:`ctx.storageDomain` diff --git a/docs/subsystems/typert.i18n.yaml b/docs/subsystems/typert.i18n.yaml index d6917635cf..5ea5ab4b27 100644 --- a/docs/subsystems/typert.i18n.yaml +++ b/docs/subsystems/typert.i18n.yaml @@ -12,11 +12,11 @@ en: 21e88d68154c2c92 zh: 8c9e05c65ef0f34d /typert-remote-calls/remote-access-resources: - en: fa95f70437c07395 - zh: d4870b678b569a89 + en: 2e27d0745a4e3eac + zh: eb4ad825852c595b /typert-remote-calls/typert-registry: - en: 5827ef50011811c9 - zh: 21a9e7b368ba211a + en: d891e9390cf890da + zh: f45a31cc2ce2021e /typert-remote-calls/host-gateway: en: 58b923de12e48f18 zh: d3c2372d8becf65e diff --git a/docs/subsystems/typert.md b/docs/subsystems/typert.md index d68d4a1a36..1fe31a9918 100644 --- a/docs/subsystems/typert.md +++ b/docs/subsystems/typert.md @@ -286,7 +286,7 @@ interface RemoteInvocation { ## Remote access resources -Every Remote method is under the access control of [`dsh-api-remote-access`](../../packages/api/remote-access/README.md): a non-owner call is allowed only when the policy for its principal kind binds, on every resource the call touches, a role that lists the endpoint action. The package that owns an identity type merge-declares its resource kind in `TypertResourceMap`; `global`, the built-in identity-less resource, is never a kind there. The Gateway reads a kind's identities from the `resources` readers of `@Remote({ resources })` or `@RemoteScope(key, { resources })`, else from a lookup parameter or scoped Context that declares the kind as its `resource`, else from the default field registered in `typert.resources`; a call that names no resource touches `global`. The [Peer principals Agent Note](../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md) owns the decision. +Every Remote method is under the access control of [`dsh-api-remote-access`](../../packages/api/remote-access/README.md): a non-owner call is allowed only when the policy for its principal kind binds, on every resource the call touches, a role that lists the endpoint action. The package that owns an identity type merge-declares its resource kind in `TypertResourceMap`; `global`, the built-in identity-less resource, is never a kind there. The Gateway reads a kind's identities from the `resources` readers of `@Remote({ resources })` or `@RemoteScope(key, { resources })`, else from a lookup parameter or scoped Context that declares the kind as its `resource`, else from the default field or resolver registered in `typert.resources`; a call that names no resource touches `global`. The [Peer principals Agent Note](../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md) owns the decision. ```ts type-equiv /** @@ -334,11 +334,14 @@ interface RemoteScopeOptions { * throw, an empty list, or an identity other than a non-empty string * refuses the call. For a kind without a reader, the Gateway reads the * identity of a scoped Context whose Host adapter declares that `resource` - * and of lookup parameters declaring it, else the field registered in - * `typert.resources`: a top-level argument or, failing that, the first - * object argument. A call that carries no identity touches `global`. The - * readers and these defaults together must name every resource the method - * accesses: access control never checks a resource they omit. + * and of lookup parameters declaring it, else the registered default of + * `typert.resources`: a `resolve` function receiving the validated named + * wire values and their ordered parameters, or a `field` naming a top-level + * argument or, failing that, a field of the first object argument. A + * throwing resolver, an array result, or a field holding an array refuses + * the call. A call that carries no identity touches `global`. The readers + * and these defaults together must name every resource the method accesses: + * access control never checks a resource they omit. */ readonly resources?: TypertResourceReaders } @@ -358,7 +361,7 @@ interface RemoteMethodOptions exten ## Typert registry -`ctx.typert` separates current-environment descriptors, explicitly selected Remote contributions, lookup providers, scoped Context providers, and the default fields of resource kinds. A lookup provider owns the stable wire declaration and default resolver; Host composition can configure an effect-scoped synchronous or asynchronous resolver for the same key, and unloading that configuration restores the default policy. Registrations are Cordis-owned effects and return awaitable disposers. +`ctx.typert` separates current-environment descriptors, explicitly selected Remote contributions, lookup providers, scoped Context providers, and the default fields or resolvers of resource kinds. A lookup provider owns the stable wire declaration and default resolver; Host composition can configure an effect-scoped synchronous or asynchronous resolver for the same key, and unloading that configuration restores the default policy. Registrations are Cordis-owned effects and return awaitable disposers. ```ts type-equiv /** Minimal Typert runtime consumed through dependency inversion. */ @@ -441,6 +444,8 @@ interface TypertGateway { * @returns whether an owner stream is open and has not been cancelled. */ hasLiveClient(): boolean + /** @returns detached metadata for all unsettled forwarded events in arrival order. */ + getPendingRemoteEvents(): readonly PendingRemoteEventInfo[] /** * Register the application-selected forwarded-event source. * @param source - stream factory installed by the Remote assembly. @@ -661,6 +666,12 @@ Resolve strict generated definitions or conservative SRC markers against current */ hasLiveClient(): boolean +/** + * Inspect unsettled forwarded events without changing their lifetime. + * @returns detached event names and Agent identities. + */ +getPendingRemoteEvents(): readonly PendingRemoteEventInfo[] + /** * Register the sole application-selected forwarded-event source. * @param source - stream factory installed by the Remote assembly. diff --git a/docs/subsystems/typert.zh.md b/docs/subsystems/typert.zh.md index 270e5509bd..840825979e 100644 --- a/docs/subsystems/typert.zh.md +++ b/docs/subsystems/typert.zh.md @@ -286,7 +286,7 @@ interface RemoteInvocation { ## Remote 访问资源 -每个 Remote 方法都受 [`dsh-api-remote-access`](../../packages/api/remote-access/README.zh.md) 的访问控制:只有当该 principal 种类的 policy 在调用访问的每个资源上都绑定了列出该端点 action 的 role 时,非 owner 调用才被放行。拥有某个身份类型的包把其资源种类声明合并进 `TypertResourceMap`;内置的无身份资源 `global` 从不是其中的种类。Gateway 从 `@Remote({ resources })` 或 `@RemoteScope(key, { resources })` 的 `resources` 读取函数读取某个种类的身份,其次是把该种类声明为 `resource` 的 lookup 参数或作用域 Context,再次是在 `typert.resources` 中登记的默认字段;不指向任何资源的调用访问 `global`。决策由 [Peer 身份属性 Agent Note](../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md) 负责。 +每个 Remote 方法都受 [`dsh-api-remote-access`](../../packages/api/remote-access/README.zh.md) 的访问控制:只有当该 principal 种类的 policy 在调用访问的每个资源上都绑定了列出该端点 action 的 role 时,非 owner 调用才被放行。拥有某个身份类型的包把其资源种类声明合并进 `TypertResourceMap`;内置的无身份资源 `global` 从不是其中的种类。Gateway 从 `@Remote({ resources })` 或 `@RemoteScope(key, { resources })` 的 `resources` 读取函数读取某个种类的身份,其次是把该种类声明为 `resource` 的 lookup 参数或作用域 Context,再次是在 `typert.resources` 中登记的默认字段或 resolver;不指向任何资源的调用访问 `global`。决策由 [Peer 身份属性 Agent Note](../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md) 负责。 ```ts type-equiv /** @@ -334,11 +334,14 @@ interface RemoteScopeOptions { * throw, an empty list, or an identity other than a non-empty string * refuses the call. For a kind without a reader, the Gateway reads the * identity of a scoped Context whose Host adapter declares that `resource` - * and of lookup parameters declaring it, else the field registered in - * `typert.resources`: a top-level argument or, failing that, the first - * object argument. A call that carries no identity touches `global`. The - * readers and these defaults together must name every resource the method - * accesses: access control never checks a resource they omit. + * and of lookup parameters declaring it, else the registered default of + * `typert.resources`: a `resolve` function receiving the validated named + * wire values and their ordered parameters, or a `field` naming a top-level + * argument or, failing that, a field of the first object argument. A + * throwing resolver, an array result, or a field holding an array refuses + * the call. A call that carries no identity touches `global`. The readers + * and these defaults together must name every resource the method accesses: + * access control never checks a resource they omit. */ readonly resources?: TypertResourceReaders } @@ -358,7 +361,7 @@ interface RemoteMethodOptions exten ## Typert 注册表 -`ctx.typert` 分开保存当前环境的 descriptor、显式选择的 Remote contribution、lookup 提供方、作用域上下文提供方与资源种类的默认字段。lookup 提供方拥有稳定 wire 声明和默认 resolver;Host 组合可以为同一个 key 配置 effect-scoped 同步或异步 resolver,配置卸载后恢复默认策略。各项注册都是由 Cordis 持有的 effect,并返回可等待的 disposer。 +`ctx.typert` 分开保存当前环境的 descriptor、显式选择的 Remote contribution、lookup 提供方、作用域上下文提供方与资源种类的默认字段或 resolver。lookup 提供方拥有稳定 wire 声明和默认 resolver;Host 组合可以为同一个 key 配置 effect-scoped 同步或异步 resolver,配置卸载后恢复默认策略。各项注册都是由 Cordis 持有的 effect,并返回可等待的 disposer。 ```ts type-equiv /** Minimal Typert runtime consumed through dependency inversion. */ @@ -441,6 +444,8 @@ interface TypertGateway { * @returns whether an owner stream is open and has not been cancelled. */ hasLiveClient(): boolean + /** @returns detached metadata for all unsettled forwarded events in arrival order. */ + getPendingRemoteEvents(): readonly PendingRemoteEventInfo[] /** * Register the application-selected forwarded-event source. * @param source - stream factory installed by the Remote assembly. @@ -661,6 +666,12 @@ Resolve strict generated definitions or conservative SRC markers against current */ hasLiveClient(): boolean +/** + * Inspect unsettled forwarded events without changing their lifetime. + * @returns detached event names and Agent identities. + */ +getPendingRemoteEvents(): readonly PendingRemoteEventInfo[] + /** * Register the sole application-selected forwarded-event source. * @param source - stream factory installed by the Remote assembly. diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index ba18ec87e4..2681677bf3 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -9,8 +9,8 @@ en: 6cc2cd9ced70bb09 zh: 1c0e6cb4ba2ed637 /tool-schema-catalog/tool-package-map: - en: b9911b8ece23135d - zh: 045264132e40e0bd + en: 2615753236eba27b + zh: 79d0231bb539567e /tool-schema-catalog/deepseek-ai-dsh-plugin-manager: en: e0143916bb634762 zh: e0143916bb634762 @@ -54,14 +54,20 @@ en: 4910ab327694ee97 zh: 17e79e4366cb636d /tool-schema-catalog/deepseek-ai-dsh-experimental-browser-use-stagehand-native/stagehand-tabs: - en: 095b18f9376e073d - zh: abd8785f8acaa555 + en: a0d5b9b891358120 + zh: 25793a62709770b5 +/tool-schema-catalog/deepseek-ai-dsh-action-cards: + en: 60c9df6ffda98a1d + zh: 60c9df6ffda98a1d +/tool-schema-catalog/deepseek-ai-dsh-action-cards/propose-action: + en: 633c32b6df889830 + zh: b88ea00b2033c11b /tool-schema-catalog/deepseek-ai-dsh-tool-ask-user: en: e713a4a11a15d13c zh: e713a4a11a15d13c /tool-schema-catalog/deepseek-ai-dsh-tool-ask-user/ask-user-question: - en: 2f86adf8ae823afb - zh: a5dad3d821e75e55 + en: 664dae29d0eae65f + zh: 2efa5d3f2cb31bf9 /tool-schema-catalog/deepseek-ai-dsh-tool-executor-ptc: en: 8c8643ef46fd075f zh: 8c8643ef46fd075f diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index 8733f7441f..7fb197a9c3 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -19,6 +19,7 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-plugin-market` | `plugin_market` | `ctx.tools`, `ctx.pluginMarket` | `tool/call`, `tool/result` | - | - | | `@deepseek-ai/dsh-mcp-resources` | `list_mcp_resource_templates`, `list_mcp_resources`, `read_mcp_resource` | `ctx.tools`, `ctx.mcpResources` | `tool/call`, `tool/result` | - | - | | `@deepseek-ai/dsh-experimental-browser-use-stagehand-native` | `stagehand_act`, `stagehand_extract`, `stagehand_navigate`, `stagehand_observe`, `stagehand_screenshot`, `stagehand_tabs` | `ctx.browserUse`, `ctx.agents`, `ctx.tools`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | - | +| `@deepseek-ai/dsh-action-cards` | `propose_action` | `ctx.tools`, `ctx.agents`, `ctx.sessionProjections`, `ctx.remoteAccess` | `tool/call`, `tool/result`, `plugin:action-cards/decision`, `user/message` | - | Declared only to an Agent that loaded the skill of a registered card kind; the kind packages register their actions, and the Personalized recommendations bundle supplies the shipped kinds. | | `@deepseek-ai/dsh-tool-ask-user` | `ask_user_question` | `ctx.tools`, `ctx.userQuestions` | `tool/call`, `tool/result after an answer or timeout`, `late user/message` | - | ask_user_question keeps the original blocking behavior by default; set `mode: timed` to opt into a foreground timeout and pending result while the question remains answerable. In timed mode, `timeout: -1` keeps that call blocking indefinitely. | | `@deepseek-ai/dsh-tool-executor-ptc` | `run_code` | `ctx.workingDirectory (Agent executions)`, `ctx.tools`, `ctx.ptcRuntime`, `ctx.systemPrompt` | `tool/call`, `one tool/ptc-dispatch-start + tool/ptc-dispatch pair per bridged sub-call`, `tool/result` | - | The PTC executor exposes only run_code to the model and declares other visible capabilities in a generated SDK in the runtime’s language. Program bindings enter the shared guarded tool pipeline in submission order; concurrency-safe bodies overlap up to maxParallelSubCalls, and nested results remain linked to the outer program. | | `@deepseek-ai/dsh-plan-mode` | `exit_plan_mode` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agents`, `ctx.userQuestions (execution time, opportunistic)` | `tool/call`, `plan/mode inactive on an approved review`, `tool/result` | - | exit_plan_mode stays in the model-facing schema while planning is inactive so transitions add no tool-catalog churn on top of the plan-policy change. Its execute path rejects calls outside plan mode; in plan mode it presents the plan over the user-questions seam (approve / keep planning with feedback), and approval logs plan mode inactive at the step boundary. | @@ -497,13 +498,56 @@ List, create, select, or close a Stagehand browser tab. Source: [`packages/experimental/browser-use-stagehand-native/src/index.ts`](../packages/experimental/browser-use-stagehand-native/src/index.ts) + + +## `@deepseek-ai/dsh-action-cards` + +### `propose_action` + +Show the user one optional action card under this answer. Call only as the skill that names the action instructs. + +```json +{ + "type": "object", + "properties": { + "action": { + "type": "string", + "description": "Action name from the skill." + }, + "title": { + "type": "string", + "description": "Card title." + }, + "brief": { + "type": "string", + "description": "What the action does, in the user's language." + }, + "details": { + "type": "object", + "description": "Fields the skill lists for this action.", + "additionalProperties": true + } + }, + "required": [ + "action", + "title", + "brief", + "details" + ] +} +``` + +Source: [`packages/experimental/action-cards/src/index.ts`](../packages/experimental/action-cards/src/index.ts) + +Declared only to an Agent that loaded the skill of a registered card kind; the kind packages register their actions, and the Personalized recommendations bundle supplies the shipped kinds. + ## `@deepseek-ai/dsh-tool-ask-user` ### `ask_user_question` -Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. +Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. An answer item with empty selected and no custom means the user skipped that question: continue without it, do not ask it again, and do not treat the skip as permission. ```json { diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index 0782f834ce..96a137f294 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -23,6 +23,7 @@ | `@deepseek-ai/dsh-plugin-market` | `plugin_market` | `ctx.tools`, `ctx.pluginMarket` | `tool/call`, `tool/result` | - | - | | `@deepseek-ai/dsh-mcp-resources` | `list_mcp_resource_templates`, `list_mcp_resources`, `read_mcp_resource` | `ctx.tools`, `ctx.mcpResources` | `tool/call`, `tool/result` | - | - | | `@deepseek-ai/dsh-experimental-browser-use-stagehand-native` | `stagehand_act`、`stagehand_extract`、`stagehand_navigate`、`stagehand_observe`、`stagehand_screenshot`、`stagehand_tabs` | `ctx.browserUse`、`ctx.agents`、`ctx.tools`、`ctx.systemPrompt` | `tool/call`、`tool/result` | - | - | +| `@deepseek-ai/dsh-action-cards` | `propose_action` | `ctx.tools`、`ctx.agents`、`ctx.sessionProjections`、`ctx.remoteAccess` | `tool/call`、`tool/result`、`plugin:action-cards/decision`、`user/message` | - | 只向加载过已注册卡片种类 Skill 的 Agent 声明;各种类的包注册自己的动作,个性化推荐 Bundle 提供随产品发布的种类。 | | `@deepseek-ai/dsh-tool-ask-user` | `ask_user_question` | `ctx.tools`、`ctx.userQuestions` | `tool/call`、`tool/result after an answer or timeout`、`late user/message` | - | ask_user_question 默认保持原有阻塞行为;设置 `mode: timed` 后才启用前台超时与 pending 结果,同时问题仍可回答;timed 模式内 `timeout: -1` 让本次调用无限期阻塞。 | | `@deepseek-ai/dsh-tool-executor-ptc` | `run_code` | `ctx.workingDirectory (Agent executions)`、`ctx.tools`、`ctx.ptcRuntime`、`ctx.systemPrompt` | `tool/call`、`one tool/ptc-dispatch-start + tool/ptc-dispatch pair per bridged sub-call`、`tool/result` | - | PTC 执行器只向模型公开 run_code,并在运行时语言生成的 SDK 中声明其他可见能力。程序绑定按提交顺序进入共享的受守卫工具流水线;并行安全的函数体最多重叠 maxParallelSubCalls 个,嵌套结果保持与外层程序关联。 | | `@deepseek-ai/dsh-plan-mode` | `exit_plan_mode` | `ctx.tools`、`ctx.systemPrompt`、`ctx.agents`、`ctx.userQuestions (execution time, opportunistic)` | `tool/call`、`plan/mode inactive on an approved review`、`tool/result` | - | 规划未激活时,exit_plan_mode 仍保留在面向模型的 schema 中,这样状态转换不会在规划策略变更之外额外造成工具目录变动。其执行路径会拒绝规划模式之外的调用;在规划模式下,它通过用户交互 seam 提交计划(批准/根据反馈继续规划),批准后会在步骤边界记录规划模式已停用。 | @@ -501,13 +502,56 @@ 来源:[`packages/experimental/browser-use-stagehand-native/src/index.ts`](../packages/experimental/browser-use-stagehand-native/src/index.ts) + + +## `@deepseek-ai/dsh-action-cards` + +### `propose_action` + +在本次回答下方向用户展示一张可选操作卡片。只按指定该操作的 Skill 的要求调用。 + +```json +{ + "type": "object", + "properties": { + "action": { + "type": "string", + "description": "Action name from the skill." + }, + "title": { + "type": "string", + "description": "Card title." + }, + "brief": { + "type": "string", + "description": "What the action does, in the user's language." + }, + "details": { + "type": "object", + "description": "Fields the skill lists for this action.", + "additionalProperties": true + } + }, + "required": [ + "action", + "title", + "brief", + "details" + ] +} +``` + +来源:[`packages/experimental/action-cards/src/index.ts`](../packages/experimental/action-cards/src/index.ts) + +只向加载过已注册卡片种类 Skill 的 Agent 声明;各种类的包注册自己的动作,个性化推荐 Bundle 提供随产品发布的种类。 + ## `@deepseek-ai/dsh-tool-ask-user` ### `ask_user_question` -继续操作前,如果需要确认、选择或缺失的信息,请向用户提出简明问题。 +继续操作前,如果需要确认、选择或缺失的信息,请向用户提出简明问题。如果回答项的 `selected` 为空且没有 `custom`,表示用户跳过了该问题:不带该回答继续执行,不要再次提问,也不要将跳过视为许可。 ```json { diff --git a/docs/upgrade-guide/v0.2.1-rc.2/approval-projection-dependency/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.2/approval-projection-dependency/guide.i18n.yaml new file mode 100644 index 0000000000..b1b9c9f0b6 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/approval-projection-dependency/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.2/approval-projection-dependency/guide.md +/: + en: 10a5bce762cfa31b + zh: eddf92b54eb31683 +/approval-requires-the-projection-registry: + en: 89b130eab1f61761 + zh: f1382f60b6f8612f +/approval-requires-the-projection-registry/change: + en: a338aa2a5279676c + zh: 8744d85c90437bfd +/approval-requires-the-projection-registry/migration: + en: fd59212cd75f01a2 + zh: a36f9f6c5101d733 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/approval-projection-dependency/guide.md b/docs/upgrade-guide/v0.2.1-rc.2/approval-projection-dependency/guide.md new file mode 100644 index 0000000000..4d0c65f2a3 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/approval-projection-dependency/guide.md @@ -0,0 +1,34 @@ +--- +kind: upgrade-guide +description: "Custom ApprovalService compositions must provide sessionProjections and await service activation." +--- + +# Approval requires the Projection registry + +English | [中文](guide.zh.md) + +## Change + +`ApprovalService` requires `sessionProjections`. It waits for projection registration during activation instead of reading the event log when the registry is absent or pending. Custom compositions that mounted approval alone must add the registry. Shipped profiles already provide it. + +Approval outcomes, audit events, policy defaults, and synchronous business methods keep their existing behavior. Session logs and checkpoint formats do not change. The private registration handle is process-local; checkpoints contain only the policy override and turn state. + +## Migration + +1. In custom `cordis.yml` files, mount `@deepseek-ai/dsh-session-projection` before `@deepseek-ai/dsh-user-approval`. Avoid adding a duplicate registry to a shipped profile. +2. In direct host compositions, use `ctx.plugin(ApprovalService)` and await activation before using `ctx.approval`. Do not construct the service with `new ApprovalService(...)`: that does not run `Service.init`. + + ```ts + import { Context } from '@deepseek-ai/cordis' + import SessionStore from '@deepseek-ai/dsh-session' + import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' + import ApprovalService from '@deepseek-ai/dsh-user-approval' + + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(ApprovalService) + ``` + +3. Let the host and registry complete Session recovery before exposing historical state to synchronous readers. Follow the [registry lifecycle](../../../../packages/session/session-projection/README.md); do not add history loading to approval getters or replay runtime hooks. +4. Confirm activation completes and the existing approval tests still produce the same outcomes and audit records. Registration errors must fail activation instead of selecting a full-log fallback. diff --git a/docs/upgrade-guide/v0.2.1-rc.2/approval-projection-dependency/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.2/approval-projection-dependency/guide.zh.md new file mode 100644 index 0000000000..9ab7d31107 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/approval-projection-dependency/guide.zh.md @@ -0,0 +1,34 @@ +--- +kind: upgrade-guide +description: "自定义 ApprovalService 组合必须提供 sessionProjections 并等待服务激活。" +--- + +# 审批服务要求 Projection 注册表 + +[English](guide.md) | 中文 + +## 变更 + +`ApprovalService` 要求 `sessionProjections`。它在激活时等待 Projection 注册,不再在注册表缺失或尚未就绪时读取事件日志。原先只挂载审批服务的自定义组合必须补上注册表。发布的配置已提供该服务。 + +审批结果、审计事件、策略默认值和同步业务方法保持原有行为。会话日志和检查点格式不变。私有注册句柄仅在进程内有效;检查点只保存策略覆盖值和轮次状态。 + +## 迁移 + +1. 在自定义 `cordis.yml` 中,先挂载 `@deepseek-ai/dsh-session-projection`,再挂载 `@deepseek-ai/dsh-user-approval`。不要向发布的配置重复添加注册表。 +2. 在直接挂载服务的宿主中,使用 `ctx.plugin(ApprovalService)` 并等待激活完成,再使用 `ctx.approval`。不要用 `new ApprovalService(...)` 直接构造服务;这不会执行 `Service.init`。 + + ```ts + import { Context } from '@deepseek-ai/cordis' + import SessionStore from '@deepseek-ai/dsh-session' + import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' + import ApprovalService from '@deepseek-ai/dsh-user-approval' + + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(ApprovalService) + ``` + +3. 由宿主和注册表完成会话恢复,再向同步读取方交付历史状态。遵循[注册表生命周期](../../../../packages/session/session-projection/README.zh.md);不要在审批 getter 中加载历史,也不要在回放时触发运行时钩子。 +4. 确认激活完成,原有审批测试仍产生相同的结果和审计记录。注册错误必须使激活失败,不能切换到全日志回退路径。 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/built-in-japanese/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.2/built-in-japanese/guide.i18n.yaml index a13ae70849..9e6e37a1bf 100644 --- a/docs/upgrade-guide/v0.2.1-rc.2/built-in-japanese/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.1-rc.2/built-in-japanese/guide.i18n.yaml @@ -3,14 +3,14 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.2/built-in-japanese/guide.md /: - en: 383326881143f69b - zh: cd7ff0e2b97f9c2f -/japanese-is-a-built-in-language: - en: f97bae63a42a3627 - zh: cec418f8bf6ac168 -/japanese-is-a-built-in-language/change: - en: feb1f2d1cafdcfe0 - zh: 94d527865ec108bb -/japanese-is-a-built-in-language/migration: - en: ced2c2baad9124b4 - zh: 7b0b5b0e345994b8 + en: cfd1ffd2cd268220 + zh: 2ed03b1063f3319d +/built-in-languages-replace-duplicate-language-packs: + en: 5855b69ac12a5f50 + zh: a81de3239837f1c4 +/built-in-languages-replace-duplicate-language-packs/change: + en: 665e68d784661f15 + zh: 2fff6fcfceea7994 +/built-in-languages-replace-duplicate-language-packs/migration: + en: 6f77e0b507e09ca7 + zh: 59e0c71780f06e9e diff --git a/docs/upgrade-guide/v0.2.1-rc.2/built-in-japanese/guide.md b/docs/upgrade-guide/v0.2.1-rc.2/built-in-japanese/guide.md index 256e77ae05..5c6cf0eaea 100644 --- a/docs/upgrade-guide/v0.2.1-rc.2/built-in-japanese/guide.md +++ b/docs/upgrade-guide/v0.2.1-rc.2/built-in-japanese/guide.md @@ -1,18 +1,18 @@ --- kind: upgrade-guide -description: "Built-in Japanese registrations conflict with third-party Japanese language packs." +description: "Built-in language registrations conflict with third-party language packs using the same ids." --- -# Japanese is a built-in language +# Built-in languages replace duplicate language packs English | [中文](guide.zh.md) ## Change -The locale plugin registers the `ja` language and Japanese dictionaries for `common` and `settings.locale`. Third-party language packs following the previous Japanese README example now fail with an already-registered language or dictionary error. +The locale plugin registers `ja`, `es`, `fr`, `de`, `ru`, and `pt`, with dictionaries for `common`, `settings.locale`, and the built-in UI plugins. Third-party language packs using these ids now fail with an already-registered language or dictionary error, including packs based on the earlier Japanese or French README examples. ## Migration -1. In the language pack's client entry, remove `ctx.locale.addLanguage({ id: 'ja', ... })` and registrations for `common` and `settings.locale` under `ja`. Remove other Japanese dictionary registrations whose namespaces are now supplied by built-in plugins; keep translations for namespaces owned by your own plugins. -2. If the pack represents a distinct language variant, register a separate BCP 47-style id, such as `ja-JP`, for both the definition and its dictionaries instead of `ja`. +1. In the language pack's client entry, remove `ctx.locale.addLanguage(...)` for these ids and dictionary registrations in namespaces supplied by built-in plugins. Keep translations for namespaces owned by your own plugins. +2. If the pack represents a distinct language variant, register a separate BCP 47-style id, such as `fr-CA`, for both the definition and its dictionaries instead of the built-in id. 3. Reload the application with the pack enabled. Confirm it starts without duplicate-registration errors and that selecting the intended language displays its translations. diff --git a/docs/upgrade-guide/v0.2.1-rc.2/built-in-japanese/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.2/built-in-japanese/guide.zh.md index 80382ebe9e..dd98916cc6 100644 --- a/docs/upgrade-guide/v0.2.1-rc.2/built-in-japanese/guide.zh.md +++ b/docs/upgrade-guide/v0.2.1-rc.2/built-in-japanese/guide.zh.md @@ -1,18 +1,18 @@ --- kind: upgrade-guide -description: "内置日语注册会与第三方日语语言包冲突。" +description: "内置语言注册会与使用相同 id 的第三方语言包冲突。" --- -# 日语成为内置语言 +# 内置语言取代重复的语言包 [English](guide.md) | 中文 ## 变更 -locale 插件注册 `ja` 语言,以及 `common` 和 `settings.locale` 的日文字典。按此前 README 日语示例编写的第三方语言包会因语言或字典已注册而加载失败。 +locale 插件注册 `ja`、`es`、`fr`、`de`、`ru` 和 `pt`,并提供 `common`、`settings.locale` 以及内置 UI 插件的字典。使用这些 id 的第三方语言包会因语言或字典已注册而加载失败,包括按此前 README 日语或法语示例编写的语言包。 ## 迁移 -1. 在语言包的 client 入口中,删除 `ctx.locale.addLanguage({ id: 'ja', ... })`,以及 `common` 和 `settings.locale` 下的 `ja` 注册。删除其他已由内置插件提供的命名空间的日语字典注册;保留自己插件所拥有命名空间的翻译。 -2. 如果语言包代表不同的语言变体,为语言定义及其字典注册独立的 BCP 47 风格 id,例如 `ja-JP`,代替 `ja`。 +1. 在语言包的 client 入口中,删除这些 id 的 `ctx.locale.addLanguage(...)`,以及内置插件已提供的命名空间下的字典注册。保留自己插件所拥有命名空间的翻译。 +2. 如果语言包代表不同的语言变体,为语言定义及其字典注册独立的 BCP 47 风格 id,例如 `fr-CA`,代替内置 id。 3. 启用语言包并重新加载应用。确认启动时没有重复注册错误,且选择目标语言后显示对应译文。 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/cua-consent-storage/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.2/cua-consent-storage/guide.i18n.yaml new file mode 100644 index 0000000000..385596d866 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/cua-consent-storage/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.2/cua-consent-storage/guide.md +/: + en: 131777d89cb23df3 + zh: 44e50f8c09b2c4b9 +/computer-use-consent-storage: + en: fb837293708860f5 + zh: 8ee31126d1faf7c7 +/computer-use-consent-storage/change: + en: 88150a92531212bf + zh: a0103c4d035a4af7 +/computer-use-consent-storage/migration: + en: c7a4989a79f4fbca + zh: 630fc23128ee0520 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/cua-consent-storage/guide.md b/docs/upgrade-guide/v0.2.1-rc.2/cua-consent-storage/guide.md new file mode 100644 index 0000000000..05a0bd4011 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/cua-consent-storage/guide.md @@ -0,0 +1,22 @@ +--- +kind: upgrade-guide +description: "Computer Use application consent moves from profile configuration to durable profile-scoped storage." +--- + +# Computer Use consent storage + +English | [中文](guide.zh.md) + +## Change + +Computer Use stores application consent through `storageDomain`. With the default JSON backend, each canonical profile directory has its own `$DSH_HOME/storages/cua_permissions_.json`. “Allow for this session” now follows the conversation ID across DSH restart and Computer Use disablement. It does not authorize another conversation. Unverifiable applications still require a matching native process identity; restarting that application may require new consent. + +`allowedApps` is a legacy import source. The first store access imports it once. Subsequent configuration edits do not grant or revoke access, and a revoked grant is not restored by reloading the old configuration. The permission page remains the authoring interface for grants and refusals. macOS privileges are unchanged. + +## Migration + +1. Keep the profile's existing storage services mounted. Shipped profiles already include `storageDomain` and the JSON backend; custom profiles need the same services. A profile without domain storage refuses authorization operations. +2. Enable Computer Use and open its details to initialize storage. Confirm that the always-allowed applications appear. +3. Remove `allowedApps` from the CUA entry in the profile configuration and other overlays after confirmation. Keep the remaining CUA configuration. +4. Use the permission page to revoke applications or allow asking again. Existing conversation-only grants held by an older running process cannot be recovered; grant those once after upgrading. Newly granted conversation access then survives restart. +5. Keep the storage file with that profile's state. Moving the profile to a different real directory selects a different store. File locks coordinate processes on one machine, not different machines sharing a network filesystem. diff --git a/docs/upgrade-guide/v0.2.1-rc.2/cua-consent-storage/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.2/cua-consent-storage/guide.zh.md new file mode 100644 index 0000000000..fb9e8f39f3 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/cua-consent-storage/guide.zh.md @@ -0,0 +1,22 @@ +--- +kind: upgrade-guide +description: "Computer Use 应用授权从 profile 配置迁移到按 profile 隔离的持久存储。" +--- + +# Computer Use 授权存储 + +[English](guide.md) | 中文 + +## 变更 + +Computer Use 通过 `storageDomain` 保存应用授权。使用默认 JSON 后端时,每个 profile 的真实目录对应独立的 `$DSH_HOME/storages/cua_permissions_.json`。“本会话允许”现在按对话 ID 跨 DSH 重启和 Computer Use 启停保留,不授权其他对话。无法验证签名的应用仍需匹配本机进程身份,应用重启后可能需要重新授权。 + +`allowedApps` 作为旧数据来源,只在首次访问存储时导入一次。此后修改配置不会授予或撤销访问权限,重新加载旧配置也不会恢复已撤销的许可。权限页继续提供授权管理和清除拒绝的操作。macOS 系统权限保持原样。 + +## 迁移 + +1. 保留 profile 的现有存储服务。随附 profile 已包含 `storageDomain` 和 JSON 后端,自定义 profile 需要挂载相同服务。有 profile 但没有域存储时,授权操作会被拒绝。 +2. 启用 Computer Use 并打开详情页,初始化存储。确认始终允许的应用显示正确。 +3. 确认后,从 profile 配置及其他覆盖层的 CUA 条目中删除 `allowedApps`,保留其他 CUA 配置。 +4. 在权限页撤销应用授权或允许再次询问。旧进程内已有的会话许可无法恢复,升级后需要重新授予一次;新授予的会话许可随后可跨重启保留。 +5. 将存储文件作为该 profile 的状态保留。把 profile 移到另一个真实目录后会使用不同存储。文件锁协调同一电脑上的进程,不支持多台电脑共用网络文件系统。 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/official-bundle-lists/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.2/official-bundle-lists/guide.i18n.yaml index 5697bed51b..e0d389e024 100644 --- a/docs/upgrade-guide/v0.2.1-rc.2/official-bundle-lists/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.1-rc.2/official-bundle-lists/guide.i18n.yaml @@ -12,5 +12,5 @@ en: 0d8984d9bead43c6 zh: 60939a14fcf1ba9a /import-bundle-lists-from-deepseek-ai-dsh-official-bundles/migration: - en: 6db29a6197a38b9e - zh: f1b445be37526806 + en: ef2f3d6258a3b2bb + zh: 65a79e9551f8b237 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/official-bundle-lists/guide.md b/docs/upgrade-guide/v0.2.1-rc.2/official-bundle-lists/guide.md index 602fa01af5..1316bd299f 100644 --- a/docs/upgrade-guide/v0.2.1-rc.2/official-bundle-lists/guide.md +++ b/docs/upgrade-guide/v0.2.1-rc.2/official-bundle-lists/guide.md @@ -15,4 +15,4 @@ English | [中文](guide.zh.md) 1. Add `@deepseek-ai/dsh-official-bundles` to the `dependencies` of each package that imports one of these names. 2. Change those imports from `@deepseek-ai/dsh-app-boot` to `@deepseek-ai/dsh-official-bundles`, for example `import { PROFILE_TEMPLATES } from '@deepseek-ai/dsh-official-bundles'`. Keep importing every other name, such as `initProfile` or `loadProfile`, from `@deepseek-ai/dsh-app-boot`. -3. Run your type check or build; it succeeds when no import of a moved name from `@deepseek-ai/dsh-app-boot` remains. See the [package README](../../../../packages/boot/official-bundles/README.md) for each list. +3. Run your type check or build; it succeeds when no import of a moved name from `@deepseek-ai/dsh-app-boot` remains. See the [package README](../../../../packages/util/official-bundles/README.md) for each list. diff --git a/docs/upgrade-guide/v0.2.1-rc.2/official-bundle-lists/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.2/official-bundle-lists/guide.zh.md index bff51e358a..50047b0522 100644 --- a/docs/upgrade-guide/v0.2.1-rc.2/official-bundle-lists/guide.zh.md +++ b/docs/upgrade-guide/v0.2.1-rc.2/official-bundle-lists/guide.zh.md @@ -15,4 +15,4 @@ description: "组合包列表和 profile 模板从 @deepseek-ai/dsh-app-boot 移 1. 在每个导入这些名称的包的 `dependencies` 中加入 `@deepseek-ai/dsh-official-bundles`。 2. 把这些导入从 `@deepseek-ai/dsh-app-boot` 改为 `@deepseek-ai/dsh-official-bundles`,例如 `import { PROFILE_TEMPLATES } from '@deepseek-ai/dsh-official-bundles'`。其他名称(如 `initProfile` 或 `loadProfile`)仍从 `@deepseek-ai/dsh-app-boot` 导入。 -3. 运行类型检查或构建;不再有从 `@deepseek-ai/dsh-app-boot` 导入已移动名称的代码时即通过。各列表的说明见[包 README](../../../../packages/boot/official-bundles/README.zh.md)。 +3. 运行类型检查或构建;不再有从 `@deepseek-ai/dsh-app-boot` 导入已移动名称的代码时即通过。各列表的说明见[包 README](../../../../packages/util/official-bundles/README.zh.md)。 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/ptc-script-format/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.2/ptc-script-format/guide.i18n.yaml new file mode 100644 index 0000000000..97b26e625d --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/ptc-script-format/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.2/ptc-script-format/guide.md +/: + en: 2503e2027c918185 + zh: ffd1bf229fdfbb7d +/handle-script-programs-and-explicit-state-retention: + en: 484afb11caae52a3 + zh: e2c5e8a365845828 +/handle-script-programs-and-explicit-state-retention/change: + en: e8631aefd51606cd + zh: 39cffa3d535b903e +/handle-script-programs-and-explicit-state-retention/migration: + en: 2f9132751d5be30e + zh: c6bc98904eff22ce diff --git a/docs/upgrade-guide/v0.2.1-rc.2/ptc-script-format/guide.md b/docs/upgrade-guide/v0.2.1-rc.2/ptc-script-format/guide.md new file mode 100644 index 0000000000..25a4c77a18 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/ptc-script-format/guide.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "PTC programFormat includes Script syntax, and consumers read retainsState for cross-call memory." +--- + +# Handle Script programs and explicit state retention + +English | [中文](guide.zh.md) + +## Change + +The published `@deepseek-ai/dsh-ptc-runtime` service widens `PtcRuntime.programFormat` from `'function-body' | 'repl'` to include `'script'`. External consumers that exhaustively match the old union must handle the new value. `retainsState` reports whether a provider preserves memory for a `stateOwner`; its base implementation returns `false`, so custom retained providers must override it. + +Node keeps `per-call` as its default. The opt-in `executionMode: vm-script` accepts Script statements and top-level await, with `scriptPersistence` selecting cross-call memory independently. Existing Node function-body and REPL configurations remain valid. + +## Migration + +1. Import the exported `PtcProgramFormat` from `@deepseek-ai/dsh-ptc-runtime` instead of copying its union literals. Update `programFormat` switches in custom tool or workflow adapters. Handle `'script'` using statements or a final expression, without top-level `return`; consult the [Node syntax reference](../../../../packages/ptc-runtime/ptc-runtime-node/README.md#use-this-package). +2. Replace checks that infer memory retention from `programFormat === 'repl'` with `runtime.retainsState`. If a custom `PtcRuntime` provider retains owner-scoped memory, override `retainsState` to return `true` and continue implementing `release(owner)`. +3. Rebuild external consumers against the new package declarations. Confirm that each supported format compiles and that persistence controls follow `retainsState` for both REPL and Script providers. diff --git a/docs/upgrade-guide/v0.2.1-rc.2/ptc-script-format/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.2/ptc-script-format/guide.zh.md new file mode 100644 index 0000000000..e5f28af66a --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/ptc-script-format/guide.zh.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "PTC programFormat 新增 Script 语法,消费者通过 retainsState 判断跨调用内存保留。" +--- + +# 处理 Script 程序与显式状态保留 + +[English](guide.md) | 中文 + +## 变更 + +已发布的 `@deepseek-ai/dsh-ptc-runtime` 服务将 `PtcRuntime.programFormat` 从 `'function-body' | 'repl'` 扩展为包含 `'script'`。对旧联合类型做穷举匹配的外部消费者必须处理新值。`retainsState` 表示提供方是否为 `stateOwner` 保留内存;基类实现返回 `false`,因此自定义保留状态的提供方必须覆盖该 getter。 + +Node 仍默认使用 `per-call`。显式启用的 `executionMode: vm-script` 接受 Script 语句和顶层 await,`scriptPersistence` 独立选择是否跨调用保留内存。已有 Node 函数体和 REPL 配置仍然有效。 + +## 迁移 + +1. 从 `@deepseek-ai/dsh-ptc-runtime` 导入已导出的 `PtcProgramFormat`,不复制其联合类型字面量。更新自定义工具或工作流适配器中的 `programFormat` 分支。使用语句或末尾表达式处理 `'script'`,不使用顶层 `return`;参见 [Node 语法参考](../../../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#use-this-package)。 +2. 将通过 `programFormat === 'repl'` 推断内存保留的检查改为读取 `runtime.retainsState`。自定义 `PtcRuntime` 提供方若按所有者保留内存,应覆盖 `retainsState` 并返回 `true`,同时继续实现 `release(owner)`。 +3. 使用新的包声明重新构建外部消费者。确认所有支持的格式均可编译,并且持久化控制对 REPL 和 Script 提供方都按 `retainsState` 判断。 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/attachment-read-access/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.3/attachment-read-access/guide.i18n.yaml new file mode 100644 index 0000000000..efe907e2eb --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/attachment-read-access/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.3/attachment-read-access/guide.md +/: + en: 1e002ad3fd9b1e79 + zh: aeba3ee1e74fa2ae +/image-read-requests-carry-the-complete-attachment-reference: + en: df690494e7cec0b8 + zh: e21d937f2f305d8e +/image-read-requests-carry-the-complete-attachment-reference/change: + en: cca17091c60b9757 + zh: 8f300ab9d0b870d8 +/image-read-requests-carry-the-complete-attachment-reference/migration: + en: b593e623619ea508 + zh: 41714f50a249f941 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/attachment-read-access/guide.md b/docs/upgrade-guide/v0.2.1-rc.3/attachment-read-access/guide.md new file mode 100644 index 0000000000..3aac18a52f --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/attachment-read-access/guide.md @@ -0,0 +1,23 @@ +--- +kind: upgrade-guide +description: "Image read requests require a complete attachment reference and no longer check Session membership." +--- + +# Image read requests carry the complete attachment reference + +English | [中文](guide.zh.md) + +## Change + +In 0.2.1-rc.3, `session/attachment` accepted `{ sessionId, attachmentId }` and searched the requested Session's history for the complete image reference. It now requires `{ sessionId, attachment: ref }`, where `ref` is an `ImageAttachmentRef` containing `attachmentId`, `mediaType`, `bytes`, `width`, and `height`. The Client's `session.readAttachment()` also takes the complete reference instead of an ID. + +The Host passes this reference to the existing `AttachmentStore.readImage(ref)`. It verifies the ID, actual format, byte length, width, and height against the stored object. The response remains `{ attachment, data }`, with base64 bytes in `data`. It preserves the supplied reference, including optional `name` and `originalDimensions`; those two fields are caller-supplied display information and are not verified against the file. Missing, corrupt, and mismatched objects fail explicitly. + +Connection authentication and Gateway permission checks still apply. Any identity authorized to call the endpoint for the supplied `sessionId` may read an image in the same store, including one referenced only by another Session or by no Session. The handler does not check image membership or Session existence and no longer returns `session/not-found` for an absent Session after authorization. + +## Migration + +1. Update wire calls from `{ sessionId, attachmentId: ref.attachmentId }` to `{ sessionId, attachment: ref }`, using the complete reference from the message image block. Update Client calls from `session.readAttachment(ref.attachmentId)` to `session.readAttachment(ref)`. +2. Treat returned `name` and `originalDimensions` as the caller's display information. Only the ID, media type, byte length, width, and height are checked against the stored object. +3. If your deployment depends on Session membership to isolate images, run separate Host instances with separate `DSH_HOME` directories before upgrading. The shipped composition does not select separate stores by Session within one Host. Gateway permissions govern endpoint invocation, not the image's Session membership. +4. Confirm that an allowed request with a complete reference can read an image absent from the supplied Session, including when that Session does not exist. Denied Gateway requests, missing images, and references with mismatched intrinsic metadata must fail. Existing Session logs and stored images need no migration. diff --git a/docs/upgrade-guide/v0.2.1-rc.3/attachment-read-access/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.3/attachment-read-access/guide.zh.md new file mode 100644 index 0000000000..d4d3a2e2b6 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/attachment-read-access/guide.zh.md @@ -0,0 +1,23 @@ +--- +kind: upgrade-guide +description: "图片读取请求必须携带完整附件引用,并且不再检查 Session 关联。" +--- + +# 图片读取请求需携带完整附件引用 + +[English](guide.md) | 中文 + +## 变更 + +在 0.2.1-rc.3 中,`session/attachment` 接收 `{ sessionId, attachmentId }`,并在请求中的 Session 历史里查找完整图片引用。现在,请求必须使用 `{ sessionId, attachment: ref }`,其中 `ref` 是包含 `attachmentId`、`mediaType`、`bytes`、`width` 和 `height` 的 `ImageAttachmentRef`。Client 的 `session.readAttachment()` 也改为接收完整引用,不再只接收 ID。 + +Host 把该引用交给已有的 `AttachmentStore.readImage(ref)`,将 ID、实际格式、字节数、宽度和高度与存储对象校验。响应仍为 `{ attachment, data }`,`data` 包含 base64 字节。响应保留传入引用,包括可选的 `name` 和 `originalDimensions`;这两个字段是调用方提交的显示信息,不根据文件校验。对象缺失、损坏或与引用不符时会明确失败。 + +连接身份认证和 Gateway 权限检查仍然适用。任何有权为请求中的 `sessionId` 调用该接口的身份,都可以读取同一存储中的图片,包括仅被其他 Session 引用或未被任何 Session 引用的图片。处理函数不检查图片关联或 Session 是否存在,授权通过后不再因 Session 不存在而返回 `session/not-found`。 + +## 迁移 + +1. 把 wire 调用从 `{ sessionId, attachmentId: ref.attachmentId }` 改为 `{ sessionId, attachment: ref }`,使用消息图片块中的完整引用。把 Client 调用从 `session.readAttachment(ref.attachmentId)` 改为 `session.readAttachment(ref)`。 +2. 把返回的 `name` 和 `originalDimensions` 视为调用方的显示信息。只有 ID、媒体类型、字节数、宽度和高度会与存储对象校验。 +3. 如果部署依赖 Session 关联来隔离图片,请在升级前改用独立 Host 实例及各自的 `DSH_HOME` 目录。随附组合不会在一个 Host 内按 Session 选择独立存储。Gateway 权限约束接口调用,不约束图片的 Session 关联。 +4. 确认获准调用的请求可以凭完整引用读取其 Session 中没有记录的图片,即使该 Session 不存在也可以读取。Gateway 拒绝的请求、缺失图片和固有元数据不符的引用必须失败。已有 Session 日志和存储图片无需迁移。 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/cua-bundle-id-consent/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.3/cua-bundle-id-consent/guide.i18n.yaml new file mode 100644 index 0000000000..c86fcc5009 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/cua-bundle-id-consent/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.3/cua-bundle-id-consent/guide.md +/: + en: af8e19ff73adbfbd + zh: 9daf099256b07409 +/macos-computer-use-application-identity: + en: d24696e5f85e9144 + zh: 184f7ebd8b8880df +/macos-computer-use-application-identity/change: + en: 7edc0de236633686 + zh: 08afc35393c95484 +/macos-computer-use-application-identity/migration: + en: 9c13aeec5e544d36 + zh: da697d3ee5a4637f diff --git a/docs/upgrade-guide/v0.2.1-rc.3/cua-bundle-id-consent/guide.md b/docs/upgrade-guide/v0.2.1-rc.3/cua-bundle-id-consent/guide.md new file mode 100644 index 0000000000..c1010bf678 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/cua-bundle-id-consent/guide.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: macOS Computer Use grants use bundle identifiers and require renewed consent for old application identities. +--- + +# macOS Computer Use application identity + +English | [中文](guide.zh.md) + +## Change + +Application grants use the case-sensitive native bundle identifier. Versions and copies at different paths share permission and revocation, regardless of signing. Applications without a bundle identifier use their canonical executable path and can also receive always-allow grants. Restarting or replacing the executable at that path retains consent; moving it requires renewed consent. A valid running bundle identifier does not require an executable path. Grant records can omit executablePath, and the permission page then shows the name without a path tooltip or icon. Existing records remain readable; older versions that require this field cannot read new pathless records. The profile storage location and conversation scopes are unchanged. + +This affects macOS users with saved path/signature grants, including grants imported from the legacy `allowedApps` configuration. Those grants do not match the new identities. They remain visible and removable but do not authorize other installations automatically. Old and new records can show the same name and path; the permission page does not distinguish them. Another program declaring an approved bundle identifier or replacing an executable at an approved fallback path inherits permission; this policy does not authenticate publishers. + +## Migration + +1. In Computer Use application management, revoke every existing always-allowed entry for each affected application before selecting it again. If you already granted access after upgrading, remove all entries for that application rather than trying to distinguish old and new records. +2. Under “Applications not allowed,” use “Allow asking again” for that application so a prior refusal or revocation does not prevent the next prompt. Select the application again and approve the intended scope. “Always allow” covers all versions and copies with the same bundle identifier within the profile. +3. Select another installed copy with that bundle identifier and confirm it does not ask again within the granted scope. Revoke the shared grant to stop access for all copies. Versions with different bundle identifiers still require separate approval. diff --git a/docs/upgrade-guide/v0.2.1-rc.3/cua-bundle-id-consent/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.3/cua-bundle-id-consent/guide.zh.md new file mode 100644 index 0000000000..c3b9103501 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/cua-bundle-id-consent/guide.zh.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: macOS Computer Use 授权改用 Bundle ID,旧应用身份需要重新授权。 +--- + +# macOS Computer Use 应用身份 + +[English](guide.md) | 中文 + +## 变更 + +应用授权使用原生应用提供的、区分大小写的 Bundle ID。不同路径的版本和副本共用许可与撤销决定,不受签名状态影响。缺少 Bundle ID 的应用使用规范化可执行路径,也可以“始终允许”。在该路径重启或替换可执行文件会沿用许可,移动文件则需重新授权。运行中的有效 Bundle ID 不依赖可执行路径。授权记录可以省略 executablePath,权限页此时显示名称,不显示路径提示或图标。已有记录仍可读取,要求该字段的旧版本无法读取缺少路径的新记录。profile 存储位置和对话范围保持不变。 + +受影响的是保存过路径和签名授权的 macOS 用户,包括通过旧 `allowedApps` 配置导入授权的用户。这些授权不匹配新身份。旧记录仍可查看和撤销,但不会自动授权其他安装副本。新旧条目可能显示相同名称和路径,权限页没有区分它们。其他程序声明已批准的 Bundle ID,或替换路径授权对应的可执行文件时,也会继承许可,这项规则不验证发布者身份。 + +## 迁移 + +1. 重新选择应用前,在 Computer Use 应用管理中撤销该应用的所有“始终允许”条目。如果升级后已经批准过,也移除该应用的全部条目,无须判断哪条是旧记录。 +2. 在“不允许访问的应用”中,对该应用点击“允许再次询问”,避免先前的拒绝或撤销阻止下次提示。重新选择应用并批准所需范围。“始终允许”覆盖当前 profile 中相同 Bundle ID 的所有版本和副本。 +3. 选择具有相同 Bundle ID 的另一个已安装副本,确认在许可范围内不再询问。需要停止所有副本的访问时,撤销共用许可。使用不同 Bundle ID 的版本仍需分别批准。 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/independent-session-forks/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.3/independent-session-forks/guide.i18n.yaml new file mode 100644 index 0000000000..d75920e7c9 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/independent-session-forks/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.3/independent-session-forks/guide.md +/: + en: 68f919837577038b + zh: 6ae8223b1542c369 +/ordinary-forks-are-independent-sessions: + en: 4556d51bd8086cfe + zh: 8811b03db9225739 +/ordinary-forks-are-independent-sessions/change: + en: 0a2790279aec9e24 + zh: 5cca673af988a228 +/ordinary-forks-are-independent-sessions/migration: + en: 53b586ad6498fdb8 + zh: dfa70928e17478e2 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/independent-session-forks/guide.md b/docs/upgrade-guide/v0.2.1-rc.3/independent-session-forks/guide.md new file mode 100644 index 0000000000..0bff80da2a --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/independent-session-forks/guide.md @@ -0,0 +1,23 @@ +--- +kind: upgrade-guide +description: "Ordinary Session forks stop recording their source relationship and stop appearing as subagents." +--- + +# Ordinary forks are independent Sessions + +English | [中文](guide.zh.md) + +## Change + +Ordinary forks copy the selected history and continue independently. They omit `SessionHeader.parentSession` and the Client's `parentSessionId`; no replacement source field is written. Subagents, including fork-backend subagents, retain their direct creator. Existing logs retain their recorded metadata. + +SDK `subagent.started` excludes ordinary forks, including historical ones carrying a parent id. ACP list/resume admits ordinary forks; headless adoption also accepts them when cwd and preset checks pass. Client lists no longer indent them or insert newly discovered forks before their sources; saved manual positions remain intact. Source-based trace queries, parent filters, telemetry, and remote logs cannot recover the source of new ordinary forks. Workspace binding, optional title increments, inherited history, and seed boundaries remain available. + +The Session format stays V4. Older V4 readers may reject a parentless fork containing inherited delivery acknowledgements as a corrupt log with `current-generation delivery marker names the wrong Session`. The tested readers refuse before granting a handle or truncating the file. They do not provide an upgrade-specific diagnostic. See the [compatibility decision](../../../../.agents/notes/implemented/architecture/2026-10-23-independent-session-forks.md). + +## Migration + +1. Upgrade every reader and writer sharing the Session directory before resuming newly created forks. Do not edit old headers or delete delivery records to bypass an older reader's rejection. +2. Replace consumer checks that treat any `parentSession` as a subagent with `origin === 'subagent'`. Continuation still requires a valid descriptor from the Session's own event range; inherited descriptors do not establish its identity. +3. Remove any ordinary-fork workflow that requires persistent source tracing. Keep source-dependent actions such as workspace selection within the fork operation. +4. Confirm that an ordinary fork has no parent field, survives restart with inherited delivery records, and produces no `subagent.started`; confirm that real subagents retain their creator and notification. diff --git a/docs/upgrade-guide/v0.2.1-rc.3/independent-session-forks/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.3/independent-session-forks/guide.zh.md new file mode 100644 index 0000000000..fdd5b53f99 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/independent-session-forks/guide.zh.md @@ -0,0 +1,23 @@ +--- +kind: upgrade-guide +description: "普通 Session fork 停止记录来源关系,也不再显示为子代理。" +--- + +# 普通 fork 是独立 Session + +[English](guide.md) | 中文 + +## 变更 + +普通 fork 复制选定历史并独立继续运行。它们省略 `SessionHeader.parentSession` 及客户端的 `parentSessionId`,不写入替代来源字段。子代理(包括使用 fork backend 的子代理)保留直接创建者。已有日志保留记录中的元数据。 + +SDK 的 `subagent.started` 排除普通 fork,包括携带父 ID 的历史会话。ACP 列表和恢复允许普通 fork;通过 cwd 和 preset 检查的普通 fork 也可由 headless 沿用。客户端列表不再将它们缩进,也不再把新发现的 fork 插到来源之前;已保存的手动位置保持不变。基于来源的追踪查询、父关系筛选、遥测和远端日志无法还原新普通 fork 的来源。工作区绑定、可选标题递增、继承历史和 seed 边界仍然可用。 + +Session 格式保持 V4。旧 V4 reader 可能将包含继承投递确认的无父关系 fork 作为损坏日志拒绝,报错为 `current-generation delivery marker names the wrong Session`。已测试的 reader 在授予句柄或截断文件之前拒绝,不提供专门的升级诊断。参见[兼容性决策](../../../../.agents/notes/implemented/architecture/2026-10-23-independent-session-forks.zh.md)。 + +## 迁移 + +1. 在恢复新建 fork 之前,升级共享 Session 目录的全部 reader 和 writer。不要编辑旧 header 或删除投递记录来绕过旧 reader 的拒绝。 +2. 将消费方中把任意 `parentSession` 视为子代理的检查替换为 `origin === 'subagent'`。继续运行仍要求来自 Session 自身事件区间的有效 descriptor;继承的 descriptor 不建立其身份。 +3. 移除依赖持久化来源追踪的普通 fork 工作流。工作区选择等依赖来源的动作保留在 fork 操作期间。 +4. 确认普通 fork 不含父字段、携带继承投递记录也能在重启后恢复,且不产生 `subagent.started`;确认真正子代理保留创建者及通知。 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/ptc-caller-cancellation/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.3/ptc-caller-cancellation/guide.i18n.yaml new file mode 100644 index 0000000000..50d54a9371 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/ptc-caller-cancellation/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.3/ptc-caller-cancellation/guide.md +/: + en: 6deb73f8bd3b1b2a + zh: 8bafa6e8c6277923 +/ptc-caller-cancellation-uses-the-standard-tool-error-code: + en: c647ac85178ef0ea + zh: a6e5b76d53bbb6ef +/ptc-caller-cancellation-uses-the-standard-tool-error-code/change: + en: 1a9a455bf55e6b81 + zh: ec925abc44d7684f +/ptc-caller-cancellation-uses-the-standard-tool-error-code/migration: + en: e3bbbebda24059c0 + zh: 926e91f3ce5a8a72 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/ptc-caller-cancellation/guide.md b/docs/upgrade-guide/v0.2.1-rc.3/ptc-caller-cancellation/guide.md new file mode 100644 index 0000000000..a53b061808 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/ptc-caller-cancellation/guide.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "Caller-cancelled run_code results use ABORTED instead of CODE_RUN_FAILED." +--- + +# PTC caller cancellation uses the standard tool error code + +English | [中文](guide.zh.md) + +## Change + +When a running `run_code` call is cancelled by its caller and the runtime reports `abort`, its `tool/result` error changes from `CodeRunFailedError` / `CODE_RUN_FAILED` to `AbortError` / `ABORTED`. The result content is `Error: tool call aborted`, replacing the runtime diagnostic, captured output and sandbox summary. SDK clients and Session consumers that classify these results are affected. + +The Agent continues to record the specific cancellation cause in `turn/end`, including a hook's `reason`. Runtime failures such as timeout and cleanup failure, and runtime-local cancellation without caller cancellation, retain `CODE_RUN_FAILED`. Cancellation still waits for cleanup; it does not roll back completed tool effects, and retained runtime variables may be cleared. + +## Migration + +1. In consumers of new `tool/result` events, classify caller cancellation by `data.error.code === 'ABORTED'`. Read the Agent cancellation cause from the corresponding `turn/end` event's `data.reason.reason` when `data.reason.kind === 'aborted'`. +2. Keep support for `CODE_RUN_FAILED` when reading historical PTC cancellation results. Existing Session logs are not rewritten. +3. Cancel a running `run_code` call and confirm its result has code `ABORTED`, followed by a `turn/end` event containing the original Agent cancellation cause. Confirm ordinary runtime failures still report `CODE_RUN_FAILED`. diff --git a/docs/upgrade-guide/v0.2.1-rc.3/ptc-caller-cancellation/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.3/ptc-caller-cancellation/guide.zh.md new file mode 100644 index 0000000000..fbd17773ec --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/ptc-caller-cancellation/guide.zh.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "调用方取消的 run_code 结果使用 ABORTED,取代 CODE_RUN_FAILED。" +--- + +# PTC 调用方取消使用标准工具错误码 + +[English](guide.md) | 中文 + +## 变更 + +运行中的 `run_code` 被调用方取消且运行时报告 `abort` 时,其 `tool/result` 错误从 `CodeRunFailedError` / `CODE_RUN_FAILED` 变为 `AbortError` / `ABORTED`。结果内容为 `Error: tool call aborted`,取代运行时诊断、捕获输出和沙箱摘要。按这些结果分类的 SDK 客户端和 Session 消费方受到影响。 + +Agent 继续在 `turn/end` 中记录具体取消原因,包括 hook 的 `reason`。超时、清理失败等运行时失败,以及没有调用方取消的运行时内部取消,保留 `CODE_RUN_FAILED`。取消仍等待清理完成;它不会回滚已完成的工具操作,保留的运行时变量可能被清空。 + +## 迁移 + +1. 在新 `tool/result` 事件的消费方中,通过 `data.error.code === 'ABORTED'` 识别调用方取消。当对应 `turn/end` 事件的 `data.reason.kind === 'aborted'` 时,从 `data.reason.reason` 读取 Agent 取消原因。 +2. 读取历史 PTC 取消结果时,继续支持 `CODE_RUN_FAILED`。已有 Session 日志不会被重写。 +3. 取消运行中的 `run_code`,确认其结果错误码为 `ABORTED`,随后的 `turn/end` 事件包含原始 Agent 取消原因。确认普通运行时失败仍报告 `CODE_RUN_FAILED`。 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/session-follow-activation/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.3/session-follow-activation/guide.i18n.yaml new file mode 100644 index 0000000000..8e84c0dcab --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/session-follow-activation/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.3/session-follow-activation/guide.md +/: + en: 789ee06aa8932a32 + zh: d465eb26824f2b4b +/request-activation-when-following-a-session: + en: 25bd54a8216b1c71 + zh: edaa12b04713528a +/request-activation-when-following-a-session/change: + en: d4021672fedcbfb7 + zh: 35d5e76a69301e4a +/request-activation-when-following-a-session/migration: + en: aa22d72ca3f91d38 + zh: ebe991eca4bf74c2 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/session-follow-activation/guide.md b/docs/upgrade-guide/v0.2.1-rc.3/session-follow-activation/guide.md new file mode 100644 index 0000000000..cb01f8e90e --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/session-follow-activation/guide.md @@ -0,0 +1,21 @@ +--- +kind: upgrade-guide +description: "Session follow callers must explicitly request background Agent activation." +--- +# Request activation when following a Session + +English | [中文](guide.zh.md) + +## Change + +`session.follow` no longer automatically resumes a cold ordinary Agent when `activate` is omitted. It reads the opening snapshot and follows subsequent events without activation. This affects integrations that used opening a history stream to make an Agent available. The shipped Web Client sends `activate: true` explicitly and retains its opening behavior. + +With `activate: true`, activation starts once the opening snapshot is computed, before it is delivered; that snapshot does not acknowledge Agent readiness. Subagent Sessions still do not use ordinary Agent activation. + +## Migration + +1. Add `activate: true` to `session.follow` requests that must resume a cold ordinary Agent. Keep the existing `address` and history-window fields. +2. For passive viewers, omit `activate` or set it to `false`. +3. Verify that an activation-enabled stream still returns its opening snapshot, then check Agent availability separately. Do not treat receipt of the snapshot as completion of activation. + +See the [Session Controller reference](../../../../packages/api/session-controller/README.md) for history and state observation behavior. diff --git a/docs/upgrade-guide/v0.2.1-rc.3/session-follow-activation/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.3/session-follow-activation/guide.zh.md new file mode 100644 index 0000000000..5df6e523a3 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/session-follow-activation/guide.zh.md @@ -0,0 +1,21 @@ +--- +kind: upgrade-guide +description: "Session follow 调用方必须显式请求后台 Agent 激活。" +--- +# 跟随 Session 时显式请求激活 + +[English](guide.md) | 中文 + +## 变更 + +`session.follow` 在省略 `activate` 时不再自动恢复冷普通 Agent。它只读取开场快照并跟随后续事件,不进行激活。这会影响通过打开历史流使 Agent 可用的集成。随产品提供的 Web Client 显式发送 `activate: true`,保留原有打开行为。 + +设置 `activate: true` 时,激活在开场快照计算完成后、交付之前开始;该快照不确认 Agent 已就绪。子会话仍不走普通 Agent 激活。 + +## 迁移 + +1. 为需要恢复冷普通 Agent 的 `session.follow` 请求添加 `activate: true`,保留原有 `address` 和历史窗口字段。 +2. 被动查看器可以省略 `activate` 或设为 `false`。 +3. 确认启用激活的流仍返回开场快照,再单独检查 Agent 是否可用。不要把收到快照当作激活完成。 + +历史与状态观察行为见 [Session Controller 参考](../../../../packages/api/session-controller/README.zh.md)。 diff --git a/docs/user/guide/plugin-market.i18n.yaml b/docs/user/guide/plugin-market.i18n.yaml index 3a940f4be4..28f727d0e0 100644 --- a/docs/user/guide/plugin-market.i18n.yaml +++ b/docs/user/guide/plugin-market.i18n.yaml @@ -2,33 +2,33 @@ # 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/user/guide/plugin-market.md -/plugin-markets: - en: 09b2a6328dcae63c - zh: ac7bce767e4f5011 -/plugin-markets/summary: - en: 2716b194b8a12aa7 - zh: b90773d095851969 -/plugin-markets/table-of-contents: +/plugin-indexes: + en: 5ee6a364e2708ab9 + zh: 369781529be73628 +/plugin-indexes/summary: + en: a1d8f17e7c4b8357 + zh: 13b95dcedde344f2 +/plugin-indexes/table-of-contents: en: a8d1e6785c3c3c30 zh: 7ea1eaa8204a5a1e -/plugin-markets/turn-on-discover: - en: a5024e57052f6e36 - zh: 39b84e247adc9a18 -/plugin-markets/browse-and-install: - en: cf616bba26958533 - zh: 1e32df16a6f4bba7 -/plugin-markets/publish-an-index: +/plugin-indexes/turn-on-discover: + en: f98bc0913d4bd046 + zh: 104094714786507e +/plugin-indexes/browse-and-install: + en: 0f5a4082d5debe9b + zh: c0e53f186cb31cd4 +/plugin-indexes/publish-an-index: en: b85b82b22c1e14b8 zh: 920c0d6f20956c07 -/plugin-markets/generate-an-index-with-the-reference-generator: +/plugin-indexes/generate-an-index-with-the-reference-generator: en: 6501406f530ffe33 zh: 700acae3f466c985 -/plugin-markets/index-format-reference: - en: d058d12c27433f64 - zh: f43b85e4934817f3 -/plugin-markets/further-exploration: - en: 3c0a90e8bf73c89b - zh: 95608eb4f6278cb4 -/plugin-markets/dev-note: +/plugin-indexes/index-format-reference: + en: 8fed66180a76f815 + zh: 7069ac4eed4bdfd9 +/plugin-indexes/further-exploration: + en: 2223e92806e7e79a + zh: 093309e1c40caa6c +/plugin-indexes/dev-note: en: b75c8458928b72b9 zh: 003ba4e17b4b5269 diff --git a/docs/user/guide/plugin-market.md b/docs/user/guide/plugin-market.md index a690e46c55..45e2629324 100644 --- a/docs/user/guide/plugin-market.md +++ b/docs/user/guide/plugin-market.md @@ -1,10 +1,10 @@ -# Plugin markets +# Plugin indexes English | [中文](plugin-market.zh.md) ## Summary -A plugin market is one JSON index file that lists installable DSH bundles with their titles, icons, authors, and versions. Turn on the experimental **Custom plugin markets** bundle to browse markets in a **Discover** tab on the Plugins page and install a listed version after a confirmation. To publish a market, write or generate an index file and serve it, together with its icon files, from any static host. +A plugin index is one JSON file that lists installable DSH bundles with their titles, icons, authors, and versions. Turn on the experimental **Custom plugin indexes** bundle to browse indexes in a **Discover** tab on the Plugins page and install a listed version after a confirmation. To publish an index, write or generate an index file and serve it, together with its icon files, from any static host. ## Table of Contents @@ -18,20 +18,20 @@ A plugin market is one JSON index file that lists installable DSH bundles with t ## Turn on Discover -Open **Plugins**, find **Custom plugin markets** under **Experimental plugins**, and switch it on. A **Discover** tab appears next to **Installed**, and Creator mode gains the read-only `plugin_market` tool. Switching the bundle off removes both again. +Open **Plugins**, find **Custom plugin indexes** under **Experimental plugins**, and switch it on. A **Discover** tab appears next to **Installed**, and Creator mode gains the read-only `plugin_market` tool. Switching the bundle off removes both again. -DSH ships no index source. Select **Discover**, choose **Add index source**, and enter the URL of an index file. A URL must use `http:` or `https:` and must not contain a user name, password, or `#` fragment. Anyone on the network path can change an `http:` index, including the install specs it lists, so use `https:` for a market reached over a network you do not control. Each source belongs to the current profile. +DSH ships no index source. Select **Discover**, choose **Add index source**, and enter the URL of an index file. A URL must use `http:` or `https:` and must not contain a user name, password, or `#` fragment. Anyone on the network path can change an `http:` index, including the install specs it lists, so use `https:` for an index reached over a network you do not control. Each source belongs to the current profile. ## Browse and install -The market menu at the left of the toolbar switches between sources and opens **Manage index sources…**, where each source shows its last error. Search matches names, authors, keywords, and titles, descriptions, categories, and labels in every language, and tolerates typos; results come in best-match order until you choose another. The **Labels** menu, category pills, and **Sort** menu use the categories, labels, and sort keys that the market declares, and **Publish date** sorts by each plugin's latest version. +The index menu at the left of the toolbar switches between sources and opens **Manage index sources…**, where each source shows its last error. Search matches names, authors, keywords, and titles, descriptions, categories, and labels in every language, and tolerates typos; results come in best-match order until you choose another. The **Labels** menu, category pills, and **Sort** menu use the categories, labels, and sort keys that the index declares, and **Publish date** sorts by each plugin's latest version. Each card shows the plugin's recommended version: the highest version compatible with the running DSH that is not a prerelease, or the highest compatible prerelease when the plugin lists no version without a prerelease tag. **Install** opens a confirmation with that version's source: the npm package and registry, or the Git repository, commit, and directory. Confirming starts the normal plugin installation, including its compatibility and registry checks; nothing is installed without that confirmation. Select a card to open its page. The **Versions** list shows every listed version with its compatibility and offers **Install** for any version DSH accepts, including older releases and prereleases. A card that shows **Installed**, **Update available**, or **Provided by DSH** opens the installed bundle instead. -Markets are third-party content. A market chooses each plugin's title, description, icon, author, and source; DSH checks the file format but not those claims. Add only sources you trust, and check the source in the confirmation before installing. +Indexes are third-party content. An index chooses each plugin's title, description, icon, author, and source; DSH checks the file format but not those claims. Add only sources you trust, and check the source in the confirmation before installing. ## Publish an index @@ -109,10 +109,10 @@ Text fields marked `LocalizedText` are a string or an object of strings keyed by | Index field | Required | Meaning | |---|---|---| | `format` | yes | `1`. | -| `title`, `description` | `title` only | Market name and description, `LocalizedText`. | +| `title`, `description` | `title` only | Index name and description, `LocalizedText`. | | `metadata.categories`, `metadata.labels` | no | Objects mapping an id to `{ "title": LocalizedText }`. | | `metadata.sortKeys` | no | Object mapping an id to `{ "title": LocalizedText, "order": "asc" \| "desc" }`; `order` is the initial direction. | -| `plugins` | yes | Plugins in the market's default order. | +| `plugins` | yes | Plugins in the index's default order. | | Plugin field | Required | Meaning | |---|---|---| @@ -140,7 +140,7 @@ DSH installs an npm version as `name@version`, asking `registry` first when pres ## Further Exploration - [Discover tab reference](../../../packages/client/ui-plugin-market/README.md) describes the tab's controls and states. -- [Plugin market service](../../../packages/boot/plugin-market/README.md) covers fetch limits, caching, and the `plugin_market` tool. +- [Plugin index service](../../../packages/boot/plugin-market/README.md) covers fetch limits, caching, and the `plugin_market` tool. - [Index validator](../../../packages/util/plugin-market-index/README.md) is the library generators can use to check an index before publishing it. ## Dev Note diff --git a/docs/user/guide/plugin-market.zh.md b/docs/user/guide/plugin-market.zh.md index 2385d0a75b..423b463a57 100644 --- a/docs/user/guide/plugin-market.zh.md +++ b/docs/user/guide/plugin-market.zh.md @@ -1,10 +1,10 @@ -# 插件市场 +# 插件索引 [English](plugin-market.md) | 中文 ## 概述 -插件市场是一个 JSON 索引文件,列出可安装的 DSH 组合包(bundle)及其标题、图标、作者和版本。打开实验性的**自定义插件市场**组合包后,可以在插件页的**发现**标签页中浏览市场,并在确认后安装列出的版本。要发布市场,编写或生成一个索引文件,并把它和图标文件一起放到任意静态主机上。 +插件索引是一个 JSON 文件,列出可安装的 DSH 组合包(bundle)及其标题、图标、作者和版本。打开实验性的**自定义插件索引**组合包后,可以在插件页的**发现**标签页中浏览索引,并在确认后安装列出的版本。要发布索引,编写或生成一个索引文件,并把它和图标文件一起放到任意静态主机上。 ## 目录 @@ -18,20 +18,20 @@ ## 打开「发现」 -打开**插件**,在**实验性插件**下找到**自定义插件市场**并打开开关。**已安装**旁边会出现**发现**标签页,Creator 模式也会获得只读的 `plugin_market` 工具。关闭该组合包会再次移除这两者。 +打开**插件**,在**实验性插件**下找到**自定义插件索引**并打开开关。**已安装**旁边会出现**发现**标签页,Creator 模式也会获得只读的 `plugin_market` 工具。关闭该组合包会再次移除这两者。 -DSH 不内置任何索引源。选择**发现**,点击**添加索引源**,输入一个索引文件的 URL。URL 必须使用 `http:` 或 `https:`,并且不能包含用户名、密码或 `#` 片段。网络路径上的任何人都能修改 `http:` 索引,包括其中列出的安装 spec,因此经由不受你控制的网络访问的市场应使用 `https:`。每个索引源属于当前 profile。 +DSH 不内置任何索引源。选择**发现**,点击**添加索引源**,输入一个索引文件的 URL。URL 必须使用 `http:` 或 `https:`,并且不能包含用户名、密码或 `#` 片段。网络路径上的任何人都能修改 `http:` 索引,包括其中列出的安装 spec,因此经由不受你控制的网络访问的索引应使用 `https:`。每个索引源属于当前 profile。 ## 浏览和安装 -工具栏左侧的市场菜单用于切换索引源,并可打开**管理索引源…**,其中每个索引源显示它最近一次的错误。搜索匹配名称、作者、关键词,以及所有语言的标题、描述、分类和标签,并容忍拼写错误;在你选择其他排序之前,结果按最佳匹配排序。**标签**菜单、分类按钮和**排序**菜单使用市场声明的分类、标签和排序键,**发布时间**按每个插件最新版本的时间排序。 +工具栏左侧的索引菜单用于切换索引源,并可打开**管理索引源…**,其中每个索引源显示它最近一次的错误。搜索匹配名称、作者、关键词,以及所有语言的标题、描述、分类和标签,并容忍拼写错误;在你选择其他排序之前,结果按最佳匹配排序。**标签**菜单、分类按钮和**排序**菜单使用索引声明的分类、标签和排序键,**发布时间**按每个插件最新版本的时间排序。 每张卡片显示插件的推荐版本:与当前运行的 DSH 兼容、且不是预发布版本的最高版本;插件没有列出任何非预发布版本时,则是兼容的最高预发布版本。**安装**会打开确认框,显示该版本的来源:npm 包和注册表,或 Git 仓库、提交和目录。确认后开始常规的插件安装,包括其中的兼容性检查和注册表检查;未经确认不会安装任何内容。 选择卡片会打开插件页面。**版本**列表显示列出的每个版本及其兼容性,并为 DSH 接受的任何版本提供**安装**,包括旧版本和预发布版本。显示**已安装**、**有新版本**或**随 DSH 提供**的卡片会改为打开已安装的组合包。 -市场是第三方内容。每个插件的标题、描述、图标、作者和来源都由市场决定;DSH 检查文件格式,但不验证这些声明。只添加你信任的索引源,并在安装前核对确认框中的来源。 +索引是第三方内容。每个插件的标题、描述、图标、作者和来源都由索引决定;DSH 检查文件格式,但不验证这些声明。只添加你信任的索引源,并在安装前核对确认框中的来源。 ## 发布索引 @@ -109,10 +109,10 @@ pnpm --filter @deepseek-ai/dsh-plugin-market-generator start --input plugins.txt | 索引字段 | 必填 | 含义 | |---|---|---| | `format` | 是 | `1`。 | -| `title`、`description` | 仅 `title` | 市场名称和描述,类型为 `LocalizedText`。 | +| `title`、`description` | 仅 `title` | 索引名称和描述,类型为 `LocalizedText`。 | | `metadata.categories`、`metadata.labels` | 否 | 将 id 映射为 `{ "title": LocalizedText }` 的对象。 | | `metadata.sortKeys` | 否 | 将 id 映射为 `{ "title": LocalizedText, "order": "asc" \| "desc" }` 的对象;`order` 是初始方向。 | -| `plugins` | 是 | 按市场默认顺序排列的插件。 | +| `plugins` | 是 | 按索引默认顺序排列的插件。 | | 插件字段 | 必填 | 含义 | |---|---|---| @@ -140,7 +140,7 @@ DSH 将 npm 版本安装为 `name@version`,存在 `registry` 时先询问它 ## 延伸阅读 - [「发现」标签页参考](../../../packages/client/ui-plugin-market/README.zh.md)说明该标签页的控件和状态。 -- [插件市场服务](../../../packages/boot/plugin-market/README.zh.md)说明获取限制、缓存和 `plugin_market` 工具。 +- [插件索引服务](../../../packages/boot/plugin-market/README.zh.md)说明获取限制、缓存和 `plugin_market` 工具。 - [索引校验器](../../../packages/util/plugin-market-index/README.zh.md)是生成器可以用来在发布前检查索引的库。 ## 开发备注 diff --git a/docs/user/guide/providers.i18n.yaml b/docs/user/guide/providers.i18n.yaml index 93bc2cc11f..b04aada43b 100644 --- a/docs/user/guide/providers.i18n.yaml +++ b/docs/user/guide/providers.i18n.yaml @@ -6,8 +6,8 @@ en: b1631dcf25e805a1 zh: 8ded02e2ae87f00b /configure-models/configure-deepseek: - en: 2c6b665adc256b4e - zh: 2240e4c1573ebe9c + en: 44852da64a6a39ec + zh: 4c280e428f0fec08 /configure-models/add-a-third-party-provider: en: f6fb44a85dc5e4dd zh: 2b86ea4492c32ed7 diff --git a/docs/user/guide/providers.md b/docs/user/guide/providers.md index 144b33d835..fe831bcaf9 100644 --- a/docs/user/guide/providers.md +++ b/docs/user/guide/providers.md @@ -12,6 +12,8 @@ Open **Settings → Models**. The DeepSeek card exposes one API-key field; enter Keys are write-only. The page receives a redacted descriptor after saving, never the literal secret. The key is stored in `$DSH_HOME/.credentials.yaml`, while settings retain only its credential reference. +With a key saved and the default endpoint, DeepSeek's models follow the list the DeepSeek API publishes. The list loads when the models are first needed, refreshes in the background about every ten minutes while they are in use, and falls back to the built-in models when it cannot load. Editing **Models** under **Customized settings** keeps your own list instead and stops following the published one; **Restore defaults** follows it again and reloads it. While the published list is in use, the card shows the built-in models, so a newly published model appears only in the model picker. The [API-key provider reference](../../../packages/llm/llm-deepseek-api-key/README.md) owns the listing, fallback, and gating rules. + ## Add a third-party provider Choose **Add model provider**. The card opens on **Third-party model provider**: pick a provider dsh ships with — the list shows provider ids such as `anthropic`, `openai`, `moonshotai` for Kimi, or `zai` for GLM — enter its API key, and save. The installed catalog supplies the endpoint, protocol, and model list. diff --git a/docs/user/guide/providers.zh.md b/docs/user/guide/providers.zh.md index e20d1eb4aa..bb518c42b9 100644 --- a/docs/user/guide/providers.zh.md +++ b/docs/user/guide/providers.zh.md @@ -12,6 +12,8 @@ 密钥是只写的。保存后,页面只会收到脱敏描述符,永远不会收到明文密钥。密钥存储在 `$DSH_HOME/.credentials.yaml` 中,settings 只保留它的凭据引用。 +保存了密钥且使用默认端点时,DeepSeek 的模型跟随 DeepSeek API 发布的列表。第一次需要模型时加载列表,使用期间约每十分钟在后台刷新一次,无法加载时退回内置模型。在**自定义设置**里编辑**模型目录**会改用你自己的列表,不再跟随发布的列表;点**恢复默认模型**会重新跟随并重新加载。使用发布的列表时,卡片上显示的是内置模型,因此新发布的模型只出现在模型选择器中。列表、兜底和门控规则见 [API key 提供方参考](../../../packages/llm/llm-deepseek-api-key/README.zh.md)。 + ## 添加第三方提供商 选择**添加模型提供商**。卡片默认打开在**第三方模型提供商**:选取 dsh 自带的提供商——列表显示的是提供商 id,例如 `anthropic`、`openai`、Kimi 对应的 `moonshotai`、GLM 对应的 `zai`——输入其 API 密钥并保存。已安装目录会提供端点、协议和模型列表。 diff --git a/package.json b/package.json index 5bc1973359..368901f21a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-root", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "license": "MIT", "private": true, "type": "module", @@ -24,7 +24,7 @@ "build:bench": "npm run build:native-system && npm run build:lib && tsdown --config-loader native --config benchmarks/tsdown.config.ts", "build:official": "tsx scripts/build.ts --profile official", "build:lib": "pnpm run build:lib:host && pnpm run build:lib:client", - "build:lib:host": "tsx scripts/compile-referenced-projects.ts host-libraries && node --max-old-space-size=4096 ./node_modules/typescript/bin/tsc -p tsconfig.host.json && pnpm --filter @deepseek-ai/dsh-desktop run bundle", + "build:lib:host": "tsx scripts/compile-referenced-projects.ts host-libraries && node --max-old-space-size=8192 ./node_modules/typescript/bin/tsc -p tsconfig.host.json && pnpm --filter @deepseek-ai/dsh-desktop run bundle", "build:lib:client": "tsc -b tsconfig.client.json && tsdown --config-loader native --env.DSH_BUILD_FACE client", "build:web": "pnpm --filter @deepseek-ai/dsh-web-frontend run build", "build:desktop": "pnpm --filter @deepseek-ai/dsh-desktop run build", @@ -63,7 +63,7 @@ "test:coverage:partitioned": "tsx scripts/run-coverage-partitions.ts", "test:e2e": "vitest run --config vitest.e2e.config.ts", "test:bench": "npm run build:bench && npm run build:web && npm run test:bench:built", - "test:bench:built": "vitest run --config vitest.bench.config.ts", + "test:bench:built": "tsx scripts/run-bench-suite.ts", "test:bench:memory": "tsx scripts/run-memory-pressure-bench.ts", "test:expected": "vitest run --config vitest.expected.config.ts", "test:expected:refresh": "DSH_SNAPSHOT=refresh vitest run --config vitest.expected.config.ts", @@ -134,7 +134,7 @@ "docs:build": "tsx website/build.ts && pnpm run verify-doc-site-fragments", "docs:build:mpa": "tsx website/build.ts --mpa && pnpm run verify-doc-site-fragments", "docs:preview": "pnpm --filter @deepseek-ai/website run preview", - "docs:check": "pnpm exec vitest run scripts/project-doc-site.spec.ts scripts/verify-doc-site-fragments.spec.ts website/tests/mermaid-viewer.spec.ts website/tests/image-viewer.spec.ts website/tests/code-groups.spec.ts website/tests/page-markdown-actions.spec.ts website/tests/raw-markdown.spec.ts && pnpm run docs:build", + "docs:check": "pnpm exec vitest run scripts/project-doc-site.spec.ts scripts/verify-doc-site-fragments.spec.ts website/tests/mermaid-viewer.spec.ts website/tests/image-viewer.spec.ts website/tests/code-groups.spec.ts website/tests/page-markdown-actions.spec.ts website/tests/raw-markdown.spec.ts website/tests/table-filter.spec.ts && pnpm run docs:build", "website:dev": "pnpm run docs:dev", "website:build": "pnpm run docs:build", "verify-package-readme-limitations": "tsx scripts/verify-package-readme-limitations.ts", @@ -300,6 +300,7 @@ "@deepseek-ai/dsh-cua-bundle": "workspace:*", "@deepseek-ai/dsh-experimental-subagent-oar": "workspace:*", "@deepseek-ai/dsh-experimental-tool-subagent-oar": "workspace:*", - "@deepseek-ai/dsh-experimental-cua-macos": "workspace:*" + "@deepseek-ai/dsh-experimental-cua-macos": "workspace:*", + "@deepseek-ai/dsh-action-cards": "workspace:*" } } diff --git a/packages/README.i18n.yaml b/packages/README.i18n.yaml index 701a4ae942..92c89f5ff2 100644 --- a/packages/README.i18n.yaml +++ b/packages/README.i18n.yaml @@ -15,8 +15,8 @@ en: ffc55792d6e922e1 zh: 83bd759638857e2d /packages/package-groups: - en: d67996086e3b4f28 - zh: cb758b1fcee5ab3e + en: c397fc0c1885058a + zh: c720d0e91dd1d15e /packages/release-expectations: en: 236081c1659b25ab zh: 809110adf003802e diff --git a/packages/README.md b/packages/README.md index b6d04e0f04..ed7c55ec5a 100644 --- a/packages/README.md +++ b/packages/README.md @@ -75,11 +75,11 @@ Every package lives in exactly one group; new packages join existing groups, and | [`sdk/`](sdk/README.md) | Out-of-process SDK: JSON-RPC protocol and TypeScript client/server | | [`acp/`](acp/README.md) | Automation-only Agent Client Protocol server | | [`interaction/`](interaction/README.md) | Human-collaboration plane: approval/interaction seams, permission preset, commands, ask-user tool | -| [`boot/`](boot/README.md) | Shared app-bin boot glue and installation bundle lists | +| [`boot/`](boot/README.md) | Shared app-bin boot glue | | [`host/`](host/README.md) | Web GUI host services, directory picking, application launch, plugin inventory, and product telemetry | | [`client/`](client/README.md) | Web-GUI browser half: shell, wire, object services, slots, `ui-*` plugins | | [`test-support/`](test-support/README.md) | Test infrastructure (testkits, replay, Loader smokes) | -| [`util/`](util/README.md) | Low-level zero-dependency utilities shared across groups (`Branded`, home/path helpers, timeout, retention) | +| [`util/`](util/README.md) | Low-level utilities and data-only package lists shared across groups (`Branded`, home/path helpers, timeout, retention, official bundle lists) | ----- diff --git a/packages/README.zh.md b/packages/README.zh.md index f1cb7f8266..ae3a18bbc1 100644 --- a/packages/README.zh.md +++ b/packages/README.zh.md @@ -75,11 +75,11 @@ harness 由 `packages/` 下的 npm 包组装而成,按能力系列分组:会 | [`sdk/`](sdk/README.zh.md) | 进程外 SDK:JSON-RPC 协议与 TypeScript 客户端/服务器 | | [`acp/`](acp/README.zh.md) | 仅面向自动化的 ACP(Agent Client Protocol)服务器 | | [`interaction/`](interaction/README.zh.md) | 人机协作平面:批准/交互 seam、权限预设、命令、询问用户的工具 | -| [`boot/`](boot/README.zh.md) | 共享的 app bin 启动粘合层与安装方组合包列表 | +| [`boot/`](boot/README.zh.md) | 共享的 app bin 启动粘合层 | | [`host/`](host/README.zh.md) | Web GUI 宿主服务、目录选择、应用启动、插件清单和产品遥测 | | [`client/`](client/README.zh.md) | web GUI 浏览器半侧:shell、协议层、对象服务、slot、`ui-*` 插件 | | [`test-support/`](test-support/README.zh.md) | 测试基础设施(testkit、回放、Loader 冒烟测试) | -| [`util/`](util/README.zh.md) | 组间共享的低层零依赖工具(`Branded`、home/路径辅助函数、超时、留存) | +| [`util/`](util/README.zh.md) | 组间共享的低层工具与纯数据包列表(`Branded`、home/路径辅助函数、超时、留存、官方组合包列表) | ----- diff --git a/packages/acp/acp/README.i18n.yaml b/packages/acp/acp/README.i18n.yaml index aca817ae8a..bbd4e8b862 100644 --- a/packages/acp/acp/README.i18n.yaml +++ b/packages/acp/acp/README.i18n.yaml @@ -27,8 +27,8 @@ en: 4ed8e37834267edb zh: a32d5dedb4e8e919 /deepseek-ai-dsh-acp/use-this-package/protocol-contract: - en: 8f358b006f93f6ab - zh: a02dc9640cac4edd + en: 195315c12edf895f + zh: de307288858a8ece /deepseek-ai-dsh-acp/understand-the-implementation: en: ea8afe89dbdd1934 zh: 6567979f92f34afd diff --git a/packages/acp/acp/README.md b/packages/acp/acp/README.md index 44a63a1da2..06ba85def5 100644 --- a/packages/acp/acp/README.md +++ b/packages/acp/acp/README.md @@ -73,6 +73,8 @@ One connection can run several sessions at once, each independent. The calls a c | `session/update` | Committed assistant messages and thoughts, generic tool lifecycle, configuration changes, and context usage, serialized per session. | | `session/request_permission` | A permission prompt with one-shot allow/reject choices; your client can answer automatically. | +Session listing and resume admit ordinary forks, including historical logs with `parentSession`; `origin: subagent` remains excluded. + A prompt remains in flight while managed descendants run, while their results trigger later root turns, and while committed output drains. Root work accepted during that output drain joins the same activity interval before completion. Its completion includes the latest root stop reason and any assistant output delivery failure; only the original prompt turn pins the model selection captured at admission. Cancellation stops the root activity present at that call and waits for that activity and its queued output. Later child messages may start autonomous work and do not delay the cancelled response; the session remains available for later prompts. Idle descendants with parked inbox messages remain resident but do not delay prompt completion. Closing the session also drains its descendants. A failure to append `turn/start` or `turn/end` rejects the prompt even when a preceding turn completed. diff --git a/packages/acp/acp/README.zh.md b/packages/acp/acp/README.zh.md index 500c90f5d2..a22b08c924 100644 --- a/packages/acp/acp/README.zh.md +++ b/packages/acp/acp/README.zh.md @@ -73,6 +73,8 @@ kind: "package-reference" | `session/update` | 已提交 assistant 消息与 thought、通用工具生命周期、配置变化与上下文用量,按会话串行交付。 | | `session/request_permission` | 带一次性允许/拒绝选项的权限提示;你的客户端可以自动回答。 | +会话列表和恢复允许普通 fork,包括含有 `parentSession` 的历史日志;`origin: subagent` 仍被排除。 + 受管理后代运行期间、它们的结果触发根 Agent 后续轮次期间,以及已提交输出仍在交付期间,提示词保持进行中。输出交付期间接受的根 Agent 工作会加入同一活动区间,并在该区间完成后结算。最终结果包含最新根轮次的停止原因与所有助手输出交付错误;只有原始提示词轮次固定使用接受时捕获的模型选择。取消会停止调用时已有的根 Agent 活动,并等待该活动及其已排队输出完成。之后到达的子 Agent 消息可以启动自主工作,但不会延迟取消响应;会话仍可接受后续提示词。收件箱消息处于停放状态的空闲后代继续驻留,但不延迟提示词完成。关闭会话还会释放其后代。 即使前一轮已经完成,追加 `turn/start` 或 `turn/end` 失败仍会使提示词请求失败。 diff --git a/packages/acp/acp/locale/de.json b/packages/acp/acp/locale/de.json new file mode 100644 index 0000000000..1d616ae6f6 --- /dev/null +++ b/packages/acp/acp/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "ACP-Server", + "description": "Führen Sie Agenten zur Automatisierung über JSON-RPC über Standardeingabe und -ausgabe aus." + } +} diff --git a/packages/acp/acp/locale/es.json b/packages/acp/acp/locale/es.json new file mode 100644 index 0000000000..4970a451fb --- /dev/null +++ b/packages/acp/acp/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "servidor ACP", + "description": "Ejecute agentes a través de JSON-RPC a través de entrada y salida estándar para automatización." + } +} diff --git a/packages/acp/acp/locale/fr.json b/packages/acp/acp/locale/fr.json new file mode 100644 index 0000000000..a8faaceeaa --- /dev/null +++ b/packages/acp/acp/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Serveur ACP", + "description": "Exécutez les agents via JSON-RPC via une entrée et une sortie standard pour l'automatisation." + } +} diff --git a/packages/acp/acp/locale/pt.json b/packages/acp/acp/locale/pt.json new file mode 100644 index 0000000000..cad2b3ae48 --- /dev/null +++ b/packages/acp/acp/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "ACP servidor", + "description": "Execute agentes por meio de JSON-RPC em entradas e saídas padrão para automação." + } +} diff --git a/packages/acp/acp/locale/ru.json b/packages/acp/acp/locale/ru.json new file mode 100644 index 0000000000..fefd7d956d --- /dev/null +++ b/packages/acp/acp/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "ACP сервер", + "description": "Запускайте агенты через JSON-RPC через стандартный ввод и вывод для автоматизации." + } +} diff --git a/packages/acp/acp/package.json b/packages/acp/acp/package.json index ca9ad8609d..41962dd596 100644 --- a/packages/acp/acp/package.json +++ b/packages/acp/acp/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-acp", "description": "Automation-only Agent Client Protocol server for driving DeepSeek Harness agents over JSON-RPC stdio", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, diff --git a/packages/acp/acp/src/index.ts b/packages/acp/acp/src/index.ts index c05ccbf3e5..792ec6a424 100644 --- a/packages/acp/acp/src/index.ts +++ b/packages/acp/acp/src/index.ts @@ -248,7 +248,7 @@ export function apply(ctx: Context, config: AcpConfig): void { activating.add(sessionId) return (async (): Promise => { const persisted = (await persistence.stat(sessionId, { signal }))?.header - if (persisted === undefined || persisted.origin === 'subagent' || persisted.parentSession !== undefined) { + if (persisted === undefined || persisted.origin === 'subagent') { throw invalidParams(`session is not resumable: ${sessionId}`) } if (!await sameDirectory(persisted.cwd, params.cwd)) { @@ -308,7 +308,6 @@ export function apply(ctx: Context, config: AcpConfig): void { || activating.has(header.id) || ctx.sessions.get(header.id) !== undefined || header.origin === 'subagent' - || header.parentSession !== undefined || header.cwd === undefined || !isAbsolute(header.cwd) ) return undefined diff --git a/packages/acp/acp/tests/bridge.spec.ts b/packages/acp/acp/tests/bridge.spec.ts index dcfcfddef6..c13044799e 100644 --- a/packages/acp/acp/tests/bridge.spec.ts +++ b/packages/acp/acp/tests/bridge.spec.ts @@ -6,7 +6,7 @@ import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { AttachmentError } from '@deepseek-ai/dsh-attachment' import { ToolCallId, type StreamChunk } from '@deepseek-ai/dsh-llm' -import { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session' +import { SESSION_FORMAT_VERSION, SessionId, SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session' import type { SessionHeader } from '@deepseek-ai/dsh-session' import { SessionPersistenceRevision, type SessionPersistenceSnapshot } from '@deepseek-ai/dsh-session-persistence' import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit' @@ -388,6 +388,22 @@ describe('automation-only ACP bridge', () => { await expect(harness.client.listSessions({ cursor: 'not-a-cursor' })).rejects.toThrow(/cursor is invalid/) }) + it.each([false, true])('resumes an ordinary fork with legacy parent metadata=%s', async (legacy) => { + harness = await makeBridgeHarness() + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const id = SessionId('ordinary-fork') + const writer = await harness.ctx.sessionPersistence.create({ + version: SESSION_FORMAT_VERSION, id, createdAt: 1, isSeeded: true, + cwd: process.cwd(), ...(legacy ? { parentSession: SessionId('source') } : {}), + }, { inheritedEventCount: SessionLogOffset(0) }) + try { + await writer.append([{ type: 'session/end-seed', seq: SessionSeq(0), time: 1, data: { inherited: true } }]) + } finally { await writer.close() } + await expect(harness.client.listSessions({})).resolves.toMatchObject({ sessions: [{ sessionId: id }] }) + await harness.client.resumeSession({ sessionId: id, cwd: process.cwd() }) + expect(harness.ctx.agents.get(id)?.session.header.parentSession).toBe(legacy ? 'source' : undefined) + }) + it('filters non-resumable headers and canonical missing workspaces', async () => { harness = await makeBridgeHarness() await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) @@ -411,6 +427,7 @@ describe('automation-only ACP bridge', () => { await expect(harness.client.listSessions({ cwd: 'relative' })).rejects.toThrow(/absolute path/) await expect(harness.client.listSessions({ cwd: '/missing/filter' })).resolves.toEqual({ sessions: [ + { sessionId: 'fork', cwd: '/missing/filter' }, { sessionId: 'valid-a', cwd: '/missing/filter' }, { sessionId: 'valid-b', cwd: '/missing/filter' }, ], diff --git a/packages/api/account-controller/locale/de.json b/packages/api/account-controller/locale/de.json new file mode 100644 index 0000000000..f1e7b8ca6c --- /dev/null +++ b/packages/api/account-controller/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Benutzeroberfläche für den Kontobetrieb", + "description": "Bieten Sie authentifizierten Clients Kontoverwaltungsfunktionen." + } +} diff --git a/packages/api/account-controller/locale/es.json b/packages/api/account-controller/locale/es.json new file mode 100644 index 0000000000..7bfaac6431 --- /dev/null +++ b/packages/api/account-controller/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Interfaz de operación de cuenta", + "description": "Proporcionar capacidades de operación de cuentas a clientes autenticados." + } +} diff --git a/packages/api/account-controller/locale/fr.json b/packages/api/account-controller/locale/fr.json new file mode 100644 index 0000000000..a77bd7e7a1 --- /dev/null +++ b/packages/api/account-controller/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Interface d'opération de compte", + "description": "Fournir des capacités d’exploitation de compte aux clients authentifiés." + } +} diff --git a/packages/api/account-controller/locale/pt.json b/packages/api/account-controller/locale/pt.json new file mode 100644 index 0000000000..22670a3e3b --- /dev/null +++ b/packages/api/account-controller/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Interface de operação da conta", + "description": "Fornece recursos de operação de conta para clientes autenticados." + } +} diff --git a/packages/api/account-controller/locale/ru.json b/packages/api/account-controller/locale/ru.json new file mode 100644 index 0000000000..dd3e515e30 --- /dev/null +++ b/packages/api/account-controller/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Интерфейс работы со счетом", + "description": "Предоставьте возможности управления учетной записью аутентифицированным клиентам." + } +} diff --git a/packages/api/account-controller/package.json b/packages/api/account-controller/package.json index 088357e98f..30aa41c6da 100644 --- a/packages/api/account-controller/package.json +++ b/packages/api/account-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-account-controller", "description": "Expose safe account operations over authenticated Remote", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, diff --git a/packages/api/gateway/README.i18n.yaml b/packages/api/gateway/README.i18n.yaml index da77f603e9..eb3352e60d 100644 --- a/packages/api/gateway/README.i18n.yaml +++ b/packages/api/gateway/README.i18n.yaml @@ -15,8 +15,8 @@ en: d9859219cdb0f367 zh: 2a3cfa8cb786e327 /deepseek-ai-dsh-api-gateway/host-service-typertgatewayservice-ctx-key-typertgateway: - en: 891bab7fceee4f0a - zh: be55b40151f049a1 + en: 6ee072ffebd2eb38 + zh: 6a8723d13f443d51 /deepseek-ai-dsh-api-gateway/client-service-clientremote-ctx-key-remote: en: 0916113cdbe794fb zh: 14893c2cba95bfd6 diff --git a/packages/api/gateway/README.md b/packages/api/gateway/README.md index fac42718bf..fea754c891 100644 --- a/packages/api/gateway/README.md +++ b/packages/api/gateway/README.md @@ -32,7 +32,9 @@ The Host entry registers a trusted-host interceptor on Connection's shared `/api Every call names the Peer it speaks for: `InvokeRemoteRequest.peer` and the `peer` argument of `wireStream.open()` are required, and the Gateway never supplies a default Peer. Dispatch from a disposed Peer fails with `gateway/peer-disposed`, for unary calls, streams, `$events`, and `$events/result` alike, and wire paths check it before they read the payload. The Host service injects `remoteAccess` and does not start without [`dsh-api-remote-access`](../remote-access/README.md). After the endpoint and argument-field checks, every call validates its JSON arguments once against their Typert-compiled types, failing with `gateway/input-invalid`, and dispatch reuses the validated values. For a call whose Peer principal is not the owner, after that validation and before lookup and Context resolution, the Gateway resolves the resources the call touches and asks `ctx.remoteAccess.decide({ principal, action, resources, args })` with the endpoint as the action and the validated arguments as `args`, or refuses with reason `resource-invalid` without asking when the resources are invalid; a refused call throws `remote-access/denied` with details `{ action, reason }`, so a refused call fails before it activates any Session. An owner call is dispatched without resource resolution or a decision. -Resources are read from the arguments validated against their Typert-compiled types, which drop object fields those types do not declare, while lookup and Context identities keep their wire values. For each resource kind, a reader in the method's `@Remote({ resources })` or `@RemoteScope(key, { resources })` options wins; it is called with the method's positional arguments, where lookup positions hold wire identities and the cancellation position holds the call's signal, and is read from the class metadata of the root Service instance. Otherwise every lookup parameter whose provider declares that kind through `resource` contributes its wire identity, an omitted optional one contributing none, and a Context method whose Host Context adapter declares that kind contributes its Context identity, read from the arguments before the Context is resolved. Otherwise the kind's default field registered in `typert.resources` is read from a top-level argument of that name or, failing that, from the first object argument. A reader that throws or returns an empty list, a default field holding an array, or an identity, including a Context identity, that is not a non-empty string makes the resolution `invalid`; a call that names no resource touches the `global` resource alone, and a call that names resources touches only those. A forwarded event carries every resource its entry declares, so there a reader returning `undefined` also makes the resolution `invalid`, while an entry without readers touches `global`. +Resources are read from validated arguments: Typert-compiled codecs drop undeclared object fields, while SRC fallback checks JSON safety without stripping them; lookup and Context identities keep their wire values. For each resource kind, a reader in the method's `@Remote({ resources })` or `@RemoteScope(key, { resources })` options wins; it is called with the method's positional arguments, where lookup positions hold wire identities and the cancellation position holds the call's signal, and is read from the class metadata of the root Service instance. Otherwise every lookup parameter whose provider declares that kind through `resource` contributes its wire identity, an omitted optional one contributing none, and a Context method whose Host Context adapter declares that kind contributes its Context identity, read from the arguments before the Context is resolved. Otherwise the kind's declaration in `typert.resources` supplies either a default field or a synchronous resolver. A field reads a top-level argument of that name or, failing that, the first object argument. A resolver is called once with `{ args, parameters }`: named validated wire values and ordered parameter descriptions containing `name` and `wire`. Both defaults return one identity or `undefined`; arrays are invalid. An explicit reader may return several identities. A resolver or reader that throws, a reader returning an empty list, or an identity, including a Context identity, that is not a non-empty string makes the resolution `invalid`; a call that names no resource touches the `global` resource alone, and a call that names resources touches only those. A forwarded event carries every resource its entry declares, so there a reader returning `undefined` also makes the resolution `invalid`, while an entry without readers touches `global`. + +`getPendingRemoteEvents()` returns detached event-name and Agent-ID metadata for currently unsettled forwarded events in arrival order. It neither exposes request bodies nor changes event lifetimes, and it does not provide a change notification. A cancellation-aware Remote method declares `signal: AbortSignal` as its final Host parameter. The signal is descriptor metadata rather than a wire argument: Connection supplies it to the Gateway, and the Gateway injects it after decoded business parameters. SRC recognizes the reserved final name, while strict generation additionally requires the global `AbortSignal` type. diff --git a/packages/api/gateway/README.zh.md b/packages/api/gateway/README.zh.md index 86ad50da63..1dad623204 100644 --- a/packages/api/gateway/README.zh.md +++ b/packages/api/gateway/README.zh.md @@ -32,7 +32,9 @@ Connection 可用时,Host 入口会在 Connection 共享的 `/api` FetchHandle 每次调用都指明它所代表的 Peer:`InvokeRemoteRequest.peer` 与 `wireStream.open()` 的 `peer` 参数都是必填项,Gateway 从不提供默认 Peer。来自已释放 Peer 的分发以 `gateway/peer-disposed` 失败,一元调用、流、`$events` 与 `$events/result` 一律如此,wire 路径在读取 payload 之前检查。Host 服务注入 `remoteAccess`,没有 [`dsh-api-remote-access`](../remote-access/README.zh.md) 就不启动。每次调用在 endpoint 与参数字段检查之后按 Typert 编译类型校验一次 JSON 参数,失败为 `gateway/input-invalid`,分派复用校验后的值。对 Peer 的 principal 不是 owner 的调用,Gateway 在该校验之后、lookup 与 Context 解析之前解析调用访问的资源,并以端点为 action、校验后的参数为 `args` 询问 `ctx.remoteAccess.decide({ principal, action, resources, args })`,资源非法时不询问而以原因 `resource-invalid` 拒绝;被拒的调用抛出 details 为 `{ action, reason }` 的 `remote-access/denied`,因此被拒绝的调用在激活任何 Session 之前就失败。owner 的调用不解析资源、不询问判定即分派。 -资源从经 Typert 编译类型校验后的参数中读取,校验会移除类型未声明的对象字段,lookup 与 Context 身份保持 wire 值。对每个资源种类,方法 `@Remote({ resources })` 或 `@RemoteScope(key, { resources })` options 中的读取函数优先;它以方法的位置参数调用(lookup 位为 wire 身份,取消参数位为调用的 signal),从根 Service 实例的类元数据读取。否则 provider 经 `resource` 声明了该种类的每个 lookup 参数贡献其 wire 身份,省略的可选 lookup 参数不贡献;Host Context adapter 声明了该种类的 Context 方法贡献其 Context 身份,在解析 Context 之前直接从参数读取。再否则从同名顶层参数读取该种类在 `typert.resources` 中登记的默认字段,没有同名参数时读第一个对象参数的同名字段。读取函数抛错或返回空列表、默认字段读到数组、或某个身份(含 Context 身份)不是非空字符串时,解析结果为 `invalid`;不指明任何资源的调用只访问 `global` 资源,指明了资源的调用只访问这些资源。转发事件携带其条目声明的每个资源,因此在事件路径上读取函数返回 `undefined` 同样使解析结果为 `invalid`,而没有读取函数的条目访问 `global`。 +资源从已校验参数中读取:Typert 编译 codec 会移除未声明的对象字段,SRC fallback 只检查 JSON 安全性而不移除字段;lookup 与 Context 身份保持 wire 值。对每个资源种类,方法 `@Remote({ resources })` 或 `@RemoteScope(key, { resources })` options 中的读取函数优先;它以方法的位置参数调用(lookup 位为 wire 身份,取消参数位为调用的 signal),从根 Service 实例的类元数据读取。否则 provider 经 `resource` 声明了该种类的每个 lookup 参数贡献其 wire 身份,省略的可选 lookup 参数不贡献;Host Context adapter 声明了该种类的 Context 方法贡献其 Context 身份,在解析 Context 之前直接从参数读取。再否则使用该种类在 `typert.resources` 中登记的默认字段或同步 resolver。字段规则读取同名顶层参数,没有时读取第一个对象参数的同名字段。resolver 以 `{ args, parameters }` 调用一次:命名的已校验 wire 值,以及包含 `name`、`wire` 的有序参数描述。两种默认规则均返回单个身份或 `undefined`,数组无效。显式读取函数可以返回多个身份。resolver 或读取函数抛错、读取函数返回空列表、或某个身份(含 Context 身份)不是非空字符串时,解析结果为 `invalid`;不指明任何资源的调用只访问 `global` 资源,指明了资源的调用只访问这些资源。转发事件携带其条目声明的每个资源,因此在事件路径上读取函数返回 `undefined` 同样使解析结果为 `invalid`,而没有读取函数的条目访问 `global`。 + +`getPendingRemoteEvents()` 按到达顺序返回当前未结算转发事件的独立元数据,仅含事件名和 Agent ID。它不暴露请求正文,不改变事件生命周期,也不提供变化通知。 支持取消的 Remote 方法会把 `signal: AbortSignal` 声明为最后一个 Host 参数。signal 是 descriptor 元数据,而不是 wire 参数:Connection 将它提供给 Gateway,Gateway 则在已解码的业务参数之后注入它。SRC 识别这个保留的末位参数名,严格生成还要求它具有全局 `AbortSignal` 类型。 diff --git a/packages/api/gateway/locale/de.json b/packages/api/gateway/locale/de.json new file mode 100644 index 0000000000..f2fd7153f5 --- /dev/null +++ b/packages/api/gateway/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Remote-Call-Gateway", + "description": "Empfangen Sie den Schnittstellenaufruf des Clients und verteilen Sie ihn an den entsprechenden Dienst." + } +} diff --git a/packages/api/gateway/locale/es.json b/packages/api/gateway/locale/es.json new file mode 100644 index 0000000000..7c02c79a8e --- /dev/null +++ b/packages/api/gateway/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "puerta de enlace de llamada remota", + "description": "Recibir la llamada de interfaz del cliente y distribuirla al servicio correspondiente." + } +} diff --git a/packages/api/gateway/locale/fr.json b/packages/api/gateway/locale/fr.json new file mode 100644 index 0000000000..2eec7623b4 --- /dev/null +++ b/packages/api/gateway/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "passerelle d'appel à distance", + "description": "Recevez l'appel d'interface du client et distribuez-le au service correspondant." + } +} diff --git a/packages/api/gateway/locale/pt.json b/packages/api/gateway/locale/pt.json new file mode 100644 index 0000000000..856eba1312 --- /dev/null +++ b/packages/api/gateway/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "gateway de chamada remota", + "description": "Receba a chamada de interface do cliente e distribua-a ao serviço correspondente." + } +} diff --git a/packages/api/gateway/locale/ru.json b/packages/api/gateway/locale/ru.json new file mode 100644 index 0000000000..7e7cf69bd3 --- /dev/null +++ b/packages/api/gateway/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "шлюз удаленных вызовов", + "description": "Получите вызов интерфейса клиента и передайте его соответствующему сервису." + } +} diff --git a/packages/api/gateway/package.json b/packages/api/gateway/package.json index d525c2dedf..2b4183a776 100644 --- a/packages/api/gateway/package.json +++ b/packages/api/gateway/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-gateway", "description": "Typert Remote Host dispatcher and Client API endpoint", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, diff --git a/packages/api/gateway/src/access.ts b/packages/api/gateway/src/access.ts index d85ebb3e65..f68079c47e 100644 --- a/packages/api/gateway/src/access.ts +++ b/packages/api/gateway/src/access.ts @@ -22,10 +22,10 @@ type ResourceIds = readonly unknown[] | 'invalid' * `resources` reader of the method wins; otherwise every lookup parameter * whose provider declares the kind contributes its wire resource id, and so * does the Context identity of a Context method whose Host adapter declares - * the kind; otherwise the kind's default field registered in - * `typert.resources` is read from a top-level argument or, failing that, - * from the first object argument. - * @param typert - registry holding default fields, lookup providers, and Host Context adapters. + * the kind; otherwise the kind's registered default resolver receives named + * wire values and ordered parameter descriptions. A default field instead + * reads a top-level argument or, failing that, the first object argument. + * @param typert - registry holding default fields or resolvers, lookup providers, and Host Context adapters. * @param readers - the method's `resources` readers, or `undefined` when it declares none. * @param descriptor - receiver, parameter order, lookups, and cancellation slot of the method. * @param args - named arguments matched to the descriptor's field set: JSON @@ -33,9 +33,9 @@ type ResourceIds = readonly unknown[] | 'invalid' * identities as wire values. * @param signal - value placed in the cancellation slot of the positional arguments. * @returns the touched resources, the global resource alone when none; - * `undefined` when the resources are invalid: a reader throws or returns - * an empty list, a default field holds an array, or a resource id is not a - * non-empty string. + * `undefined` when the resources are invalid: a reader or resolver throws, + * a reader returns an empty list, a default field or resolver holds an + * array, or a resource id is not a non-empty string. */ export function callResources( typert: Pick, @@ -46,25 +46,32 @@ export function callResources( ): readonly RemoteAccessResource[] | undefined { // Each later source replaces an earlier one for its kind and keeps the kind's position. const sources = new Map ResourceIds>() - for (const { kind, field } of typert.resources.entries()) { - sources.set(kind, () => { - // A default field names exactly one resource id; only a reader may return several. - const id = defaultFieldId(descriptor, args, field) + const positionalArgs: readonly unknown[] = [ + ...descriptor.parameters.map(parameter => args[parameter.wire]), + ...descriptor.cancellation === undefined ? [] : [signal], + ] + for (const declaration of typert.resources.entries()) { + sources.set(declaration.kind, () => { + let id: unknown + if (declaration.resolve !== undefined) { + const resolve = declaration.resolve + try { + id = resolve({ args, parameters: descriptor.parameters }) + } catch { + // A resolver failure cannot identify an authorized resource. + return 'invalid' + } + } else { + id = defaultFieldId(descriptor, args, declaration.field) + } return Array.isArray(id) ? 'invalid' : id === undefined ? [] : [id] }) } for (const [kind, ids] of lookupResources(typert, descriptor, args)) { sources.set(kind, () => ids) } - let positional: readonly unknown[] | undefined for (const [kind, reader] of Object.entries(readers ?? {})) { - sources.set(kind, () => { - positional ??= [ - ...descriptor.parameters.map(parameter => args[parameter.wire]), - ...descriptor.cancellation === undefined ? [] : [signal], - ] - return read(reader, positional, []) - }) + sources.set(kind, () => read(() => reader(...positionalArgs), [])) } const resources: RemoteAccessResource[] = [] for (const [kind, ids] of sources) { @@ -91,7 +98,7 @@ export function eventResources( if (declared.length === 0) return GLOBAL const resources: RemoteAccessResource[] = [] for (const [kind, reader] of declared) { - if (!collect(resources, kind, read(reader, args, 'invalid'))) return undefined + if (!collect(resources, kind, read(() => reader(...args), 'invalid'))) return undefined } return resources } @@ -129,11 +136,11 @@ function lookupResources( return ids } -/** Run one reader with spread positional arguments: `undefined` yields `absent`, a list names several and must not be empty. */ -function read(reader: TypertResourceReader, args: readonly unknown[], absent: ResourceIds): ResourceIds { +/** Read resource identities: `undefined` yields `absent`, a list names several and must not be empty. */ +function read(reader: () => unknown, absent: ResourceIds): ResourceIds { let value: unknown try { - value = reader(...args) + value = reader() } catch { // Any reader error means it cannot name its resources, so they are invalid. return 'invalid' diff --git a/packages/api/gateway/src/index.ts b/packages/api/gateway/src/index.ts index 878c77cf5e..4fe2652671 100644 --- a/packages/api/gateway/src/index.ts +++ b/packages/api/gateway/src/index.ts @@ -36,6 +36,7 @@ import { } from '@deepseek-ai/dsh-typert-protocol' import type { InvokeRemoteRequest, + PendingRemoteEventInfo, TypertGateway, TypertGatewayErrorCode, TypertGatewayWireStream, @@ -70,6 +71,7 @@ import { export type { InvokeRemoteRequest, + PendingRemoteEventInfo, TypertGateway, TypertGatewayErrorCode, TypertGatewayWireStream, @@ -333,6 +335,14 @@ export class TypertGatewayService extends Service implements TypertGateway { return false } + /** + * Inspect unsettled forwarded events without changing their lifetime. + * @returns detached event names and Agent identities. + */ + getPendingRemoteEvents(): readonly PendingRemoteEventInfo[] { + return [...this.pendingRemoteEvents.values()].map(({ frame }) => ({ event: frame.event, agentId: frame.agentId })) + } + /** * Register the sole application-selected forwarded-event source. * @param source - stream factory installed by the Remote assembly. diff --git a/packages/api/gateway/src/types.ts b/packages/api/gateway/src/types.ts index 83ae7f0730..b802aba061 100644 --- a/packages/api/gateway/src/types.ts +++ b/packages/api/gateway/src/types.ts @@ -5,7 +5,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { PeerScope, RemoteUplinkWindow, TypertResourceReader } from '@deepseek-ai/dsh-typert-protocol' -import type { RemoteEventHostInfo } from './stream-protocol.ts' +import type { RemoteEventAgentId, RemoteEventHostInfo } from './stream-protocol.ts' /** One Remote method request after a carrier has decoded its envelope. */ export interface InvokeRemoteRequest { @@ -144,6 +144,12 @@ export type TypertGatewayErrorCode = | 'gateway/signature-invalid' | 'gateway/uplink-overflow' +/** Public metadata of one unsettled forwarded Remote event. */ +export interface PendingRemoteEventInfo { + readonly event: string + readonly agentId: RemoteEventAgentId +} + /** Host dispatcher consumed by Connection adapters. */ export interface TypertGateway { /** Carrier adapter shared by WebSocket and in-process transports. */ @@ -155,6 +161,9 @@ export interface TypertGateway { */ hasLiveClient(): boolean + /** @returns detached metadata for all unsettled forwarded events in arrival order. */ + getPendingRemoteEvents(): readonly PendingRemoteEventInfo[] + /** * Register the application-selected forwarded-event source. * @param source - stream factory installed by the Remote assembly. diff --git a/packages/api/gateway/tests/gateway-access.host.spec.ts b/packages/api/gateway/tests/gateway-access.host.spec.ts index 960405939f..346f50a8be 100644 --- a/packages/api/gateway/tests/gateway-access.host.spec.ts +++ b/packages/api/gateway/tests/gateway-access.host.spec.ts @@ -21,6 +21,7 @@ import { type TypertContext, type TypertLookup, type TypertResource, + type TypertResourceResolveInput, } from '@deepseek-ai/dsh-typert-protocol' import TypertRegistry from '@deepseek-ai/dsh-typert-registry' import { z } from 'zod' @@ -48,6 +49,7 @@ declare module '@deepseek-ai/dsh-typert-protocol' { /** Test-only resource kinds; the Gateway itself names no kind. */ 'test-shelf': TypertResource 'test-desk': TypertResource + 'test-frame': TypertResource } } @@ -58,11 +60,12 @@ const GUEST: Guest = { kind: 'test-guest', guest: 'gateway' } const GLOBAL = { kind: 'global' } as const const shelf = (id: string) => ({ kind: 'test-shelf', id }) as const const desk = (id: string) => ({ kind: 'test-desk', id }) as const +const frame = (id: string) => ({ kind: 'test-frame', id }) as const const FIXTURE_ACTIONS: readonly RemoteAccessAction[] = [ 'accessFixture/open', 'accessFixture/read', 'accessFixture/byAgent', 'accessFixture/byLookup', 'accessFixture/byLookupAndOption', 'accessFixture/byList', 'accessFixture/scoped', 'accessFixture/scopedOnDesk', - 'accessFixture/scopedByReader', 'accessFixture/annotate', 'absentAccess/read', 'event:fixture/notice', 'event:fixture/shelf', + 'accessFixture/scopedByReader', 'accessFixture/annotate', 'accessFixture/bySession', 'absentAccess/read', 'event:fixture/notice', 'event:fixture/shelf', ] function role(resource: K): RemoteAccessRole { @@ -78,6 +81,8 @@ function on(resource: RemoteAccessResource): RemoteAccessBinding { return { role: role('test-shelf'), resource } case 'test-desk': return { role: role('test-desk'), resource } + case 'test-frame': + return { role: role('test-frame'), resource } default: throw new Error('no fixture role for this resource kind') } @@ -126,6 +131,12 @@ class AccessFixture extends TypertRemoteService { return this.seen() } + @Remote + bySession(sessionId: string): string { + void sessionId + return this.seen() + } + @Remote annotate(request: { readonly title: string }): string { this.requests.push(request) @@ -365,6 +376,22 @@ describe('Gateway access checks', () => { expect(decisions()).toEqual([{ action: 'absentAccess/read', resources: [GLOBAL] }]) }) + it('passes declared parameter names to a registered resolver through dispatch', async () => { + const { ctx, hold } = await setup() + const resolve = vi.fn(({ args, parameters }: TypertResourceResolveInput) => { + const named = parameters.find(parameter => parameter.name === 'sessionId') + return named === undefined ? undefined : args[named.wire] as string + }) + const dispose = ctx.typert.resources.register('test-frame', { resolve }) + const guest = peerFor(ctx, GUEST) + hold(frame('f1')) + await expect(call(ctx, guest, 'bySession', { sessionId: 'f1' })).resolves.toBe('test-guest') + await expect(call(ctx, guest, 'bySession', { sessionId: 'f2' })) + .rejects.toMatchObject({ code: 'remote-access/denied' }) + expect(resolve).toHaveBeenCalledTimes(2) + await dispose() + }) + it('checks access before resolving lookups, so a refused call activates nothing', async () => { const { ctx, hold } = await setup() const resolve = vi.fn((id: string) => ({ id })) @@ -703,6 +730,7 @@ describe('Gateway forwarded events for non-owner Peers', () => { await expect(ownerEvents.next()).resolves.toMatchObject({ value: { type: 'ready', host: { home: '/fixture' } } }) expect(ctx.typertGateway.hasLiveClient()).toBe(true) + expect(ctx.typertGateway.getPendingRemoteEvents()).toEqual([]) const agentCtx = ctx.extend({}) const subject = {} const settled = vi.fn() @@ -718,6 +746,10 @@ describe('Gateway forwarded events for non-owner Peers', () => { push({ event: 'fixture/shelf', args: ['s2'], resources }) push({ event: 'fixture/shelf', args: ['s1'], resources }) await expect(ownerEvents.next()).resolves.toMatchObject({ value: { type: 'waterfall', event: 'fixture/ask' } }) + const pending = ctx.typertGateway.getPendingRemoteEvents() + expect(pending).toEqual([{ event: 'fixture/ask', agentId: 'agent-1' }]) + expect(pending).not.toBe(ctx.typertGateway.getPendingRemoteEvents()) + expect(pending[0]).not.toBe(ctx.typertGateway.getPendingRemoteEvents()[0]) await expect(ownerEvents.next()).resolves.toMatchObject({ value: { type: 'emit', event: 'fixture/notice' } }) await expect(ownerEvents.next()).resolves.toMatchObject({ value: { type: 'emit', event: 'fixture/shelf', args: ['s2'] } }) await expect(ownerEvents.next()).resolves.toMatchObject({ value: { type: 'emit', event: 'fixture/shelf', args: ['s1'] } }) @@ -868,6 +900,55 @@ describe('resource resolution', () => { expect(callResources(typert, undefined, method(), {}, NEVER)).toEqual([GLOBAL]) }) + it('resolves default identities through the registered function and preserves explicit overrides', async () => { + const ctx = new Context() + roots.push(ctx) + await ctx.plugin(TypertRegistry) + const resolve = vi.fn(({ args, parameters }: TypertResourceResolveInput) => { + const named = parameters.find(parameter => parameter.wire === 'roomId') + if (named !== undefined) return args[named.wire] as string | undefined + const first = parameters[0] + const request = first === undefined ? undefined : args[first.wire] as { address?: { id: string } } | undefined + return request?.address?.id + }) + const dispose = ctx.typert.resources.register('test-shelf', { resolve }) + expect(callResources(ctx.typert, undefined, method('roomId'), { roomId: 'r1' }, NEVER)).toEqual([ROOM]) + expect(callResources(ctx.typert, undefined, method('request'), { request: { address: { id: 'r1' } } }, NEVER)).toEqual([ROOM]) + expect(callResources(ctx.typert, undefined, method('request'), { request: {} }, NEVER)).toEqual([GLOBAL]) + resolve.mockClear() + const args = { other: {}, later: { address: { id: 'r1' } } } + expect(callResources(ctx.typert, undefined, method('other', 'later'), args, NEVER)).toEqual([GLOBAL]) + expect(resolve).toHaveBeenCalledExactlyOnceWith({ args, parameters: method('other', 'later').parameters }) + resolve.mockClear() + expect(callResources(ctx.typert, undefined, { + ...method('renamed'), cancellation: { parameter: 'signal' }, + }, { renamed: { address: { id: 'r1' } } }, NEVER)).toEqual([ROOM]) + expect(resolve).toHaveBeenCalledExactlyOnceWith({ + args: { renamed: { address: { id: 'r1' } } }, parameters: method('renamed').parameters, + }) + expect(callResources(ctx.typert, { 'test-shelf': () => 'override' }, method('request'), { + request: { address: { id: 'r1' } }, + }, NEVER)).toEqual([shelf('override')]) + await dispose() + expect(ctx.typert.resources.entries()).toEqual([]) + ctx.typert.resources.register('test-shelf', { resolve: () => { throw new Error('cannot resolve') } }) + expect(callResources(ctx.typert, undefined, method('request'), { request: {} }, NEVER)).toBeUndefined() + }) + + it('rejects arrays from a default resolver instead of authorizing several identities', async () => { + const ctx = new Context() + roots.push(ctx) + await ctx.plugin(TypertRegistry) + for (const ids of [[], ['r1'], ['r1', 'r2']]) { + const dispose = ctx.typert.resources.register('test-shelf', { + // Exercise invalid results from an untyped provider at the authorization boundary. + resolve: () => ids as never, + }) + expect(callResources(ctx.typert, undefined, method(), {}, NEVER)).toBeUndefined() + await dispose() + } + }) + it('lets a reader replace the defaults for its kind, called with the positional wire arguments', async () => { const typert = await registry() const readers = { 'test-shelf': (ids: unknown) => ids } diff --git a/packages/api/job-controller/locale/de.json b/packages/api/job-controller/locale/de.json new file mode 100644 index 0000000000..ffddc2d9c6 --- /dev/null +++ b/packages/api/job-controller/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Schnittstelle zur Beobachtung von Hintergrundaufgaben", + "description": "Stellen Sie dem Kunden kontinuierlich den Status und die Ausgabe von Hintergrundaufgaben zur Verfügung." + } +} diff --git a/packages/api/job-controller/locale/es.json b/packages/api/job-controller/locale/es.json new file mode 100644 index 0000000000..d7fbfdc02e --- /dev/null +++ b/packages/api/job-controller/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Interfaz de observación de tareas en segundo plano", + "description": "Proporcionar continuamente el estado y la salida de las tareas en segundo plano al cliente." + } +} diff --git a/packages/api/job-controller/locale/fr.json b/packages/api/job-controller/locale/fr.json new file mode 100644 index 0000000000..aad494710a --- /dev/null +++ b/packages/api/job-controller/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Interface d'observation des tâches en arrière-plan", + "description": "Fournir en permanence l'état et la sortie des tâches en arrière-plan au client." + } +} diff --git a/packages/api/job-controller/locale/pt.json b/packages/api/job-controller/locale/pt.json new file mode 100644 index 0000000000..c98a63561b --- /dev/null +++ b/packages/api/job-controller/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Interface de observação de tarefas em segundo plano", + "description": "Fornece continuamente o status e a saída de tarefas em segundo plano ao cliente." + } +} diff --git a/packages/api/job-controller/locale/ru.json b/packages/api/job-controller/locale/ru.json new file mode 100644 index 0000000000..60ecb46b94 --- /dev/null +++ b/packages/api/job-controller/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Интерфейс наблюдения за фоновыми задачами", + "description": "Постоянно предоставляйте клиенту статус и вывод фоновых задач." + } +} diff --git a/packages/api/job-controller/package.json b/packages/api/job-controller/package.json index da53adf0fe..40649ebff3 100644 --- a/packages/api/job-controller/package.json +++ b/packages/api/job-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-job-controller", "description": "Job Remote observation stream and the reference-counted client job-output service", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, diff --git a/packages/api/remote-access/README.i18n.yaml b/packages/api/remote-access/README.i18n.yaml index 461af0d1f9..a95b536e3c 100644 --- a/packages/api/remote-access/README.i18n.yaml +++ b/packages/api/remote-access/README.i18n.yaml @@ -15,8 +15,8 @@ en: a18ecc232e3c3933 zh: b8e43580403f6d77 /deepseek-ai-dsh-api-remote-access/host-service-remoteaccessservice-ctx-key-remoteaccess: - en: 8a4be795c7aa2ef0 - zh: 02550b975e2e8d61 + en: 3d009c4a86374cbf + zh: ba3c624639ed18b9 /deepseek-ai-dsh-api-remote-access/client-face: en: d4cf8f646fdf2d39 zh: 247f643e991aa806 diff --git a/packages/api/remote-access/README.md b/packages/api/remote-access/README.md index ab35a6b598..f888679c15 100644 --- a/packages/api/remote-access/README.md +++ b/packages/api/remote-access/README.md @@ -37,7 +37,9 @@ Every composition that mounts [API Gateway](../gateway/README.md) mounts this se A role `{ name, resource, actions }` is a plain value naming an action set over one resource kind, `global` or a kind declared in `TypertResourceMap`. A binding `{ role, resource, condition? }` grants the role on one resource of the role's kind. A policy answers `bindings(principal)` and an optional `explain(request)` synchronously from state it holds in memory. A request is allowed only when, on every resolved resource, some binding names that resource, its role lists the action, and it has no condition or its condition allows. Resources are independent: a grant on `global` implies nothing on any other resource, and no resource implies another. A condition receives `{ action, resource, args? }` and runs only for a binding whose resource and role match; `args` is absent for events, snapshots, and list filtering. `bindings()` runs once per `decide()`, once per `allows()` check, and once per snapshot computation; it is never cached across decisions, so time-dependent state applies to the next call. -The Gateway resolves resources from `@Remote` and `@RemoteScope` `resources` readers, lookup and Host Context adapter `resource` declarations, and the default fields in `typert.resources`, and the [API Gateway](../gateway/README.md) owns that order; this package reads no argument field. A call that names no resource touches the `global` resource alone, so only a `global` role can allow it; putting an action in a `global` role lets the principal call it on any resource the call does not name. The Gateway refuses a call whose resources are invalid with `resource-invalid` without asking `decide()`. +The Gateway resolves resources from `@Remote` and `@RemoteScope` `resources` readers, lookup and Host Context adapter `resource` declarations, and the default field or resolver declarations in `typert.resources`, and the [API Gateway](../gateway/README.md) owns that order; this package reads no argument field. A call that names no resource touches the `global` resource alone, so only a `global` role can allow it; putting an action in a `global` role lets the principal call it on any resource the call does not name. The Gateway refuses a call whose resources are invalid with `resource-invalid` without asking `decide()`. + +Policy authors must treat `session/attachment` as access to the entire attachment store: granting that action on any one Session resource lets the caller supply that `sessionId` and read images referenced by other Sessions or by none. Gateway still checks that Session resource, but the handler checks neither Session existence nor image membership. Use separate Host instances with separate `DSH_HOME` directories when readers require separate image stores; see the [image access rule](../../../.agents/notes/implemented/architecture/2026-10-23-store-scoped-image-reads.md). When `bindings()`, a condition, or `explain()` throws, the decision is refused with `policy-failed`; in a snapshot, a throwing `bindings()` leaves the principal no grant and a throwing condition excludes its action. A faulty rule therefore never breaks the shared `$events` source, the snapshot stream, or page rendering. The service logger reports the first failure of each policy after each `invalidate()` and each policy registration or removal; later failures of that policy stay silent until then. diff --git a/packages/api/remote-access/README.zh.md b/packages/api/remote-access/README.zh.md index 514f885b33..ab073ed7c0 100644 --- a/packages/api/remote-access/README.zh.md +++ b/packages/api/remote-access/README.zh.md @@ -37,7 +37,9 @@ kind: "package-reference" role `{ name, resource, actions }` 是普通值,表示限定一种资源种类(`global` 或在 `TypertResourceMap` 中声明的种类)的 action 集合。binding `{ role, resource, condition? }` 在该 role 种类的一个资源上授予该 role。policy 根据预先载入内存的状态同步回答 `bindings(principal)` 与可选的 `explain(request)`。只有在每个已解析资源上都有某个 binding 指向该资源、其 role 列出该 action、且没有 condition 或 condition 放行时,请求才被放行。资源之间相互独立:`global` 上的授权不蕴含任何其他资源上的授权,任何资源也不蕴含另一个资源。condition 收到 `{ action, resource, args? }`,只对资源与 role 都匹配的 binding 调用;事件、快照与列表过滤时没有 `args`。`bindings()` 在每次 `decide()`、每次 `allows()` 判定与每次快照计算中各调用一次,不跨判定缓存,因此依赖时间的状态对下一次调用即时生效。 -Gateway 依次从 `@Remote` 与 `@RemoteScope` 的 `resources` 读取函数、lookup 与 Host Context adapter 的 `resource` 声明、`typert.resources` 中的默认字段解析资源,解析顺序由 [API Gateway](../gateway/README.zh.md) 负责;本包不读取任何参数字段。不指明任何资源的调用只访问 `global` 资源,因此只有 `global` 级 role 能放行;把某个 action 放进 `global` 级 role,等于允许该 principal 在调用未指明的任何资源上调用它。资源非法的调用由 Gateway 以 `resource-invalid` 拒绝,不询问 `decide()`。 +Gateway 依次从 `@Remote` 与 `@RemoteScope` 的 `resources` 读取函数、lookup 与 Host Context adapter 的 `resource` 声明、`typert.resources` 中的默认字段或 resolver 声明解析资源,解析顺序由 [API Gateway](../gateway/README.zh.md) 负责;本包不读取任何参数字段。不指明任何资源的调用只访问 `global` 资源,因此只有 `global` 级 role 能放行;把某个 action 放进 `global` 级 role,等于允许该 principal 在调用未指明的任何资源上调用它。资源非法的调用由 Gateway 以 `resource-invalid` 拒绝,不询问 `decide()`。 + +policy 作者必须把 `session/attachment` 视为整个附件存储的读取权限:在任意一条 Session 资源上授予该 action,就允许调用方使用这个 `sessionId` 读取其他 Session 引用或未被任何 Session 引用的图片。Gateway 仍检查该 Session 资源,但处理函数既不检查 Session 是否存在,也不检查图片关联。需要让不同读者使用不同图片存储时,须使用独立 Host 实例及各自的 `DSH_HOME` 目录;见[图片访问规则](../../../.agents/notes/implemented/architecture/2026-10-23-store-scoped-image-reads.zh.md)。 `bindings()`、condition 或 `explain()` 抛错时,本次判定以 `policy-failed` 拒绝;计算快照时,`bindings()` 抛错即该 principal 没有 grant,condition 抛错即该 action 不放行。有问题的规则因此不会破坏共享的 `$events` 事件源、快照流或页面渲染。每次 `invalidate()` 以及每次 policy 注册或撤回之后,服务日志对每个 policy 只报告第一次失败;此后该 policy 的失败不再记录,直到下一次上述变化。 diff --git a/packages/api/remote-access/locale/de.json b/packages/api/remote-access/locale/de.json new file mode 100644 index 0000000000..14b83f143c --- /dev/null +++ b/packages/api/remote-access/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Fernzugriffskontrolle", + "description": "Steuern Sie, mit welchen Methoden Nicht-Eigentümer-Verbindungen auf Berechtigungs-Snapshots für jede Verbindung zugreifen und diese beibehalten können." + } +} diff --git a/packages/api/remote-access/locale/es.json b/packages/api/remote-access/locale/es.json new file mode 100644 index 0000000000..dda54e1529 --- /dev/null +++ b/packages/api/remote-access/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "control de acceso remoto", + "description": "Controle a qué métodos pueden acceder las conexiones que no son propietarios y retener instantáneas de permisos para cada conexión." + } +} diff --git a/packages/api/remote-access/locale/fr.json b/packages/api/remote-access/locale/fr.json new file mode 100644 index 0000000000..96082a9342 --- /dev/null +++ b/packages/api/remote-access/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Contrôle d'accès à distance", + "description": "Contrôlez les méthodes auxquelles les connexions non propriétaires peuvent accéder et conserver les instantanés d'autorisation pour chaque connexion." + } +} diff --git a/packages/api/remote-access/locale/pt.json b/packages/api/remote-access/locale/pt.json new file mode 100644 index 0000000000..840eaf556f --- /dev/null +++ b/packages/api/remote-access/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Controle de acesso remoto", + "description": "Controle quais métodos as conexões não proprietárias podem acessar e reter instantâneos de permissão para cada conexão." + } +} diff --git a/packages/api/remote-access/locale/ru.json b/packages/api/remote-access/locale/ru.json new file mode 100644 index 0000000000..1faa15dd38 --- /dev/null +++ b/packages/api/remote-access/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Управление удаленным доступом", + "description": "Контролируйте, какие методы соединения, не являющиеся владельцами, могут получать доступ и сохранять снимки разрешений для каждого соединения." + } +} diff --git a/packages/api/remote-access/package.json b/packages/api/remote-access/package.json index bcc911aee9..f4e3e13975 100644 --- a/packages/api/remote-access/package.json +++ b/packages/api/remote-access/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-remote-access", "description": "Method-level Remote access control for non-owner Peers and the per-Peer access snapshot", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, diff --git a/packages/api/remotes/locale/de.json b/packages/api/remotes/locale/de.json new file mode 100644 index 0000000000..dcc7ff1da3 --- /dev/null +++ b/packages/api/remotes/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Zusammenfassung des Kunden API", + "description": "Fasst die Serverfunktionen zusammen, die Clients durch Anwendungen zur Verfügung stehen." + } +} diff --git a/packages/api/remotes/locale/es.json b/packages/api/remotes/locale/es.json new file mode 100644 index 0000000000..d731b0c788 --- /dev/null +++ b/packages/api/remotes/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Resumen del cliente API", + "description": "Resume las capacidades del servidor abiertas a los clientes por las aplicaciones." + } +} diff --git a/packages/api/remotes/locale/fr.json b/packages/api/remotes/locale/fr.json new file mode 100644 index 0000000000..a85835665d --- /dev/null +++ b/packages/api/remotes/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Récapitulatif du client API", + "description": "Résume les fonctionnalités du serveur ouvertes aux clients par les applications." + } +} diff --git a/packages/api/remotes/locale/pt.json b/packages/api/remotes/locale/pt.json new file mode 100644 index 0000000000..9bc13b83ff --- /dev/null +++ b/packages/api/remotes/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Resumo do cliente API", + "description": "Resume os recursos do servidor abertos aos clientes pelos aplicativos." + } +} diff --git a/packages/api/remotes/locale/ru.json b/packages/api/remotes/locale/ru.json new file mode 100644 index 0000000000..804cf94148 --- /dev/null +++ b/packages/api/remotes/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Сводная информация о клиенте API", + "description": "Обобщает возможности сервера, открытые для клиентов приложениями." + } +} diff --git a/packages/api/remotes/package.json b/packages/api/remotes/package.json index c0ae5bdf82..288aabea9b 100644 --- a/packages/api/remotes/package.json +++ b/packages/api/remotes/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-remotes", "description": "Remote BFF assembly for application-selected Host capabilities", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index 6df1300fd1..010c41bf94 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -15,14 +15,14 @@ en: 1fdf707322fb6996 zh: 0204f7e9d4aa3cce /session-controller/use-this-package: - en: aabd5be911e477f5 - zh: 2f7fdb44bc8777bc + en: d3d53e899960d96e + zh: 16b2bc7fe74215d8 /session-controller/client-references: en: 41bdda1ac32df558 zh: aa5d0e325924066b /session-controller/session-media-references: - en: 25e40cb508265c01 - zh: c8ce39a94997af00 + en: 954923654eebe2dc + zh: 6bd9a7d2ea965aed /session-controller/configuration: en: c92590fbaf75e45e zh: fcac67017bb0e3ab diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index abbb52cd63..6fd7b24561 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -33,9 +33,11 @@ History pages and follow opening snapshots carry one `{ type: 'event', event: Se The Client journal validates current Session event envelopes before publishing follow snapshots, live entries, or history pages. It reuses the browser-safe Session validators for required surface markers, exact replacement endpoints, earlier unique source seqs, embedded Assistant provider metadata, request-header omissions, and tool-error consistency. Invalid records fail without field stripping or normalization; range membership and source existence remain durable-log checks on the Host. -Each endpoint states its activation policy. List reads only stored headers and projection-cache rows: it never calls per-session stat or opens a cold Session body. A current-format cache identity may supply every list hint; a lifecycle-matching predecessor cache may supply only its version-compatible title as a stale display fact, never as an authoritative fold seed. Search, attachment, history pages, log following, skill discovery, and workspace-path opening can inspect persistence without activating an Agent; `canOpenWorkspacePath()` reports native-opening availability without addressing a Session. Cancellation requires live state; queue mutation, model, rename, prompt, and file-reference operations may resolve or resume an ordinary Session. Prompt rejects content with neither non-whitespace text nor an attachment before resolving the Agent or appending Session events; queue edits accept only non-empty text content. Prompt admission consumes opaque receipts from the injected [`fileUploads`](../../client/file-upload/README.md) Host service and resolves every same-Agent receipt before sending the complete ordered content list through `ctx.attachments`. A receipt names a staged file or a staged image, and an image receipt subjects the prompt to the same image-input check as an encoded image. Prompt retries whose `requestId` is already queued or logged return the original acceptance without inserting another message. Create and fork are the only operations that create a new Agent directly. The service applies one preset-aware resume policy and subagent ownership fence to its own methods and to the Typert Agent and Session lookups used by other Remote namespaces. Queue mutation has one narrow exception: a live child whose current projected identity is continuable and comes from its own non-seed suffix accepts the ordinary Edit, Remove, and QueueDock Steer actions across both inbox destinations. One-shot, missing, unknown, corrupt, seed-only, or cold children remain rejected without resume. The skill catalog uses a live Agent's effective working directory and scoped registry when present. Cold listing uses the projected current directory, falling back to the recorded origin and then the configured directory default. It retains the preset standing scope without activating an Agent. The authenticated delivery routes use `workspaceDesktop()` for the serving Host name and file-manager behavior. `openWorkspacePath({ path, action: "reveal" })` delegates file-manager navigation to the native adapter; omitting `action` opens the file-type association, including HTML and SVG. Both operations require the composed filesystem to map the requested Host path to the same canonical process path; unmapped remote paths are refused before a native command runs. `session.projections` normally reads an exact baseline, including current-format cold logs, and returns `kind: sequenced`. Only a read requiring migration returns `kind: migration-required` hints without `asOfSeq`; missing keys remain absent. It returns null for a missing Session. Fork callers may set `allowMigration: false` to receive `session/migration-required` instead of starting source migration; omission retains automatic migration. The Client exposes shared values and explicit-read state through `projectionsBySession`; domains select their own keys. Session-list summaries carry `agentAvailable`, updated through existing summary and status events independently of durable projections. Sequenced reads and live projection frames use the same sequence ordering; cached reads fill hints without replacing sequenced values. +Each endpoint states its activation policy. List reads only stored headers and projection-cache rows: it never calls per-session stat or opens a cold Session body. A current-format cache identity may supply every list hint; a lifecycle-matching predecessor cache may supply only its version-compatible title as a stale display fact, never as an authoritative fold seed. Search, history pages, log following, skill discovery, and workspace-path opening can inspect persistence without activating an Agent; `canOpenWorkspacePath()` reports native-opening availability without addressing a Session. Cancellation requires live state; queue mutation, model, rename, prompt, and file-reference operations may resolve or resume an ordinary Session. Prompt rejects content with neither non-whitespace text nor an attachment before resolving the Agent or appending Session events; queue edits accept only non-empty text content. Prompt admission consumes opaque receipts from the injected [`fileUploads`](../../client/file-upload/README.md) Host service and resolves every same-Agent receipt before sending the complete ordered content list through `ctx.attachments`. A receipt names a staged file or a staged image, and an image receipt subjects the prompt to the same image-input check as an encoded image. Prompt retries whose `requestId` is already queued or logged return the original acceptance without inserting another message. Create and fork are the only operations that create a new Agent directly. The service applies one preset-aware resume policy and subagent ownership fence to its own methods and to the Typert Agent and Session lookups used by other Remote namespaces. Queue mutation has one narrow exception: a live child whose current projected identity is continuable and comes from its own non-seed suffix accepts the ordinary Edit, Remove, and QueueDock Steer actions across both inbox destinations. One-shot, missing, unknown, corrupt, seed-only, or cold children remain rejected without resume. The skill catalog uses a live Agent's effective working directory and scoped registry when present. Cold listing uses the projected current directory, falling back to the recorded origin and then the configured directory default. It retains the preset standing scope without activating an Agent. The authenticated delivery routes use `workspaceDesktop()` for the serving Host name and file-manager behavior. `openWorkspacePath({ path, action: "reveal" })` delegates file-manager navigation to the native adapter; omitting `action` opens the file-type association, including HTML and SVG. Both operations require the composed filesystem to map the requested Host path to the same canonical process path; unmapped remote paths are refused before a native command runs. `session.projections` normally reads an exact baseline, including current-format cold logs, and returns `kind: sequenced`. Only a read requiring migration returns `kind: migration-required` hints without `asOfSeq`; missing keys remain absent. It returns null for a missing Session. Fork callers may set `allowMigration: false` to receive `session/migration-required` instead of starting source migration; omission retains automatic migration. The Client exposes shared values and explicit-read state through `projectionsBySession`; domains select their own keys. Session-list summaries carry `agentAvailable`, updated through existing summary and status events independently of durable projections. Sequenced reads and live projection frames use the same sequence ordering; cached reads fill hints without replacing sequenced values. -Every Remote endpoint is access-controlled: a Peer whose principal is not the owner reaches an endpoint only when, on every resource the call touches, a binding of that principal kind's policy in [`dsh-api-remote-access`](../remote-access/README.md) grants a role listing the action ([Peer principals Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md)). The controller injects `remoteAccess` and registers the `session` resource kind with the default field `sessionId` through `typert.resources`. `session/page` and `session/follow` declare a `session` reader in `@Remote({ resources })` that reads `request.address.sessionId` for an ordinary Session address and `request.address.childSessionId` for a subagent address; whether access to the parent Session covers its children is the policy's rule. `session/projections` reads the Session resource from `request.sessionId`, so a reconnecting reader reloads only the projections of Sessions it may read. `session/list`, `session/search`, and `session/control` read no resource, so their calls touch the `global` resource and need a `global` role; for a non-owner caller, `session/list` returns only the rows, `session/search` only the hits, and `session/control` only the baseline projections and projection frames, whose Session `ctx.remoteAccess.allows()` admits for the same action, so that action also belongs to a `session` role; owner results are unfiltered. `session/prompt` builds the durable `user-rpc` message source in its Remote method and records `principal` only for a non-owner caller, read through `principalOf(this.ctx.invocation)`; a source without `principal` belongs to the owner. +Every Remote endpoint is access-controlled: a Peer whose principal is not the owner reaches an endpoint only when, on every resource the call touches, a binding of that principal kind's policy in [`dsh-api-remote-access`](../remote-access/README.md) grants a role listing the action ([Peer principals Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md)). The controller injects `remoteAccess` and registers a default resolver for the `session` resource kind through `typert.resources`. It reads a named `sessionId` parameter, otherwise the first object argument's `sessionId` or `address`; unrelated string parameters name no Session. An object containing both `sessionId` and `address` is invalid, even when they name the same Session. `session/events`, the deprecated `session/page`, `session/observeEvent`, and `session/follow` use this resolver to read `address.sessionId` for an ordinary Session address and `address.childSessionId` for a subagent address; whether access to the parent Session covers its children is the policy's rule. `session/projections`, `session/observeProjections`, `session/state`, `session/observeState`, and `session/wait` read the Session resource from `request.sessionId`, so each call and subscription names only the Sessions it may read. `session/list`, `session/search`, and `session/control` read no resource, so their calls touch the `global` resource and need a `global` role; for a non-owner caller, `session/list` returns only the rows, `session/search` only the hits, and `session/control` only the baseline projections and projection frames, whose Session `ctx.remoteAccess.allows()` admits for the same action, so that action also belongs to a `session` role; owner results are unfiltered. `session/prompt` builds the durable `user-rpc` message source in its Remote method and records `principal` only for a non-owner caller, read through `principalOf(this.ctx.invocation)`; a source without `principal` belongs to the owner. + +`events` reads one chronological page from a durable cut and returns its records, `hasMore`, and an inclusive `cursor`; omitting `throughSeq` selects the observed log end, and the compatible `page` method carries the same read with a deprecated entry point. `events`, `observeEvent`, and `follow` take an Address; projection and state operations take a Session ID. Page reads and Follow openings validate the supplied Address. Pure `observeEvent` and `observeProjections` subscriptions neither acquire an Observation nor establish existence: their `ready` frame carries no snapshot cursor. List rows carry `formatStatus` when available, so Clients can identify migration-required Sessions without requesting their projections. @@ -55,14 +57,14 @@ Accepted prompts and observed running keep their Client display conversion acros The Client adapter exposes `SessionEventStream`, a Gateway `RemoteJournalStream` bound to one ordinary or direct-subagent address. It opens follow before the initial page, publishes only contiguous `replace`, `prepend`, `append`, and `settle-assistant` changes, and repairs reconnect or sequence gaps through a tail page. Backwards paging has two verbs: `loadOlder()` pulls one Turn-aligned page, and `loadThrough(seq)` — the turn-jump loader — loops Turn-aligned pages until the window covers the target seq, lowering a shared target on repeated calls, stopping on a page that makes no progress, and reporting busy through the same `loadingOlder` snapshot bit. The Web adapter explicitly opts into cursorless Assistant frames: each opening carries the active attempt's `startedAfterSeq`, `nextIndex`, and compact stream, and every stream member becomes a Client-only `assistant/live-chunk` entry ordered between durable cursors. The Host captures a follower-local arrival ordinal with that baseline and suppresses buffered frames at or before the cut; a replacement Agent may restart frame revision at one. A durable `assistant/message` or `assistant/attempt` arriving after an active opening stays staged only when its seq follows `startedAfterSeq` and its Turn and Step match; the matching end type, seq, and index releases the durable entry. A successful message retains its transient rows until the owning `step/end`, so pending tool identities remain available for dispatch. Failed or interrupted settlements retire their rows immediately; earlier same-step retries remain visible. Revision, dense-index, or settlement gaps for a known attempt reopen follow, while a controller that missed the start ignores unknown-attempt frames and publishes their durable settlement normally. An abandoned end publishes a settlement delta without a durable entry so its transient rows retire immediately. A durable gap-repair page has no Assistant baseline, so its held notification reopens follow once for a paired page and baseline. Every history record covers exactly its event seq. A business, persistence, or unresolved continuity failure terminates the stream, while only physical carrier loss selects automatic resumption. `SessionControlStream` is a Gateway `RemoteSnapshotStream`; every generation opens with a complete process-local baseline, so reconnect replaces projection state instead of treating transient values as durable events. At each ready Host generation, a synchronous Client subscription clears retained projection values and watermarks before refreshing queries and restarting the control stream, including Sessions absent from the control baseline. The first control stream waits for generation readiness, so its opening values cannot precede invalidation. Outstanding list responses from the previous generation cannot republish those values. Within a generation, a delayed control baseline cannot overwrite or clear newer sequenced values, whether they arrived through a live Session's list block, a history page, or a frame; a cached list block, viewed from the projection cache for a cold Session, yields to the connected Session's baseline whatever watermark it carries. The durable `inbox` projection carries both pending lists through the same cold-read and reconnect path as other projections. Client Agent contexts provide the identity used by the independent [`fileUpload`](../../client/file-upload/README.md) service; Session objects expose lifecycle, prompt, queue, and history operations rather than file transfer. -The Session object also carries local submission echoes: `session.beginSubmission` inserts one into `SessionSnapshot.pendingSubmissions` synchronously, before the caller serializes and prompts, so a conversation UI can show the message on the submit click's own frame. The echo stores ordered image previews and durable file references. Session derives its `transcript`, `queued`, or `steering` placement from the current running state and requested delivery mode, then retains that placement until the display handoff. The prompt's `requestId` is the correlation identity: the Host echoes it as the durable user source's `rpcId`, including pending messages in the `inbox` projection. Queued echoes retire one animation frame after queue acceptance; Chat echoes follow the admission rule below. Identified failures and abandonment retire unadmitted echoes immediately. Disposal preserves observed admission and fails other unsettled submissions. Each retirement fires `onRetire` exactly once; an observed retirement includes the ordered durable attachment references so the composer can release successful cards while preserving failed drafts. Echoes are Client memory only; reload and reconnect rebuild the conversation from durable events alone. +The Session object also carries local submission echoes: `session.beginSubmission` registers one before the caller serializes and prompts, and Session publishes it in `SessionSnapshot.pendingSubmissions` once the Host has accepted the prompt, as the `prompt` receipt or an `inbox` row carrying the request id shows, whichever arrives first. A conversation UI therefore shows the message from acceptance until its durable entry renders, and Chat and QueueDock exclude the matching Inbox row from the moment it arrives. The blank-to-engaging transition happens at the same acceptance. The echo stores ordered image previews and durable file references. Session derives its `transcript`, `queued`, or `steering` placement from the current running state and requested delivery mode, then retains that placement until the display handoff. The prompt's `requestId` is the correlation identity: the Host echoes it as the durable user source's `rpcId`, including pending messages in the `inbox` projection. Queued echoes retire one animation frame after queue acceptance; Chat echoes follow the admission rule below. Identified failures and abandonment retire unadmitted echoes immediately. Disposal preserves observed admission and fails other unsettled submissions. Acceptance fires `onAccept` once, in the same update that publishes the echo, so the sender can settle its composer together with the echo. Each retirement fires `onRetire` exactly once; an observed retirement includes the ordered durable attachment references so the sender can release or hand over the sent attachments. Echoes are Client memory only; reload and reconnect rebuild the conversation from durable events alone. During uninterrupted following, transcript and steering echoes stay in Chat through Inbox acceptance and claim until their durable messages arrive. After a local Chat message is admitted, its identity remains until the Inbox watermark reaches its next-turn or next-step claim seq: Chat already renders the durable Node, while Chat and QueueDock exclude matching stale Inbox rows. Other queued messages remain visible. A replacement follow baseline withdraws receipt-confirmed echoes as observed, using their accepted attachment references; unconfirmed submissions remain pending. Host data then supplies the pending or admitted rows. Reconnecting between claim and admission can briefly omit that bubble; withdrawal confirms acceptance, not execution or failure. The user-invocable `skills/list` metadata includes the winning provider’s optional instruction-file `path`. The composer can preview that file without loading every skill body or activating a cold Agent. -Fork copies the exact inclusive event prefix selected by `atSeq`, including a cut inside an open turn. The child records its inherited marker before synthetic fork results and closing events. Omitting `atSeq` selects the latest completed turn and its standalone tail, stopping before the next turn or queued input; a nonexistent event is rejected. The chat action selects a completed turn. +Fork copies the exact inclusive event prefix selected by `atSeq`, including a cut inside an open turn, into an independent Session without `parentSession`. Client placeholders likewise omit `parentSessionId`; list indentation applies only to subagent-origin rows, including when historical ordinary forks retain a parent id. Workspace attachment and optional title increments use the source selected for the operation. The child records its inherited marker before synthetic fork results and closing events. Omitting `atSeq` selects the latest completed turn and its standalone tail, stopping before the next turn or queued input; a nonexistent event is rejected. The chat action selects a completed turn. A resume blocked by an existing write handle returns `session/writer-held` with the Session id; other resume failures retain `gateway/internal`. @@ -72,7 +74,7 @@ The Client's initial `follow`, reconnect openings, and `loadOlder()` request at Queue edits replace pending content with non-empty text only. -Attachment authorization reads declared content fields of built-in Session events and completed assistant stream blocks, including flat V4 tool-role messages. Unknown event payloads and unrelated fields cannot authorize attachment reads. +`session.attachment` receives `{ sessionId, attachment: ImageAttachmentRef }` and passes the complete reference to `AttachmentStore.readImage()`, without reading or traversing Session history. The Client supplies the message's reference through `session.readAttachment(ref)`. Connection authentication and Gateway permission checks still apply; `sessionId` selects the Session resource for the endpoint's permission check. After authorization, the handler does not check whether that Session exists and does not return `session/not-found` merely because it is absent. An authorized caller may read any image in the same store, including an image referenced only by another Session or by no Session. The response preserves the supplied reference after verifying its ID, media type, byte length, width, and height against the stored bytes. Optional `name` and `originalDimensions` pass through as caller-supplied display information and are not verified against the file. Missing or invalid objects return a terminal attachment failure. The Client's historical-image cache retains one result and browser URL per Session and attachment ID. The controller composes `ArchivedSessionGate` through `ctx.plugin`: it loads once the Agent registry, Session store, and Workspace registry exist and unwinds with the controller. Its `agent/pre-step` listener rejects a step proposed for an archived Session or for a subagent descendant of one — read from the Session header's lineage fields, never a fork — so a late waking delivery ends its turn as `blocked` without a model request; unarchiving lifts the gate for the whole lineage. The work an archived Session still runs is reported and stopped by its owners through the Workspace registry's archive admission ([seam](../../workspace/workspace/README.md)): the running turn by the [Agent registry](../../core/agent/README.md), owned jobs by the [job registry seam](../../jobs/jobs/README.md), subagent descendants by the [Subagent](../../subagent/subagent/README.md) runtime, reminders by the [Schedule](../../schedule/schedule/README.md) plugin; this controller reports nothing itself. @@ -86,7 +88,7 @@ References keep local Session data, scoped Contexts, and history streams alive, ## Session media references -`SessionMediaReferences` mounts `GET|HEAD /api/file?path=` on the authenticated `connection.fetch` channel when `connection`, `fs`, and `attachments` are composed. It reads ordinary files through `ctx.fs`, including temporary paths outside registered workspaces and files in remote providers. Neither directory containment nor MIME categories restrict access; `mime-types` supplies the response type, with `application/octet-stream` for unknown extensions. GET reuses `readBytes` for preflight and ongoing byte limits; HEAD reads metadata only. All files use `ctx.attachments.imageLimits.maxImageBytes` (normally 50 MiB); exceeding this limit returns 413. Responses contain the complete file, ignore Range, and carry `private, no-store`, `nosniff`, and a sandbox CSP so directly opened HTML/SVG cannot execute with the API origin. The Client rewrite lives in `ui-chat` (`AssistantMarkdown`); audio/video responses are available, while Markdown audio/video player nodes remain separate work. +`SessionMediaReferences` mounts `GET|HEAD /api/file?path=` on the authenticated `connection.fetch` channel when `connection`, `fs`, and `attachments` are composed. It reads ordinary files through `ctx.fs`, including temporary paths outside registered workspaces and files in remote providers. Neither directory containment nor MIME categories restrict access; `mime-types` supplies the response type, with `application/octet-stream` for unknown extensions. GET reuses `readBytes` for preflight and ongoing byte limits; HEAD reads metadata only. All files use `ctx.attachments.imageLimits.maxImageBytes` (normally 50 MiB); exceeding this limit returns 413. A request whose `v` parameter differs from the file's current `ctx.fs` version, including a request without one, receives a `private, no-store` 302 to the same route with only `path` and the current `v`; the versioned response is `private, max-age=31536000, immutable`, so browsers reuse cached bytes until the file changes, and private file contents may enter the browser disk cache. Responses contain the complete file, ignore Range, and carry `nosniff`, and a sandbox CSP so directly opened HTML/SVG cannot execute with the API origin. The Client rewrite lives in `ui-chat` (`AssistantMarkdown`); audio/video responses are available, while Markdown audio/video player nodes remain separate work. GUI model selection requires the exact provider/model pair in the available catalog; unavailable choices reject with `session/model-unavailable`. Prompt admission retains the saved route without a catalog availability gate, so request execution reports missing credentials or unavailable models. `initializeDefaultModel()` saves the first available account model after login when no other provider has a configured API key; credential checks use configured references independently of model availability. A provider with no available models rejects initialization with `session/provider-models-unavailable`. Availability never substitutes another model or rewrites a Session selection. diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index 58bdbbf48b..8729f555ba 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -33,9 +33,11 @@ kind: "package-reference" Client journal 在发布 follow 快照、live entry 或历史页之前验证当前 Session 事件 envelope。它复用浏览器安全的 Session validator,检查必需的 surface marker、精确的 replacement endpoint、更早且唯一的 source seq、内嵌 Assistant 提供方元数据、request header 可选字段的省略规则以及工具错误一致性。无效 record 直接失败,不删除字段或归一化;范围成员与来源存在性仍由 Host 的持久日志检查。 -每个 endpoint 都声明自己的激活策略。列表只读取持久化 header 与 projection cache row,绝不调用逐 Session stat 或打开冷 Session body。当前格式 cache identity 可以提供全部列表 hint;生命周期匹配的 predecessor cache 只能提供版本兼容的 title,作为可能过时的展示事实,绝不能作为权威 fold seed。搜索、附件、历史页、日志跟随、skill 发现和工作区路径打开可以在不激活 Agent 的情况下检查 persistence;`canOpenWorkspacePath()` 无需指定 Session 即可报告原生打开能力。取消要求 live 状态;queue 变更、模型、重命名、prompt 和文件引用操作可以解析或恢复普通 Session。提示词会在解析 Agent 或追加 Session 事件前,拒绝既没有非空白文本也没有附件的 content;queue edit 只接受非空文本 content。prompt 准入从注入的 [`fileUploads`](../../client/file-upload/README.zh.md) Host 服务取得不透明凭证,在把完整有序内容列表交给 `ctx.attachments` 前解析每个属于同一 Agent 的凭证。凭证指向一个暂存文件或一张暂存图片;图片凭证与编码图片一样要经过图片输入检查。`requestId` 已进入 queue 或日志时,prompt 重试直接返回原来的接受结果,不会重复插入消息。只有 create 与 fork 会直接创建新 Agent。该服务把同一套感知 preset 的恢复策略和 subagent ownership fence 同时用于自身方法,以及其他 Remote namespace 使用的 Typert Agent 与 Session lookup。Queue 变更只有一个狭窄例外:当前 projection identity 为 continuable 且来自自身非 seed suffix 的在线 child,可以在两个 inbox 目标上使用普通 Edit、Remove 与 QueueDock Steer action。One-shot、缺失、未知、损坏、仅含 seed identity 或冷 child 继续被拒绝,且不会恢复。skill 目录优先使用已有 live Agent 的有效工作目录与限定范围内的注册表。冷态列表使用投影中的当前目录,依次回退到记录的起始目录与配置的默认目录。它保留 preset 常驻 scope,不会激活 Agent。经过鉴权的文件交付路由通过 `workspaceDesktop()` 获取提供服务的 Host 名称和文件管理器行为。`openWorkspacePath({ path, action: "reveal" })` 将文件管理器导航委托给原生适配器;省略 `action` 时按文件类型关联打开,包括 HTML 和 SVG。两种操作都要求当前文件系统将请求的 Host 路径映射到同一个规范进程路径;无法映射的远端路径会在执行原生命令之前被拒绝。 `session.projections` 正常读取准确基线,包括当前格式的冷日志,返回 `kind: sequenced`。只有需要迁移时才返回不带 `asOfSeq` 的 `kind: migration-required` 提示,缺少的键保持缺席。Session 不存在时返回 null。Fork 调用者可设置 `allowMigration: false`,在源历史需要迁移时收到 `session/migration-required`;省略则保持自动迁移。Client 通过 `projectionsBySession` 暴露共享值和显式读取状态,由领域选择自身的 key。Session 列表摘要携带 `agentAvailable`,通过已有摘要与状态事件更新,与持久化 projection 相互独立。有序读取与实时 projection 帧使用相同的序号排序规则;缓存读取只补充提示,不替换有序值。 +每个 endpoint 都声明自己的激活策略。列表只读取持久化 header 与 projection cache row,绝不调用逐 Session stat 或打开冷 Session body。当前格式 cache identity 可以提供全部列表 hint;生命周期匹配的 predecessor cache 只能提供版本兼容的 title,作为可能过时的展示事实,绝不能作为权威 fold seed。搜索、历史页、日志跟随、skill 发现和工作区路径打开可以在不激活 Agent 的情况下检查 persistence;`canOpenWorkspacePath()` 无需指定 Session 即可报告原生打开能力。取消要求 live 状态;queue 变更、模型、重命名、prompt 和文件引用操作可以解析或恢复普通 Session。提示词会在解析 Agent 或追加 Session 事件前,拒绝既没有非空白文本也没有附件的 content;queue edit 只接受非空文本 content。prompt 准入从注入的 [`fileUploads`](../../client/file-upload/README.zh.md) Host 服务取得不透明凭证,在把完整有序内容列表交给 `ctx.attachments` 前解析每个属于同一 Agent 的凭证。凭证指向一个暂存文件或一张暂存图片;图片凭证与编码图片一样要经过图片输入检查。`requestId` 已进入 queue 或日志时,prompt 重试直接返回原来的接受结果,不会重复插入消息。只有 create 与 fork 会直接创建新 Agent。该服务把同一套感知 preset 的恢复策略和 subagent ownership fence 同时用于自身方法,以及其他 Remote namespace 使用的 Typert Agent 与 Session lookup。Queue 变更只有一个狭窄例外:当前 projection identity 为 continuable 且来自自身非 seed suffix 的在线 child,可以在两个 inbox 目标上使用普通 Edit、Remove 与 QueueDock Steer action。One-shot、缺失、未知、损坏、仅含 seed identity 或冷 child 继续被拒绝,且不会恢复。skill 目录优先使用已有 live Agent 的有效工作目录与限定范围内的注册表。冷态列表使用投影中的当前目录,依次回退到记录的起始目录与配置的默认目录。它保留 preset 常驻 scope,不会激活 Agent。经过鉴权的文件交付路由通过 `workspaceDesktop()` 获取提供服务的 Host 名称和文件管理器行为。`openWorkspacePath({ path, action: "reveal" })` 将文件管理器导航委托给原生适配器;省略 `action` 时按文件类型关联打开,包括 HTML 和 SVG。两种操作都要求当前文件系统将请求的 Host 路径映射到同一个规范进程路径;无法映射的远端路径会在执行原生命令之前被拒绝。 `session.projections` 正常读取准确基线,包括当前格式的冷日志,返回 `kind: sequenced`。只有需要迁移时才返回不带 `asOfSeq` 的 `kind: migration-required` 提示,缺少的键保持缺席。Session 不存在时返回 null。Fork 调用者可设置 `allowMigration: false`,在源历史需要迁移时收到 `session/migration-required`;省略则保持自动迁移。Client 通过 `projectionsBySession` 暴露共享值和显式读取状态,由领域选择自身的 key。Session 列表摘要携带 `agentAvailable`,通过已有摘要与状态事件更新,与持久化 projection 相互独立。有序读取与实时 projection 帧使用相同的序号排序规则;缓存读取只补充提示,不替换有序值。 -每个 Remote 端点都受访问控制:principal 不是 owner 的 Peer 只有在本次调用访问的每个资源上,该 principal kind 在 [`dsh-api-remote-access`](../remote-access/README.zh.md) 中的 policy 都有某个 binding 授予列出该 action 的 role 时,才能调用该端点([Peer 身份属性 Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md))。控制器注入 `remoteAccess`,并经 `typert.resources` 以默认字段 `sessionId` 登记 `session` 资源种类。`session/page` 与 `session/follow` 在 `@Remote({ resources })` 中声明 `session` 读取函数:对普通 Session 地址读 `request.address.sessionId`,对 subagent 地址读 `request.address.childSessionId`;父会话的访问权是否覆盖其子会话由 policy 决定。`session/projections` 从 `request.sessionId` 读取会话资源,因此重连的读者只会重新读取它可读的会话的 projections。`session/list`、`session/search` 与 `session/control` 不读取资源,其调用访问 `global` 资源,需要 `global` role;对非 owner 调用方,`session/list` 只返回其 Session 被 `ctx.remoteAccess.allows()` 按同一 action 允许的行,`session/search` 只返回这类 Session 的命中,`session/control` 也只返回这类 Session 的 baseline projection 与 projection 帧,因此该 action 也要列在 `session` role 中;owner 的结果不过滤。`session/prompt` 在其 Remote 方法内构造持久的 `user-rpc` 消息 source,且只为非 owner 调用方记录经 `principalOf(this.ctx.invocation)` 读取的 `principal`;不带 `principal` 的 source 属于 owner。 +每个 Remote 端点都受访问控制:principal 不是 owner 的 Peer 只有在本次调用访问的每个资源上,该 principal kind 在 [`dsh-api-remote-access`](../remote-access/README.zh.md) 中的 policy 都有某个 binding 授予列出该 action 的 role 时,才能调用该端点([Peer 身份属性 Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md))。控制器注入 `remoteAccess`,并经 `typert.resources` 为 `session` 资源种类登记默认 resolver。它读取具名 `sessionId` 参数,否则读取第一个对象参数的 `sessionId` 或 `address`;无关字符串参数不指明 Session。对象同时包含 `sessionId` 和 `address` 时无效,即使两者指向同一 Session。`session/events`、已弃用的 `session/page`、`session/observeEvent` 与 `session/follow` 使用该 resolver:对普通 Session 地址读 `address.sessionId`,对 subagent 地址读 `address.childSessionId`;父会话的访问权是否覆盖其子会话由 policy 决定。`session/projections`、`session/observeProjections`、`session/state`、`session/observeState` 与 `session/wait` 从 `request.sessionId` 读取会话资源,因此每次调用与订阅都只点名它可读的会话。`session/list`、`session/search` 与 `session/control` 不读取资源,其调用访问 `global` 资源,需要 `global` role;对非 owner 调用方,`session/list` 只返回其 Session 被 `ctx.remoteAccess.allows()` 按同一 action 允许的行,`session/search` 只返回这类 Session 的命中,`session/control` 也只返回这类 Session 的 baseline projection 与 projection 帧,因此该 action 也要列在 `session` role 中;owner 的结果不过滤。`session/prompt` 在其 Remote 方法内构造持久的 `user-rpc` 消息 source,且只为非 owner 调用方记录经 `principalOf(this.ctx.invocation)` 读取的 `principal`;不带 `principal` 的 source 属于 owner。 + +`events` 从一个持久切点读取一页时间正序的记录,返回记录、`hasMore` 和包含末项的 `cursor`;省略 `throughSeq` 时选取观察到的日志末尾,兼容的 `page` 方法提供同样的读取,但入口已弃用。`events`、`observeEvent` 和 `follow` 接收 Address,投影和状态操作接收 Session ID。分页读取与 Follow 开场会校验传入的 Address。纯 `observeEvent` 和 `observeProjections` 订阅既不获取 Observation,也不确认实体存在:其 `ready` 帧不携带快照游标。 列表行在状态可用时携带 `formatStatus`,Client 无需请求其投影即可识别需要迁移的 Session。 @@ -55,14 +57,14 @@ Client 列表刷新保留未变化的行对象,并在顺序和值均相同时 Client 适配器提供 `SessionEventStream`,即绑定到一个普通 Session 或 direct subagent address 的 Gateway `RemoteJournalStream`。它在读取首个 page 前打开 follow,只发布连续的 `replace`、`prepend`、`append` 与 `settle-assistant` 变更,并通过 tail page 修复重连或 seq 缺口。向后分页有两个动词:`loadOlder()` 拉一页按轮次开头对齐的历史,而 `loadThrough(seq)`——轮次跳转加载器——按轮次开头对齐页面循环拉取直到窗口覆盖目标 seq,重复调用会下调共享目标,遇到无进展的页即停止,忙碌状态复用同一个 `loadingOlder` 快照位。Web 适配器显式选择接收无 cursor 的 Assistant frame:每个 opening 携带活跃 attempt 的 `startedAfterSeq`、`nextIndex` 与紧凑 stream,每个 stream member 都成为排在持久 cursor 之间的 Client-only `assistant/live-chunk` 条目。Host 会随该 baseline 捕获 follower 本地到达序号,并抑制该 cut 及之前的 buffered frame;replacement Agent 可以从 revision 一重新开始。活跃 opening 之后到达的持久 `assistant/message` 或 `assistant/attempt` 只有在其 seq 晚于 `startedAfterSeq` 且轮次与步骤匹配时才会保持暂存;匹配的 end type、seq 与 index 会发布持久条目。成功消息的瞬态 row 保留到所属 `step/end`,让待派发工具的身份持续可用;失败或中断的 settlement 立即移除对应 row,同一步骤中更早的 retry 仍然保留。已知 attempt 的 revision、密集 index 或 settlement 缺口会重新打开 follow;若 controller 错过 start,则忽略 unknown-attempt frame,并正常发布其持久 settlement。Abandoned end 会发布不含持久条目的 settlement delta,使瞬态 row 立即退出。持久缺口修复 page 不携带 Assistant baseline,因此 held notification 会重新打开 follow 一次,以取得配对的 page 与 baseline。每条历史 record 只覆盖自身的事件 seq。业务、persistence 或无法恢复的连续性错误会终止 stream,只有物理载体断开才触发自动恢复。`SessionControlStream` 是 Gateway `RemoteSnapshotStream`;每代都以完整的进程本地 baseline 开始,因此重连会替换 projection 状态,而不会把瞬态值当作 durable event。每次 Host generation 就绪时,同步的 Client 订阅会先清除保留的投影值及其水位,再刷新查询并重新打开 control stream,其中也包括 control baseline 中没有列出的 Session。首次 control stream 会等待 generation 就绪,确保其 opening 值不会先于旧状态清理到达。上一代尚未完成的 list 响应无法重新发布这些值。同一 generation 内,延迟到达的 control baseline 不能覆盖或清除较新的 sequenced 值,无论它们来自活 Session 的 list block、history page 还是 frame;冷 Session 从 projection cache 看出来的 cached list block 则不论水位都让位于建连 Session 的 baseline。持久 `inbox` 投影通过与其他投影相同的冷读取和重连路径传输两份待处理列表。Client Agent 上下文提供独立 [`fileUpload`](../../client/file-upload/README.zh.md) 服务使用的身份;Session 对象提供生命周期、prompt、queue 与历史操作,不提供文件传输。 -Session 对象还承载本地提交回显:`session.beginSubmission` 在调用方序列化与提示词之前,同步把一条回显写入 `SessionSnapshot.pendingSubmissions`,会话 UI 因此能在点击提交的当帧显示消息。回显按顺序存放图片预览与持久文件引用。Session 根据当前运行状态与请求的投递模式推导其 `transcript`、`queued` 或 `steering` 位置,并保留该位置直到展示接管。提示词的 `requestId` 是关联标识:Host 把它回显为 durable user source 的 `rpcId`,`inbox` 投影中的待处理消息也保留同一 source。排队回显在队列接受后延迟一个动画帧退休;Chat 回显遵循下述入档规则。尚未入档的回显在带标识的提示词失败或被放弃时立即退休。销毁时保留已观察到的入档结果,其余未结算提交按 failed 退休。每次退休恰好触发一次 `onRetire`;observed 退休还会携带有序的持久附件引用,让 composer 释放成功卡片并保留失败草稿。回显只存在于 Client 内存;刷新与重连只从持久事件重建会话。 +Session 对象还承载本地提交回显:`session.beginSubmission` 在调用方序列化与发送提示词之前登记一条回显,Host 接收该提示词后,Session 才把它公开在 `SessionSnapshot.pendingSubmissions` 中;`prompt` 的回执和带有该请求 id 的 `inbox` 行都能表明已接收,以先到者为准。因此会话 UI 从接收起显示消息,直到它的持久条目渲染出来,Chat 和 QueueDock 也从对应的 Inbox 行到达起就把它排除。新会话从空白进入 engaging 也发生在这次接收时。回显按顺序存放图片预览与持久文件引用。Session 根据当前运行状态与请求的投递模式推导其 `transcript`、`queued` 或 `steering` 位置,并保留该位置直到展示接管。提示词的 `requestId` 是关联标识:Host 把它回显为 durable user source 的 `rpcId`,`inbox` 投影中的待处理消息也保留同一 source。排队回显在队列接受后延迟一个动画帧退休;Chat 回显遵循下述入档规则。尚未入档的回显在带标识的提示词失败或被放弃时立即退休。销毁时保留已观察到的入档结果,其余未结算提交按 failed 退休。接收时触发一次 `onAccept`,与公开回显处于同一次更新,让发送方与回显同时结算输入框。每次退休恰好触发一次 `onRetire`;observed 退休还会携带有序的持久附件引用,让发送方释放或移交已发送的附件。回显只存在于 Client 内存;刷新与重连只从持久事件重建会话。 正常在线时,transcript 与 steering 回显在 Inbox 接受与领取期间留在 Chat,直到持久消息到达。本地 Chat 消息入档后,其身份保留到 Inbox 水位覆盖 next-turn 或 next-step 领取序号:Chat 已显示真实 Node,而 Chat 与 QueueDock 排除匹配的旧 Inbox 行。其他排队消息照常显示。新的 follow 基线会将已有接收回执的回显按 observed 撤去,使用已接受的附件引用完成结算;尚未确认接收的提交继续保留。待处理或已入档的消息随后由 Host 数据呈现。在领取与入档之间重连时,气泡可能短暂消失;撤去回显只确认接收,不代表执行或失败。 面向用户调用的 `skills/list` 元数据包含胜出提供方可选的指令文件 `path`。输入框可据此预览文件,无需加载每个 skill 的正文或激活冷态 Agent。 -Fork 复制 `atSeq` 所选的精确事件前缀,包含切点事件,允许在开放轮次内截取。子会话在合成的 fork 结果和结束事件之前记录继承标记。省略 `atSeq` 时选择最近已结束轮次及其独立尾部,在下一轮次或排队输入之前停止;不存在的事件会被拒绝。聊天操作选择已结束轮次。 +Fork 将 `atSeq` 选定的含边界事件前缀(包括开放轮次内的截点)复制到不带 `parentSession` 的独立 Session。客户端占位项同样省略 `parentSessionId`;列表缩进仅适用于 subagent 来源的行,历史普通 fork 即使保留父 ID 也不缩进。工作区绑定及可选标题递增使用本次操作选定的源会话。子会话在合成的 fork 结果和结束事件之前记录继承标记。省略 `atSeq` 时选择最近已结束轮次及其独立尾部,在下一轮次或排队输入之前停止;不存在的事件会被拒绝。聊天操作选择已结束轮次。 恢复会话时若已有写句柄占用,返回 `session/writer-held`,并携带会话 id;其他恢复失败仍返回 `gateway/internal`。 @@ -72,7 +74,7 @@ Client 的首次 `follow`、重连首屏与 `loadOlder()` 至少请求 50 条以 队列编辑仅允许用非空文本替换待处理内容。 -附件授权读取内置 Session 事件声明的内容字段与已完成的 assistant 流块,包括扁平的 V4 tool 角色消息。未知事件载荷与无关字段不能授权附件读取。 +`session.attachment` 接收 `{ sessionId, attachment: ImageAttachmentRef }`,并把完整引用交给 `AttachmentStore.readImage()`,不读取或遍历 Session 历史。Client 通过 `session.readAttachment(ref)` 传入消息中的引用。连接身份认证和 Gateway 权限检查仍然适用;`sessionId` 为该接口的权限检查指定 Session 资源。授权通过后,处理函数不检查该 Session 是否存在,也不会仅因其不存在而返回 `session/not-found`。获准调用的身份可以读取同一存储中的任意图片,包括仅被其他 Session 引用或未被任何 Session 引用的图片。响应在把 ID、媒体类型、字节数、宽度和高度与存储字节校验后,保留传入的引用。可选的 `name` 和 `originalDimensions` 作为调用方提交的显示信息原样返回,不根据文件校验。对象缺失或无效时返回明确的附件失败。Client 的历史图片缓存按 Session 和附件 ID 保留一份结果与浏览器 URL。 本控制器通过 `ctx.plugin` 组合 `ArchivedSessionGate`:在 Agent 注册表、Session store 与 Workspace 注册表就绪后加载,随控制器一起释放。它的 `agent/pre-step` 监听器会拒绝为已归档会话或其子代理子孙——从 Session header 的血缘字段读出,从不包括 fork——提出的步骤,因此迟到的唤醒投递会让该回合以 `blocked` 收口而不发出模型请求;取消归档即为整条血缘解除门禁。已归档会话仍在跑的工作由各自的 owner 通过 Workspace 注册表的归档准入([接缝](../../workspace/workspace/README.zh.md))报告与停止:运行中的回合由 [Agent 注册表](../../core/agent/README.zh.md)负责,所属任务由[任务注册表接缝](../../jobs/jobs/README.zh.md)负责,子代理子孙由 [Subagent](../../subagent/subagent/README.zh.md) runtime 负责,提醒由 [Schedule](../../schedule/schedule/README.zh.md) 插件负责;本控制器自己不报告任何内容。 @@ -86,7 +88,7 @@ Client 的首次 `follow`、重连首屏与 `loadOlder()` 至少请求 50 条以 ## 会话媒体引用 -当 `connection`、`fs` 与 `attachments` 均被组合时,`SessionMediaReferences` 在鉴权 `connection.fetch` 通道上挂载 `GET|HEAD /api/file?path=<绝对路径>`。它通过 `ctx.fs` 读取普通文件,包括已注册工作区之外的临时路径与远程提供方中的文件。目录包含关系与 MIME 类别均不限制访问;`mime-types` 提供响应类型,未知扩展名使用 `application/octet-stream`。GET 复用 `readBytes` 执行读取前及读取中的字节限制;HEAD 只读取元数据。所有文件均使用 `ctx.attachments.imageLimits.maxImageBytes`(通常为 50 MiB);超过此上限返回 413。响应包含完整文件,忽略 Range,并携带 `private, no-store`、`nosniff` 与沙箱 CSP,使直接打开的 HTML/SVG 无法以 API 源身份执行脚本。客户端重写位于 `ui-chat`(`AssistantMarkdown`);音视频文件响应已可用,Markdown 音视频播放器节点仍是独立工作。 +当 `connection`、`fs` 与 `attachments` 均被组合时,`SessionMediaReferences` 在鉴权 `connection.fetch` 通道上挂载 `GET|HEAD /api/file?path=<绝对路径>`。它通过 `ctx.fs` 读取普通文件,包括已注册工作区之外的临时路径与远程提供方中的文件。目录包含关系与 MIME 类别均不限制访问;`mime-types` 提供响应类型,未知扩展名使用 `application/octet-stream`。GET 复用 `readBytes` 执行读取前及读取中的字节限制;HEAD 只读取元数据。所有文件均使用 `ctx.attachments.imageLimits.maxImageBytes`(通常为 50 MiB);超过此上限返回 413。`v` 参数与文件当前 `ctx.fs` 版本不同(包括没有该参数)的请求,会收到 `private, no-store` 的 302,跳转到只含 `path` 与当前 `v` 的同一路由;版本化响应为 `private, max-age=31536000, immutable`,因此浏览器在文件变化前复用缓存内容,私有文件内容可能进入浏览器磁盘缓存。响应包含完整文件,忽略 Range,并携带 `nosniff` 与沙箱 CSP,使直接打开的 HTML/SVG 无法以 API 源身份执行脚本。客户端重写位于 `ui-chat`(`AssistantMarkdown`);音视频文件响应已可用,Markdown 音视频播放器节点仍是独立工作。 GUI 模型选择要求确切提供方/模型对出现在可用目录中;不可用的选择以 `session/model-unavailable` 拒绝。提示词准入保留已保存的路由,不按目录可用性阻断发送,由请求执行报告凭据缺失或模型不可用。`initializeDefaultModel()` 在账号登录后、其他提供方均未配置 API key 时,将第一个可用账号模型保存为默认模型;凭据检查使用已配置的引用,不依赖模型是否可用。提供方没有可用模型时,初始化以 `session/provider-models-unavailable` 拒绝。可用性变化不会替换模型或改写会话选择。 diff --git a/packages/api/session-controller/locale/de.json b/packages/api/session-controller/locale/de.json new file mode 100644 index 0000000000..217f0baf00 --- /dev/null +++ b/packages/api/session-controller/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Sitzungssteuerungsschnittstelle", + "description": "Bietet Clients Funktionen zum Lesen von Sitzungen, zur Laufsteuerung und zur Statusaktualisierung." + } +} diff --git a/packages/api/session-controller/locale/es.json b/packages/api/session-controller/locale/es.json new file mode 100644 index 0000000000..764c28e00b --- /dev/null +++ b/packages/api/session-controller/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "interfaz de control de sesión", + "description": "Proporciona capacidades de lectura de sesiones, control de ejecución y actualización de estado a los clientes." + } +} diff --git a/packages/api/session-controller/locale/fr.json b/packages/api/session-controller/locale/fr.json new file mode 100644 index 0000000000..689e058b56 --- /dev/null +++ b/packages/api/session-controller/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "interface de contrôle de session", + "description": "Fournit des fonctionnalités de lecture de session, de contrôle d’exécution et de mise à jour de statut aux clients." + } +} diff --git a/packages/api/session-controller/locale/pt.json b/packages/api/session-controller/locale/pt.json new file mode 100644 index 0000000000..537a8f934d --- /dev/null +++ b/packages/api/session-controller/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "interface de controle de sessão", + "description": "Fornece leitura de sessão, controle de execução e recursos de atualização de status aos clientes." + } +} diff --git a/packages/api/session-controller/locale/ru.json b/packages/api/session-controller/locale/ru.json new file mode 100644 index 0000000000..885910a705 --- /dev/null +++ b/packages/api/session-controller/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "интерфейс управления сеансом", + "description": "Предоставляет клиентам возможности чтения сеанса, управления запуском и обновления статуса." + } +} diff --git a/packages/api/session-controller/package.json b/packages/api/session-controller/package.json index faf27a4fa3..3eadb51df1 100644 --- a/packages/api/session-controller/package.json +++ b/packages/api/session-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-session-controller", "description": "Session Remote commands, cold reads, and live control transport", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, @@ -73,6 +73,7 @@ "dependencies": { "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-deque": "workspace:*", + "@deepseek-ai/dsh-timeout": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", "mime-types": "^3.0.2", "zod": "4.4.3" @@ -131,6 +132,7 @@ "@deepseek-ai/dsh-agent-preset-registry": "workspace:*", "@deepseek-ai/dsh-api-gateway": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", + "@deepseek-ai/dsh-attachment-local": "workspace:*", "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-client-file-upload": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", diff --git a/packages/api/session-controller/src/agent.ts b/packages/api/session-controller/src/agent.ts index 4467fefc0f..d16e041773 100644 --- a/packages/api/session-controller/src/agent.ts +++ b/packages/api/session-controller/src/agent.ts @@ -9,7 +9,6 @@ import { installModelSelection } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-agent-preset-registry' import { brandString } from '@deepseek-ai/dsh-brand' import type { Session, SessionId } from '@deepseek-ai/dsh-session' -import type { SessionInspection } from '@deepseek-ai/dsh-session-persistence' import { SessionQueryError, type SessionObservation } from '@deepseek-ai/dsh-session-query' import { RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' import type {} from '@deepseek-ai/dsh-typert-registry' @@ -123,40 +122,6 @@ export function apiSessionSubagentOwnershipError(sessionId: SessionId): ApiSessi ) } -/** - * Inspect one cold Session without repairing, resuming, or publishing it. - * @param ctx - Host context carrying Session persistence. - * @param sessionId - durable Session identity. - * @param signal - optional cancellation for persistence reads. - * @returns the persisted header and complete event prefix. - */ -export async function inspectApiSession( - ctx: Context, - sessionId: SessionId, - signal?: AbortSignal, -): Promise { - try { - using observation = await ctx.sessionQuery.observeSession(sessionId, { - ...(signal === undefined ? {} : { signal }), - projectionMode: 'none', - }) - if (observation.header.cwd === undefined) { - throw new ApiSessionNotFound(`session "${sessionId}" not found`) - } - return { - meta: observation.header, - inheritedEventCount: observation.inheritedEventCount, - events: [...observation.events], - } - } catch (error: unknown) { - if (error instanceof SessionQueryError - && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') { - throw new ApiSessionNotFound(`session "${sessionId}" not found`) - } - throw error - } -} - /** Owns every operation that may create, resume, or configure a Web Agent. */ export class ApiSessionAgentController { private readonly resumes = new Map>() diff --git a/packages/api/session-controller/src/client/contract/session.ts b/packages/api/session-controller/src/client/contract/session.ts index 2c8f16c4ae..9233ac84cb 100644 --- a/packages/api/session-controller/src/client/contract/session.ts +++ b/packages/api/session-controller/src/client/contract/session.ts @@ -7,7 +7,7 @@ * must stub); implementation-internal entry points (history staging, wire-frame * dispatch) stay on the class, invisible out here. */ -import type { AttachmentIdType, FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' +import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { MessageId } from '@deepseek-ai/dsh-llm/brand' import type { SessionId, SessionSeq } from '@deepseek-ai/dsh-session/types' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' @@ -36,6 +36,11 @@ export interface BeginSubmissionInput { readonly text: string /** Ordered image previews and durable file metadata matching the upcoming prompt attachments. */ readonly attachments: readonly PendingSubmissionAttachment[] + /** + * Called once when the Host accepted the prompt, in the same update that + * publishes the echo, whether the receipt or an Inbox row showed it first. + */ + readonly onAccept?: () => void /** Settlement callback fired exactly once when the echo retires. */ readonly onRetire?: (retirement: PendingSubmissionRetirement) => void } @@ -66,18 +71,24 @@ export interface ISession { /** Host-computed projection values by key (the useProjection seat). */ readonly projections: ProjectionsFace /** - * Register one local submission echo in `snapshot.pendingSubmissions`, - * synchronously, before the caller serializes and sends the prompt. The - * Chat echoes persist until durable admission; transcript identities also - * wait for the Inbox claim watermark so stale queue rows stay suppressed. - * Queued echoes retire on queue acceptance. Identified failures retire - * submissions that have not already reached durable admission. + * Register one local submission echo before the caller serializes and sends + * the prompt. The echo reconciles against Host events from then on, and + * enters `snapshot.pendingSubmissions` once the Host accepted the prompt: + * when {@link prompt} reports the receipt or an Inbox row carrying the + * request id arrives, whichever comes first. The Chat echoes persist until + * durable admission; transcript identities also wait for the Inbox claim + * watermark so stale queue rows stay suppressed. Queued echoes retire on + * queue acceptance. Identified failures retire submissions that have not + * already reached durable admission. * @param input - echo content and the optional settlement callback. * @returns the minted identity for {@link prompt} plus the pre-prompt abandon path. */ beginSubmission(input: BeginSubmissionInput): SubmissionHandle /** - * Send a prompt into the session. + * Send a prompt into the session. The Host can hold the prompt at its + * admission stage, so the call can stay open; acceptance publishes the + * prompt's echo and moves a blank Session to engaging, before the call + * returns when an Inbox row carrying the request id arrives first. * @param content - text plus browser-owned temporary image uploads. * @param mode - 'queue' appends a turn; 'steer' interrupts the running one. * @param signal - optional caller cancellation for the complete admission round-trip. @@ -91,12 +102,12 @@ export interface ISession { requestId?: SessionRequestId, ): Promise> /** - * Resolve one durable image referenced by this session. - * @param attachmentId - opaque id found in the folded session log. - * @returns the authenticated reference and decoded bytes. + * Resolve one stored image using this Session's gateway permission scope. + * @param attachment - complete image reference from the folded session log. + * @returns the supplied reference after storage verification, and decoded bytes. */ readAttachment( - attachmentId: AttachmentIdType, + attachment: ImageAttachmentRef, ): Promise> /** * Apply one edit, remove, or Steer action to a still-pending queue occurrence. diff --git a/packages/api/session-controller/src/client/contract/snapshot.ts b/packages/api/session-controller/src/client/contract/snapshot.ts index 161cd858b4..78e0c8c8a3 100644 --- a/packages/api/session-controller/src/client/contract/snapshot.ts +++ b/packages/api/session-controller/src/client/contract/snapshot.ts @@ -38,10 +38,10 @@ export type PendingSubmissionAttachment = export type PendingSubmissionPlacement = 'transcript' | 'queued' | 'steering' /** - * One local prompt-submission echo: inserted synchronously when a submission - * begins, so the conversation can show the message before serialization, - * transport, and durable admission complete. Client-memory only — reload and - * reconnect rebuild the conversation from durable events alone. + * One local prompt-submission echo: registered when a submission begins and + * published once the Host accepts the prompt, so the conversation shows the + * message before its durable admission completes. Client-memory only — reload + * and reconnect rebuild the conversation from durable events alone. */ export interface PendingSubmission { /** The prompt RPC identity; the durable `user/message` source echoes it as `rpcId`. */ @@ -68,7 +68,7 @@ export interface PromptError { /** Immutable Session lifecycle and control snapshot. */ export interface SessionSnapshot { readonly sessionId: SessionId - /** Local prompt-submission echoes not yet observed as durable events or queue occurrences. */ + /** Local prompt-submission echoes the Host accepted and that are not yet observed as durable events or queue occurrences. */ readonly pendingSubmissions: readonly PendingSubmission[] readonly running: boolean readonly subagent: { diff --git a/packages/api/session-controller/src/client/sessions/lineage.ts b/packages/api/session-controller/src/client/sessions/lineage.ts index 298ff2183b..b6d8bbdfc5 100644 --- a/packages/api/session-controller/src/client/sessions/lineage.ts +++ b/packages/api/session-controller/src/client/sessions/lineage.ts @@ -60,7 +60,8 @@ export function flattenLineage( const children = new Map() const roots: TitledSessionSummary[] = [] for (const s of summaries) { - if (s.parentSessionId !== undefined && byId.has(s.parentSessionId)) { + // Historical ordinary forks may retain a parent id without being subagents. + if (s.origin === 'subagent' && s.parentSessionId !== undefined && byId.has(s.parentSessionId)) { const list = children.get(s.parentSessionId) ?? [] list.push(s) children.set(s.parentSessionId, list) diff --git a/packages/api/session-controller/src/client/sessions/manager.ts b/packages/api/session-controller/src/client/sessions/manager.ts index f800a8c2be..105930d1ef 100644 --- a/packages/api/session-controller/src/client/sessions/manager.ts +++ b/packages/api/session-controller/src/client/sessions/manager.ts @@ -553,7 +553,7 @@ export class SessionManager { * immediately (same synchronous-addressability guarantee as create). * Blankness starts provisionally true so the authoritative Host summary can * preserve it or lower it after an exact cut before the first `turn/start`; - * lineage rides parentSessionId. A child published before Workspace + * the fork has no durable source relationship. A child published before Workspace * attachment fails is also reconciled into the list. * @param opts - source session, optional exact inclusive boundary seq, and permission to start migration. * @returns the fork result (the child session id). @@ -573,7 +573,6 @@ export class SessionManager { if (childId !== undefined) { this.recordMutation({ kind: 'placeholder', summary: { agentAvailable: true, sessionId: childId, updatedAt: Date.now(), running: false, blank: true, - parentSessionId: opts.sessionId, ...(source?.cwd !== undefined ? { cwd: source.cwd } : {}), } }) } diff --git a/packages/api/session-controller/src/client/sessions/session.ts b/packages/api/session-controller/src/client/sessions/session.ts index 09494e01ab..9cb61e55bf 100644 --- a/packages/api/session-controller/src/client/sessions/session.ts +++ b/packages/api/session-controller/src/client/sessions/session.ts @@ -3,7 +3,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { InboxState, InboxTarget } from '@deepseek-ai/dsh-agent/types' import { randomUUID } from '@deepseek-ai/dsh-util-crypto' -import type { AttachmentIdType, FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' +import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { MessageId } from '@deepseek-ai/dsh-llm/brand' import type { UserMessage } from '@deepseek-ai/dsh-llm/types' @@ -116,8 +116,8 @@ export class Session implements SessionFace { private parentAvailable: boolean | undefined /** * Sticky send marker, private input of the composerPhase derivation: set - * synchronously before prompt()'s first await, never reset — the blank → - * engaging edge of the phase machine (see ComposerPhase). + * when the Host accepts a prompt, never reset — the blank → engaging edge of + * the phase machine (see ComposerPhase). */ private promptAttempted = false /** A first accepted prompt stays in the engaging phase until its turn is observable. */ @@ -127,8 +127,10 @@ export class Session implements SessionFace { private removed = false private promptError: PromptError | null = null private lastAgentError: string | null = null - /** Local submission echoes, insertion-ordered (see SessionSnapshot.pendingSubmissions). */ + /** Local submission echoes, insertion-ordered, including those the Host has not accepted yet. */ private pendingSubmissions: readonly PendingSubmission[] = [] + /** The accepted echoes, published as SessionSnapshot.pendingSubmissions; rebuilt when one is accepted or removed. */ + private acceptedSubmissions: readonly PendingSubmission[] = [] /** Per-echo settlement state; `retiring` latches the first observation so a * Inbox projection and its durable event cannot both retire one echo. */ private readonly submissionSettlements = new Map void) | undefined readonly onRetire?: ((retirement: PendingSubmissionRetirement) => void) | undefined retiring: boolean }>() @@ -219,9 +224,10 @@ export class Session implements SessionFace { // ---- Operations ---- /** - * Register one local submission echo (see the ISession declaration). - * Synchronous through markDirty: the echo is in the very next snapshot, so - * the conversation can paint it before the caller starts serializing. + * Register one local submission echo (see the ISession declaration). The + * echo reconciles against Host events from now on, but it enters the + * snapshot only once the prompt receipt or an Inbox row carrying its + * request id shows that the Host accepted it. * @param input - echo content and the optional settlement callback. * @returns the minted identity for {@link prompt} plus the pre-prompt abandon path. */ @@ -235,16 +241,17 @@ export class Session implements SessionFace { text: input.text, attachments: input.attachments, }] - this.submissionSettlements.set(requestId, { placement, onRetire: input.onRetire, retiring: false }) - // The blank → engaging edge flips here, ahead of prompt(): the composer - // docks and the echo renders on the click's own frame. - this.promptAttempted = true - this.notifier.markDirty() + this.submissionSettlements.set(requestId, { + placement, accepted: false, onAccept: input.onAccept, onRetire: input.onRetire, retiring: false, + }) return { requestId, abandon: () => { this.retireFailedSubmission(requestId) } } } /** - * Send (queue/steer passed through 1:1); failures land in the snapshot's promptError. + * Send (queue/steer passed through 1:1); failures land in the snapshot's + * promptError. The Host can hold the prompt at its admission stage, so the + * call can stay open; the echo appears and the blank → engaging edge flips + * only once the Host accepts the prompt. * @param content - text, browser-owned temporary image uploads, and staged-file receipts. * @param mode - queue appends after the current turn; steer interrupts it. * @param signal - optional caller cancellation for the complete admission round-trip. @@ -259,12 +266,9 @@ export class Session implements SessionFace { ): Promise> { this.promptError = null this.lastAgentError = null - // Synchronous, before the first await: the blank → engaging edge must be - // visible on the session area's very first frame when a caller sends - // ahead of navigation (first-send flow). - this.promptAttempted = true - if (this.blankBit) this.firstPromptPendingTurn = true - this.notifier.markDirty() + // Before the first await, so a turn observed ahead of the receipt clears it. + const firstPrompt = this.blankBit && !this.firstPromptPendingTurn + if (firstPrompt) this.firstPromptPendingTurn = true let result: RemoteResult<{ accepted: true }> if (this.address === undefined) { const clientTimeZone = resolvedClientTimeZone() @@ -300,31 +304,50 @@ export class Session implements SessionFace { result = routed.ok ? { ok: true, value: { accepted: true } } : routed } if (!result.ok) { + // Rejection must leave a first prompt blank and eligible for workspace reuse. + if (firstPrompt) this.firstPromptPendingTurn = false if (requestId !== undefined) this.retireFailedSubmission(requestId) this.promptError = { op: 'send', error: result.error } this.notifier.markDirty() return result } - // Rejection must leave a first prompt blank and eligible for workspace reuse. - if (this.blankBit) { - this.blankBit = false - this.notifier.markDirty() - } - this.options.onEngaged?.(this) + this.acceptPrompt(requestId) return result } /** - * Resolve one image referenced by this session into browser-consumable bytes. - * @param attachmentId - opaque id found in the folded session log. - * @returns the authenticated reference and decoded bytes. + * Apply the Host's acceptance of one prompt: publish its echo, move a blank + * Session to engaging, and tell the submitter. The prompt receipt and an + * Inbox row carrying the prompt's request id both prove acceptance. + * Whichever arrives first publishes the echo; a later proof for an echo + * still pending changes nothing. + * @param requestId - identity from {@link beginSubmission}; absent for a prompt sent without an echo. + */ + private acceptPrompt(requestId: SessionRequestId | undefined): void { + const settlement = requestId === undefined ? undefined : this.submissionSettlements.get(requestId) + if (settlement?.accepted === true) return + if (settlement !== undefined) { + settlement.accepted = true + this.refreshAcceptedSubmissions() + } + this.promptAttempted = true + this.blankBit = false + this.notifier.markDirty() + this.options.onEngaged?.(this) + settlement?.onAccept?.() + } + + /** + * Resolve one stored image into browser-consumable bytes using this Session's gateway permission scope. + * @param attachment - complete image reference from the folded session log. + * @returns the supplied reference after storage verification, and decoded bytes. */ async readAttachment( - attachmentId: AttachmentIdType, + attachment: ImageAttachmentRef, ): Promise> { const result = await this.remote.session.attachment({ sessionId: this.sessionId, - attachmentId, + attachment, }) if (!result.ok) return result const binary = atob(result.value.data) @@ -798,6 +821,8 @@ export class Session implements SessionFace { if (settlement === undefined || settlement.placement === 'queued' || settlement.retiring || (settlement.receipt?.seq ?? -1) > seq) continue settlement.receipt = { target, seq, index: start + index, attachments: attachmentRefsIn(message.content) } + // An Inbox row can reach the Client before the prompt receipt. + this.acceptPrompt(source.rpcId) } } @@ -861,6 +886,11 @@ export class Session implements SessionFace { this.finishSubmission(requestId, { reason: 'failed' }) } + private refreshAcceptedSubmissions(): void { + this.acceptedSubmissions = this.pendingSubmissions + .filter(echo => this.submissionSettlements.get(echo.requestId)?.accepted === true) + } + /** Single removal point: drop the echo, publish, then notify the owner. */ private finishSubmission(requestId: SessionRequestId, retirement: PendingSubmissionRetirement): void { const settlement = this.submissionSettlements.get(requestId) @@ -868,6 +898,7 @@ export class Session implements SessionFace { if (settlement === undefined) return this.submissionSettlements.delete(requestId) this.pendingSubmissions = this.pendingSubmissions.filter(echo => echo.requestId !== requestId) + if (settlement.accepted) this.refreshAcceptedSubmissions() this.notifier.markDirty() settlement.onRetire?.(retirement) } @@ -889,7 +920,7 @@ export class Session implements SessionFace { const identity = this.projections.values().subagent return { sessionId: this.sessionId, - pendingSubmissions: this.pendingSubmissions, + pendingSubmissions: this.acceptedSubmissions, running: this.running, subagent: this.address === undefined ? null @@ -908,7 +939,8 @@ export class Session implements SessionFace { blank: this.blankBit, lastAgentError: this.lastAgentError, promptAttempted: this.promptAttempted, - awaitingFirstTurn: this.firstPromptPendingTurn, + // The flag is set before the receipt; the Session leaves blank only once the Host accepted the prompt. + awaitingFirstTurn: this.firstPromptPendingTurn && !this.blankBit, } } diff --git a/packages/api/session-controller/src/client/transport.ts b/packages/api/session-controller/src/client/transport.ts index fc2a11a0bb..554eec515e 100644 --- a/packages/api/session-controller/src/client/transport.ts +++ b/packages/api/session-controller/src/client/transport.ts @@ -178,6 +178,7 @@ export class SessionEventStream extends RemoteJournalStream< let assistantRevision: number | undefined for await (const frame of this.remote.session.follow({ address: this.address, + activate: true, assistantStream: true, ...this.repairRequest(request), }, signal)) { diff --git a/packages/api/session-controller/src/commands.ts b/packages/api/session-controller/src/commands.ts index c91f6e5b02..5309872331 100644 --- a/packages/api/session-controller/src/commands.ts +++ b/packages/api/session-controller/src/commands.ts @@ -7,12 +7,12 @@ import { brandString } from '@deepseek-ai/dsh-brand' import type { Agent, ModelSelection as AgentModelSelection } from '@deepseek-ai/dsh-agent' import { AttachmentError } from '@deepseek-ai/dsh-attachment' import type { - AttachmentAdmissionPart, ImageAttachmentRef, + AttachmentAdmissionPart, } from '@deepseek-ai/dsh-attachment' import type { FileUploadReceiptId, StagedAttachment } from '@deepseek-ai/dsh-client-file-upload/types' import type {} from '@deepseek-ai/dsh-client-file-upload' import { - ReasoningEffortId, assistantStreamChunks, createUserMessage, freezeMessage, + ReasoningEffortId, createUserMessage, freezeMessage, } from '@deepseek-ai/dsh-llm' import type { MessageSource } from '@deepseek-ai/dsh-llm' import { buildForkSeed } from '@deepseek-ai/dsh-session/fork' @@ -26,12 +26,10 @@ import type { Workspace } from '@deepseek-ai/dsh-workspace' import { ApiSessionAgentController, ApiSessionCwdConflict, - ApiSessionNotFound, ApiSessionPresetConflict, ApiSessionSubagentOwnership, apiSessionSubagentOwnershipError, hasApiSessionSubagentOwner, - inspectApiSession, type ApiSessionCreated, } from './agent.ts' import type { @@ -54,12 +52,6 @@ import type { SessionRequestId, } from './types.ts' -interface SessionReadState { - readonly id: SessionId - readonly header: SessionHeader - readonly events: readonly SessionEvent[] -} - type PromptContentCandidate = | SessionPromptRequest['content'][number] | Extract['content'][number] @@ -273,7 +265,6 @@ export class SessionCommandController { inheritedEventCount: SessionLogOffset(boundary + 1), meta: { ...(source.header.cwd === undefined ? {} : { cwd: source.header.cwd }), - parentSession: source.header.id, isSeeded: true, ...(composition.agentPreset === undefined ? {} @@ -367,34 +358,13 @@ export class SessionCommandController { } /** - * Read one durable image after proving the Session log references it. - * @param request - Session and attachment identities used for authorization. + * Read one durable image using the supplied reference without consulting Session history. + * @param request - image reference and gateway permission scope; Session existence is not checked. * @returns the durable attachment reference and base64-encoded bytes. */ async attachment(request: SessionAttachmentRequest): Promise { - let source: SessionReadState try { - source = await this.readSessionState(request.sessionId) - } catch (error) { - if (error instanceof ApiSessionNotFound) { - throw new RemoteError('session/not-found', error.message, { sessionId: request.sessionId }) - } - throw new RemoteError( - 'gateway/internal', - `attachment authorization unavailable for session "${request.sessionId}": ${String(error)}`, - {}, - ) - } - const ref = referencedImage(source.events, String(request.attachmentId)) - if (ref === undefined) { - throw new RemoteError( - 'session/attachment-invalid', - 'Image is not referenced by this session.', - { reason: 'ATTACHMENT_NOT_REFERENCED' }, - ) - } - try { - const stored = await this.ctx.attachments.readImage(ref) + const stored = await this.ctx.attachments.readImage(request.attachment) return { attachment: stored.ref, data: Buffer.from(stored.data).toString('base64'), @@ -534,16 +504,6 @@ export class SessionCommandController { throw new RemoteError('gateway/internal', `failed to create session: ${String(error)}`, {}) } - private async readSessionState(sessionId: SessionId): Promise { - const attached = this.ctx.sessions.get(sessionId) - if (attached !== undefined) { - // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred. - return { id: attached.id, header: attached.header, events: attached.snapshotEvents() } - } - const inspected = await inspectApiSession(this.ctx, sessionId) - return { id: inspected.meta.id, header: inspected.meta, events: inspected.events } - } - private async forkWorkspace(source: SessionHeader): Promise { const workspaces = this.ctx.workspaceRegistry.list() const direct = workspaces.find(workspace => workspace.sessionIds.includes(source.id)) @@ -592,80 +552,3 @@ function hasPromptRequest(agent: Agent, requestId: SessionRequestId): boolean { return source.kind === 'user' && 'rpcId' in source && source.rpcId === requestId }) } -function imageBlockIn( - content: unknown, - match: (ref: ImageAttachmentRef) => boolean, -): ImageAttachmentRef | undefined { - if (!Array.isArray(content)) return undefined - for (const value of content) { - if (typeof value !== 'object' || value === null || Array.isArray(value)) continue - const block = value as { readonly type?: unknown; readonly attachment?: unknown } - if (block.type === 'image' && typeof block.attachment === 'object' && block.attachment !== null) { - const ref = block.attachment as ImageAttachmentRef - if (match(ref)) return ref - } - } - return undefined -} - -/** Read only first-party declared content fields; unknown event payloads stay opaque. */ -function imageInEvent( - event: SessionEvent, - match: (ref: ImageAttachmentRef) => boolean, -): ImageAttachmentRef | undefined { - const data = event.data as { - readonly content?: unknown - readonly message?: { readonly content?: unknown } - readonly inserted?: unknown - readonly summary?: unknown - readonly rawOutput?: unknown - } - // First-party event payloads can be present without their producer plugin mounted. - const type: string = event.type - switch (type) { - case 'user/message': - case 'tool/ptc-dispatch': - return imageBlockIn(data.content, match) - case 'system/message': - case 'developer/message': - case 'tool/result': - case 'team/message/queued': - return imageBlockIn(data.message?.content, match) - case 'agent/inbox/spliced': { - const messages = data.inserted - if (!Array.isArray(messages)) return undefined - for (const message of messages as readonly unknown[]) { - if (typeof message !== 'object' || message === null || Array.isArray(message)) continue - const found = imageBlockIn((message as { readonly content?: unknown }).content, match) - if (found !== undefined) return found - } - return undefined - } - case 'compaction/summary': - return imageBlockIn(data.summary, match) ?? imageBlockIn(data.rawOutput, match) - case 'assistant/message': { - const found = imageBlockIn(data.message?.content, match) - if (found !== undefined) return found - break - } - case 'assistant/attempt': break - default: return undefined - } - const assistant = event as SessionEvent<'assistant/message' | 'assistant/attempt'> - for (const chunk of assistantStreamChunks(assistant.data.stream, 'block-end')) { - const found = imageBlockIn([chunk.block], match) - if (found !== undefined) return found - } - return undefined -} - -function referencedImage( - events: readonly SessionEvent[], - attachmentId: string, -): ImageAttachmentRef | undefined { - for (const event of events) { - const found = imageInEvent(event, ref => String(ref.attachmentId) === attachmentId) - if (found !== undefined) return found - } - return undefined -} diff --git a/packages/api/session-controller/src/history.ts b/packages/api/session-controller/src/history.ts index 07fbbfe6be..91cc3508da 100644 --- a/packages/api/session-controller/src/history.ts +++ b/packages/api/session-controller/src/history.ts @@ -1,12 +1,8 @@ -/** Cold Session history pagination and live-event source. */ +/** Shared Session history pagination, address validation and wire conversion. */ -import type { Context } from '@deepseek-ai/cordis' -import { Deque } from '@deepseek-ai/dsh-deque' -import type { AssistantStreamFrame } from '@deepseek-ai/dsh-agent' import { isAppendSurfaceEvent, SessionLogOffset, - SessionSeq, } from '@deepseek-ai/dsh-session' import type { SessionEvent, @@ -15,309 +11,26 @@ import type { SessionLogOffset as SessionLogOffsetType, SessionSeqCursor, } from '@deepseek-ai/dsh-session' -import { SessionQueryError, type SessionObservation } from '@deepseek-ai/dsh-session-query' +import type { SessionObservation } from '@deepseek-ai/dsh-session-query' import type {} from '@deepseek-ai/dsh-subagent' import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' -import type { JsonValue } from '@deepseek-ai/dsh-util-values' import type { SessionAddress, - SessionAssistantStreamFrame, SessionEventEntry, - SessionFollowRequest, - SessionFollowFrame, SessionHistoryRecord, - SessionPage, SessionPageRequest, - SessionProjectionBaseline, - SessionProjectionValues, - SessionWireHeader, SessionWireEvent, } from './types.ts' -import { SessionAssistantStreamAccumulator } from './assistant-stream.ts' -const DEFAULT_MAX_MESSAGES = 50 +/** Message budget applied when a history request omits `maxMessages`. */ +export const DEFAULT_MAX_MESSAGES = 50 const MESSAGE_TYPES = new Set(['user/message', 'assistant/message']) -/** Implements cold-safe history operations delegated by the Session Controller. */ -export class SessionHistoryController { - private readonly closeFollowers = new Set<() => void>() - private readonly assistantStreams = new Map() - - /** - * @param ctx - Host context carrying Session query and projection services. - * @param promote - starts ordinary Session activation after snapshot delivery. - */ - constructor( - private readonly ctx: Context, - private readonly promote: (observation: SessionObservation) => void, - ) { - ctx.on('agent/assistant-stream', ({ agent, frame }) => { - let stream = this.assistantStreams.get(agent.session.id) - if (stream === undefined) { - stream = new SessionAssistantStreamAccumulator() - this.assistantStreams.set(agent.session.id, stream) - } - stream.accept(frame, cursorBeforeNext(agent.session.seq)) - }, { global: true }) - ctx.on('agent/disposed', ({ agent }) => { - this.assistantStreams.delete(agent.session.id) - }, { global: true }) - ctx.effect(() => () => { - for (const close of this.closeFollowers) close() - this.closeFollowers.clear() - }, 'session-controller.history') - } - - /** - * Read one message-aligned history page without activating an Agent. - * @param request - durable address and backwards-page cursor. - * @param signal - caller cancellation for persistence reads. - * @returns a contiguous event page. - */ - async page(request: SessionPageRequest, signal: AbortSignal): Promise { - validatePageRequest(request) - const throughSeq: SessionSeqCursor = request.throughSeq === -1 - ? -1 - : SessionSeq(request.throughSeq) - const beforeSeq = request.beforeSeq === undefined - ? undefined - : SessionLogOffset(request.beforeSeq) - using source = await this.sourceFor(request.address, signal, false) - signal.throwIfAborted() - const sourceLog = source.events - const sourceCursor: SessionSeqCursor = sourceLog.at(-1)?.seq ?? -1 - if (throughSeq > sourceCursor) { - throw new RemoteError( - 'gateway/bad-request', - `session page through seq ${String(throughSeq)} is past cursor ${String(sourceCursor)}`, - {}, - ) - } - /* v8 ignore next -- Session and persistence validation guarantee a dense zero-based event prefix. */ - if (throughSeq >= 0 && sourceLog[throughSeq]?.seq !== throughSeq) { - throw new RemoteError('gateway/internal', `session log does not contain through seq ${String(throughSeq)}`, {}) - } - const page = paginate( - sourceLog, - beforeSeq, - request.maxMessages ?? DEFAULT_MAX_MESSAGES, - throughSeq, - request.turnWindow, - ) - const records = pageRecords(page.events) - return { - records, - hasMore: page.hasMore, - } - } - - /** - * Follow events appended after an initial cursor on one durable address. - * @param request - durable address and last committed sequence already held by the caller. - * @param signal - stream cancellation owned by the Remote carrier. - * @returns a complete opening snapshot followed by gap-free durable events and opted-in assistant frames. - */ - async *follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable { - validateHistoryWindow(request) - const { address } = request - const target = addressId(address) - const buffered = new Deque< - | { readonly type: 'event'; readonly event: SessionEvent } - | { - readonly type: 'assistant-stream' - readonly frame: SessionAssistantStreamFrame - readonly ordinal: number - } - >() - let snapshotCursor: SessionSeqCursor | undefined - let assistantStreamOrdinal = 0 - let wake: (() => void) | undefined - const notify = (): void => { - const resume = wake - wake = undefined - resume?.() - } - const follower = { closed: false } - const close = (): void => { - follower.closed = true - notify() - } - this.closeFollowers.add(close) - const disposeEvent = this.ctx.on('session/event', (session, event) => { - if (session.id !== target) return - buffered.pushBack({ type: 'event', event }) - notify() - }, { global: true }) - const disposeCreated = this.ctx.on('session/created', (session) => { - if (session.id !== target) return - // Constructor seed events have no session/event notification. Normally - // only the end-seed suffix is new; if persistence advanced after the - // opening observation, replay everything beyond that snapshot cursor. - // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred. - const suffix = session.snapshotEvents(snapshotCursor === undefined - ? session.firstLiveSeq - : SessionLogOffset(snapshotCursor + 1)) - for (let index = suffix.length - 1; index >= 0; index -= 1) { - buffered.pushFront({ type: 'event', event: suffix[index] as SessionEvent }) - } - notify() - }, { global: true }) - const disposeAssistantStream = request.assistantStream !== true - ? undefined - : this.ctx.on('agent/assistant-stream', ({ agent, frame }) => { - if (agent.session.id !== target) return - buffered.pushBack({ - type: 'assistant-stream', - frame: wireAssistantStreamFrame(frame, cursorBeforeNext(agent.session.seq)), - ordinal: ++assistantStreamOrdinal, - }) - notify() - }, { global: true }) - const onAbort = (): void => { notify() } - signal.addEventListener('abort', onAbort, { once: true }) - try { - using source = await this.sourceFor(address, signal, true) - const events = source.events - signal.throwIfAborted() - const cursor = source.cursor - snapshotCursor = cursor - const page = paginate(events, undefined, request.maxMessages ?? DEFAULT_MAX_MESSAGES, cursor, request.turnWindow) - const assistantStream = request.assistantStream === true - ? this.assistantStreams.get(target)?.snapshot() ?? { revision: 0 } - : undefined - // The accumulator snapshot and this watermark are synchronous. Frames - // through the cut are represented or superseded by that baseline, - // including larger revisions from a retired Agent; later revision - // resets reach Client continuity validation. - const assistantStreamOrdinalCut = assistantStreamOrdinal - yield { - type: 'snapshot', - header: wireHeader(source.header), - cursor, - records: pageRecords(page.events), - hasMore: page.hasMore, - projections: source.projections === undefined - ? { asOfSeq: cursor, values: {} } - : projectionBlock(source.projections), - ...assistantStream === undefined ? {} : { assistantStream }, - } - if (address.kind === 'session' && source.source === 'prepared') { - const promotion = source.retain() - try { - this.promote(promotion) - } catch (error: unknown) { - promotion[Symbol.dispose]() - throw error - } - } - let nextOffset = SessionLogOffset(cursor + 1) - while (!follower.closed && !signal.aborted) { - const item = buffered.popFront() - if (item === undefined) { - await new Promise((resolve) => { wake = resolve }) - continue - } - if (item.type === 'assistant-stream') { - if (item.ordinal > assistantStreamOrdinalCut) { - yield { type: 'assistant-stream', frame: item.frame } - } - continue - } - const expectedSeq = SessionSeq(nextOffset) - if (item.event.seq < expectedSeq) continue - if (item.event.seq !== expectedSeq) { - throw new RemoteError('gateway/internal', `session event stream skipped seq ${String(expectedSeq)}`, {}) - } - nextOffset = SessionLogOffset(nextOffset + 1) - yield entryFor(item.event) - } - } finally { - this.closeFollowers.delete(close) - signal.removeEventListener('abort', onAbort) - disposeCreated() - disposeEvent() - disposeAssistantStream?.() - } - } - - private async sourceFor( - address: SessionAddress, - signal: AbortSignal, - withProjections: boolean, - ): Promise { - const sessionId = addressId(address) - try { - const observation = await this.ctx.sessionQuery.observeSession(sessionId, { - signal, - projectionMode: withProjections || address.kind === 'subagent' ? 'all' : 'none', - }) - if (observation.header.cwd === undefined) { - observation[Symbol.dispose]() - rejectNotFound(address) - } - try { - validateAddress( - address, - observation.header, - observation.inheritedEventCount, - observation.projections, - ) - } catch (error: unknown) { - observation[Symbol.dispose]() - throw error - } - return observation - } catch (error: unknown) { - if (error instanceof SessionQueryError - && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') rejectNotFound(address) - throw error - } - } - -} - -function cursorBeforeNext(nextSeq: SessionLogOffsetType): SessionSeqCursor { - return nextSeq === 0 ? -1 : SessionSeq(nextSeq - 1) -} - -function wireAssistantStreamFrame( - frame: AssistantStreamFrame, - durableCursor: SessionSeqCursor, -): SessionAssistantStreamFrame { - if (frame.type === 'start') return { ...frame, startedAfterSeq: durableCursor } - if (frame.type === 'end') return frame - return { - ...frame, - chunk: frame.chunk as JsonValue, - } -} - -function projectionBlock( - snapshot: NonNullable, -): SessionProjectionBaseline { - return { - asOfSeq: snapshot.asOfSeq, - // Projection definitions validate whole JSON values before snapshot publication. - values: snapshot.values as SessionProjectionValues, - } -} - -function validatePageRequest(request: SessionPageRequest): void { - if (!Number.isSafeInteger(request.throughSeq) - || request.throughSeq < -1 - || Object.is(request.throughSeq, -0)) { - throw new RemoteError('gateway/bad-request', 'throughSeq must be an integer greater than or equal to -1', {}) - } - if (request.beforeSeq !== undefined - && (!Number.isSafeInteger(request.beforeSeq) - || request.beforeSeq < 0 - || Object.is(request.beforeSeq, -0))) { - throw new RemoteError('gateway/bad-request', 'beforeSeq must be a non-negative safe integer', {}) - } - validateHistoryWindow(request) -} - -function validateHistoryWindow(request: Pick): void { +/** + * Reject an invalid message budget or turn window. + * @param request - history window fields. + */ +export function validateHistoryWindow(request: Pick): void { if (request.maxMessages !== undefined && (!Number.isSafeInteger(request.maxMessages) || request.maxMessages <= 0)) { throw new RemoteError('gateway/bad-request', 'maxMessages must be a positive safe integer', {}) @@ -334,11 +47,23 @@ function validateHistoryWindow(request: Pick 0 } } -/** Translate current logical Session metadata to the browser wire. */ -function wireHeader(header: SessionHeader): SessionWireHeader { - return { ...header } -} - -function entryFor(event: SessionEvent): SessionEventEntry { +/** + * Convert a committed event to its wire entry. + * @param event - committed Session event. + * @returns the wire event entry. + */ +export function entryFor(event: SessionEvent): SessionEventEntry { return { type: 'event', // Session.append validates and freezes event data as JSON before publication. @@ -439,7 +179,11 @@ function entryFor(event: SessionEvent): SessionEventEntry { } } -/** Encode one bounded logical page without changing its pagination cut. */ -function pageRecords(events: readonly SessionEvent[]): SessionHistoryRecord[] { +/** + * Encode one bounded logical page without changing its pagination cut. + * @param events - page events. + * @returns the wire records. + */ +export function pageRecords(events: readonly SessionEvent[]): SessionHistoryRecord[] { return events.map(entryFor) } diff --git a/packages/api/session-controller/src/history/assistant-stream.ts b/packages/api/session-controller/src/history/assistant-stream.ts new file mode 100644 index 0000000000..b42a0aba29 --- /dev/null +++ b/packages/api/session-controller/src/history/assistant-stream.ts @@ -0,0 +1,102 @@ +/** Assistant stream baselines and per-connection subscriptions. */ + +import type { Context } from '@deepseek-ai/cordis' +import { SessionSeq } from '@deepseek-ai/dsh-session' +import type { Session, SessionId } from '@deepseek-ai/dsh-session' +import type { JsonValue } from '@deepseek-ai/dsh-util-values' +import { SessionAssistantStreamAccumulator } from '../assistant-stream.ts' +import type { SessionAssistantStreamBaseline, SessionAssistantStreamFrame } from '../types.ts' +import { ListenerBuffer } from './listener.ts' + +/** One accumulator per live Session, shared by every subscription bound to it. */ +export class SessionAssistantStreamsListener { + private readonly streams = new Map() + + /** @param ctx - service context owning the accumulator listeners. */ + constructor(private readonly ctx: Context) { + ctx.on('agent/assistant-stream', ({ agent, frame }) => { + let stream = this.streams.get(agent.session.id) + if (stream === undefined) { + stream = new SessionAssistantStreamAccumulator() + this.streams.set(agent.session.id, stream) + } + stream.accept(frame, agent.session.seq === 0 ? -1 : SessionSeq(agent.session.seq - 1)) + }, { global: true }) + ctx.on('agent/disposed', ({ agent }) => { this.streams.delete(agent.session.id) }, { global: true }) + ctx.effect(() => () => { this.streams.clear() }, 'session-controller.assistant-streams') + } + + /** + * Bind one connection to a Session assistant stream. + * @param sessionId - Session to subscribe. + * @param signal - cancellation owned by the caller. + * @param queue - caller-owned raw notification buffer. + * @returns a listener the caller disposes. + */ + bind(sessionId: SessionId, signal: AbortSignal, + queue: Pick, 'createInput' | 'capture'>): AssistantStreamListener { + return new AssistantStreamListener(this.ctx, sessionId, signal, () => { + return this.streams.get(sessionId)?.snapshot() ?? { revision: 0 } + }, queue) + } +} + +type AssistantEntry = { type: 'assistant-stream'; frame: SessionAssistantStreamFrame } + +/** An assistant notification and its connection-local arrival position. */ +interface AssistantItem { + readonly type: 'assistant-stream' + readonly session: Session + readonly frame: SessionAssistantStreamFrame + readonly ordinal: number +} + +/** Writes assistant notifications into the connection's shared queue. */ +class AssistantStreamListener implements Disposable { + private readonly disposes: (() => void)[] = [] + private ordinal = 0 + private cut = 0 + + constructor( + ctx: Context, + sessionId: SessionId, + signal: AbortSignal, + private _snapshot: () => SessionAssistantStreamBaseline, + output: Pick, 'createInput' | 'capture'>) { + signal.throwIfAborted() + const input = output.createInput(item => this.transform(item)) + try { + this.disposes.push(ctx.on('agent/assistant-stream', ({ agent, frame }) => { + if (agent.session.id !== sessionId) return + output.capture(() => { + const wire: SessionAssistantStreamFrame = frame.type === 'start' + ? { ...frame, startedAfterSeq: agent.session.seq === 0 ? -1 : SessionSeq(agent.session.seq - 1) } + : frame.type === 'chunk' ? { ...frame, chunk: frame.chunk as JsonValue } : frame + input.append({ type: 'assistant-stream', session: agent.session, frame: wire, ordinal: ++this.ordinal }) + }) + }, { global: true })) + } catch (error: unknown) { + this[Symbol.dispose]() + throw error + } + } + + /** @returns the baseline and local arrival cut captured synchronously together. */ + snapshot(): { baseline: SessionAssistantStreamBaseline; ordinal: number } { + return { baseline: this._snapshot(), ordinal: this.ordinal } + } + + /** @param ordinal - local snapshot cut set before queue consumption. */ + setOrdinalCut(ordinal: number): void { + this.cut = ordinal + } + + private *transform(item: AssistantItem): Iterable { + if (this.disposes.length === 0 || item.ordinal <= this.cut) return + yield { type: 'assistant-stream', frame: item.frame } + } + + [Symbol.dispose](): void { + for (const dispose of this.disposes.splice(0).reverse()) dispose() + } +} diff --git a/packages/api/session-controller/src/history/controller.ts b/packages/api/session-controller/src/history/controller.ts new file mode 100644 index 0000000000..d090f0a3f7 --- /dev/null +++ b/packages/api/session-controller/src/history/controller.ts @@ -0,0 +1,256 @@ +/** Independent Session snapshots and passive event subscriptions. */ + +import type { Context } from '@deepseek-ai/cordis' +import { SessionLogOffset, SessionSeq, isAppendSurfaceEvent } from '@deepseek-ai/dsh-session' +import type { SessionId, SessionEvent } from '@deepseek-ai/dsh-session' +import type { SessionObservation } from '@deepseek-ai/dsh-session-query' +import { RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' +import { + DEFAULT_MAX_MESSAGES, paginate, pageRecords, entryFor, addressId, + validateHistoryWindow, validateAddress, rejectNotFound, +} from '../history.ts' +import { EventListener, ProjectionListener } from './listener.ts' +import { SessionAssistantStreamsListener } from './assistant-stream.ts' +import type { + SessionEventFrame, SessionEventsPage, SessionPageRequest, + SessionObserveEventRequest, SessionProjectionsRequest, SessionProjectionFrame, + SessionAddress, SessionProjectionBaseline, SessionProjectionValues, SessionProjectionsValue, SessionWaitOutput, SessionHistoryRecord, +} from '../types.ts' + + +/** Session snapshots do not share lifetime with passive subscriptions. */ +export class HistoryController { + + /** Reconnect state for this controller's assistant subscriptions. */ + readonly streamsListener: SessionAssistantStreamsListener + + /** @param ctx - Host context carrying Session reads and projections. */ + constructor(private readonly ctx: Context) { + this.streamsListener = new SessionAssistantStreamsListener(this.ctx) + } + + /** + * Read a passive page of Session events at an exact cut. + * @param request - Session identity and optional cut and page window. + * @param signal - read cancellation. + * @returns a page at the supplied cut, or the observed log end when omitted. + */ + async events(request: SessionPageRequest, signal: AbortSignal): Promise { + const spec = resolveHistoryRequest(request) + try { + return await this.usingObservation({ sessionId: addressId(request.address), projection: request.address.kind === 'subagent' }, signal, (observation) => { + validateObservationAddress(request.address, observation) + return history(observation, spec) + }) + } catch (error: unknown) { + if (remoteErrorOf(error)?.code === 'session/not-found') rejectNotFound(request.address) + throw error + } + } + + /** + * Subscribe to Session events without reading or activating the Session. + * @param request - Session address to subscribe. + * @param signal - stream cancellation. + * @returns subscription readiness followed by event frames; readiness does not establish existence. + */ + async *observeEvent(request: SessionObserveEventRequest, signal: AbortSignal): AsyncIterable { + using listener = new EventListener(this.ctx, addressId(request.address), signal) + yield { type: 'ready' } + yield* listener.events() + } + + /** + * Read exact projections or migration cache hints without activating the Session. + * @param request - Session identity whose exact projection baseline is required. + * @param signal - read cancellation. + * @returns exact sequenced values, migration cache hints, or null when absent. + */ + async projections(request: SessionProjectionsRequest, signal: AbortSignal): Promise { + const { sessionId } = request + if (sessionId.length === 0) { + throw new RemoteError('gateway/bad-request', 'sessionId must not be empty', {}) + } + try { + signal.throwIfAborted() + const live = this.ctx.sessions.get(sessionId) + if (live !== undefined) { + const snapshot = this.ctx.sessionProjections.snapshot(live) + return { kind: 'sequenced', asOfSeq: snapshot.asOfSeq, values: snapshot.values as SessionProjectionValues } + } else { + const stored = await this.ctx.get('sessionPersistence')?.stat(sessionId, { signal }) + signal.throwIfAborted() + if (stored?.formatStatus === 'migration-required') { + const cached = this.ctx.get('sessionProjectionCache')?.cachedSnapshot(stored.header) + return { kind: 'migration-required', values: { ...cached?.values } as SessionProjectionValues } + } + return await this.usingObservation({ sessionId: request.sessionId, projection: true }, signal, observation => ({ + kind: 'sequenced' as const, + ...projections(observation), + })) + } + } catch (error: unknown) { + const code = typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined + if (code === 'SESSION_QUERY_SESSION_NOT_FOUND' || code === 'session/not-found') { + return null + } + if (signal.aborted || code === 'SESSION_QUERY_ABORTED') { + throw new RemoteError('gateway/cancelled', 'Session projection read was cancelled', {}, { cause: error }) + } + if (remoteErrorOf(error) !== undefined) throw error + throw new RemoteError('gateway/internal', 'Session projection read failed', {}, { cause: error }) + } + } + + /** + * Subscribe to sparse projection replacements without reading a baseline. + * @param request - Session identity to subscribe without reading a baseline. + * @param signal - stream cancellation. + * @returns readiness followed by sparse per-key replacement values. + */ + async *observeProjections(request: SessionProjectionsRequest, signal: AbortSignal): AsyncIterable { + using listener = new ProjectionListener(this.ctx, request.sessionId, signal) + yield { type: 'ready' } + yield* listener.changes() + } + + /** + * Read bounded committed assistant messages through a stopping cursor. + * @param sessionId - Session whose committed assistant messages are requested. + * @param afterSeq - exclusive lower bound. + * @param throughSeq - inclusive stopping-state cursor. + * @param maxMessages - positive assistant record limit. + * @param signal - caller cancellation, independent of a completed wait deadline. + * @returns newest-first assistant messages and whether further matching records were omitted. + */ + async assistantOutput( + sessionId: SessionId, afterSeq: number, throughSeq: number, maxMessages: number, signal: AbortSignal, + ): Promise { + return this.usingObservation({ sessionId, projection: false }, signal, (observation) => { + if (throughSeq > observation.cursor) { + throw new RemoteError('gateway/internal', 'Session history no longer covers the wait cursor', {}) + } + const records: SessionHistoryRecord[] = [] + const events = observation.events + for (let index = throughSeq; index > afterSeq; index--) { + const event = events[index] as SessionEvent + if (event.type !== 'assistant/message' || !isAppendSurfaceEvent(event)) continue + if (records.length === maxMessages) return { records, truncated: true } + records.push(entryFor(event)) + } + return { records, truncated: false } + }) + } + + /** + * Acquire a read without activating a Session; projections are opt-in. + * @param request - Session identity and whether to compute projections. + * @param signal - read cancellation. + * @param callback - omitted to transfer lease ownership to the caller. + * @returns a lease the caller must dispose. + */ + usingObservation( + request: { readonly sessionId: SessionId; readonly projection: boolean }, signal: AbortSignal, callback?: undefined, + ): Promise + /** + * Keep the borrowed lease alive until the callback settles, then dispose it. + * @param request - Session identity and whether to compute projections. + * @param signal - read cancellation. + * @param callback - synchronous or asynchronous computation; retain a separate lease if it must escape. + * @returns the callback result; read and callback failures propagate. + */ + usingObservation( + request: { readonly sessionId: SessionId; readonly projection: boolean }, signal: AbortSignal, + callback: (observation: SessionObservation) => T, + ): Promise> + async usingObservation( + { sessionId, projection }: { readonly sessionId: SessionId; readonly projection: boolean }, signal: AbortSignal, + callback?: (observation: SessionObservation) => T, + ): Promise> { + let observation: SessionObservation + try { + observation = await this.ctx.sessionQuery.observeSession(sessionId, { signal, projectionMode: projection ? 'all' : 'none' }) + } catch (error: unknown) { + const code = (error as { readonly code?: unknown } | null | undefined)?.code + if (code === 'SESSION_QUERY_SESSION_NOT_FOUND') { + throw new RemoteError('session/not-found', `session "${sessionId}" not found`, { sessionId }) + } + if (code === 'SESSION_QUERY_ABORTED') { + // Keep the query's own message: cancellation detail was visible before this mapping. + throw new RemoteError('gateway/cancelled', + error instanceof Error ? error.message : 'Session read was cancelled', {}, { cause: error }) + } + throw error + } + try { + signal.throwIfAborted() + } catch (error: unknown) { + observation[Symbol.dispose]() + throw error + } + if (callback === undefined) return observation + using ownedObservation = observation + return await callback(ownedObservation) + } +} + +/** + * Validate an Address against the exact read used by a Controller. + * @param address - caller-supplied Session address. + * @param observation - borrowed read; subagent addresses require projections. + */ +export function validateObservationAddress(address: SessionAddress, observation: SessionObservation): void { + if (observation.header.cwd === undefined) rejectNotFound(address) + validateAddress(address, observation.header, observation.inheritedEventCount, observation.projections) +} + +/** + * Convert a borrowed observation to one page without acquiring or retaining it. + * @param observation - exact read cut owned by the caller. + * @param request - validated page window and optional inclusive cut. + * @returns a chronological page at the requested cut. + */ +export function history(observation: SessionObservation, request: Omit & { readonly maxMessages: number }): SessionEventsPage { + const cursor = request.throughSeq === undefined ? observation.cursor + : request.throughSeq === -1 ? -1 : SessionSeq(request.throughSeq) + if (cursor > observation.cursor) { + throw new RemoteError('gateway/bad-request', `session history cut ${String(cursor)} exceeds ${String(observation.cursor)}`, {}) + } + const page = paginate( + observation.events, + request.beforeSeq === undefined ? undefined : SessionLogOffset(request.beforeSeq), + request.maxMessages, + cursor, + request.turnWindow, + ) + return { cursor, records: pageRecords(page.events), hasMore: page.hasMore } +} + +/** + * Convert the projection baseline without acquiring or retaining its observation. + * @param observation - projected read cut owned by the caller. + * @returns the exact baseline; missing projection support fails explicitly. + */ +export function projections(observation: SessionObservation): SessionProjectionBaseline { + const snapshot = observation.projections + if (snapshot === undefined) throw new RemoteError('session/projections-unavailable', 'Session projections are unavailable', {}) + return { asOfSeq: snapshot.asOfSeq, values: snapshot.values as SessionProjectionValues } +} + +/** + * Validate and resolve the history page window. + * @param request - external history window. + * @returns the validated request with an explicit message budget. + */ +export function resolveHistoryRequest(request: SessionPageRequest): SessionPageRequest & { readonly maxMessages: number } { + if (request.throughSeq !== undefined + && (!Number.isSafeInteger(request.throughSeq) || request.throughSeq < -1 || Object.is(request.throughSeq, -0))) { + throw new RemoteError('gateway/bad-request', 'throughSeq must be an integer greater than or equal to -1', {}) + } + if (request.beforeSeq !== undefined + && (!Number.isSafeInteger(request.beforeSeq) || request.beforeSeq < 0 || Object.is(request.beforeSeq, -0))) { + throw new RemoteError('gateway/bad-request', 'beforeSeq must be a non-negative safe integer', {}) + } + validateHistoryWindow(request) + return { ...request, maxMessages: request.maxMessages ?? DEFAULT_MAX_MESSAGES } +} diff --git a/packages/api/session-controller/src/history/listener.ts b/packages/api/session-controller/src/history/listener.ts new file mode 100644 index 0000000000..a272081620 --- /dev/null +++ b/packages/api/session-controller/src/history/listener.ts @@ -0,0 +1,303 @@ +/** Passive per-Session streams; subscriptions never acquire Session observations. */ + +import type { Context } from '@deepseek-ai/cordis' +import { Deque } from '@deepseek-ai/dsh-deque' +import { SessionLogOffset } from '@deepseek-ai/dsh-session' +import type { Session, SessionEvent, SessionId } from '@deepseek-ai/dsh-session' +import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' +import type { JsonValue } from '@deepseek-ai/dsh-util-values' +import { entryFor } from '../history.ts' +import type { SessionProjectionChange, SessionEventEntry } from '../types.ts' + +/** Raw history notifications buffered before an opening cut is known. */ +export type EventItem = + | { readonly type: 'event'; readonly session: Session; readonly event: SessionEvent } + | { readonly type: 'created'; readonly session: Session; readonly end: number } + +/** A single subscription buffers before either consumption mode starts. */ +export class EventListener implements Disposable { + private readonly buffer: ListenerBuffer | undefined + private readonly disposes: (() => void)[] = [] + private firstReceivedSeq: number | undefined + private nextExpectedSeq: number | undefined + + /** + * @param ctx - context owning the event registrations. + * @param sessionId - Session whose notifications are emitted. + * @param signal - cancellation that wakes consumers. + * @param queue - optional caller-owned buffer; only an internally created buffer is disposed here. + */ + constructor(ctx: Context, sessionId: SessionId, signal: AbortSignal, + queue?: Pick, 'createInput' | 'capture'>) { + signal.throwIfAborted() + const buffer = queue ?? new ListenerBuffer(ctx, signal) + this.buffer = queue === undefined ? buffer as ListenerBuffer : undefined + const input = buffer.createInput(item => this.transform(item)) + const target = sessionId + try { + this.disposes.push(ctx.on('session/event', (session, event) => { + if (session.id !== target) return + buffer.capture(() => { + this.recordFirst(event.seq) + input.append({ type: 'event', session, event }) + }) + }, { global: true })) + this.disposes.push(ctx.on('session/created', (session) => { + if (session.id !== target) return + buffer.capture(() => { + if (session.firstLiveSeq < session.seq) this.recordFirst(session.firstLiveSeq) + input.prepend({ type: 'created', session, end: session.seq }) + }) + }, { global: true })) + this.buffer?.own(() => { this[Symbol.dispose]() }) + } catch (error: unknown) { + this[Symbol.dispose]() + throw error + } + } + + /** Consume notifications without reading history. + * @returns event frames from the first received event, without loading a baseline. */ + events(): AsyncIterable { + return this.iterate() + } + + /** Set the inclusive opening cut for buffered history notifications. + * @param cursor - snapshot cut set before consuming the queue. */ + setCursor(cursor: number): void { + this.nextExpectedSeq = cursor + 1 + } + + private *transform(item: EventItem): Iterable { + if (this.disposes.length === 0) return + this.nextExpectedSeq ??= this.firstReceivedSeq + const result = eventItem(item, this.nextExpectedSeq) + this.nextExpectedSeq = result.next + for (const event of result.events) { + if (this.disposes.length === 0) return + yield entryFor(event) + } + } + + private async *iterate(): AsyncIterable { + if (this.buffer === undefined) throw new Error('Consume the externally owned history buffer directly') + try { + yield* this.buffer.items() + } finally { + this[Symbol.dispose]() + } + } + + private recordFirst(seq: number): void { + this.firstReceivedSeq = this.firstReceivedSeq === undefined ? seq : Math.min(this.firstReceivedSeq, seq) + } + + [Symbol.dispose](): void { + for (const dispose of this.disposes.splice(0).reverse()) dispose() + this.buffer?.[Symbol.dispose]() + } +} + +/** + * Select the uncovered events represented by one notification. + * @param item - one buffered notification. + * @param next - next required seq, or undefined before the first event. + * @returns uncovered events and the next required seq without acquiring an observation. + */ +export function eventItem(item: EventItem, next?: number): { + events: readonly SessionEvent[] + next: number | undefined +} { + if (item.type === 'event') { + if (next !== undefined && item.event.seq < next) return { events: [], next } + if (next !== undefined && item.event.seq !== next) { + throw new RemoteError('gateway/internal', `session event stream skipped seq ${String(next)}`, {}) + } + return { events: [item.event], next: item.event.seq + 1 } + } + const start = next ?? item.session.firstLiveSeq + if (start >= item.end) return { events: [], next } + // oxlint-disable-next-line typescript/no-deprecated -- Existing Session-created history adaptation. + const events = item.session.snapshotEvents(SessionLogOffset(start), SessionLogOffset(item.end)) + for (const event of events) { + if (next !== undefined && event.seq !== next) { + throw new RemoteError('gateway/internal', `session event stream skipped seq ${String(next)}`, {}) + } + next = event.seq + 1 + } + return { events, next } +} + +/** Sparse projection changes retain every key, including keys sharing a seq. */ +export class ProjectionListener implements Disposable { + private readonly buffer: ListenerBuffer<{ session: Session; change: SessionProjectionChange }> + + /** + * @param ctx - context owning projection notifications. + * @param sessionId - Session whose notifications are emitted. + * @param signal - cancellation that removes registrations and wakes consumers. + */ + constructor(ctx: Context, sessionId: SessionId, signal: AbortSignal) { + this.buffer = new ListenerBuffer(ctx, signal) + const input = this.buffer.createInput<{ session: Session; change: SessionProjectionChange }>(item => [item]) + const target = sessionId + try { + this.buffer.own(ctx.sessionProjections.onChanged((session, key, value, seq) => { + if (session.id !== target) return + this.buffer.capture(() => { + input.append({ + session, change: { type: 'projection', key, value: value as JsonValue, seq } satisfies SessionProjectionChange, + }) + }) + })) + } catch (error: unknown) { + this.buffer[Symbol.dispose]() + throw error + } + } + + /** Consume sparse per-key projection replacements. + * @returns validated replacement frames; projection seqs need not be contiguous. */ + async *changes(): AsyncIterable { + try { + for await (const { change } of this.buffer.items()) { + yield change + } + } finally { + this[Symbol.dispose]() + } + } + + [Symbol.dispose](): void { + this.buffer[Symbol.dispose]() + } +} + +/** Owns buffering, callback failure and registration cleanup for one consumer. */ +export class ListenerBuffer implements Disposable { + private readonly values = new Deque() + private readonly transformIds = new Deque() + private readonly transforms: ((value: unknown) => Iterable)[] = [] + private readonly cleanup: (() => void)[] = [] + private wake: (() => void) | undefined + private closed = false + private failure: { readonly error: unknown } | undefined + private consumed = false + + constructor(ctx: Context, signal: AbortSignal) { + signal.throwIfAborted() + const close = (): void => { this[Symbol.dispose]() } + signal.addEventListener('abort', close, { once: true }) + this.own(() => { signal.removeEventListener('abort', close) }) + try { + const dispose = ctx.effect(() => close, 'session-controller.listener-buffer') + this.own(() => { void dispose() }) + } catch (error: unknown) { + this[Symbol.dispose]() + throw error + } + } + + /** + * Register cleanup, or run it immediately when already closed. + * @param dispose - synchronous cleanup. + */ + own(dispose: () => void): void { + if (this.closed) dispose() + else this.cleanup.push(dispose) + } + + /** + * Contain producer failure and wake the consumer with that failure. + * @param action - synchronous producer operation. + */ + capture(action: () => void): void { + if (this.closed) return + try { + action() + } catch (error: unknown) { + this.failure = { error } + this[Symbol.dispose]() + } + } + + /** + * Register a dequeue transform and obtain its write-only input. + * @param transform - conversion bound once and evaluated when each input is dequeued. + * @returns a write-only input sharing this buffer's storage and lifetime. + * @throws when this buffer is already closed. + */ + createInput(transform: (item: Input) => Iterable): { append(item: Input): void; prepend(item: Input): void } { + if (this.closed) throw new Error('Cannot register a transform on a closed listener buffer') + const transformId = this.transforms.length + // Only this typed input can enqueue values with its private transform id. + this.transforms.push(value => transform(value as Input)) + return { + append: (item) => { + if (this.closed) return + this.values.pushBack(item) + this.transformIds.pushBack(transformId) + this.notify() + }, + prepend: (item) => { + if (this.closed) return + this.values.pushFront(item) + this.transformIds.pushFront(transformId) + this.notify() + }, + } + } + + /** + * Consume queued values once, releasing the buffer when iteration ends. + * @returns transformed output values. + */ + async *items(): AsyncIterable { + if (this.consumed) throw new RemoteError('gateway/internal', 'Session listener already has a consumer', {}) + this.consumed = true + try { + for (;;) { + if (this.failure !== undefined) throw this.failure.error + if (this.closed) return + if (this.transformIds.size === 0) { + await new Promise((resolve) => { this.wake = resolve }) + continue + } + const transformId = this.transformIds.popFront() as number + const value = this.values.popFront() + for (const item of (this.transforms[transformId] as (value: unknown) => Iterable)(value)) { + this.throwIfFailed() + if (this.isClosed()) return + yield item + } + } + } finally { + this[Symbol.dispose]() + } + } + + private throwIfFailed(): void { + if (this.failure !== undefined) throw this.failure.error + } + + /** @returns whether disposal ended this buffer while a transform was yielding. */ + private isClosed(): boolean { + return this.closed + } + + private notify(): void { + const wake = this.wake + this.wake = undefined + wake?.() + } + + [Symbol.dispose](): void { + if (this.closed) return + this.closed = true + this.values.clear() + this.transformIds.clear() + this.transforms.length = 0 + this.notify() + for (const dispose of this.cleanup.splice(0).reverse()) dispose() + } +} diff --git a/packages/api/session-controller/src/index.ts b/packages/api/session-controller/src/index.ts index 5eeb7ae03d..94d08c77e3 100644 --- a/packages/api/session-controller/src/index.ts +++ b/packages/api/session-controller/src/index.ts @@ -10,21 +10,21 @@ import { errorChain, ReasoningEffortId, type MessageSource } from '@deepseek-ai/ import type {} from '@deepseek-ai/dsh-client-file-upload' import { canOpenNativePath, nativeFileManager, nativeFileApplications, openNativeFileApplication, openNativeAssociatedPath, revealNativePath } from '@deepseek-ai/dsh-native-command' import type { SessionId } from '@deepseek-ai/dsh-session' -import type { SessionInspection } from '@deepseek-ai/dsh-session-persistence' import type {} from '@deepseek-ai/dsh-session-projection-cache' -import { SessionQueryError, type SessionObservation } from '@deepseek-ai/dsh-session-query' -import { Remote, RemoteError, TypertRemoteService, principalOf } from '@deepseek-ai/dsh-typert-protocol' +import type { SessionObservation } from '@deepseek-ai/dsh-session-query' +import { Remote, RemoteError, TypertRemoteService, principalOf, type TypertResourceResolveInput } from '@deepseek-ai/dsh-typert-protocol' import { canonicalClientTimeZone } from '@deepseek-ai/dsh-util-time' import { assertNever } from '@deepseek-ai/dsh-util-values' import type {} from '@deepseek-ai/dsh-api-remote-access' import { ApiSessionAgentController, - inspectApiSession, type ApiSessionAgentResult, } from './agent.ts' import { SessionCommandController, hasPromptContent } from './commands.ts' import { SessionControlController } from './control.ts' -import { SessionHistoryController } from './history.ts' +import { HistoryController } from './history/controller.ts' +import { StateController } from './state/controller.ts' +import { WebController } from './web/controller.ts' import { SessionFileReferences } from './file-references.ts' import { ApiSessionList } from './list.ts' import { buildModelCatalog, hasProviderApiKey } from './catalog.ts' @@ -50,8 +50,8 @@ import type { SessionListValue, SessionOpenWorkspacePathRequest, SessionOpenWorkspacePathValue, - SessionPage, - SessionPageRequest, + SessionEventsPage, SessionPageRequest, SessionEventFrame, SessionObserveEventRequest, + SessionProjectionFrame, SessionStateRequest, SessionState, SessionWaitRequest, SessionWaitValue, SessionPromptRequest, SessionPromptValue, SessionRenameRequest, @@ -62,7 +62,6 @@ import type { SessionSelectModelValue, SessionProjectionsRequest, SessionProjectionsValue, - SessionProjectionValues, SessionUpdateQueueRequest, SessionUpdateQueueValue, } from './types.ts' @@ -80,13 +79,31 @@ declare module '@deepseek-ai/cordis' { } /** - * Read the Session resource a history address names: the Session itself, or - * the child Session whose transcript a subagent address reads. - * @param request - history request carrying the durable address. - * @returns the Session whose access the read requires. + * Extract the Session resource from an ID or a history address. + * + * Registers as the `session` kind default, so it applies to every Remote method of + * every namespace: a top-level `sessionId` parameter, otherwise the first object + * parameter carrying `sessionId` or an `address`. A new request type whose first + * object parameter has an unrelated `address` field would be read as an address. + * @param input - validated wire arguments and their ordered parameter descriptions. + * @returns the named Session identity, otherwise the first object's Session identity or history address. + * @throws Error when the request object supplies both sessionId and address. */ -function addressedSession(request: { readonly address: SessionAddress }): SessionId { - return request.address.kind === 'session' ? request.address.sessionId : request.address.childSessionId +function resolveSessionResource({ args, parameters }: TypertResourceResolveInput): SessionId | undefined { + const sessionParameter = parameters.find(parameter => parameter.name === 'sessionId' || parameter.wire === 'sessionId') + if (sessionParameter !== undefined) return args[sessionParameter.wire] as SessionId | undefined + for (const parameter of parameters) { + const value = args[parameter.wire] + if (typeof value !== 'object' || value === null || Array.isArray(value)) continue + const request = value as { readonly sessionId?: SessionId; readonly address?: SessionAddress } + const address = request.address + if (request.sessionId !== undefined && address !== undefined) { + throw new Error('Session resource request must not contain both sessionId and address') + } + return request.sessionId ?? (address === undefined ? undefined + : address.kind === 'session' ? address.sessionId : address.childSessionId) + } + return undefined } /** Session Controller deployment policy. */ @@ -128,6 +145,7 @@ export class SessionController extends TypertRemoteService { 'sessionProjections', 'sessionQuery', 'typert', + 'typertGateway', 'workspaceRegistry', ] @@ -136,10 +154,13 @@ export class SessionController extends TypertRemoteService { listWorkSliceMs: z.natural().min(1).default(16), }) + private historyController!: HistoryController + private stateController!: StateController + private webController!: WebController + private agents!: ApiSessionAgentController private commands!: SessionCommandController private controlState!: SessionControlController - private history!: SessionHistoryController private listState!: ApiSessionList private readonly openPath: (path: string, signal: AbortSignal) => Promise private readonly fileApplications: typeof nativeFileApplications @@ -167,7 +188,7 @@ export class SessionController extends TypertRemoteService { protected async [Service.init](): Promise { const ctx = this.ctx - ctx.typert.resources.register('session', { field: 'sessionId' }) + ctx.typert.resources.register('session', { resolve: resolveSessionResource }) this.agents = new ApiSessionAgentController(ctx) this.agents.initialize() this.commands = new SessionCommandController(ctx, this.agents, process.cwd()) @@ -182,7 +203,11 @@ export class SessionController extends TypertRemoteService { ctx.effect(() => async () => { await Promise.allSettled([...this.promotions]) }, 'session-controller.promotions') - this.history = new SessionHistoryController(ctx, (observation) => { this.promote(observation) }) + // Assistant-stream observation must be live before the list read yields: an Agent's + // opening frame arriving during that await would otherwise have no listener. + this.historyController = new HistoryController(ctx) + this.stateController = new StateController(ctx, this.historyController) + this.webController = new WebController(ctx, this.historyController, (observation) => { this.promote(observation) }) this.listState = new ApiSessionList(ctx, this.listWorkSliceMs) await this.listState.initialize() ctx.plugin(SessionFileReferences) @@ -218,6 +243,10 @@ export class SessionController extends TypertRemoteService { }) } + /** + * Request background activation through the existing Session Agent controller. + * @param observation - owned lease disposed by the background task; callers retain their own lease separately. + */ private promote(observation: SessionObservation): void { const sessionId = observation.header.id const task = (async () => { @@ -240,28 +269,6 @@ export class SessionController extends TypertRemoteService { return this.agents.resolveAgent(sessionId) } - /** - * Inspect one attached or persisted Session without activating its Agent. - * @param sessionId - durable Session identity. - * @param signal - optional caller cancellation for persistence reads. - * @returns the current attached state or persisted header and event prefix. - */ - inspect( - sessionId: SessionId, - signal?: AbortSignal, - ): Promise { - const attached = this.ctx.sessions.get(sessionId) - if (attached !== undefined) { - return Promise.resolve({ - meta: attached.header, - inheritedEventCount: attached.inheritedEventCount, - // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred. - events: attached.snapshotEvents(), - }) - } - return inspectApiSession(this.ctx, sessionId, signal) - } - /** * Read all visible Session rows without resuming an Agent. * @param _request - reserved empty list request. @@ -482,8 +489,8 @@ export class SessionController extends TypertRemoteService { } /** - * Read one image proven reachable from the addressed Session log. - * @param request - Session and attachment identities used for authorization. + * Read one image from the attachment store after gateway authorization. + * @param request - image reference and gateway permission scope; Session existence is not checked. * @returns the durable attachment reference and base64-encoded bytes. */ @Remote('attachment') @@ -513,13 +520,80 @@ export class SessionController extends TypertRemoteService { /** * Read one cold-safe, message-aligned Session history page. - * @param request - durable address, backward cursor, and page budget. + * @deprecated Use `events`; this entry point remains for existing Web callers. + * @param request - durable address, optional fixed cut, backward cursor, and page budget. * @param signal - cancellation for persistence reads. - * @returns one chronological page. + * @returns one chronological page with its inclusive cursor; an omitted `throughSeq` selects the observed log end. */ - @Remote({ name: 'page', resources: { session: addressedSession } }) - page(request: SessionPageRequest, signal: AbortSignal): Promise { - return this.history.page(request, signal) + @Remote('page') + page(request: SessionPageRequest, signal: AbortSignal): Promise { + return this.historyController.events(request, signal) + } + + /** + * Read one cold-safe, message-aligned Session history page. + * @param request - durable address, optional fixed cut, backward cursor, and page budget. + * @param signal - cancellation for persistence reads. + * @returns one chronological page with its inclusive cursor. + */ + @Remote + events(request: SessionPageRequest, signal: AbortSignal): Promise { + return this.historyController.events(request, signal) + } + + /** + * Subscribe to Session events without reading a snapshot. + * @param request - Session address. + * @param signal - subscription cancellation. + * @returns readiness and subsequent events, without a snapshot. + */ + @Remote({ mode: 'stream' }) + observeEvent(request: SessionObserveEventRequest, signal: AbortSignal): AsyncIterable { + return this.historyController.observeEvent(request, signal) + } + + /** + * Subscribe to sparse Session projection changes. + * @param request - target Session. + * @param signal - subscription cancellation. + * @returns readiness and sparse projection changes. + */ + @Remote({ mode: 'stream' }) + observeProjections(request: SessionProjectionsRequest, signal: AbortSignal): AsyncIterable { + return this.historyController.observeProjections(request, signal) + } + + /** + * Read passive Session state. + * @param request - target Session. + * @param signal - read cancellation. + * @returns current passive state. + */ + @Remote + state(request: SessionStateRequest, signal: AbortSignal): Promise { + return this.stateController.state(request, signal) + } + + /** + * Subscribe to complete Session state replacements. + * @param request - target Session. + * @param signal - subscription cancellation. + * @returns complete passive state replacements. + */ + @Remote({ mode: 'stream' }) + observeState(request: SessionStateRequest, signal: AbortSignal): AsyncIterable { + return this.stateController.observeState(request, signal) + } + + /** + * Wait for Session quiescence or pending input with bounded assistant output. + * @param request - Session, wait bounds and output window. + * @param signal - caller cancellation. + * @returns stopping state and bounded assistant output. + */ + @Remote + wait(request: SessionWaitRequest, signal: AbortSignal): Promise { + return this.stateController.wait(request, signal) } /** @@ -529,9 +603,9 @@ export class SessionController extends TypertRemoteService { * @returns a complete opening snapshot followed by gap-free durable event * frames and optional cursorless assistant-stream frames. */ - @Remote({ mode: 'stream', resources: { session: addressedSession } }) + @Remote({ mode: 'stream' }) follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable { - return this.history.follow(request, signal) + return this.webController.follow(request, signal) } /** @@ -541,49 +615,8 @@ export class SessionController extends TypertRemoteService { * @returns a sequenced baseline, cached hints when migration is deferred, or null when absent. */ @Remote('projections') - async projections(request: SessionProjectionsRequest, signal: AbortSignal): Promise { - const { sessionId } = request - if (sessionId.length === 0) { - throw new RemoteError('gateway/bad-request', 'sessionId must not be empty', {}) - } - try { - signal.throwIfAborted() - const live = this.liveProjections(sessionId) - if (live !== undefined) return live - const stored = await this.ctx.get('sessionPersistence')?.stat(sessionId, { signal }) - signal.throwIfAborted() - const attached = this.liveProjections(sessionId) - if (attached !== undefined) return attached - if (stored === undefined) return null - if (stored.formatStatus === 'migration-required') { - const cached = this.ctx.get('sessionProjectionCache')?.cachedSnapshot(stored.header) - return { kind: 'migration-required', values: { ...cached?.values } as SessionProjectionValues } - } - using observation = await this.ctx.sessionQuery.observeSession(sessionId, { signal }) - const projections = observation.projections - if (projections === undefined) { - throw new RemoteError('session/projections-unavailable', 'Session projections are unavailable', {}) - } - return { kind: 'sequenced', asOfSeq: projections.asOfSeq, values: projections.values as SessionProjectionValues } - } catch (error: unknown) { - if (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') { - return this.liveProjections(sessionId) ?? null - } - if (signal.aborted || (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_ABORTED')) { - throw new RemoteError('gateway/cancelled', 'Session projection read was cancelled', {}, { cause: error }) - } - if (error instanceof RemoteError) throw error - throw new RemoteError('gateway/internal', 'Session projection read failed', {}, { cause: error }) - } - } - - private liveProjections( - sessionId: SessionId, - ): Extract | undefined { - const session = this.ctx.sessions.get(sessionId) - if (session === undefined) return undefined - const snapshot = this.ctx.sessionProjections.snapshot(session) - return { kind: 'sequenced', asOfSeq: snapshot.asOfSeq, values: snapshot.values as SessionProjectionValues } + projections(request: SessionProjectionsRequest, signal: AbortSignal): Promise { + return this.historyController.projections(request, signal) } /** @@ -610,9 +643,6 @@ export class SessionController extends TypertRemoteService { } } } - - } -export { buildModelCatalog } export default SessionController diff --git a/packages/api/session-controller/src/media-references.ts b/packages/api/session-controller/src/media-references.ts index 9da80029f5..7effd7a18e 100644 --- a/packages/api/session-controller/src/media-references.ts +++ b/packages/api/session-controller/src/media-references.ts @@ -1,7 +1,9 @@ /** * Authenticated GET/HEAD /api/file reads bounded file responses through * the composed filesystem provider. Paths and MIME types do not restrict access; - * the connection service authenticates requests before this handler. + * the connection service authenticates requests before this handler. A request + * without the current `v` version is redirected, uncached, to the versioned URL, + * whose response is cacheable indefinitely. * @module @deepseek-ai/dsh-api-session-controller/media-references */ @@ -13,33 +15,38 @@ import { FsError, type FileSystem } from '@deepseek-ai/dsh-fs' import mime from 'mime-types' const BASE_HEADERS = { - 'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff', // HTML and SVG files may be opened directly on the authenticated API origin. 'Content-Security-Policy': "sandbox; default-src 'none'", } +const NO_STORE = { ...BASE_HEADERS, 'Cache-Control': 'private, no-store' } +// A versioned URL names one file version, so its response never changes. +const VERSIONED = { ...BASE_HEADERS, 'Cache-Control': 'private, max-age=31536000, immutable' } async function serveFile(request: Request, fs: FileSystem, maxBytes: number): Promise { const fail = (status: number, text: string): Response => - new Response(request.method === 'HEAD' ? null : text, { status, headers: BASE_HEADERS }) - const path = new URL(request.url).searchParams.get('path') + new Response(request.method === 'HEAD' ? null : text, { status, headers: NO_STORE }) + const params = new URL(request.url).searchParams + const path = params.get('path') if (path === null || path.length === 0) return fail(400, 'missing path') if (path.includes('\0') || !isAbsolute(path)) return fail(400, 'absolute path required') try { const target = await fs.resolve(path, { signal: request.signal }) - const mediaType = mime.lookup(target.displayPath) || 'application/octet-stream' + const info = await fs.stat(target, request.signal) + if (info === undefined) return fail(404, 'not found') + if (info.type !== 'file') return fail(403, 'not a regular file') + if (info.size !== undefined && info.size > maxBytes) return fail(413, 'file exceeds byte limit') + if (params.get('v') !== info.version) { + // Relative to the request URL, so deployment prefixes and the Desktop scheme are kept. + const location = `?${new URLSearchParams({ path, v: info.version }).toString()}` + return new Response(null, { status: 302, headers: { ...NO_STORE, Location: location } }) + } const headers: Record = { - ...BASE_HEADERS, - 'Content-Type': mediaType, + ...VERSIONED, + 'Content-Type': mime.lookup(target.displayPath) || 'application/octet-stream', } if (request.method === 'HEAD') { - const info = await fs.stat(target, request.signal) - if (info === undefined) return fail(404, 'not found') - if (info.type !== 'file') return fail(403, 'not a regular file') - if (info.size !== undefined) { - if (info.size > maxBytes) return fail(413, 'file exceeds byte limit') - headers['Content-Length'] = String(info.size) - } + if (info.size !== undefined) headers['Content-Length'] = String(info.size) return new Response(null, { headers }) } const bytes = await fs.readBytes(target, request.signal, maxBytes) diff --git a/packages/api/session-controller/src/state/controller.ts b/packages/api/session-controller/src/state/controller.ts new file mode 100644 index 0000000000..60b97776d9 --- /dev/null +++ b/packages/api/session-controller/src/state/controller.ts @@ -0,0 +1,221 @@ +/** Passive Session state, coalesced observations and quiescence waits. */ + +import type { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import type {} from '@deepseek-ai/dsh-api-gateway' +import type { UserMessage } from '@deepseek-ai/dsh-llm' +import type { SessionId } from '@deepseek-ai/dsh-session' +import { deadline, MAX_TIMER_DELAY_MS, timeoutOf } from '@deepseek-ai/dsh-timeout' +import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' +import type { JsonValue } from '@deepseek-ai/dsh-util-values' +import type { HistoryController } from '../history/controller.ts' +import { DEFAULT_MAX_MESSAGES, rejectNotFound } from '../history.ts' +import type { SessionPendingInput, SessionQueuedItem, SessionState, SessionStateRequest, SessionWaitRequest, SessionWaitValue } from '../types.ts' + +import { StateListener } from './listener.ts' +import type { VersionedSessionState } from './listener.ts' + +const DEFAULT_WAIT_TIMEOUT_MS = 30_000 + +/** Reads and waits without activating or cancelling Session execution. */ +export class StateController { + + /** + * @param ctx - live Session and pending Remote event services. + * @param historyController - passive read entry used for cold state and its bounded output. + */ + constructor(private readonly ctx: Context, private readonly historyController: HistoryController) {} + + /** + * Read passive execution and pending-input state. + * @param request - Session identity. + * @param signal - read cancellation. + * @returns current passive state. + */ + async state(request: SessionStateRequest, signal: AbortSignal): Promise { + return this.readState(request.sessionId, signal) + } + + /** + * Observe complete passive state replacements. + * @param request - Session identity. + * @param signal - observation cancellation. + * @returns complete state replacements, starting with the current state. + */ + async *observeState(request: SessionStateRequest, signal: AbortSignal): AsyncIterable { + using listener = this.listen(request.sessionId, signal) + for await (const { state } of listener.observeStates()) yield state + } + + /** + * Wait for quiescence, pending input, or the deadline without cancelling execution. + * @param request - Session identity, timeout and assistant output window. + * @param signal - cancellation of this wait only, never of Agent execution. + * @returns the stopping reason and last complete state; no state before timeout is an error. + */ + async wait(request: SessionWaitRequest, signal: AbortSignal): Promise { + const timeoutMs = request.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS + const afterSeq = request.afterSeq ?? -1 + const maxMessages = request.maxMessages ?? DEFAULT_MAX_MESSAGES + if (!Number.isSafeInteger(afterSeq) || afterSeq < -1 || Object.is(afterSeq, -0)) { + throw new RemoteError('gateway/bad-request', 'afterSeq must be an integer greater than or equal to -1', {}) + } + if (!Number.isSafeInteger(maxMessages) || maxMessages <= 0) { + throw new RemoteError('gateway/bad-request', 'maxMessages must be a positive safe integer', {}) + } + if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_DELAY_MS) { + throw new RemoteError('gateway/bad-request', 'timeoutMs must be a positive supported timer delay', {}) + } + using timer = deadline(signal, timeoutMs, 'session/wait-timeout') + using listener = this.listen(request.sessionId, timer.signal) + const sessionId = request.sessionId + const statesGenerator = listener.observeStates(1_000) + let nextStatePromise = statesGenerator.next() + let currentState: SessionState | undefined + let reason: SessionWaitValue['reason'] = 'timeout' + try { + for (;;) { + const observedState = await nextStatePromise + if (observedState.done) { + timer.signal.throwIfAborted() + throw new RemoteError('session/observation-ended', 'Session observation ended before a stopping state', {}) + } + nextStatePromise = statesGenerator.next() + // Observe rejection on immediate exits without replacing the original demand. + void nextStatePromise.catch(() => undefined) + // Only a state the listener still confirms may drive this wait; an invalidated + // sample never becomes the state a timeout reports. + if (!listener.isCurrent(observedState.value.revision)) continue + currentState = observedState.value.state + const action = computeWaitAction(currentState) + if (action === 'continue') continue + if (action === 'input-required' || action === 'idle') { + reason = action + break + } + + const agent = this.ctx.agents.get(sessionId) + if (agent === undefined || this.ctx.sessions.get(sessionId) !== agent.session) continue + if (await waitForIdleOrStateChange(agent, nextStatePromise) === 'state-changed') continue + if (!listener.isCurrent(observedState.value.revision) || this.ctx.agents.get(sessionId) !== agent + || this.ctx.sessions.get(sessionId) !== agent.session) continue + reason = 'idle' + break + } + } catch (error: unknown) { + // A caller cancellation is never a wait outcome; the deadline absorbs only the read + // it cancelled, and any other failure keeps its own error. + if (signal.aborted) throw signal.reason + if (!expired(timer.signal, error)) throw error + } finally { + // Wake/cancel a pending read before asking the generator to return. + listener[Symbol.dispose]() + await nextStatePromise.catch(() => undefined) + await statesGenerator.return(undefined) + } + signal.throwIfAborted() + if (currentState === undefined) throw new RemoteError('session/wait-timeout', 'No Session state arrived before the wait deadline', {}) + const output = await this.historyController.assistantOutput( + sessionId, afterSeq, currentState.cursor, maxMessages, signal, + ) + return { reason, state: currentState, output } + } + + private listen(sessionId: SessionId, signal: AbortSignal): StateListener { + return new StateListener(this.ctx, sessionId, signal, readSignal => this.readState(sessionId, readSignal)) + } + + /** + * @param sessionId - Session to sample. + * @param signal - read cancellation. + * @param retried - whether a live source already redirected this read once. + * @returns one passive state sample. + */ + private async readState(sessionId: SessionId, signal: AbortSignal, retried = false): Promise { + signal.throwIfAborted() + const agent = this.ctx.agents.get(sessionId) + if (agent !== undefined) { + if (agent.session.header.cwd === undefined) rejectNotFound({ kind: 'session', sessionId }) + return { + cursor: agent.session.seq - 1, + active: true, + running: agent.status === 'running', + queue: queueItems(agent), + pendingInput: this.pendingInput(agent.session.id), + } + } + const state = await this.historyController.usingObservation({ sessionId, projection: false }, signal, (observation) => { + // A live source means the Session attached during this read; report its live state + // rather than a live cursor paired with an inactive sample. + if (!retried && observation.source === 'live') return undefined + if (observation.header.cwd === undefined) rejectNotFound({ kind: 'session', sessionId }) + return { + cursor: observation.cursor, + active: false, + running: false, + queue: null, + pendingInput: this.pendingInput(observation.header.id), + } + }) + signal.throwIfAborted() + return state ?? this.readState(sessionId, signal, true) + } + + private pendingInput(sessionId: SessionId): readonly SessionPendingInput[] { + const kinds = new Set() + for (const { event, agentId } of this.ctx.typertGateway.getPendingRemoteEvents()) { + if (String(agentId) !== sessionId) continue + kinds.add(event === 'approval/request' ? 'approval' : event === 'user-questions/request' ? 'question' : 'other') + } + return [...kinds] + } +} + +/** + * @param signal - wait deadline signal. + * @param error - failure raised by the in-flight read. + * @returns whether the deadline expired and cancelled that read. + */ +function expired(signal: AbortSignal, error: unknown): boolean { + const reason = timeoutOf(signal, 'session/wait-timeout') + if (reason === undefined) return false + // Cancellation carries the deadline reason along its cause chain; any other failure does not. + let current: unknown = error + for (let depth = 0; depth < 4 && current instanceof Error; depth++) { + if (current === reason || current.cause === reason) return true + current = current.cause + } + return error === reason +} + +/** Choose the next wait action; check-idle requires the caller's whenIdle and identity checks. */ +function computeWaitAction(state: SessionState): 'input-required' | 'continue' | 'idle' | 'check-idle' { + if (state.pendingInput.length > 0) return 'input-required' + if (state.running) return 'continue' + if (!state.active) return 'idle' + return 'check-idle' +} + +/** Wait for either driver quiescence or the already-armed next state; preserve rejections from both. */ +function waitForIdleOrStateChange( + agent: Agent, + nextStatePromise: Promise>, +): Promise<'idle' | 'state-changed'> { + return Promise.race([ + agent.whenIdle().then(() => 'idle' as const), + nextStatePromise.then(() => 'state-changed' as const), + ]) +} + +function queueItems(agent: Agent): SessionQueuedItem[] { + const item = (message: UserMessage, placement: SessionQueuedItem['placement']): SessionQueuedItem => ({ + id: message.id, + placement, + ...message.source.kind === 'user' && 'rpcId' in message.source ? { rpcId: message.source.rpcId } : {}, + content: message.content as typeof message.content & readonly JsonValue[], + }) + return [ + ...agent.inbox.nextTurn.map(message => item(message, 'queued')), + ...agent.inbox.nextStep.map(message => item(message, message.source.kind === 'user' ? 'steering' : 'context')), + ] +} diff --git a/packages/api/session-controller/src/state/listener.ts b/packages/api/session-controller/src/state/listener.ts new file mode 100644 index 0000000000..15633a7cd8 --- /dev/null +++ b/packages/api/session-controller/src/state/listener.ts @@ -0,0 +1,116 @@ +/** Coalesced Session state observations with Host-local revisions. */ + +import type { Context } from '@deepseek-ai/cordis' +import type { SessionId } from '@deepseek-ai/dsh-session' +import type { SessionState } from '../types.ts' + +/** One complete state with its listener-local revision. */ +export interface VersionedSessionState { state: SessionState; revision: number } + +/** Coalesces Session/Agent invalidations with local revisions; pending events are sampled on reads. */ +export class StateListener implements Disposable { + private readonly disposes: (() => void)[] = [] + private readonly cancellation = new AbortController() + private readonly signal: AbortSignal + private revision = 0 + private resolver = createDeferredSignal() + private closed = false + + /** + * @param ctx - lifecycle notification owner. + * @param target - Session to observe. + * @param signal - caller cancellation. + * @param readState - passive complete-state reader. + */ + constructor( + ctx: Context, target: SessionId, signal: AbortSignal, + private readonly readState: (signal: AbortSignal) => Promise, + ) { + signal.throwIfAborted() + this.signal = AbortSignal.any([signal, this.cancellation.signal]) + const notify = (id: string | undefined): void => { + if (id !== target || this.closed) return + this.revision++ + const resolver = this.resolver + this.resolver = createDeferredSignal() + resolver.resolve() + } + const close = (): void => { this[Symbol.dispose]() } + signal.addEventListener('abort', close, { once: true }) + this.disposes.push(() => { signal.removeEventListener('abort', close) }) + try { + this.disposes.push(ctx.on('session/event', (session) => { notify(session.id) }, { global: true })) + this.disposes.push(ctx.on('session/created', (session) => { notify(session.id) }, { global: true })) + this.disposes.push(ctx.on('session/disposed', (session) => { notify(session.id) }, { global: true })) + this.disposes.push(ctx.on('agent/status', ({ agent }) => { notify(agent.id) }, { global: true })) + this.disposes.push(ctx.on('agent/created', ({ agent }) => { notify(agent.id) }, { global: true })) + this.disposes.push(ctx.on('agent/disposed', ({ agent }) => { notify(agent.id) }, { global: true })) + const dispose = ctx.effect(() => close, 'session-controller.state-listener') + this.disposes.push(() => { void dispose() }) + } catch (error: unknown) { + this[Symbol.dispose]() + throw error + } + } + + /** + * Check whether a completed read still represents the latest invalidation. + * @param revision - revision captured with a completed read. + * @returns whether no intervening invalidation occurred. + */ + isCurrent(revision: number): boolean { return !this.closed && revision === this.revision } + + /** + * Read coalesced state replacements with optional periodic refresh. + * @param refreshMs - optional idle recheck interval; omitted for event-only observation. + * @returns complete state replacements with internal consistency revisions. + */ + async *observeStates(refreshMs?: number): AsyncGenerator { + let lastRevision = -1 + try { + while (!this.closed) { + if (lastRevision === this.revision) { + if (refreshMs === undefined) { + await this.resolver.promise + } else { + let timer: ReturnType | undefined + try { + await Promise.race([ + this.resolver.promise, + new Promise((resolve) => { timer = setTimeout(resolve, refreshMs) }), + ]) + } finally { + clearTimeout(timer) + } + if (this.isCurrent(lastRevision)) { + this.revision++ + const resolver = this.resolver + this.resolver = createDeferredSignal() + resolver.resolve() + } + } + } + if (!this.isCurrent(this.revision)) return + lastRevision = this.revision + const state = await this.readState(this.signal) + if (this.isCurrent(lastRevision)) yield { state, revision: lastRevision } + } + } finally { + this[Symbol.dispose]() + } + } + + [Symbol.dispose](): void { + if (this.closed) return + this.closed = true + this.cancellation.abort() + this.resolver.resolve() + for (const dispose of this.disposes.splice(0).reverse()) dispose() + } +} + +function createDeferredSignal(): { promise: Promise; resolve: () => void } { + let resolve!: () => void + const promise = new Promise((settle) => { resolve = settle }) + return { promise, resolve } +} diff --git a/packages/api/session-controller/src/types.ts b/packages/api/session-controller/src/types.ts index 8c6da77a60..e3e2ea375a 100644 --- a/packages/api/session-controller/src/types.ts +++ b/packages/api/session-controller/src/types.ts @@ -3,7 +3,7 @@ import type {} from '@deepseek-ai/dsh-agent/types' import type { NativeFileApplication } from '@deepseek-ai/dsh-native-command/types' import type { - AttachmentIdType, ImageAttachmentLimits, ImageAttachmentRef, ImageMediaType, + ImageAttachmentLimits, ImageAttachmentRef, ImageMediaType, } from '@deepseek-ai/dsh-attachment' import type { Branded } from '@deepseek-ai/dsh-brand' import type { LlmAttemptId, MessageId } from '@deepseek-ai/dsh-llm/brand' @@ -175,6 +175,10 @@ export const SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS = 240 declare module '@deepseek-ai/dsh-typert-protocol' { interface RemoteErrorDetailsMap { + /** A wait observation ended before a stopping state; the caller should reread. */ + 'session/observation-ended': Record + /** No state arrived before the deadline; a timeout after a state returns its value instead. */ + 'session/wait-timeout': Record 'session/provider-credentials-unavailable': Record 'session/provider-models-unavailable': { readonly provider: string } 'session/model-unavailable': { readonly provider: string; readonly model: string } @@ -329,12 +333,14 @@ export interface SessionPromptValue { /** Durable image read request. */ export interface SessionAttachmentRequest { + /** Gateway permission scope only; neither Session existence nor its image references are checked. */ readonly sessionId: SessionId - readonly attachmentId: AttachmentIdType + readonly attachment: ImageAttachmentRef } /** Durable image read response value. */ export interface SessionAttachmentValue { + /** Supplied reference after ID, format, byte length, and dimensions verification; display fields are preserved. */ readonly attachment: ImageAttachmentRef readonly data: string } @@ -459,8 +465,11 @@ export interface SessionWireEvent { /** One message-aligned backwards-history request. */ export interface SessionPageRequest { readonly address: SessionAddress - /** Inclusive log cut obtained from the corresponding follow opening frame. */ - readonly throughSeq: number + /** + * Inclusive log cut; omission selects the observed log end. A follow opening + * reports the cut it covered so a caller can pin the same point. + */ + readonly throughSeq?: number readonly beforeSeq?: number readonly maxMessages?: number /** Stop at a Turn start after both minima, unless maxMessages or history exhaustion wins. */ @@ -475,6 +484,8 @@ export interface SessionPageRequest { /** One live event request for a durable Session address. */ export interface SessionFollowRequest extends Pick { readonly address: SessionAddress + /** Request background activation; omission leaves the read passive. */ + readonly activate?: boolean /** Include process-local assistant presentation frames for the Web client. */ readonly assistantStream?: true } @@ -569,6 +580,84 @@ export type SessionControlFrame = | { readonly type: 'baseline'; readonly value: SessionControlBaseline } | ({ readonly type: 'projection' } & SessionProjectionUpdate) +/** One pending live-Agent inbox item, preserving placement and content order. */ +export interface SessionQueuedItem { + readonly id: MessageId + readonly placement: 'queued' | 'steering' | 'context' + readonly rpcId?: SessionRequestId + readonly content: readonly JsonValue[] +} + +/** State-owned classification of pending forwarded Remote events. */ +export type SessionPendingInput = 'approval' | 'question' | 'other' + +/** Passive Session state; a missing live Agent has no readable queue. */ +export interface SessionState { + readonly cursor: number + readonly active: boolean + readonly running: boolean + readonly queue: readonly SessionQueuedItem[] | null + /** + * Pending Remote requests sampled when this state was read. A pending change alone does not + * trigger `observeState`; `wait` refreshes on its own interval. + */ + readonly pendingInput: readonly SessionPendingInput[] +} + +/** Session identity for a passive state read or subscription. */ +export interface SessionStateRequest { + readonly sessionId: SessionId +} + +/** Wait bounds and assistant output window; timeout omission uses the fixed 30-second default. */ +export interface SessionWaitRequest extends SessionStateRequest { + readonly timeoutMs?: number + /** Exclusive output cursor; omission includes all available assistant records. */ + readonly afterSeq?: number + /** Positive assistant-record limit; omission uses the history message budget. */ + readonly maxMessages?: number +} + +/** Assistant messages after afterSeq through the stopping state's cursor, newest first. */ +export interface SessionWaitOutput { + readonly records: readonly SessionHistoryRecord[] + /** More eligible assistant messages exist in the selected interval. */ + readonly truncated: boolean +} + +/** A stopping condition, the last complete passive state and its bounded assistant output. */ +export interface SessionWaitValue { + readonly reason: 'idle' | 'input-required' | 'timeout' + readonly state: SessionState + readonly output: SessionWaitOutput +} + +/** + * One `session.events` page (or its deprecated `page` alias) with its inclusive cut: + * the supplied `throughSeq`, otherwise the log end it was read at. + */ +export interface SessionEventsPage extends SessionPage { + readonly cursor: number +} + +/** Address for a passive event subscription. */ +export interface SessionObserveEventRequest { + readonly address: SessionAddress +} + +/** Readiness confirms subscription only; event continuity starts with the first delivered event. */ +export type SessionEventFrame = + | { readonly type: 'ready' } + | SessionEventEntry + +/** One sparse per-key replacement; different keys can share a seq. */ +export type SessionProjectionChange = { readonly type: 'projection' } & Omit + +/** Subscription readiness without a baseline, followed by per-key changes. */ +export type SessionProjectionFrame = + | { readonly type: 'ready' } + | SessionProjectionChange + declare module '@deepseek-ai/cordis' { interface Events { /** diff --git a/packages/api/session-controller/src/web/controller.ts b/packages/api/session-controller/src/web/controller.ts new file mode 100644 index 0000000000..7e849e4cca --- /dev/null +++ b/packages/api/session-controller/src/web/controller.ts @@ -0,0 +1,78 @@ +/** Web opening aggregation over one observation and a shared transforming buffer. */ + +import type { Context } from '@deepseek-ai/cordis' +import { remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' +import type { SessionObservation } from '@deepseek-ai/dsh-session-query' +import type { HistoryController } from '../history/controller.ts' +import { addressId, rejectNotFound } from '../history.ts' +import { EventListener, ListenerBuffer } from '../history/listener.ts' +import { history, projections, resolveHistoryRequest, validateObservationAddress } from '../history/controller.ts' +import type { SessionFollowFrame, SessionFollowRequest } from '../types.ts' + +/** Combines opening data and consumes transformed listener output from one queue. */ +export class WebController { + + /** + * @param ctx - Host context carrying Session queries and identity projections. + * @param historyController - passive reading and listener construction. + * @param promote - background activation requested before an opening snapshot is delivered. + */ + constructor( + private readonly ctx: Context, + private readonly historyController: HistoryController, + private readonly promote: (observation: SessionObservation) => void, + ) {} + + /** + * Open a history snapshot and follow uncovered history and assistant notifications. + * @param request - Session identity, page budget, assistant output and optional activation (default false). + * @param signal - cancellation for opening and streaming. + * @returns an opening snapshot followed by uncovered queued increments. + */ + async *follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable { + const sessionId = addressId(request.address) + const spec = resolveHistoryRequest(request) + using queue = new ListenerBuffer(this.ctx, signal) + using listener = new EventListener(this.ctx, sessionId, signal, queue) + const streams = this.historyController.streamsListener + using assistantListener = request.assistantStream === true + ? streams.bind(sessionId, signal, queue) + : undefined + using observation = await this.historyController.usingObservation({ sessionId, projection: true }, signal) + .catch((error: unknown) => { + if (remoteErrorOf(error)?.code === 'session/not-found') rejectNotFound(request.address) + throw error + }) + validateObservationAddress(request.address, observation) + let opening: SessionFollowFrame = { + type: 'snapshot', + header: { ...observation.header }, + projections: projections(observation), + ...history(observation, spec), + } + listener.setCursor(opening.cursor) + if (assistantListener !== undefined) { + const { baseline: assistantStream, ordinal } = assistantListener.snapshot() + opening = { ...opening, assistantStream } + assistantListener.setOrdinalCut(ordinal) + } + // Increments come from the queue, so the opening ends this lease in every branch; + // activation continues on its own retained lease. Promotion starts before the opening is + // delivered, so a consumer that stops after the snapshot still gets the activation it asked for. + if (request.activate === true && !signal.aborted + && observation.header.origin !== 'subagent' && observation.source === 'prepared') { + const promotion = observation.retain() + observation[Symbol.dispose]() + try { + this.promote(promotion) + } catch (error: unknown) { + promotion[Symbol.dispose]() + throw error + } + } else { + observation[Symbol.dispose]() + } + yield opening + yield* queue.items() + } +} diff --git a/packages/api/session-controller/tests/agent.host.spec.ts b/packages/api/session-controller/tests/agent.host.spec.ts index 76380d69fb..aea96d5e04 100644 --- a/packages/api/session-controller/tests/agent.host.spec.ts +++ b/packages/api/session-controller/tests/agent.host.spec.ts @@ -6,7 +6,7 @@ import { Context } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import { agentPresetProjectionDefinition } from '@deepseek-ai/dsh-agent-preset-registry' -import SessionStore, { SESSION_FORMAT_VERSION, SessionLogOffset, SessionId } from '@deepseek-ai/dsh-session' +import SessionStore, { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session' import type { SessionHeader } from '@deepseek-ai/dsh-session' import { SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence' import type { SessionObservation } from '@deepseek-ai/dsh-session-query' @@ -15,8 +15,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { ApiSessionAgentController, ApiSessionCwdConflict, - ApiSessionNotFound, - inspectApiSession, } from '../src/agent.ts' import { installSessionReadTestServices, testSessionPersistence } from './test-remote.ts' @@ -83,61 +81,6 @@ describe('ApiSession identity failures', () => { expect(new ApiSessionCwdConflict(SessionId('wrong-cwd'), '/wanted', '/existing').message) .toContain('belongs to "/existing"') }) - - it('maps absent and cwd-less point observations to not found', async () => { - const ctx = new Context() - roots.push(ctx) - await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) - await expect(inspectApiSession(ctx, SessionId('missing'))) - .rejects.toBeInstanceOf(ApiSessionNotFound) - - const inspect = vi.fn(() => Promise.resolve(undefined)) - const stat = vi.fn(() => Promise.resolve(undefined)) - const disposeMissing = providePersistence(ctx, { - list: () => Promise.resolve([]), - stat, - inspect, - }) - await expect(inspectApiSession(ctx, SessionId('missing'))).rejects.toBeInstanceOf(ApiSessionNotFound) - // Absence is decided by the stat preflight; the log itself is never opened. - expect(stat).toHaveBeenCalledOnce() - expect(inspect).not.toHaveBeenCalled() - disposeMissing() - - const listed = header('cwd-less-catalog', null) - const disposeListed = providePersistence(ctx, { - list: () => Promise.resolve([listed]), - inspect: () => Promise.resolve({ meta: listed, events: [] }), - }) - await expect(inspectApiSession(ctx, listed.id)).rejects.toBeInstanceOf(ApiSessionNotFound) - disposeListed() - - const catalog = header('cwd-less-inspect') - const inspected = header('cwd-less-inspect', null) - providePersistence(ctx, { - list: () => Promise.resolve([catalog]), - inspect: () => Promise.resolve({ meta: inspected, events: [] }), - }) - await expect(inspectApiSession(ctx, catalog.id)).rejects.toBeInstanceOf(ApiSessionNotFound) - }) - - it('forwards an explicit inspection signal', async () => { - const ctx = new Context() - roots.push(ctx) - await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) - const meta = header('signalled-inspection') - const inspect = vi.fn(() => Promise.resolve({ meta, inheritedEventCount: SessionLogOffset(0), events: [] })) - providePersistence(ctx, { - list: () => Promise.resolve([meta]), - inspect, - }) - const signal = new AbortController().signal - - await expect(inspectApiSession(ctx, meta.id, signal)).resolves.toEqual({ meta, inheritedEventCount: SessionLogOffset(0), events: [] }) - expect(inspect).toHaveBeenCalledWith(meta.id, signal) - }) }) describe('ApiSession Agent lookup and recovery', () => { diff --git a/packages/api/session-controller/tests/client-contract.client.spec.ts b/packages/api/session-controller/tests/client-contract.client.spec.ts index b2abdc2dc2..20a0f08065 100644 --- a/packages/api/session-controller/tests/client-contract.client.spec.ts +++ b/packages/api/session-controller/tests/client-contract.client.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, expectTypeOf, it, vi } from 'vitest' import type { PromptContentPart as AttachmentPromptContentPart } from '@deepseek-ai/dsh-attachment/types' -import { SessionSeq, type SessionSeqCursor } from '@deepseek-ai/dsh-session/types' +import { SessionSeq, type SessionId, type SessionSeqCursor } from '@deepseek-ai/dsh-session/types' import { MutableSessionEventSource, type SessionAssistantSettlementEntry, type SessionLiveEventEntry, type SessionTransientEventEntry, @@ -11,6 +11,7 @@ import type { ProjectionsBaseline } from '../src/client/sessions/projection-stor import { ProjectionValueStore } from '../src/client/sessions/projection-store.ts' import type { PromptContentPart as SessionPromptContentPart, SessionPageRequest } from '../src/types.ts' import { ev, plainTurn } from './event-script.client.ts' +import { history, pageRule } from './remote/session.client.ts' type RenameSuccess = Extract>, { readonly ok: true }> @@ -70,7 +71,21 @@ describe('Client Session contracts', () => { expectTypeOf().toEqualTypeOf() expectTypeOf().parameter(2).toEqualTypeOf() expectTypeOf().toEqualTypeOf() - expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf() + }) + + it('returns the current page cursor when throughSeq is omitted and preserves explicit cuts', async () => { + const address = { kind: 'session', sessionId: 'page-fixture' as SessionId } as const + const rule = pageRule(history(plainTurn(SessionSeq(0), 1, 'question', 'answer'))) + const current = await rule({ address }) + expect(current).toMatchObject({ ok: true, value: { cursor: 5, hasMore: false } }) + const cut = await rule({ address, throughSeq: 2 }) + expect(cut).toMatchObject({ ok: true, value: { cursor: 2, hasMore: false } }) + if (!cut.ok) throw new Error('expected a successful history page') + expect(cut.value.records.map(record => record.event.seq)).toEqual([0, 1, 2]) + await expect(rule({ address, throughSeq: -1 })).resolves.toEqual({ + ok: true, value: { cursor: -1, records: [], hasMore: false }, + }) }) it('keeps its text and image prompt parts identical to attachment intake', () => { diff --git a/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts b/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts index a23917b312..f575583063 100644 --- a/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts +++ b/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts @@ -6,19 +6,19 @@ import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent, Inbox } from '@deepseek-ai/dsh-agent' import { AttachmentError, AttachmentId } from '@deepseek-ai/dsh-attachment' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' -import { createAssistantMessage, createUserMessage, MessageId } from '@deepseek-ai/dsh-llm' +import { createUserMessage, MessageId } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' import SessionStore, { - SESSION_FORMAT_VERSION, Session, SessionId, SessionLogOffset, SessionSeq, + Session, SessionId, SessionLogOffset, } from '@deepseek-ai/dsh-session' -import type { SessionEvent, SessionHeader, UserMessage } from '@deepseek-ai/dsh-session' +import type { UserMessage } from '@deepseek-ai/dsh-session' import { snapshotSubagentDescriptor, SUBAGENT_DESCRIPTOR_VERSION } from '@deepseek-ai/dsh-subagent' import { subagentIdentityProjectionDefinition } from '@deepseek-ai/dsh-subagent/src/projection.ts' import { describe, expect, it, vi } from 'vitest' import { ApiSessionAgentController } from '../src/agent.ts' import { SessionCommandController } from '../src/commands.ts' import { unsupportedModel, createInboxStub } from '@deepseek-ai/dsh-agent-loop-testkit' -import { installSessionReadTestServices, testSessionPersistence } from './test-remote.ts' +import { installSessionReadTestServices } from './test-remote.ts' declare module '@deepseek-ai/dsh-llm' { interface MessageSourceMap { @@ -324,259 +324,68 @@ describe('Session queue commands', () => { }) }) -function imageRef(id: string): ImageAttachmentRef { - return { - attachmentId: AttachmentId(id), - mediaType: 'image/png', - bytes: 1, - width: 1, - height: 1, - } -} - -function event(type: string, seq: SessionSeq, data: unknown): SessionEvent { - const surface = ['user/message', 'system/message', 'developer/message', 'tool/result'].includes(type) - return { type, seq, time: seq + 1, data, ...surface ? { surfaceOp: 'append' } : {} } as SessionEvent -} - -async function persistedController( - events: SessionEvent[], - readImage: (ref: ImageAttachmentRef) => Promise<{ ref: ImageAttachmentRef; data: Uint8Array }>, -): Promise<{ ctx: Context; controller: SessionCommandController; sessionId: SessionId }> { - const ctx = new Context() - await ctx.plugin(SessionStore) - const sessionId = SessionId('cold-attachment') - const meta: SessionHeader = { - version: SESSION_FORMAT_VERSION, - id: sessionId, - createdAt: 1, - cwd: '/workspace', - isSeeded: false, - } - ctx.provide('sessionPersistence', testSessionPersistence(ctx, { - list: () => Promise.resolve([meta]), - inspect: () => Promise.resolve({ - meta, - inheritedEventCount: SessionLogOffset(0), - events, - }), - }) as never) - installSessionReadTestServices(ctx) - ctx.provide('attachments', { readImage } as never) - const agents = { resolveAgent: vi.fn() } as unknown as ApiSessionAgentController - return { ctx, controller: new SessionCommandController(ctx, agents, '/workspace'), sessionId } -} - -describe('Session attachment authorization', () => { - it.each([ - ['system/message', 'message'], ['developer/message', 'message'], ['tool/result', 'message'], - ['team/message/queued', 'message'], ['tool/ptc-dispatch', 'content'], - ['compaction/summary', 'summary'], ['compaction/summary', 'rawOutput'], - ] as const)('reads the declared %s %s content without rewriting it', async (type, field) => { - const ref = imageRef(`${type}-${field}`) - const content = [{ type: 'image', attachment: ref }] - const message = type === 'team/message/queued' ? { content } - : type === 'tool/result' ? { - id: 'declared-message', role: 'tool', source: { kind: 'tool', callId: 'declared-call' }, - toolCallId: 'declared-call', isError: false, content, - } : { - id: 'declared-message', role: type === 'developer/message' ? 'developer' : 'system', - source: { kind: 'system-prompt' }, content, - } - const data = field === 'message' ? { message } : { [field]: content } - const events = [event(type, SessionSeq(0), data)] - const saved = JSON.stringify(events) - const readImage = vi.fn((image: ImageAttachmentRef) => Promise.resolve({ ref: image, data: Uint8Array.of(1) })) - const fixture = await persistedController(events, readImage) +describe('Session attachment reads', () => { + it.each(['commands-session', 'other-session', 'missing-session'])('reads a supplied reference without looking up history for %s', async (id) => { + const { ctx, controller, agent, resolveAgent } = await commandHarness() + const ref: ImageAttachmentRef = { + attachmentId: AttachmentId(`sha256:${'ab'.repeat(32)}`), + mediaType: 'image/png', bytes: 2, width: 1, height: 1, + } + agent.session.append('user/message', createUserMessage({ + content: [{ type: 'image', attachment: ref }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + const readImage = vi.fn(() => Promise.resolve({ ref, data: Uint8Array.of(1, 2) })) + ctx.provide('attachments', { readImage } as never) + const failHistory = (): never => { throw new Error('image reads must not access Session history') } + const get = vi.spyOn(ctx.sessions, 'get').mockImplementation(failHistory) + const snapshot = vi.spyOn(agent.session, 'snapshotEvents').mockImplementation(failHistory) + const observe = vi.spyOn(ctx.sessionQuery, 'observeSession').mockImplementation(failHistory) try { - await expect(fixture.controller.attachment({ sessionId: fixture.sessionId, attachmentId: ref.attachmentId })) - .resolves.toEqual({ attachment: ref, data: 'AQ==' }) + await expect(controller.attachment({ sessionId: SessionId(id), attachment: ref })) + .resolves.toEqual({ attachment: ref, data: 'AQI=' }) expect(readImage).toHaveBeenCalledExactlyOnceWith(ref) - expect(JSON.stringify(events)).toBe(saved) + expect(get).not.toHaveBeenCalled() + expect(snapshot).not.toHaveBeenCalled() + expect(observe).not.toHaveBeenCalled() + expect(resolveAgent).not.toHaveBeenCalled() } finally { - await fixture.ctx.fiber.dispose() + get.mockRestore() + snapshot.mockRestore() + observe.mockRestore() + await ctx.fiber.dispose() } }) - it('does not authorize an attachment through malformed inbox entries', async () => { - const ref = imageRef('not-referenced') - for (const value of [undefined, null, {}, [null, 1, []]]) { - const readImage = vi.fn((image: ImageAttachmentRef) => Promise.resolve({ ref: image, data: Uint8Array.of(1) })) - const fixture = await persistedController([event('agent/inbox/spliced', SessionSeq(0), { inserted: value })], readImage) - try { - await expect(fixture.controller.attachment({ sessionId: fixture.sessionId, attachmentId: ref.attachmentId })) - .rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'ATTACHMENT_NOT_REFERENCED' } }) - expect(readImage).not.toHaveBeenCalled() - } finally { - await fixture.ctx.fiber.dispose() - } - } - }) - - it('ignores unrelated fields of a known message event and its content blocks', async () => { - const ref = imageRef('not-a-content-occurrence') - const content = [{ type: 'image', attachment: ref }] - const stored = event('user/message', SessionSeq(0), { - id: 'metadata', role: 'user', source: { kind: 'user' }, - content: [{ type: 'text', text: 'no image', content }, { type: 'plugin:vendor', data: { content }, content }], - message: { content }, inserted: [{ content }], - }) - const readImage = vi.fn((image: ImageAttachmentRef) => Promise.resolve({ ref: image, data: Uint8Array.of(1) })) - const fixture = await persistedController([stored], readImage) - try { - await expect(fixture.controller.attachment({ sessionId: fixture.sessionId, attachmentId: ref.attachmentId })) - .rejects.toMatchObject({ code: 'session/attachment-invalid' }) - expect(readImage).not.toHaveBeenCalled() - } finally { - await fixture.ctx.fiber.dispose() - } - }) - - it.each(['external/image-record', 'session/title-llm-request'])('denies attachment access from %s without an attachment carrier', async (type) => { - const ref = imageRef('opaque-event-image') - const content = [{ type: 'image', attachment: ref }] - const opaque = { ...event(type, SessionSeq(0), { - content, message: { content }, inserted: [{ content }], messages: [{ content }], - stream: [{ type: 'chunk', time: 1, chunk: { type: 'block-end', index: 0, block: content[0] } }], - }), ignorable: true as const } - const readImage = vi.fn((image: ImageAttachmentRef) => Promise.resolve({ ref: image, data: Uint8Array.of(1) })) - const fixture = await persistedController([opaque], readImage) - try { - await expect(fixture.controller.attachment({ sessionId: fixture.sessionId, attachmentId: ref.attachmentId })) - .rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'ATTACHMENT_NOT_REFERENCED' } }) - expect(readImage).not.toHaveBeenCalled() - } finally { - await fixture.ctx.fiber.dispose() - } - }) - - it('finds references in direct, message, inserted, and streamed content', async () => { - const direct = imageRef('direct') - const message = imageRef('message') - const inserted = imageRef('inserted') - const streamed = imageRef('streamed') - const events: SessionEvent[] = [ - { ...event('user/message', SessionSeq(0), { - id: 'direct', role: 'user', source: { kind: 'user' }, - content: [null, [], { type: 'text', text: 'none' }, { type: 'image', attachment: direct }], - }), ignorable: true as const }, - { - type: 'assistant/message', seq: SessionSeq(1), time: 2, surfaceOp: 'append', - data: { - turn: 1, - step: 1, - stream: [], - message: createAssistantMessage({ - content: [{ type: 'image', attachment: message }], - source: { provider: 'fixture', model: 'fixture' }, - }), - }, - }, - event('agent/inbox/spliced', SessionSeq(2), { - target: 'next-turn', - start: 0, - inserted: [null, 1, [], { content: [] }, createUserMessage({ - content: [{ type: 'image', attachment: inserted }], - source: { kind: 'user' }, - })], - }), - event('assistant/attempt', SessionSeq(3), { - turn: 1, - step: 1, - stream: [ - { - type: 'chunk', - time: 3, - chunk: { type: 'block-start', index: 0, blockType: 'text' }, - }, - { - type: 'chunk', - time: 3, - chunk: { type: 'block-end', index: 0, block: { type: 'text', text: '' } }, - }, - ], - }), - event('assistant/attempt', SessionSeq(4), { - turn: 1, - step: 1, - stream: [{ - type: 'chunk', - time: 4, - chunk: { type: 'block-end', index: 0, block: { type: 'image', attachment: streamed } }, - }], - }), - ] - const readImage = vi.fn((ref: ImageAttachmentRef) => Promise.resolve({ ref, data: Uint8Array.of(1) })) - const { ctx, controller, sessionId } = await persistedController(events, readImage) - - for (const ref of [direct, message, inserted, streamed]) { - await expect(controller.attachment({ sessionId, attachmentId: ref.attachmentId })) - .resolves.toEqual({ attachment: ref, data: 'AQ==' }) - } - expect(readImage).toHaveBeenCalledTimes(4) - await ctx.fiber.dispose() - }) - - it('maps missing persistence identities and attachment backend failures', async () => { - const noPersistence = new Context() - await noPersistence.plugin(SessionStore) - installSessionReadTestServices(noPersistence) - const noPersistenceController = new SessionCommandController( - noPersistence, - { resolveAgent: vi.fn() } as unknown as ApiSessionAgentController, - '/workspace', - ) - await expectFailure(noPersistenceController.attachment({ - sessionId: SessionId('missing'), attachmentId: AttachmentId('att'), - }), 'session/not-found') - - const missing = new Context() - await missing.plugin(SessionStore) - missing.provide('sessionPersistence', testSessionPersistence(missing, { - list: () => Promise.resolve([]), - inspect: vi.fn(), - }) as never) - installSessionReadTestServices(missing) - const missingController = new SessionCommandController( - missing, - { resolveAgent: vi.fn() } as unknown as ApiSessionAgentController, - '/workspace', - ) - await expectFailure(missingController.attachment({ - sessionId: SessionId('missing'), attachmentId: 'att' as never, - }), 'session/not-found') - - for (const thrown of [ - new AttachmentError('stored image is unavailable', 'ATTACHMENT_NOT_FOUND'), - new Error('backend offline'), - ]) { - const ref = imageRef(`failure-${thrown.name}`) - const fixture = await persistedController( - [event('user/message', SessionSeq(0), { id: 'failure', role: 'user', source: { kind: 'user' }, content: [{ type: 'image', attachment: ref }] })], - () => Promise.reject(thrown), - ) - await expectFailure(fixture.controller.attachment({ - sessionId: fixture.sessionId, - attachmentId: ref.attachmentId, - }), thrown instanceof AttachmentError ? 'session/attachment-invalid' : 'gateway/internal') - await fixture.ctx.fiber.dispose() - } - }) - - it('maps a cold observation failure to an internal authorization error', async () => { + it.each([ + 'INVALID_ATTACHMENT_REF', 'ATTACHMENT_NOT_FOUND', 'ATTACHMENT_CORRUPT', 'ATTACHMENT_READ_FAILED', + ] as const)('returns %s as an explicit attachment failure', async (reason) => { const ctx = new Context() - await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) - vi.spyOn(ctx.sessionQuery, 'observeSession').mockRejectedValue(new Error('storage offline')) - const controller = new SessionCommandController( - ctx, - { resolveAgent: vi.fn() } as unknown as ApiSessionAgentController, - '/workspace', - ) + const readImage = vi.fn(() => Promise.reject(new AttachmentError('Stored image is unavailable.', reason))) + ctx.provide('attachments', { readImage } as never) + const controller = new SessionCommandController(ctx, new ApiSessionAgentController(ctx), '/workspace') + try { + await expect(controller.attachment({ + sessionId: SessionId('unopened'), + attachment: { attachmentId: AttachmentId('requested'), mediaType: 'image/png', bytes: 1, width: 1, height: 1 }, + })) + .rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason } }) + } finally { + await ctx.fiber.dispose() + } + }) - await expectFailure(controller.attachment({ - sessionId: SessionId('unreadable'), attachmentId: AttachmentId('att'), - }), 'gateway/internal') - await ctx.fiber.dispose() + it('contains unexpected backend failures without exposing internal details', async () => { + const ctx = new Context() + ctx.provide('attachments', { readImage: () => Promise.reject(new Error('/private/storage failed')) } as never) + const controller = new SessionCommandController(ctx, new ApiSessionAgentController(ctx), '/workspace') + try { + await expect(controller.attachment({ + sessionId: SessionId('unopened'), + attachment: { attachmentId: AttachmentId('requested'), mediaType: 'image/png', bytes: 1, width: 1, height: 1 }, + })) + .rejects.toMatchObject({ code: 'gateway/internal', message: 'Unable to read image attachment.', details: {} }) + } finally { + await ctx.fiber.dispose() + } }) }) diff --git a/packages/api/session-controller/tests/controller.host.spec.ts b/packages/api/session-controller/tests/controller.host.spec.ts index 789caf78d5..664c4f9244 100644 --- a/packages/api/session-controller/tests/controller.host.spec.ts +++ b/packages/api/session-controller/tests/controller.host.spec.ts @@ -3,7 +3,8 @@ import { Context } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' -import { createUserMessage } from '@deepseek-ai/dsh-llm' +import { LlmAttemptId, createUserMessage } from '@deepseek-ai/dsh-llm' +import type TypertGatewayService from '@deepseek-ai/dsh-api-gateway' import SessionStore, { SESSION_FORMAT_VERSION, SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session' import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' @@ -22,6 +23,75 @@ describe('SessionController facade', () => { expect(SessionController.inject).not.toContain('tools') }) + it('keeps assistant stream observation live while list initialization awaits', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await mountAgentLoopTestDependencies(ctx) + await mountAgentLoopTestHarness(ctx) + const gateway: Partial = { getPendingRemoteEvents: () => [] } + ctx.provide('typertGateway', gateway as TypertGatewayService) + const session = ctx.sessions.create(SessionId('assistant-interleave'), { meta: { cwd: '/workspace' } }) + const partial: Partial = { id: session.id, session, status: 'running', ctx } + const agent = partial as Agent + const entered = Promise.withResolvers() + const gate = Promise.withResolvers() + const original = ctx.sessionProjections.register.bind(ctx.sessionProjections) + let first = true + vi.spyOn(ctx.sessionProjections, 'register').mockImplementation(async (...args: Parameters) => { + if (first) { + first = false + entered.resolve(undefined) + await gate.promise + } + return original(...args) + }) + const mounting = createSessionTestController(ctx, defaults) + await entered.promise + // An Agent start racing the list read must not be lost before the controller publishes. + ctx.emit('agent/assistant-stream', { + agent, + frame: { type: 'start', attemptId: LlmAttemptId('boot-attempt'), revision: 1, turn: 1, step: 1 }, + }) + gate.resolve(undefined) + const controller = await mounting + const frames = controller.follow({ + address: { kind: 'session', sessionId: session.id }, assistantStream: true, + }, new AbortController().signal)[Symbol.asyncIterator]() + await expect(frames.next()).resolves.toMatchObject({ + value: { type: 'snapshot', assistantStream: { revision: 1 } }, + }) + await frames.return?.(undefined) + }) + + it('serves passive reads, subscriptions and waits through its plain controllers', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await mountAgentLoopTestDependencies(ctx) + await mountAgentLoopTestHarness(ctx) + const gateway: Partial = { getPendingRemoteEvents: () => [] } + ctx.provide('typertGateway', gateway as TypertGatewayService) + const controller = await createSessionTestController(ctx, defaults) + const sessionId = SessionId('passive-facade') + ctx.sessions.create(sessionId, { meta: { cwd: '/workspace' } }) + const address = { kind: 'session' as const, sessionId } + const signal = new AbortController().signal + + await expect(controller.events({ address }, signal)).resolves.toMatchObject({ records: [], hasMore: false }) + const historyFrames = controller.observeEvent({ address }, signal)[Symbol.asyncIterator]() + await expect(historyFrames.next()).resolves.toMatchObject({ value: { type: 'ready' } }) + await historyFrames.return?.(undefined) + const projectionFrames = controller.observeProjections({ sessionId }, signal)[Symbol.asyncIterator]() + await expect(projectionFrames.next()).resolves.toMatchObject({ value: { type: 'ready' } }) + await projectionFrames.return?.(undefined) + await expect(controller.state({ sessionId }, signal)) + .resolves.toMatchObject({ active: false, running: false, queue: null }) + const stateFrames = controller.observeState({ sessionId }, signal)[Symbol.asyncIterator]() + await expect(stateFrames.next()).resolves.toMatchObject({ value: { active: false } }) + await stateFrames.return?.(undefined) + await expect(controller.wait({ sessionId, afterSeq: -1, maxMessages: 10, timeoutMs: 50 }, signal)) + .resolves.toMatchObject({ reason: 'idle' }) + }) + it('owns Host service methods and publishes Agent lifecycle projections', async () => { const ctx = new Context() onTestFinished(() => ctx.fiber.dispose()) @@ -63,13 +133,6 @@ describe('SessionController facade', () => { ctx.on('api-session/error', failure) ctx.on('api-session/activity', activity) - await expect(controller.inspect(sessionId)).resolves.toEqual({ - meta: header, - inheritedEventCount: SessionLogOffset(0), - events, - }) - expect(inspect).toHaveBeenCalledOnce() - const session = ctx.sessions.create(sessionId, { meta: header }) const agent = { id: sessionId, @@ -91,12 +154,6 @@ describe('SessionController facade', () => { await expect(resolveUploadAgent(sessionId)).rejects.toBe(activationError) await expect(controller.resolveAgent(sessionId)).resolves.toEqual({ agent }) - await expect(controller.inspect(sessionId)).resolves.toEqual({ - meta: header, - inheritedEventCount: SessionLogOffset(0), - events, - }) - expect(inspect).toHaveBeenCalledOnce() ctx.emit('agent/status', { agent, status: 'running' }) ctx.emit('agent/error', { agent, turn: 1, step: 0, error: new Error('fixture failure') }) session.append('user/message', createUserMessage({ @@ -177,6 +234,7 @@ describe('SessionController facade', () => { const abort = new AbortController() const iterator = controller.follow({ address: { kind: 'session', sessionId }, + activate: true, }, abort.signal)[Symbol.asyncIterator]() await expect(iterator.next()).resolves.toMatchObject({ value: { type: 'snapshot' } }) @@ -229,6 +287,7 @@ describe('SessionController facade', () => { }) const iterator = controller.follow({ address: { kind: 'session', sessionId }, + activate: true, }, new AbortController().signal)[Symbol.asyncIterator]() await expect(iterator.next()).resolves.toMatchObject({ value: { type: 'snapshot' } }) diff --git a/packages/api/session-controller/tests/event-script.client.ts b/packages/api/session-controller/tests/event-script.client.ts index 0e7eaed7d1..0d9eea291b 100644 --- a/packages/api/session-controller/tests/event-script.client.ts +++ b/packages/api/session-controller/tests/event-script.client.ts @@ -8,7 +8,7 @@ import type { ContentBlock } from '@deepseek-ai/dsh-llm/types' import type { SessionEvent } from '@deepseek-ai/dsh-session/types' import type { SessionEventEntry, - SessionPage, + SessionEventsPage, SessionWireEvent, } from '../src/types.ts' @@ -185,8 +185,9 @@ export function entries(events: readonly SessionEvent[]): SessionEventEntry[] { } /** Build one view-less history response value. */ -export function historyValue(events: readonly SessionEvent[], hasMore = false): SessionPage { +export function historyValue(events: readonly SessionEvent[], hasMore = false): SessionEventsPage { return { + cursor: events.at(-1)?.seq ?? -1, records: entries(events), hasMore, } diff --git a/packages/api/session-controller/tests/history-controller.host.spec.ts b/packages/api/session-controller/tests/history-controller.host.spec.ts new file mode 100644 index 0000000000..e3592ddbad --- /dev/null +++ b/packages/api/session-controller/tests/history-controller.host.spec.ts @@ -0,0 +1,171 @@ +import { Context } from '@deepseek-ai/cordis' +import { createMessage } from '@deepseek-ai/dsh-llm' +import SessionStore, { SessionId, SessionSeq } from '@deepseek-ai/dsh-session' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { HistoryController } from '../src/history/controller.ts' +import { WebController } from '../src/web/controller.ts' +import { installSessionReadTestServices } from './test-remote.ts' + +const roots: Context[] = [] +const aborters: AbortController[] = [] +afterEach(async () => { + for (const abort of aborters.splice(0)) abort.abort() + await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) + vi.restoreAllMocks() +}) +async function fixture() { + const ctx = new Context() + roots.push(ctx) + await ctx.plugin(SessionStore) + installSessionReadTestServices(ctx) + const history = new HistoryController(ctx) + const web = new WebController(ctx, history, (observation) => { observation[Symbol.dispose]() }) + const session = ctx.sessions.create(SessionId('history-target'), { meta: { cwd: '/history-test' } }) + const abort = new AbortController() + aborters.push(abort) + const address = { kind: 'session' as const, sessionId: session.id } + return { ctx, history, web, session, abort, address } +} + +describe('HistoryController passive reads', () => { + it('subscribes without reading an Observation and emits later durable events', async () => { + const f = await fixture() + const observe = vi.spyOn(f.ctx.sessionQuery, 'observeSession') + const stream = f.history.observeEvent({ address: f.address }, f.abort.signal)[Symbol.asyncIterator]() + expect(await stream.next()).toEqual({ done: false, value: { type: 'ready' } }) + expect(observe).not.toHaveBeenCalled() + f.session.append('turn/start', { turn: 1 }) + expect(await stream.next()).toMatchObject({ value: { type: 'event', event: { seq: 0 } } }) + f.abort.abort() + expect(await stream.next()).toMatchObject({ done: true }) + }) + + it('subscribes to sparse projection changes without an Observation', async () => { + const f = await fixture() + const observe = vi.spyOn(f.ctx.sessionQuery, 'observeSession') + let receive: Parameters[0] | undefined + const dispose = vi.fn() + vi.spyOn(f.ctx.sessionProjections, 'onChanged').mockImplementation((callback) => { + receive = callback + return dispose + }) + const stream = f.history.observeProjections({ sessionId: f.session.id }, f.abort.signal)[Symbol.asyncIterator]() + expect(await stream.next()).toMatchObject({ value: { type: 'ready' } }) + receive?.(f.session, 'title', 'new title', SessionSeq(0)) + expect(await stream.next()).toMatchObject({ value: { type: 'projection', key: 'title', value: 'new title', seq: 0 } }) + expect(observe).not.toHaveBeenCalled() + f.abort.abort() + expect(await stream.next()).toMatchObject({ done: true }) + expect(dispose).toHaveBeenCalledOnce() + }) + + it('reads newest assistant messages within the exclusive/inclusive interval and detects actual truncation', async () => { + const f = await fixture() + f.session.append('turn/start', { turn: 1 }) + const first = f.session.append('assistant/message', { + turn: 1, step: 1, + message: createMessage({ role: 'assistant', content: [{ type: 'text', text: 'first' }], source: { kind: 'model', provider: 'p', model: 'm' } }), + stream: [], + }, { surfaceOp: 'append' }) + const second = f.session.append('assistant/message', { + turn: 1, step: 2, + message: createMessage({ role: 'assistant', content: [{ type: 'text', text: 'second' }], source: { kind: 'model', provider: 'p', model: 'm' } }), + stream: [], + }, { surfaceOp: 'append' }) + f.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + const observe = vi.spyOn(f.ctx.sessionQuery, 'observeSession') + const all = await f.history.assistantOutput(f.session.id, -1, 3, 2, f.abort.signal) + expect(all.records.map(record => record.event.seq)).toEqual([second.seq, first.seq]) + expect(all.truncated).toBe(false) + const limited = await f.history.assistantOutput(f.session.id, -1, 3, 1, f.abort.signal) + expect(limited.records.map(record => record.event.seq)).toEqual([second.seq]) + expect(limited.truncated).toBe(true) + const interval = await f.history.assistantOutput(f.session.id, first.seq, second.seq, 2, f.abort.signal) + expect(interval.records.map(record => record.event.seq)).toEqual([second.seq]) + expect(observe).toHaveBeenCalledWith(f.session.id, { signal: f.abort.signal, projectionMode: 'none' }) + await expect(f.history.assistantOutput(f.session.id, -1, 9, 2, f.abort.signal)).rejects.toMatchObject({ code: 'gateway/internal' }) + }) + + it('reads at the observed log end when throughSeq is omitted', async () => { + const f = await fixture() + f.session.append('turn/start', { turn: 1 }) + f.session.append('assistant/message', { + turn: 1, step: 1, + message: createMessage({ role: 'assistant', content: [{ type: 'text', text: 'latest' }], source: { kind: 'model', provider: 'p', model: 'm' } }), + stream: [], + }, { surfaceOp: 'append' }) + const page = await f.history.events({ address: f.address }, f.abort.signal) + expect(page.cursor).toBe(f.session.seq - 1) + expect(page.records.at(-1)?.event.seq).toBe(f.session.seq - 1) + }) + + it('keeps the append copy a model-facing replacement shadowed', async () => { + const f = await fixture() + f.session.append('turn/start', { turn: 1 }) + const replaced = f.session.append('assistant/message', { + turn: 1, step: 1, + message: createMessage({ role: 'assistant', content: [{ type: 'text', text: 'visible' }], source: { kind: 'model', provider: 'p', model: 'm' } }), + stream: [], + }, { surfaceOp: 'append' }) + // Compaction rewrites the model-facing surface with a replacement that shadows the original; + // the human-readable transcript keeps the shadowed append copy. + const replacement = f.session.append('user/message', createMessage({ + role: 'user', content: [{ type: 'text', text: 'compacted' }], source: { kind: 'user' }, + }), { surfaceOp: { op: 'replace', startSeq: replaced.seq, endSeq: replaced.seq }, sourceEventSeqs: [replaced.seq] }) + const output = await f.history.assistantOutput(f.session.id, -1, replacement.seq, 5, f.abort.signal) + expect(output.records.map(record => record.event.seq)).toEqual([replaced.seq]) + }) + + it('releases the opening Observation when activation has nothing to promote', async () => { + const f = await fixture() + const source = await f.ctx.sessionQuery.observeSession(f.session.id) + const dispose = vi.fn(() => { source[Symbol.dispose]() }) + vi.spyOn(f.ctx.sessionQuery, 'observeSession').mockResolvedValue({ ...source, [Symbol.dispose]: dispose }) + const stream = f.web.follow({ address: f.address, activate: true }, f.abort.signal)[Symbol.asyncIterator]() + await stream.next() + f.abort.abort() + await stream.next() + expect(dispose).toHaveBeenCalled() + }) + + it('releases an acquired Observation when caller cancellation wins its return', async () => { + const f = await fixture() + const source = await f.ctx.sessionQuery.observeSession(f.session.id) + const dispose = vi.fn(() => { source[Symbol.dispose]() }) + vi.spyOn(f.ctx.sessionQuery, 'observeSession').mockImplementation(async () => { + f.abort.abort() + return { ...source, [Symbol.dispose]: dispose } + }) + await expect(f.history.usingObservation({ sessionId: f.session.id, projection: false }, f.abort.signal)).rejects.toBeDefined() + expect(dispose).toHaveBeenCalledOnce() + }) + + it('maps a non-Error query cancellation to a cancelled Remote error', async () => { + const f = await fixture() + // A cross-realm or opaque source may reject with the code alone; the message falls back. + vi.spyOn(f.ctx.sessionQuery, 'observeSession').mockRejectedValue({ code: 'SESSION_QUERY_ABORTED' }) + await expect(f.history.events({ address: f.address }, f.abort.signal)).rejects.toMatchObject({ + code: 'gateway/cancelled', message: 'Session read was cancelled', + }) + }) + + it('maps missing subagent Follow reads through the Address error', async () => { + const f = await fixture() + const stream = f.web.follow({ address: { + kind: 'subagent', parentSessionId: f.session.id, childSessionId: SessionId('missing-child'), mode: 'continuable', + } }, f.abort.signal)[Symbol.asyncIterator]() + await expect(stream.next()).rejects.toMatchObject({ code: 'subagent/not-found' }) + }) + + it('does not promote a live Session when activation was requested', async () => { + const f = await fixture() + const promote = vi.fn() + const web = new WebController(f.ctx, f.history, promote) + const stream = web.follow({ address: f.address, activate: true }, f.abort.signal)[Symbol.asyncIterator]() + expect(await stream.next()).toMatchObject({ value: { type: 'snapshot' } }) + const pending = stream.next() + f.abort.abort() + expect(await pending).toMatchObject({ done: true }) + expect(promote).not.toHaveBeenCalled() + }) +}) diff --git a/packages/api/session-controller/tests/image-read.perf.config.ts b/packages/api/session-controller/tests/image-read.perf.config.ts new file mode 100644 index 0000000000..4b9de690db --- /dev/null +++ b/packages/api/session-controller/tests/image-read.perf.config.ts @@ -0,0 +1,16 @@ +/** Compile the diagnostic's private controller adapter; workspace services remain built package imports. */ + +import { defineConfig } from 'tsdown' + +export default defineConfig({ + entry: { 'image-read.perf': 'image-read.perf.ts' }, + outDir: '../.dsh-build/image-read', + format: 'esm', + platform: 'node', + target: 'es2024', + fixedExtension: false, + dts: false, + clean: true, + tsconfig: '../../../../tsconfig.base.json', + deps: { neverBundle: [/^@deepseek-ai\//], onlyBundle: false }, +}) diff --git a/packages/api/session-controller/tests/image-read.perf.ts b/packages/api/session-controller/tests/image-read.perf.ts new file mode 100644 index 0000000000..18a267131a --- /dev/null +++ b/packages/api/session-controller/tests/image-read.perf.ts @@ -0,0 +1,336 @@ +/** Threshold-free, built-runtime measurements of uncached historical image requests. */ + +import assert from 'node:assert/strict' +import { execFileSync, spawnSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { once } from 'node:events' +import { mkdtemp, rm } from 'node:fs/promises' +import { createServer } from 'node:http' +import { arch, cpus, platform, release, tmpdir } from 'node:os' +import { join } from 'node:path' +import { performance } from 'node:perf_hooks' +import { fileURLToPath } from 'node:url' +import { crc32, deflateSync } from 'node:zlib' +import { Context } from '@deepseek-ai/cordis' +import { LocalAttachmentStore } from '@deepseek-ai/dsh-attachment-local' +import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' +import { MessageId, ToolCallId } from '@deepseek-ai/dsh-llm' +import { AssistantStreamAccumulator } from '@deepseek-ai/dsh-llm/assistant-stream' +import SessionStore, { SessionId, type Session } from '@deepseek-ai/dsh-session' +import SessionQueryEngine from '@deepseek-ai/dsh-session-query' +import { ApiSessionAgentController } from '../src/agent.ts' +import { SessionCommandController } from '../src/commands.ts' +import type { SessionAttachmentValue } from '../src/types.ts' + +const WORKLOADS = { + typical: { turns: 120, images: 8 }, + tail: { turns: 2_000, images: 32 }, +} as const +const SAMPLES = 5 +const WIDTH = 1024 +const HEIGHT = 768 + +interface Timings { + historyObservations: number + historyQueries: number + historySnapshots: number + observationMs: number + snapshotMs: number + beforeStoreMs: number + storeMs: number + storeFinished: number + started: number +} + +/** Production point reads; full-text search is outside this diagnostic. */ +class ImageReadSessionQuery extends SessionQueryEngine { + override searchSessions(): Promise { + return Promise.reject(new Error('image read diagnostic does not search sessions')) + } + + override searchEvents(): Promise { + return Promise.reject(new Error('image read diagnostic does not search events')) + } +} + +function image(ordinal: number): Uint8Array { + const pixels = Buffer.alloc((WIDTH * 3 + 1) * HEIGHT) + let seed = ordinal + 1 + for (let y = 0; y < HEIGHT; y++) { + for (let x = 0; x < WIDTH; x++) { + seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0 + const offset = y * (WIDTH * 3 + 1) + 1 + x * 3 + const value = x < WIDTH / 4 ? seed >>> 24 : (Math.floor(x / 16) + Math.floor(y / 16) + ordinal) % 256 + pixels[offset] = value + pixels[offset + 1] = (value + ordinal * 17) % 256 + pixels[offset + 2] = (value + y) % 256 + } + } + const chunk = (name: string, data: Buffer): Buffer => { + const output = Buffer.alloc(data.length + 12) + output.writeUInt32BE(data.length) + output.write(name, 4) + data.copy(output, 8) + output.writeUInt32BE(crc32(output.subarray(4, -4)), output.length - 4) + return output + } + const header = Buffer.alloc(13) + header.writeUInt32BE(WIDTH) + header.writeUInt32BE(HEIGHT, 4) + header[8] = 8 + header[9] = 2 + return Buffer.concat([ + Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), + chunk('IHDR', header), chunk('IDAT', deflateSync(pixels)), chunk('IEND', Buffer.alloc(0)), + ]) +} + +function populate(session: Session, turns: number, refs: readonly ImageAttachmentRef[]): void { + for (let turn = 1; turn <= turns; turn++) { + const imageIndex = refs.findIndex((_, ordinal) => Math.floor(ordinal * turns / refs.length) + 1 === turn) + const ref = refs[imageIndex] + session.append('turn/start', { turn }) + session.append('step/start', { turn, step: 1 }) + session.append('user/message', { + id: MessageId(`input-${turn}`), role: 'user', source: { kind: 'user' }, + content: [ + { type: 'text', text: `Inspect synthetic module ${turn}. ` + 'Describe the visible result. '.repeat(8) }, + ...(ref === undefined ? [] : [{ type: 'image' as const, attachment: ref }]), + ], + }, { surfaceOp: 'append' }) + const callId = ToolCallId(`call-${turn}`) + const call = session.append('tool/call', { turn, step: 1, callId, name: 'synthetic_read', arguments: '{}' }) + session.append('tool/result', { + turn, step: 1, + message: { id: MessageId(`result-${turn}`), role: 'tool', toolCallId: callId, isError: false, + source: { kind: 'tool', callId }, content: [{ type: 'text', text: `module ${turn}\n` + 'export const value = 42;\n'.repeat(80) }] }, + }, { surfaceOp: 'append', sourceEventSeqs: [call.seq] }) + const block = { type: 'text' as const, text: `Result ${turn}. ` + 'Synthetic response. '.repeat(40) } + const stream = new AssistantStreamAccumulator() + stream.push({ time: 1_700_000_000_000 + turn, chunk: { type: 'block-start', index: 0, blockType: 'text' } }) + for (let offset = 0; offset < block.text.length; offset += 32) { + stream.push({ time: 1_700_000_000_001 + turn + offset, chunk: { type: 'text-delta', index: 0, text: block.text.slice(offset, offset + 32) } }) + } + stream.push({ time: 1_700_000_001_000 + turn, chunk: { type: 'block-end', index: 0, block } }) + stream.push({ time: 1_700_000_001_001 + turn, chunk: { type: 'finish', reason: { kind: 'stop' } } }) + session.append('assistant/message', { + turn, step: 1, stream: [...stream.snapshot()], + message: { id: MessageId(`reply-${turn}`), role: 'assistant', content: [block], source: { kind: 'model', provider: 'synthetic', model: 'synthetic' } }, + }, { surfaceOp: 'append' }) + session.append('step/end', { turn, step: 1 }) + session.append('turn/end', { turn, reason: { kind: 'completed' } }) + } +} + +function memory(): { heapUsedBytes: number; rssBytes: number; peakRssBytes: number } { + assert.ok(global.gc, 'run the diagnostic with --expose-gc') + global.gc() + const usage = process.memoryUsage() + return { heapUsedBytes: usage.heapUsed, rssBytes: usage.rss, peakRssBytes: process.resourceUsage().maxRSS * 1024 } +} + +async function transfer(payloads: readonly string[]): Promise { + let index = 0 + const server = createServer((_request, response) => { + response.setHeader('content-type', 'application/json') + response.end(payloads[index++]) + }) + try { + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const address = server.address() + assert.ok(address !== null && typeof address !== 'string') + const samples: number[] = [] + for (const payload of payloads) { + const start = performance.now() + const response: Response = await fetch(`http://127.0.0.1:${address.port}`, { signal: AbortSignal.timeout(15_000) }) + const received: string = await response.text() + samples.push(performance.now() - start) + assert.equal(received, payload) + } + return samples + } finally { + server.closeAllConnections() + if (server.listening) await new Promise((resolve, reject) => { + server.close((error) => { if (error === undefined) resolve(); else reject(error) }) + }) + } +} + +async function measure(workload: keyof typeof WORKLOADS) { + const root = await mkdtemp(join(tmpdir(), 'dsh-image-read-perf-')) + const ctx = new Context() + try { + await ctx.plugin(SessionStore) + await ctx.plugin(ImageReadSessionQuery) + await ctx.plugin(LocalAttachmentStore, { dshHome: root }) + const refs: ImageAttachmentRef[] = [] + for (let ordinal = 0; ordinal < WORKLOADS[workload].images; ordinal++) { + refs.push(await ctx.attachments.saveImage({ data: image(ordinal), mediaType: 'image/png' })) + } + const session = ctx.sessions.create(SessionId('synthetic-image-history'), { meta: { cwd: '/synthetic-image-history' } }) + populate(session, WORKLOADS[workload].turns, refs) + let timing: Timings = { + historyObservations: 0, historyQueries: 0, historySnapshots: 0, + observationMs: 0, snapshotMs: 0, beforeStoreMs: 0, + storeMs: 0, storeFinished: 0, started: 0, + } + let traversedEvents = 0 + let countEvents = false + const observeSession = ctx.sessionQuery.observeSession.bind(ctx.sessionQuery) + ctx.sessionQuery.observeSession = async (...args) => { + timing.historyObservations++ + const start = performance.now() + try { + return await observeSession(...args) + } finally { + timing.observationMs += performance.now() - start + } + } + const getSession = ctx.sessions.get.bind(ctx.sessions) + ctx.sessions.get = (id) => { + timing.historyQueries++ + const found = getSession(id) + return found === undefined ? undefined : new Proxy(found, { + get(target, key) { + const member: unknown = Reflect.get(target, key, target) + if (key !== 'snapshotEvents' || typeof member !== 'function') return member + return (...args: unknown[]) => { + timing.historySnapshots++ + const start = performance.now() + const events = Reflect.apply(member as (...args: unknown[]) => readonly unknown[], target, args) + timing.snapshotMs += performance.now() - start + if (!countEvents) return events + return new Proxy(events, { get(array, property) { + if (property !== Symbol.iterator) { + const value: unknown = Reflect.get(array, property, array) + return value + } + return function* () { for (const event of array) { traversedEvents++; yield event } } + } }) + } + }, + }) + } + const attachments = ctx.attachments + const observedAttachments = new Proxy(attachments, { + get(target, key) { + const member: unknown = Reflect.get(target, key, target) + if (key !== 'readImage' || typeof member !== 'function') return member + return async (...args: unknown[]) => { + const start = performance.now() + timing.beforeStoreMs = start - timing.started + const result: unknown = await Reflect.apply(member, target, args) + timing.storeFinished = performance.now() + timing.storeMs = timing.storeFinished - start + return result + } + }, + }) + const observedContext = new Proxy(ctx, { + get(target, key) { + if (key === 'attachments') return observedAttachments + const value: unknown = Reflect.get(target, key, target) + return value + }, + }) + const controller = new SessionCommandController(observedContext, new ApiSessionAgentController(ctx), '/synthetic-image-history') + const baselineMemory = memory() + const outputs: SessionAttachmentValue[] = [] + const samples = [] + for (const ref of refs) { + timing = { + historyObservations: 0, historyQueries: 0, historySnapshots: 0, + observationMs: 0, snapshotMs: 0, beforeStoreMs: 0, + storeMs: 0, storeFinished: 0, started: performance.now(), + } + const cpu = process.cpuUsage() + const value = await controller.attachment({ sessionId: session.id, attachment: ref }) + const completed = performance.now() + const usedCpu = process.cpuUsage(cpu) + assert.deepEqual(value.attachment, ref) + assert.equal(`sha256:${createHash('sha256').update(Buffer.from(value.data, 'base64')).digest('hex')}`, ref.attachmentId) + samples.push({ + controllerMs: completed - timing.started, + controllerCpuMs: (usedCpu.user + usedCpu.system) / 1000, + historyObservations: timing.historyObservations, + historyQueries: timing.historyQueries, historySnapshots: timing.historySnapshots, + observationMs: timing.observationMs, snapshotMs: timing.snapshotMs, + scanAndDispatchMs: timing.beforeStoreMs - timing.observationMs - timing.snapshotMs, + storeMs: timing.storeMs, base64AndReturnMs: completed - timing.storeFinished, + }) + outputs.push(value) + } + const retainedMemory = memory() + const jsonMs: number[] = [] + const payloads = outputs.map((value) => { + const start = performance.now() + const text = JSON.stringify(value) + jsonMs.push(performance.now() - start) + return text + }) + const loopbackTransferMs = await transfer(payloads) + countEvents = true + timing.historyObservations = 0 + timing.historyQueries = 0 + timing.historySnapshots = 0 + for (const ref of refs) await controller.attachment({ sessionId: session.id, attachment: ref }) + const workCounts = { + historyObservations: timing.historyObservations, historyQueries: timing.historyQueries, + historySnapshots: timing.historySnapshots, traversedEvents, + } + if (process.argv.includes('--expect-no-history')) { + assert.deepEqual(workCounts, { historyObservations: 0, historyQueries: 0, historySnapshots: 0, traversedEvents: 0 }) + } + return { + workload, fixture: { ...WORKLOADS[workload], events: session.seq, width: WIDTH, height: HEIGHT, + imageBytes: refs.map(ref => ref.bytes), attachmentIds: refs.map(ref => ref.attachmentId), + fullReferenceRequestJsonBytes: refs.map(attachment => Buffer.byteLength(JSON.stringify({ sessionId: session.id, attachment }))), + idOnlyRequestJsonBytes: refs.map(ref => Buffer.byteLength(JSON.stringify({ + sessionId: session.id, attachmentId: ref.attachmentId, + }))), + responseJsonBytes: payloads.map(text => Buffer.byteLength(text)) }, + samples, jsonMs, loopbackTransferMs, workCounts, baselineMemory, retainedMemory, + } + } finally { + await ctx.fiber.dispose() + await rm(root, { recursive: true, force: true }) + } +} + +for (const specifier of [ + '@deepseek-ai/cordis', '@deepseek-ai/dsh-attachment-local', '@deepseek-ai/dsh-session', '@deepseek-ai/dsh-session-query', +]) { + assert.match(import.meta.resolve(specifier), /\/lib\/.*\.js$/, `${specifier} must resolve to built JavaScript`) +} +assert.ok(import.meta.url.endsWith('.js'), 'compile this diagnostic before running it') +assert.ok(process.execArgv.every(value => !value.includes('tsx')), 'do not use a TypeScript loader') + +const workload = process.argv[3] +if (process.argv[2] === '--sample') { + assert.ok(workload === 'typical' || workload === 'tail') + process.stdout.write(`${JSON.stringify(await measure(workload))}\n`) +} else { + const samples: unknown[] = [] + for (const name of Object.keys(WORKLOADS)) { + for (let sample = 0; sample < SAMPLES; sample++) { + const child = spawnSync(process.execPath, ['--expose-gc', fileURLToPath(import.meta.url), '--sample', name, + ...process.argv.includes('--expect-no-history') ? ['--expect-no-history'] : []], { + encoding: 'utf8', timeout: 60_000, maxBuffer: 16 * 1024 * 1024, + env: { ...process.env, NODE_OPTIONS: '', TSX_TSCONFIG_PATH: '' }, + }) + if (child.error !== undefined) throw child.error + assert.equal(child.signal, null, child.stderr) + assert.equal(child.status, 0, child.stderr) + const report: unknown = JSON.parse(child.stdout) + samples.push(report) + } + } + process.stdout.write(JSON.stringify({ + revision: execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(), + node: process.version, platform: platform(), release: release(), arch: arch(), cpu: cpus()[0]?.model, + clock: 'Fresh child per sample; loaded Session; first uncached request per image; OS file cache may be warm from fixture writes. Store includes file I/O, digest and header validation. observationMs measures the production SessionQuery point observation; snapshotMs measures its lazy event-array acquisition. scanAndDispatchMs is the residual before store entry after subtracting observation and snapshot acquisition. JSON and loopback HTTP transfer are separate measurements over retained responses. Gateway, browser, remote network, upload and model inference are excluded.', + memory: 'GC after setup and after all image responses; Session and all base64 responses remain reachable. Process peak RSS includes fixture creation. No retained-memory budget.', + samples, + }, null, 2) + '\n') +} diff --git a/packages/api/session-controller/tests/lineage.client.spec.ts b/packages/api/session-controller/tests/lineage.client.spec.ts index 16f10c14f4..ae9c4389fe 100644 --- a/packages/api/session-controller/tests/lineage.client.spec.ts +++ b/packages/api/session-controller/tests/lineage.client.spec.ts @@ -9,7 +9,7 @@ import { flattenLineage } from '../src/client/sessions/lineage.ts' const s = (id: string, updatedAt: number, parent?: string): SessionSummary => ({ agentAvailable: true, sessionId: id as SessionId, updatedAt, running: false, blank: false, - ...(parent !== undefined ? { parentSessionId: parent as SessionId } : {}), + ...(parent !== undefined ? { parentSessionId: parent as SessionId, origin: 'subagent' as const } : {}), }) describe('Session lineage flattening', () => { @@ -26,6 +26,16 @@ describe('Session lineage flattening', () => { ]) }) + it('keeps historical ordinary forks at root level in input order', () => { + const out = flattenLineage([ + s('source', 10), s('unrelated', 20), + { ...s('legacy-fork', 30), parentSessionId: 'source' as SessionId }, + ]) + expect(out.map(row => [row.sessionId, row.depth])).toEqual([ + ['source', 0], ['unrelated', 0], ['legacy-fork', 0], + ]) + }) + it('degrades an orphan (absent parent) to root level without dropping it', () => { const out = flattenLineage([s('orphan', 20, 'ghost-parent'), s('root', 10)]) expect(out.map(e => [e.sessionId, e.depth])).toEqual([['orphan', 0], ['root', 0]]) diff --git a/packages/api/session-controller/tests/listeners.host.spec.ts b/packages/api/session-controller/tests/listeners.host.spec.ts new file mode 100644 index 0000000000..34207efb3c --- /dev/null +++ b/packages/api/session-controller/tests/listeners.host.spec.ts @@ -0,0 +1,263 @@ +import { Context } from '@deepseek-ai/cordis' +import type { Agent, AssistantStreamFrame } from '@deepseek-ai/dsh-agent' +import { LlmAttemptId } from '@deepseek-ai/dsh-llm' +import SessionStore, { SessionId, SessionSeq } from '@deepseek-ai/dsh-session' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { EventListener, ListenerBuffer, ProjectionListener, eventItem } from '../src/history/listener.ts' +import { SessionAssistantStreamsListener } from '../src/history/assistant-stream.ts' +import type { SessionFollowFrame, SessionEventEntry } from '../src/types.ts' +import { installSessionReadTestServices } from './test-remote.ts' + +const roots: Context[] = [] +const aborts: AbortController[] = [] +function cancellation() { + const abort = new AbortController() + aborts.push(abort) + return abort +} +afterEach(async () => { + for (const abort of aborts.splice(0)) abort.abort() + await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) + vi.restoreAllMocks() +}) +async function fixture() { + const ctx = new Context() + roots.push(ctx) + await ctx.plugin(SessionStore) + installSessionReadTestServices(ctx) + const session = ctx.sessions.create(SessionId('listener-target'), { meta: { cwd: '/listeners' } }) + const abort = cancellation() + const partial: Partial = { id: session.id, session } + const agent = partial as Agent + const emit = (frame: AssistantStreamFrame) => { ctx.emit('agent/assistant-stream', { agent, frame }) } + return { ctx, session, abort, emit, agent } +} +const start = (revision = 1): AssistantStreamFrame => ({ type: 'start', attemptId: LlmAttemptId('attempt'), revision, turn: 1, step: 1 }) + +describe('ListenerBuffer', () => { + it('orders heterogeneous inputs lazily, supports prepend, and admits only one consumer', async () => { + const { ctx, abort } = await fixture() + using buffer = new ListenerBuffer(ctx, abort.signal) + const convert = vi.fn((value: number) => [`n:${value}`]) + const numbers = buffer.createInput(convert) + const words = buffer.createInput(value => [value]) + numbers.append(2) + words.prepend('first') + expect(convert).not.toHaveBeenCalled() + const values = buffer.items()[Symbol.asyncIterator]() + expect(await values.next()).toEqual({ done: false, value: 'first' }) + expect(await values.next()).toEqual({ done: false, value: 'n:2' }) + await expect(buffer.items()[Symbol.asyncIterator]().next()).rejects.toMatchObject({ code: 'gateway/internal' }) + const waiting = values.next() + numbers.append(3) + expect(await waiting).toMatchObject({ value: 'n:3' }) + await values.return?.() + const action = vi.fn() + buffer.capture(action) + numbers.append(4) + words.prepend('closed') + expect(action).not.toHaveBeenCalled() + buffer.own(action) + expect(action).toHaveBeenCalledOnce() + expect(() => buffer.createInput(value => [value])).toThrow('closed') + }) + + it('propagates captured failure both before and during transformation', async () => { + const { ctx, abort } = await fixture() + using first = new ListenerBuffer(ctx, abort.signal) + first.capture(() => { throw new Error('captured') }) + await expect(first.items()[Symbol.asyncIterator]().next()).rejects.toThrow('captured') + using second = new ListenerBuffer(ctx, abort.signal) + const input = second.createInput(function* (value) { + second.capture(() => { throw new Error('transform failure') }) + yield value + }) + input.append(1) + await expect(second.items()[Symbol.asyncIterator]().next()).rejects.toThrow('transform failure') + }) + + it('does not emit after transformation closes its own buffer', async () => { + const { ctx, abort } = await fixture() + using buffer = new ListenerBuffer(ctx, abort.signal) + buffer.createInput(function* (value) { buffer[Symbol.dispose](); yield value }).append(1) + expect(await buffer.items()[Symbol.asyncIterator]().next()).toEqual({ done: true, value: undefined }) + }) + + it('releases abort registration when effect installation fails', async () => { + const { ctx, abort } = await fixture() + const remove = vi.spyOn(abort.signal, 'removeEventListener') + vi.spyOn(ctx, 'effect').mockImplementation(() => { throw new Error('effect failure') }) + expect(() => new ListenerBuffer(ctx, abort.signal)).toThrow('effect failure') + expect(remove).toHaveBeenCalledWith('abort', expect.any(Function)) + }) +}) + +describe('EventListener', () => { + it('starts at the first notification without acquiring a snapshot', async () => { + const { ctx, session, abort } = await fixture() + using listener = new EventListener(ctx, session.id, abort.signal) + const event = session.append('turn/start', { turn: 1 }) + const values = listener.events()[Symbol.asyncIterator]() + expect(await values.next()).toMatchObject({ value: { type: 'event', event } }) + abort.abort() + expect(await values.next()).toMatchObject({ done: true }) + }) + + it('subscribes before an empty Session is created and follows its first later event', async () => { + const { ctx, abort } = await fixture() + const id = SessionId('created-after-bind') + using listener = new EventListener(ctx, id, abort.signal) + const session = ctx.sessions.create(id) + const values = listener.events()[Symbol.asyncIterator]() + const waiting = values.next() + const event = session.append('turn/start', { turn: 1 }) + expect(await waiting).toMatchObject({ value: { event } }) + await values.return?.() + }) + + it('filters buffered events through a supplied cursor', async () => { + const { ctx, session, abort } = await fixture() + using listener = new EventListener(ctx, session.id, abort.signal) + session.append('turn/start', { turn: 1 }) + const event = session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + listener.setCursor(0) + const values = listener.events()[Symbol.asyncIterator]() + expect(await values.next()).toMatchObject({ value: { event } }) + await values.return?.() + }) + + it('leaves an external buffer open and drops notifications after listener disposal', async () => { + const { ctx, session, abort } = await fixture() + using queue = new ListenerBuffer(ctx, abort.signal) + const listener = new EventListener(ctx, session.id, abort.signal, queue) + session.append('turn/start', { turn: 1 }) + await expect(listener.events()[Symbol.asyncIterator]().next()).rejects.toThrow('externally owned') + listener[Symbol.dispose]() + const values = queue.items()[Symbol.asyncIterator]() + const next = values.next() + abort.abort() + expect(await next).toMatchObject({ done: true }) + }) + + it('stops within a creation batch when its binding is disposed', async () => { + const { ctx, session, abort } = await fixture() + session.append('turn/start', { turn: 1 }) + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + using queue = new ListenerBuffer(ctx, abort.signal) + const listener = new EventListener(ctx, session.id, abort.signal, queue) + listener.setCursor(-1) + ctx.emit('session/created', session) + const values = queue.items()[Symbol.asyncIterator]() + expect(await values.next()).toMatchObject({ value: { event: { seq: 0 } } }) + listener[Symbol.dispose]() + const waiting = values.next() + abort.abort() + expect(await waiting).toMatchObject({ done: true }) + }) + + it('cleans a partially installed registration when a later one fails', async () => { + const { ctx, session, abort } = await fixture() + const on = ctx.on.bind(ctx) + let count = 0 + vi.spyOn(ctx, 'on').mockImplementation((...args) => { + if (++count === 2) throw new Error('registration failure') + return on(...args) + }) + expect(() => new EventListener(ctx, session.id, abort.signal)).toThrow('registration failure') + }) + + it('handles raw events and rejects a noncontiguous supplied creation prefix', async () => { + const { session } = await fixture() + const event = session.append('turn/start', { turn: 1 }) + expect(eventItem({ type: 'event', session, event })).toEqual({ events: [event], next: 1 }) + expect(eventItem({ type: 'created', session, end: 0 })).toEqual({ events: [], next: undefined }) + vi.spyOn(session, 'snapshotEvents').mockReturnValue([{ ...event, seq: SessionSeq(1) }]) + expect(() => eventItem({ type: 'created', session, end: 2 }, 0)).toThrow('skipped seq') + expect(eventItem({ type: 'created', session, end: 2 })).toMatchObject({ next: 2 }) + }) +}) + +describe('ProjectionListener', () => { + it('emits sparse changes only for the selected Session', async () => { + const { ctx, session, abort } = await fixture() + let receive!: Parameters[0] + const dispose = vi.fn() + vi.spyOn(ctx.sessionProjections, 'onChanged').mockImplementation((listener) => { receive = listener; return dispose }) + using listener = new ProjectionListener(ctx, session.id, abort.signal) + const other = ctx.sessions.create(SessionId('other')) + receive(other, 'subagent', null, SessionSeq(0)) + receive(session, 'subagent', null, SessionSeq(1)) + const changes = listener.changes()[Symbol.asyncIterator]() + expect(await changes.next()).toMatchObject({ value: { type: 'projection', key: 'subagent', value: null, seq: 1 } }) + abort.abort() + expect(await changes.next()).toMatchObject({ done: true }) + expect(dispose).toHaveBeenCalledOnce() + }) + + it('releases its buffer when projection subscription fails', async () => { + const { ctx, session, abort } = await fixture() + const remove = vi.spyOn(abort.signal, 'removeEventListener') + vi.spyOn(ctx.sessionProjections, 'onChanged').mockImplementation(() => { throw new Error('projection subscribe failed') }) + expect(() => new ProjectionListener(ctx, session.id, abort.signal)).toThrow('projection subscribe failed') + expect(remove).toHaveBeenCalled() + }) +}) + +describe('AssistantStreamListener', () => { + it('cuts baseline-covered arrivals and clears reconnect state on Agent disposal', async () => { + const { ctx, session, abort, emit, agent } = await fixture() + const streams = new SessionAssistantStreamsListener(ctx) + using queue = new ListenerBuffer(ctx, abort.signal) + using listener = streams.bind(session.id, abort.signal, queue) + expect(listener.snapshot()).toEqual({ baseline: { revision: 0 }, ordinal: 0 }) + emit(start()) + expect(listener.snapshot()).toMatchObject({ baseline: { revision: 1 }, ordinal: 1 }) + listener.setOrdinalCut(1) + const frames = queue.items()[Symbol.asyncIterator]() + const end: AssistantStreamFrame = { type: 'end', attemptId: LlmAttemptId('attempt'), revision: 2, index: 0, outcome: { kind: 'abandoned' } } + emit(end) + expect(await frames.next()).toMatchObject({ value: { type: 'assistant-stream', frame: end } }) + ctx.emit('agent/disposed', { agent }) + expect(listener.snapshot()).toEqual({ baseline: { revision: 0 }, ordinal: 2 }) + abort.abort() + expect(await frames.next()).toMatchObject({ done: true }) + }) + + it('records the durable cursor for an attempt started after a committed event', async () => { + const { ctx, session, abort, emit } = await fixture() + session.append('turn/start', { turn: 1 }) + const streams = new SessionAssistantStreamsListener(ctx) + using queue = new ListenerBuffer(ctx, abort.signal) + using listener = streams.bind(session.id, abort.signal, queue) + emit(start()) + listener.setOrdinalCut(0) + const frames = queue.items()[Symbol.asyncIterator]() + expect(await frames.next()).toMatchObject({ value: { frame: { type: 'start', startedAfterSeq: 0 } } }) + await frames.return?.() + }) + + it('leaves queue ownership intact and drops notifications after unbinding', async () => { + const { ctx, session, abort, emit } = await fixture() + const streams = new SessionAssistantStreamsListener(ctx) + using queue = new ListenerBuffer(ctx, abort.signal) + const listener = streams.bind(session.id, abort.signal, queue) + emit(start()) + listener[Symbol.dispose]() + const next = queue.items()[Symbol.asyncIterator]().next() + abort.abort() + expect(await next).toMatchObject({ done: true }) + }) + + it('propagates registration failure without closing the shared queue', async () => { + const { ctx, session, abort } = await fixture() + const streams = new SessionAssistantStreamsListener(ctx) + using queue = new ListenerBuffer(ctx, abort.signal) + vi.spyOn(ctx, 'on').mockImplementation(() => { throw new Error('assistant subscribe failed') }) + expect(() => streams.bind(session.id, abort.signal, queue)).toThrow('assistant subscribe failed') + // The failed binding leaves the shared queue usable for the rest of the connection. + const input = queue.createInput(value => [value]) + const event = session.append('turn/start', { turn: 1 }) + input.append({ type: 'event', event }) + await expect(queue.items()[Symbol.asyncIterator]().next()).resolves.toMatchObject({ value: { type: 'event', event } }) + }) +}) diff --git a/packages/api/session-controller/tests/manager.client.spec.ts b/packages/api/session-controller/tests/manager.client.spec.ts index a4f9367735..9661f66a01 100644 --- a/packages/api/session-controller/tests/manager.client.spec.ts +++ b/packages/api/session-controller/tests/manager.client.spec.ts @@ -862,7 +862,7 @@ describe('subagent catalogs', () => { childSessionId: S2, mode: 'continuable', }, - assistantStream: true, + activate: true, assistantStream: true, maxMessages: 500, turnWindow: { minMessages: 50, minTurns: 2 }, }, @@ -958,7 +958,7 @@ describe('subagent catalogs', () => { if (source === 'control') { manager.handleControlFrame({ type: 'baseline', value: { projections: { [S1]: baseline } } }) } else { - mock.stream(FOLLOW, followScript(ok({ records: [], hasMore: false, projections: baseline }))) + mock.stream(FOLLOW, followScript(ok({ cursor: baseline.asOfSeq, records: [], hasMore: false, projections: baseline }))) await session.open() } @@ -983,7 +983,7 @@ describe('subagent catalogs', () => { if (source === 'control') { manager.handleControlFrame({ type: 'baseline', value: { projections: { [S1]: baseline } } }) } else { - mock.stream(FOLLOW, followScript(ok({ records: [], hasMore: false, projections: baseline }))) + mock.stream(FOLLOW, followScript(ok({ cursor: baseline.asOfSeq, records: [], hasMore: false, projections: baseline }))) await manager.get(S1).open() } response.resolve(ok({ kind: 'migration-required', values: { @@ -1261,7 +1261,8 @@ describe('remaining branches', () => { expect(remote.session.fork).toHaveBeenCalledExactlyOnceWith({ sessionId: S1, atSeq: 7, ...permission }) expect(remote.session.follow).not.toHaveBeenCalled() - expect(manager.getListSnapshot().items[0]).toMatchObject({ sessionId: S2, parentSessionId: S1 }) + expect(manager.getListSnapshot().items[0]).toMatchObject({ sessionId: S2 }) + expect(manager.getListSnapshot().items[0]).not.toHaveProperty('parentSessionId') }) it('reconciles a fork child published before workspace attachment fails', async ({ mock, remote }) => { @@ -1273,13 +1274,12 @@ describe('remaining branches', () => { expect(result).toMatchObject({ ok: false, error: { code: 'session/workspace-attach-failed' } }) expect(manager.getListSnapshot().items).toEqual([expect.objectContaining({ sessionId: S2, - parentSessionId: S1, blank: true, })]) - manager.handleSessionAdded(summary(S2, { blank: true, parentSessionId: S1 })) + manager.handleSessionAdded(summary(S2, { blank: true })) expect(manager.getListSnapshot().items[0]?.blank).toBe(true) - manager.handleSessionAdded(summary(S2, { blank: false, parentSessionId: S1 })) + manager.handleSessionAdded(summary(S2, { blank: false })) expect(manager.getListSnapshot().items[0]?.blank).toBe(false) }) @@ -1545,6 +1545,7 @@ describe('connected generation', () => { it('refreshes query baselines without rebuilding independently resumed Session sources', async ({ mock, remote, start }) => { mock.stream(FOLLOW, followScript(ok({ + cursor: 5, records: entries(plainTurn(SessionSeq(0), 0, 'a', 'b')) as never[], hasMore: false, modelSelection: { provider: 'deepseek-official', model: 'deepseek-chat' }, diff --git a/packages/api/session-controller/tests/media-references.host.spec.ts b/packages/api/session-controller/tests/media-references.host.spec.ts index 61572ab0be..d25885ed7f 100644 --- a/packages/api/session-controller/tests/media-references.host.spec.ts +++ b/packages/api/session-controller/tests/media-references.host.spec.ts @@ -47,8 +47,15 @@ describe('SessionMediaReferences /api/file', () => { if (handler === undefined) throw new Error('route not registered') return handler(new Request(url, init)) } + const url = (path: string) => `http://127.0.0.1/api/file?path=${encodeURIComponent(path)}` return { - call: (path: string, init?: RequestInit) => raw(`http://127.0.0.1/api/file?path=${encodeURIComponent(path)}`, init), + /** Request a path and follow its version redirect, as an image element does. */ + call: async (path: string, init?: RequestInit) => { + const first = await raw(url(path), init) + const location = first.headers.get('location') + return location === null ? first : raw(new URL(location, url(path)).href, init) + }, + url, raw, fs: ctx.fs as LocalFileSystem, unregister, @@ -105,7 +112,7 @@ describe('SessionMediaReferences /api/file', () => { expect(response.status).toBe(200) expect(response.headers.get('content-type')).toBe(mediaType) expect(response.headers.get('content-length')).toBe(String(PNG_BYTES.length)) - expect(response.headers.get('cache-control')).toBe('private, no-store') + expect(response.headers.get('cache-control')).toBe('private, max-age=31536000, immutable') expect(response.headers.get('x-content-type-options')).toBe('nosniff') expect(response.headers.get('content-security-policy')).toBe("sandbox; default-src 'none'") expect(await responseBytes(response)).toEqual(PNG_BYTES) @@ -121,6 +128,29 @@ describe('SessionMediaReferences /api/file', () => { expect((await route.call(path, { method: 'HEAD' })).status).toBe(413) }) + it('redirects uncached to the current version and serves versioned URLs as immutable', async () => { + const route = await mount() + const path = join(root, 'chart.png') + await writeFile(path, PNG_BYTES) + const first = await route.raw(`${route.url(path)}&load=7`) + expect(first.status).toBe(302) + expect(first.headers.get('cache-control')).toBe('private, no-store') + expect(first.body).toBeNull() + const location = new URL(first.headers.get('location')!, route.url(path)) + expect(location.pathname).toBe('/api/file') + expect([...location.searchParams.keys()]).toEqual(['path', 'v']) + expect(location.searchParams.get('path')).toBe(path) + const versioned = await route.raw(location.href) + expect(versioned.status).toBe(200) + expect(await responseBytes(versioned)).toEqual(PNG_BYTES) + await writeFile(path, new Uint8Array([...PNG_BYTES, 9])) + const stale = await route.raw(location.href) + expect(stale.status).toBe(302) + const next = new URL(stale.headers.get('location')!, route.url(path)) + expect(next.searchParams.get('v')).not.toBe(location.searchParams.get('v')) + expect((await responseBytes(await route.raw(next.href))).at(-1)).toBe(9) + }) + it('ignores Range headers and returns complete bodies without advertising ranges', async () => { const route = await mount() const path = join(root, 'clip.mp4') @@ -192,6 +222,7 @@ describe('SessionMediaReferences /api/file', () => { const route = await mount() const target = { targetKey: FsTargetKey('opaque-remote-id'), displayPath: '/remote/photo.png' } vi.spyOn(route.fs, 'resolve').mockResolvedValue(target) + vi.spyOn(route.fs, 'stat').mockResolvedValue({ type: 'file', version: FsVersion('r1') }) const read = vi.spyOn(route.fs, 'readBytes').mockResolvedValue(PNG_BYTES) expect(await responseBytes(await route.call('/remote/photo.png'))).toEqual(PNG_BYTES) expect(read).toHaveBeenCalledWith(target, expect.any(AbortSignal), DEFAULT_LIMIT) diff --git a/packages/api/session-controller/tests/projection-discovery.host.spec.ts b/packages/api/session-controller/tests/projection-discovery.host.spec.ts index 150b82d415..539962a622 100644 --- a/packages/api/session-controller/tests/projection-discovery.host.spec.ts +++ b/packages/api/session-controller/tests/projection-discovery.host.spec.ts @@ -239,7 +239,7 @@ describe('Session projection discovery', () => { kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [{ id: 'current-child', mode: 'continuable', label: 'worker' }] }, }) - expect(observe).toHaveBeenCalledWith(parent.header.id, { signal }) + expect(observe).toHaveBeenCalledWith(parent.header.id, { signal, projectionMode: 'all' }) expect(open).toHaveBeenCalledWith(parent.header.id, 'read', { signal }) expect(fixture.ctx.sessions.get(parent.header.id)).toBeUndefined() expect(fixture.ctx.agents.get(parent.header.id)).toBeUndefined() @@ -310,7 +310,7 @@ describe('Session projection discovery', () => { .rejects.toMatchObject({ code: 'session/projections-unavailable' }) }) - it.each([false, true])('rechecks live history when the stored source disappears after preflight (attached: %s)', async (attached) => { + it.each([false, true])('returns the observation not-found result without a second live lookup (attached: %s)', async (attached) => { const fixture = await harness() const parent = await stored(fixture, SessionId('missing-after-preflight')) const snapshot = await fixture.ctx.sessionPersistence.stat(parent.header.id) @@ -322,9 +322,8 @@ describe('Session projection discovery', () => { }) const result = await fixture.controller.projections({ sessionId: parent.header.id }, new AbortController().signal) - expect(result).toEqual(attached - ? { kind: 'sequenced', ...fixture.ctx.sessionProjections.snapshot(fixture.ctx.sessions.get(parent.header.id)!) } - : null) + expect(result).toBeNull() + expect(fixture.ctx.sessions.get(parent.header.id) !== undefined).toBe(attached) }) it('serves the live registry cut instead of a conflicting cached hint', async () => { @@ -342,7 +341,7 @@ describe('Session projection discovery', () => { expect(cached).not.toHaveBeenCalled() }) - it.each([true, false])('prefers a Session attached during stat (stored header present: %s)', async (present) => { + it.each([true, false])('uses migration preflight before observing a Session attached during stat (stored header present: %s)', async (present) => { const fixture = await harness() const parent = await stored(fixture, SessionId('stat-race'), {}, 3) const snapshot = await fixture.ctx.sessionPersistence.stat(parent.header.id) @@ -358,7 +357,9 @@ describe('Session projection discovery', () => { const live = fixture.ctx.sessions.create(parent.header.id, { meta: parent.header }) live.append('turn/start', { turn: 1 }) finish.resolve(present ? snapshot : undefined) - await expect(operation).resolves.toEqual({ kind: 'sequenced', ...fixture.ctx.sessionProjections.snapshot(live) }) + await expect(operation).resolves.toEqual(present + ? { kind: 'migration-required', values: {} } + : { kind: 'sequenced', ...fixture.ctx.sessionProjections.snapshot(live) }) } finally { finish.resolve(undefined) await Promise.allSettled([operation]) diff --git a/packages/api/session-controller/tests/projection-store.client.spec.ts b/packages/api/session-controller/tests/projection-store.client.spec.ts index 40e1f3c95f..ab1e185744 100644 --- a/packages/api/session-controller/tests/projection-store.client.spec.ts +++ b/packages/api/session-controller/tests/projection-store.client.spec.ts @@ -214,7 +214,7 @@ describe('Session tail-page seeding', () => { it('treats a blockless response as no reset: pushed values survive', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) - mock.stream(FOLLOW, followScript(ok({ records: entries(plainTurn(SessionSeq(0), 0, 'a', 'b')) as never[], hasMore: false }))) + mock.stream(FOLLOW, followScript(ok({ cursor: 5, records: entries(plainTurn(SessionSeq(0), 0, 'a', 'b')) as never[], hasMore: false }))) await session.open() session.projections.apply('test/marks', { marks: ['pushed'] }, SessionSeq(9)) await session.resync() diff --git a/packages/api/session-controller/tests/reference-ownership.client.spec.ts b/packages/api/session-controller/tests/reference-ownership.client.spec.ts index 16de92ef02..b0563eb879 100644 --- a/packages/api/session-controller/tests/reference-ownership.client.spec.ts +++ b/packages/api/session-controller/tests/reference-ownership.client.spec.ts @@ -21,7 +21,7 @@ declare module '@deepseek-ai/dsh-api-session-controller/client' { const viewSource: SessionReferenceSource = 'referenceTestView' const workSource: SessionReferenceSource = 'referenceTestWork' const ID = SessionId('reference-session') -const EMPTY_HISTORY = ok({ records: [], hasMore: false }) +const EMPTY_HISTORY = ok({ cursor: -1, records: [], hasMore: false }) const it = createClientTest({ roster: webApp.closure(['@deepseek-ai/dsh-api-gateway']) }) async function bench(mock: RemoteMock, start: () => Promise, listed = true) { diff --git a/packages/api/session-controller/tests/remote-access.host.spec.ts b/packages/api/session-controller/tests/remote-access.host.spec.ts index 42b78e5190..8be0dac78e 100644 --- a/packages/api/session-controller/tests/remote-access.host.spec.ts +++ b/packages/api/session-controller/tests/remote-access.host.spec.ts @@ -1,13 +1,14 @@ /** * Session Controller under non-owner callers: the Session resource kind it - * registers, the Session readers of `session/page` and `session/follow`, - * `session/list`, `session/search`, and `session/control` called through a - * `global` role and filtered per Session through `remoteAccess.allows()`, the caller recorded - * on prompt sources, and `session/projections` admitted per Session through - * the Gateway. + * registers and its default resolver, which supplies the identities of + * `session/page` and `session/follow`, `session/list`, `session/search`, and + * `session/control` called through a `global` role and filtered per Session + * through `remoteAccess.allows()`, the caller recorded on prompt sources, and + * `session/projections` admitted per Session through the Gateway. */ import { Context } from '@deepseek-ai/cordis' +import { AttachmentId } from '@deepseek-ai/dsh-attachment' import type { Agent } from '@deepseek-ai/dsh-agent' import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' import TypertGatewayService from '@deepseek-ai/dsh-api-gateway' @@ -86,8 +87,8 @@ async function harness(): Promise<{ await ctx.plugin(TypertRegistry) await mountAgentLoopTestDependencies(ctx) const loop = await mountAgentLoopTestHarness(ctx) - const shared = await loop.create(SHARED) - const hidden = await loop.create(PRIVATE) + const shared = await loop.create(SHARED, {}, { cwd: '/tmp' }) + const hidden = await loop.create(PRIVATE, {}, { cwd: '/tmp' }) const controller = await createSessionTestController(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' }) const as = (principal: Principal, method: string): Context => { const invocation: RemoteInvocation = { @@ -107,18 +108,77 @@ function message(text: string) { } describe('Session Controller access', () => { - it('owns the Session resource kind and its default sessionId field', async () => { + it('owns the Session resource kind and its default resolver', async () => { const { ctx } = await harness() expect(() => ctx.typert.resources.register('session', { field: 'sessionId' })).toThrow(/already registered/) }) it('reads the Session resource of page and follow requests from the addressed Session', async () => { - const { controller } = await harness() + const { ctx, controller } = await harness() + const resource = ctx.typert.resources.get('session') + if (resource?.resolve === undefined) throw new Error('Session resource resolver is missing') for (const method of ['page', 'follow']) { - const reader = remoteMethods(controller).find(marker => marker.method === method)?.resources?.['session'] - expect(reader?.({ address: { kind: 'session', sessionId: SHARED } })).toBe(SHARED) - // A subagent address reads the child transcript; whether the parent's access covers it is the policy's rule. - expect(reader?.({ address: { kind: 'subagent', parentSessionId: SHARED, childSessionId: PRIVATE } })).toBe(PRIVATE) + const marker = remoteMethods(controller).find(marker => marker.method === method) + expect(marker).toBeDefined() + expect(marker?.resources?.['session']).toBeUndefined() + } + const resolve = (request: unknown) => resource.resolve({ args: { request }, parameters: [{ name: 'request', wire: 'request' }] }) + expect(resolve({ address: { kind: 'session', sessionId: SHARED } })).toBe(SHARED) + expect(resolve({ address: { kind: 'subagent', parentSessionId: SHARED, childSessionId: PRIVATE } })).toBe(PRIVATE) + }) + + it('resolves named Session IDs and first-object requests without treating unrelated strings as identities', async () => { + const { ctx } = await harness() + const resource = ctx.typert.resources.get('session') + if (resource?.resolve === undefined) throw new Error('Session resource resolver is missing') + const resolve = (args: Readonly>, ...names: string[]) => resource.resolve({ + args, parameters: names.map(name => ({ name, wire: name })), + }) + expect(resolve({ sessionId: SHARED, zzz: 'other' }, 'sessionId', 'zzz')).toBe(SHARED) + expect(resolve({ options: { sessionId: SHARED }, yyy: 'other' }, 'options', 'yyy')).toBe(SHARED) + expect(resolve({ options: { address: { kind: 'session', sessionId: SHARED } }, xxx: 'other' }, 'options', 'xxx')).toBe(SHARED) + expect(resolve({ options: { address: { kind: 'subagent', parentSessionId: SHARED, childSessionId: PRIVATE } } }, 'options')).toBe(PRIVATE) + expect(resolve({ ns: SHARED, value: 'other' }, 'ns', 'value')).toBeUndefined() + expect(resolve({ ref: SHARED, value: 'other' }, 'ref', 'value')).toBeUndefined() + expect(resolve({ zzz: 'other', sessionId: SHARED }, 'zzz', 'sessionId')).toBe(SHARED) + expect(resolve({ first: {}, later: { sessionId: SHARED } }, 'first', 'later')).toBeUndefined() + expect(resolve({ count: 1, tags: [], empty: null, options: { sessionId: SHARED } }, 'count', 'tags', 'empty', 'options')).toBe(SHARED) + expect(resolve({}, 'sessionId')).toBeUndefined() + expect(resolve({})).toBeUndefined() + expect(resource.resolve({ args: { target: SHARED }, parameters: [{ name: 'sessionId', wire: 'target' }] })).toBe(SHARED) + }) + + it.each(['page', 'follow'])('authorizes %s by Address and rejects coexisting Session IDs through SRC dispatch', async (method) => { + const { ctx, shared, hidden } = await harness() + shared.inbox.append('next-turn', message('shared history')) + hidden.inbox.append('next-turn', message('private history')) + await ctx.plugin(TypertGatewayService) + guestPolicy(ctx, { + role: { name: 'test:history-reader', resource: 'session', actions: ['session/page', 'session/follow'] }, + resource: { kind: 'session', id: SHARED }, + }) + const abort = new AbortController() + const peer: PeerScope = { id: 'history-access-peer' as PeerId, ctx, principal: GUEST, interactions: 'answer', signal: abort.signal, dispose: async () => {} } + const invoke = async (request: Record): Promise => { + const call = { peer, namespace: 'session', method, args: { request }, signal: abort.signal } + if (method === 'page') return ctx.typertGateway.invoke(call) + const stream = (await ctx.typertGateway.stream(call))[Symbol.asyncIterator]() + try { + return (await stream.next()).value + } finally { + await stream.return?.() + } + } + const request = (sessionId: SessionId) => ({ address: { kind: 'session', sessionId }, throughSeq: 0 }) + try { + await expect(invoke(request(SHARED))).resolves.toBeDefined() + await expect(invoke(request(PRIVATE))).rejects.toMatchObject({ code: 'remote-access/denied', details: { reason: 'no-allow' } }) + for (const target of [SHARED, PRIVATE]) { + await expect(invoke({ ...request(target), sessionId: SHARED })) + .rejects.toMatchObject({ code: 'remote-access/denied', details: { reason: 'resource-invalid' } }) + } + } finally { + abort.abort() } }) @@ -209,6 +269,34 @@ describe('Session Controller access', () => { ]) }) + it('keeps gateway permission checks while allowing an image referenced only by another Session', async () => { + const { ctx, hidden } = await harness() + await ctx.plugin(TypertGatewayService) + const bindings = guestPolicy(ctx) + const ref = { + attachmentId: AttachmentId(`sha256:${'ab'.repeat(32)}`), + mediaType: 'image/png' as const, bytes: 2, width: 1, height: 1, + } + hidden.session.append('user/message', createUserMessage({ + content: [{ type: 'image', attachment: ref }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + const readImage = vi.fn(() => Promise.resolve({ ref, data: Uint8Array.of(1, 2) })) + ctx.attachments.readImage = readImage + const read = (sessionId: SessionId): Promise => guestCall(ctx, 'attachment', { + request: { sessionId, attachment: ref }, + }) + await expect(read(SHARED)).rejects.toMatchObject({ code: 'remote-access/denied' }) + expect(readImage).not.toHaveBeenCalled() + bindings.push({ + role: { name: 'test:attachment-reader', resource: 'session', actions: ['session/attachment'] }, + resource: { kind: 'session', id: SHARED }, + }) + await expect(read(SHARED)).resolves.toEqual({ attachment: ref, data: 'AQI=' }) + expect(readImage).toHaveBeenCalledExactlyOnceWith(ref) + await expect(read(PRIVATE)).rejects.toMatchObject({ code: 'remote-access/denied' }) + expect(readImage).toHaveBeenCalledTimes(1) + }) + it('lets a non-owner read projections only in a Session its Session role names', async () => { const { ctx } = await harness() await ctx.plugin(TypertGatewayService) diff --git a/packages/api/session-controller/tests/remote/history.client.ts b/packages/api/session-controller/tests/remote/history.client.ts index e954f89a2b..080571b09d 100644 --- a/packages/api/session-controller/tests/remote/history.client.ts +++ b/packages/api/session-controller/tests/remote/history.client.ts @@ -1,7 +1,7 @@ /** Pure history response builders for assembled Session tests. */ import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session/types' import type { - SessionAssistantStreamBaseline, SessionFollowFrame, SessionFollowRequest, SessionPage, SessionProjectionBaseline, + SessionAssistantStreamBaseline, SessionFollowFrame, SessionFollowRequest, SessionPage, SessionEventsPage, SessionProjectionBaseline, } from '../../src/types.ts' import { historyRecordLastSeq } from '../../src/client/sessions/history-records.ts' @@ -11,8 +11,8 @@ import { historyRecordLastSeq } from '../../src/client/sessions/history-records. * @param throughSeq - inclusive final sequence. * @returns the page without records beyond the cursor. */ -export function pageThrough(page: SessionPage, throughSeq: number): SessionPage { - return { ...page, records: page.records.filter(record => historyRecordLastSeq(record) <= throughSeq) } +export function pageThrough(page: SessionPage, throughSeq: number): SessionEventsPage { + return { ...page, cursor: throughSeq, records: page.records.filter(record => historyRecordLastSeq(record) <= throughSeq) } } /** diff --git a/packages/api/session-controller/tests/remote/session.client.ts b/packages/api/session-controller/tests/remote/session.client.ts index 591dd60985..f920d1592e 100644 --- a/packages/api/session-controller/tests/remote/session.client.ts +++ b/packages/api/session-controller/tests/remote/session.client.ts @@ -12,7 +12,7 @@ import type { SessionEvent } from '@deepseek-ai/dsh-session/types' import type { RemoteFailure, RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import type { SessionAssistantStreamBaseline, SessionFollowFrame, SessionFollowRequest, - SessionPage, SessionPageRequest, + SessionEventsPage, SessionPageRequest, } from '../../src/types.ts' import { entries, historyValue } from '../event-script.client.ts' import { followSnapshot, pageThrough } from './history.client.ts' @@ -24,7 +24,7 @@ export const FOLLOW = 'session/follow' export const PAGE = 'session/page' /** A history answer as the Host returns it, possibly still pending. */ -export type HistoryAnswer = RemoteResult | Promise> +export type HistoryAnswer = RemoteResult | Promise> /** A history answer, or a function of the request that produces one. */ export type HistorySource = HistoryAnswer | ((request: Request) => HistoryAnswer) @@ -43,7 +43,7 @@ export function err(error: RemoteFailure): RemoteResult { * @param hasMore - whether older history exists. * @returns the success result. */ -export function history(events: readonly SessionEvent[], hasMore = false): RemoteResult { +export function history(events: readonly SessionEvent[], hasMore = false): RemoteResult { return ok(historyValue(events, hasMore)) } @@ -102,11 +102,11 @@ export function followScript( */ export function pageRule( history: HistorySource, -): UnaryRuleFn>> { +): UnaryRuleFn>> { return async (page) => { const result = await answer(history, page) if (!result.ok) return result - return ok(pageThrough(result.value, page.throughSeq)) + return ok(pageThrough(result.value, page.throughSeq ?? result.value.cursor)) } } @@ -144,12 +144,12 @@ export const sessionWorld: RemoteTable = { attachment: { attachmentId: 'a', mediaType: 'image/png', bytes: 1, width: 1, height: 1 }, data: 'AA==', }), - 'session/page': pageRule(ok({ records: [], hasMore: false })), + 'session/page': pageRule(ok({ cursor: -1, records: [], hasMore: false })), 'session/projections': ok({ kind: 'sequenced', asOfSeq: -1, values: { subagentCatalog: [] } }), 'subagents/prompt': ok({ messageId: 'fake-message' }), 'subagents/interruptByParent': ok({ accepted: true }), }, stream: { - 'session/follow': followScript(ok({ records: [], hasMore: false })), + 'session/follow': followScript(ok({ cursor: -1, records: [], hasMore: false })), }, } diff --git a/packages/api/session-controller/tests/session-cold.host.spec.ts b/packages/api/session-controller/tests/session-cold.host.spec.ts index 1bc9297103..560c05514f 100644 --- a/packages/api/session-controller/tests/session-cold.host.spec.ts +++ b/packages/api/session-controller/tests/session-cold.host.spec.ts @@ -11,7 +11,6 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import SessionStore from '@deepseek-ai/dsh-session' import AgentRegistry from '@deepseek-ai/dsh-agent' -import { SessionHistoryController } from '@deepseek-ai/dsh-api-session-controller/src/history.ts' import { subagentIdentityProjectionDefinition } from '@deepseek-ai/dsh-subagent/src/projection.ts' import TypertRegistry from '@deepseek-ai/dsh-typert-registry' import { createUserMessage, MessageId } from '@deepseek-ai/dsh-llm' @@ -574,10 +573,7 @@ describe('subagent ownership fence', () => { const remote = await createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' }) await ctx.sessionProjections.register(subagentIdentityProjectionDefinition) - const history = await new SessionHistoryController( - ctx, - (observation) => { observation[Symbol.dispose]() }, - ).page({ + const history = await ctx.sessionController.events({ address: { kind: 'subagent', parentSessionId: meta.parentSession as SessionId, diff --git a/packages/api/session-controller/tests/session-fork.host.spec.ts b/packages/api/session-controller/tests/session-fork.host.spec.ts index 5b00f060f1..72b21aa31e 100644 --- a/packages/api/session-controller/tests/session-fork.host.spec.ts +++ b/packages/api/session-controller/tests/session-fork.host.spec.ts @@ -328,7 +328,7 @@ describe('sessions.fork', () => { }, ) - it('cuts exactly at a completed turn and records lineage and cwd', async () => { + it('cuts exactly at a completed turn and retains cwd without source lineage', async () => { const ctx = await composed() const source = await liveAgent(ctx, 'session-source', 2) const response = await (await remote(ctx)).fork(request({ sessionId: source.id, atSeq: 2 })) @@ -338,7 +338,7 @@ describe('sessions.fork', () => { expect(child?.snapshotEvents().map(event => event.type)).toEqual([ 'turn/start', 'user/message', 'turn/end', 'session/end-seed', ]) - expect(child?.header.parentSession).toBe(source.id) + expect(child?.header.parentSession).toBeUndefined() expect(child?.header.cwd).toBe('/proj') await ctx.fiber.dispose() }) @@ -379,10 +379,10 @@ describe('sessions.fork', () => { if (!response.ok) return expect(attachSession).toHaveBeenCalledWith(response.value.sessionId) expect(ctx.sessions.get(response.value.sessionId)?.header).toMatchObject({ - parentSession: grandchild.id, cwd: '/proj', }) expect(ctx.sessions.get(response.value.sessionId)?.header.origin).toBeUndefined() + expect(ctx.sessions.get(response.value.sessionId)?.header.parentSession).toBeUndefined() await ctx.fiber.dispose() }) @@ -435,10 +435,10 @@ describe('sessions.fork', () => { expect(resume).not.toHaveBeenCalled() expect(ctx.agents.get(sourceId)).toBeUndefined() expect(ctx.sessions.get(response.value.sessionId)?.header).toMatchObject({ - parentSession: sourceId, cwd: '/proj', }) expect(ctx.sessions.get(response.value.sessionId)?.header.origin).toBeUndefined() + expect(ctx.sessions.get(response.value.sessionId)?.header.parentSession).toBeUndefined() await ctx.fiber.dispose() }) diff --git a/packages/api/session-controller/tests/session-history-journal.host.spec.ts b/packages/api/session-controller/tests/session-history-journal.host.spec.ts index f1954ed935..328e797677 100644 --- a/packages/api/session-controller/tests/session-history-journal.host.spec.ts +++ b/packages/api/session-controller/tests/session-history-journal.host.spec.ts @@ -8,7 +8,8 @@ import SessionStore from '@deepseek-ai/dsh-session' import { LlmAttemptId, ToolCallId, createMessage, createToolResultMessage, createUserMessage } from '@deepseek-ai/dsh-llm' import type { MessageSource } from '@deepseek-ai/dsh-llm' import type { Session, SessionEvent, SessionId } from '@deepseek-ai/dsh-session' -import { SessionHistoryController } from '@deepseek-ai/dsh-api-session-controller/src/history.ts' +import { HistoryController } from '../src/history/controller.ts' +import { WebController } from '../src/web/controller.ts' import type { SessionFollowFrame, SessionPage, SessionWireEvent } from '@deepseek-ai/dsh-api-session-controller/types' import { createSessionTestRemote, installSessionReadTestServices } from './test-remote.ts' @@ -57,6 +58,12 @@ async function harness(): Promise<{ ctx: Context }> { return { ctx } } +/** Initialize the independent snapshot owner and Web aggregation for direct journal tests. */ +async function controllers(ctx: Context): Promise<{ history: HistoryController; web: WebController }> { + const history = new HistoryController(ctx) + return { history, web: new WebController(ctx, history, (observation) => { observation[Symbol.dispose]() }) } +} + /** Drain one Session follow until `count` event frames arrive. */ async function collect( iterable: AsyncIterable, @@ -73,11 +80,11 @@ async function collect( /** Open follow and wait until its cursor is fixed before appending fixtures. */ async function openFollow( - history: SessionHistoryController, + web: WebController, sessionId: SessionId, signal: AbortSignal, ): Promise> { - const iterator = history.follow({ + const iterator = web.follow({ address: { kind: 'session', sessionId }, }, signal)[Symbol.asyncIterator]() await expect(iterator.next()).resolves.toMatchObject({ @@ -107,9 +114,9 @@ describe('Session history raw journal', () => { it('opens an empty opted-in Assistant baseline before any live attempt exists', async () => { const { ctx } = await harness() const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) - const history = new SessionHistoryController(ctx, (observation) => { observation[Symbol.dispose]() }) + const { web } = await controllers(ctx) const abort = new AbortController() - const iterator = history.follow({ + const iterator = web.follow({ address: { kind: 'session', sessionId: session.id }, assistantStream: true, }, abort.signal)[Symbol.asyncIterator]() @@ -127,7 +134,7 @@ describe('Session history raw journal', () => { const { ctx } = await harness() const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) const agent = { id: session.id, session, status: 'running', ctx } as Agent - const history = new SessionHistoryController(ctx, (observation) => { observation[Symbol.dispose]() }) + const { web } = await controllers(ctx) const originalObserve = ctx.sessionQuery.observeSession.bind(ctx.sessionQuery) const entered = Promise.withResolvers() const release = Promise.withResolvers() @@ -137,7 +144,7 @@ describe('Session history raw journal', () => { return originalObserve(...args) }) const abort = new AbortController() - const iterator = history.follow({ + const iterator = web.follow({ address: { kind: 'session', sessionId: session.id }, assistantStream: true, }, abort.signal)[Symbol.asyncIterator]() @@ -182,7 +189,7 @@ describe('Session history raw journal', () => { const { ctx } = await harness() const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) const agent = { id: session.id, session, status: 'running', ctx } as Agent - const history = new SessionHistoryController(ctx, (observation) => { observation[Symbol.dispose]() }) + const { web } = await controllers(ctx) const attemptId = LlmAttemptId('live-follow-attempt') const emit = (frame: AssistantStreamFrame): void => { ctx.emit('agent/assistant-stream', { agent, frame }) @@ -197,7 +204,7 @@ describe('Session history raw journal', () => { time: 1, chunk: firstChunk, }) const abort = new AbortController() - const iterator = history.follow({ + const iterator = web.follow({ address: { kind: 'session', sessionId: session.id }, assistantStream: true, }, abort.signal)[Symbol.asyncIterator]() @@ -249,7 +256,7 @@ describe('Session history raw journal', () => { const { ctx } = await harness() const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) const agent = { id: session.id, session, status: 'running', ctx } as Agent - const history = new SessionHistoryController(ctx, (observation) => { observation[Symbol.dispose]() }) + const { web } = await controllers(ctx) const attemptId = LlmAttemptId(`${session.id}:1`) ctx.emit('agent/assistant-stream', { agent, @@ -267,7 +274,7 @@ describe('Session history raw journal', () => { }, }) const abort = new AbortController() - const iterator = history.follow({ + const iterator = web.follow({ address: { kind: 'session', sessionId: session.id }, assistantStream: true, }, abort.signal)[Symbol.asyncIterator]() @@ -311,7 +318,7 @@ describe('Session history raw journal', () => { const { ctx } = await harness() const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) const agent = { id: session.id, session, status: 'running', ctx } as Agent - const history = new SessionHistoryController(ctx, (observation) => { observation[Symbol.dispose]() }) + const { web } = await controllers(ctx) const attemptId = LlmAttemptId('revision-gap-attempt') ctx.emit('agent/assistant-stream', { agent, @@ -329,7 +336,7 @@ describe('Session history raw journal', () => { }, }) const abort = new AbortController() - const iterator = history.follow({ + const iterator = web.follow({ address: { kind: 'session', sessionId: session.id }, assistantStream: true, }, abort.signal)[Symbol.asyncIterator]() @@ -351,7 +358,7 @@ describe('Session history raw journal', () => { const { ctx } = await harness() const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) const agent = { id: session.id, session, status: 'running', ctx } as Agent - const history = new SessionHistoryController(ctx, (observation) => { observation[Symbol.dispose]() }) + const { web } = await controllers(ctx) const attemptId = LlmAttemptId('dense-index-attempt') ctx.emit('agent/assistant-stream', { agent, @@ -369,7 +376,7 @@ describe('Session history raw journal', () => { }, }) const abort = new AbortController() - const iterator = history.follow({ + const iterator = web.follow({ address: { kind: 'session', sessionId: session.id }, assistantStream: true, }, abort.signal)[Symbol.asyncIterator]() @@ -391,7 +398,7 @@ describe('Session history raw journal', () => { const { ctx } = await harness() const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) const agent = { id: session.id, session, status: 'running', ctx } as Agent - const history = new SessionHistoryController(ctx, (observation) => { observation[Symbol.dispose]() }) + const { web } = await controllers(ctx) const attemptId = LlmAttemptId('cached-baseline-attempt') ctx.emit('agent/assistant-stream', { agent, @@ -402,12 +409,12 @@ describe('Session history raw journal', () => { }) const firstAbort = new AbortController() - const firstIterator = history.follow({ + const firstIterator = web.follow({ address: { kind: 'session', sessionId: session.id }, assistantStream: true, }, firstAbort.signal)[Symbol.asyncIterator]() const secondAbort = new AbortController() - const secondIterator = history.follow({ + const secondIterator = web.follow({ address: { kind: 'session', sessionId: session.id }, assistantStream: true, }, secondAbort.signal)[Symbol.asyncIterator]() @@ -431,9 +438,9 @@ describe('Session history raw journal', () => { it('opens an empty Assistant baseline before the target Agent emits frames', async () => { const { ctx } = await harness() const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) - const history = new SessionHistoryController(ctx, (observation) => { observation[Symbol.dispose]() }) + const { web } = await controllers(ctx) const abort = new AbortController() - const iterator = history.follow({ + const iterator = web.follow({ address: { kind: 'session', sessionId: session.id }, assistantStream: true, }, abort.signal)[Symbol.asyncIterator]() @@ -456,9 +463,9 @@ describe('Session history raw journal', () => { const target = ctx.sessions.create(undefined, { meta: { cwd: '/target' } }) const other = ctx.sessions.create(undefined, { meta: { cwd: '/other' } }) const otherAgent = { id: other.id, session: other, status: 'running', ctx } as Agent - const history = new SessionHistoryController(ctx, (observation) => { observation[Symbol.dispose]() }) + const { web } = await controllers(ctx) const abort = new AbortController() - const iterator = history.follow({ + const iterator = web.follow({ address: { kind: 'session', sessionId: target.id }, assistantStream: true, }, abort.signal)[Symbol.asyncIterator]() @@ -489,7 +496,7 @@ describe('Session history raw journal', () => { const { ctx } = await harness() const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) const agent = { id: session.id, session, status: 'running', ctx } as Agent - const history = new SessionHistoryController(ctx, (observation) => { observation[Symbol.dispose]() }) + const { web } = await controllers(ctx) const observationStarted = Promise.withResolvers() const releaseObservation = Promise.withResolvers() const originalObserve = ctx.sessionQuery.observeSession.bind(ctx.sessionQuery) @@ -499,7 +506,7 @@ describe('Session history raw journal', () => { return await originalObserve(sessionId, options) }) const abort = new AbortController() - const iterator = history.follow({ + const iterator = web.follow({ address: { kind: 'session', sessionId: session.id }, assistantStream: true, }, abort.signal)[Symbol.asyncIterator]() @@ -539,7 +546,7 @@ describe('Session history raw journal', () => { const { ctx } = await harness() const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) const agent = { id: session.id, session, status: 'running', ctx } as Agent - const history = new SessionHistoryController(ctx, (observation) => { observation[Symbol.dispose]() }) + const { web } = await controllers(ctx) const attemptId = LlmAttemptId(`${session.id}:1`) ctx.emit('agent/assistant-stream', { agent, @@ -557,7 +564,7 @@ describe('Session history raw journal', () => { return await originalObserve(sessionId, options) }) const abort = new AbortController() - const iterator = history.follow({ + const iterator = web.follow({ address: { kind: 'session', sessionId: session.id }, assistantStream: true, }, abort.signal)[Symbol.asyncIterator]() @@ -613,9 +620,9 @@ describe('Session history raw journal', () => { const { ctx } = await harness() const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) const agent = { id: session.id, session, status: 'running', ctx } as Agent - const history = new SessionHistoryController(ctx, (observation) => { observation[Symbol.dispose]() }) + const { web } = await controllers(ctx) const abort = new AbortController() - const iterator = history.follow({ + const iterator = web.follow({ address: { kind: 'session', sessionId: session.id }, }, abort.signal)[Symbol.asyncIterator]() const opening = await iterator.next() @@ -655,9 +662,9 @@ describe('Session history raw journal', () => { it('follows raw tool events and preserves result metadata without a Tools service', async () => { const { ctx } = await harness() const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) - const history = new SessionHistoryController(ctx, (observation) => { observation[Symbol.dispose]() }) + const { web } = await controllers(ctx) const abort = new AbortController() - const stream = await openFollow(history, session.id, abort.signal) + const stream = await openFollow(web, session.id, abort.signal) const collected = collect(stream, 2, abort) const call = session.append('tool/call', { turn: 1, step: 1, callId: ToolCallId('raw-call'), name: 'custom', arguments: '{malformed', @@ -684,9 +691,9 @@ describe('Session history raw journal', () => { it('follows live results without rescanning Session history', async () => { const { ctx } = await harness() const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) - const history = new SessionHistoryController(ctx, (observation) => { observation[Symbol.dispose]() }) + const { web } = await controllers(ctx) const abort = new AbortController() - const stream = await openFollow(history, session.id, abort.signal) + const stream = await openFollow(web, session.id, abort.signal) const iterator = stream[Symbol.asyncIterator]() session.append('tool/call', { @@ -957,9 +964,9 @@ describe('Session history raw journal', () => { it('follows a result after turn/end without reading the addressed Session log', async () => { const { ctx } = await harness() const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) - const history = new SessionHistoryController(ctx, (observation) => { observation[Symbol.dispose]() }) + const { web } = await controllers(ctx) const abort = new AbortController() - const stream = await openFollow(history, session.id, abort.signal) + const stream = await openFollow(web, session.id, abort.signal) const iterator = stream[Symbol.asyncIterator]() session.append('turn/start', { turn: 1 }) diff --git a/packages/api/session-controller/tests/session-models.host.spec.ts b/packages/api/session-controller/tests/session-models.host.spec.ts index cda4c14e6a..7c7db7e856 100644 --- a/packages/api/session-controller/tests/session-models.host.spec.ts +++ b/packages/api/session-controller/tests/session-models.host.spec.ts @@ -329,40 +329,6 @@ describe('Web session model selection', () => { await ctx.fiber.dispose() }) - it('authorizes attachment bytes only when the session event stream references the id', async () => { - const { ctx, agent, sessionId } = await harness() - const ref = { - attachmentId: 'att-authorized', mediaType: 'image/png' as const, bytes: 2, width: 1, height: 1, - } - const readImage = vi.fn(() => Promise.resolve({ ref, data: Uint8Array.of(1, 2) })) - ctx.provide('attachments', { readImage } as never) - const remote = await createSessionTestRemote(ctx, { - defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }), - cwd: '/tmp', - }) - agent.session.append('agent/inbox/spliced', { - target: 'next-turn', - start: 0, - inserted: [{ - id: 'queued-image', role: 'user', source: { kind: 'user' }, - content: [{ type: 'image', attachment: ref }], - }], - } as never) - - const allowed = await remote.attachment(request({ - sessionId, attachmentId: 'att-authorized' as never, - })) - expect(allowed).toMatchObject({ ok: true, value: { attachment: ref, data: 'AQI=' } }) - const denied = await remote.attachment(request({ - sessionId, attachmentId: 'att-other' as never, - })) - expect(denied).toMatchObject({ - ok: false, - error: { code: 'session/attachment-invalid', details: { reason: 'ATTACHMENT_NOT_REFERENCED' } }, - }) - expect(readImage).toHaveBeenCalledOnce() - await ctx.fiber.dispose() - }) it('checks configured key references even for empty catalogs and skips profiles without keys', async () => { const ctx = new Context() await ctx.plugin(LlmRuntime) diff --git a/packages/api/session-controller/tests/session-pending-submissions.client.spec.ts b/packages/api/session-controller/tests/session-pending-submissions.client.spec.ts index af3c06a0b6..608c59a8e0 100644 --- a/packages/api/session-controller/tests/session-pending-submissions.client.spec.ts +++ b/packages/api/session-controller/tests/session-pending-submissions.client.spec.ts @@ -68,17 +68,43 @@ async function settleFrames(): Promise { await new Promise(resolve => setTimeout(resolve, 0)) } +type BenchSession = Awaited> + +/** Register an echo and let the Host accept its prompt, which publishes the echo. */ +async function submitAccepted( + session: BenchSession, + input: Parameters[0], +): Promise> { + const handle = session.beginSubmission(input) + const result = await session.prompt([{ type: 'text', text: input.text }], input.mode, undefined, handle.requestId) + expect(result.ok).toBe(true) + return handle +} + describe('beginSubmission', () => { - it('inserts the echo synchronously and flips the engaging edge before any prompt call', async ({ mock, start }) => { + it('publishes the echo and the engaging edge only once the Host accepts the prompt', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) expect(session.getSnapshot()).toMatchObject({ pendingSubmissions: [], promptAttempted: false }) + const onAccept = vi.fn() const handle = session.beginSubmission({ mode: 'queue', text: '你好', attachments: [{ type: 'image', value: { previewUrl: 'blob:p1', name: 'a.png', width: 4, height: 3 }, }], + onAccept, }) + expect(session.getSnapshot()).toMatchObject({ pendingSubmissions: [], promptAttempted: false }) + expect(mock.log.requests()).toEqual([]) + const receipt = Promise.withResolvers<{ ok: true; value: { accepted: true } }>() + mock.remote.session.prompt.mockImplementationOnce(() => receipt.promise) + const inFlight = session.prompt([{ type: 'text', text: '你好' }], 'queue', undefined, handle.requestId) + await Promise.resolve() + expect(session.getSnapshot()).toMatchObject({ pendingSubmissions: [], promptAttempted: false }) + expect(onAccept).not.toHaveBeenCalled() + receipt.resolve({ ok: true, value: { accepted: true } }) + expect((await inFlight).ok).toBe(true) + expect(onAccept).toHaveBeenCalledOnce() expect(session.getSnapshot().promptAttempted).toBe(true) expect(session.getSnapshot().pendingSubmissions).toMatchObject([{ requestId: handle.requestId, @@ -88,15 +114,81 @@ describe('beginSubmission', () => { type: 'image', value: { previewUrl: 'blob:p1', name: 'a.png', width: 4, height: 3 }, }], }]) - expect(mock.log.requests()).toEqual([]) }, COLD_BOOT_TIMEOUT_MS) + for (const { mode, running, target, placement } of [ + { mode: 'queue', running: false, target: 'next-turn', placement: 'transcript' }, + { mode: 'steer', running: true, target: 'next-step', placement: 'steering' }, + ] as const) { + for (const path of ['projection', 'durable event'] as const) { + it(`accepts a ${placement} prompt once the Inbox holds it, ahead of the Host receipt (${path})`, async ({ mock, start }) => { + const onEngaged = vi.fn() + const session = await sessionBench(mock, start, SID, { onEngaged }) + await session.open() + session.handleBlank(!running) + session.handleRunning(running) + const onAccept = vi.fn() + const handle = session.beginSubmission({ mode, text: '先进收件箱', attachments: [], onAccept }) + const receipt = Promise.withResolvers<{ ok: true; value: { accepted: true } }>() + mock.remote.session.prompt.mockImplementationOnce(() => receipt.promise) + const inFlight = session.prompt([{ type: 'text', text: '先进收件箱' }], mode, undefined, handle.requestId) + const empty = { 'next-turn': [], 'next-step': [] } + // Projection faces notify in a microtask. + session.projections.apply('inbox', { ...empty, [target]: [queuedItem('another-request' as SessionRequestId)] }, -1) + await Promise.resolve() + expect(session.getSnapshot()).toMatchObject({ pendingSubmissions: [], blank: !running, promptAttempted: false }) + expect(onAccept).not.toHaveBeenCalled() + const message = queuedItem(handle.requestId) + if (path === 'projection') { + session.projections.apply('inbox', { ...empty, [target]: [message] }, SessionSeq(0)) + await Promise.resolve() + } else { + await pushEvent(mock, { + type: 'agent/inbox/spliced', seq: SessionSeq(0), time: 1, + data: { target, start: 0, inserted: [message] }, + }) + } + expect(session.getSnapshot()).toMatchObject({ + pendingSubmissions: [{ requestId: handle.requestId, placement, text: '先进收件箱' }], + blank: false, + promptAttempted: true, + ...running ? {} : { awaitingFirstTurn: true }, + }) + expect(onEngaged).toHaveBeenCalledOnce() + expect(onAccept).toHaveBeenCalledOnce() + receipt.resolve({ ok: true, value: { accepted: true } }) + expect((await inFlight).ok).toBe(true) + expect(session.getSnapshot().pendingSubmissions).toHaveLength(1) + expect(onEngaged).toHaveBeenCalledOnce() + expect(onAccept).toHaveBeenCalledOnce() + }) + } + } + + it('never publishes an echo whose message was observed before the Host receipt', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + await session.open() + const retirements: PendingSubmissionRetirement[] = [] + const handle = session.beginSubmission({ + mode: 'queue', text: '先到', attachments: [], onRetire: retirement => retirements.push(retirement), + }) + const receipt = Promise.withResolvers<{ ok: true; value: { accepted: true } }>() + mock.remote.session.prompt.mockImplementationOnce(() => receipt.promise) + const inFlight = session.prompt([{ type: 'text', text: '先到' }], 'queue', undefined, handle.requestId) + await pushEvent(mock, promptEvent(SessionSeq(0), handle.requestId)) + await settleFrames() + expect(retirements).toEqual([{ reason: 'observed', attachments: [] }]) + receipt.resolve({ ok: true, value: { accepted: true } }) + expect((await inFlight).ok).toBe(true) + expect(session.getSnapshot().pendingSubmissions).toEqual([]) + }) + it('derives and captures the echo placement from running state and delivery mode', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) - session.beginSubmission({ mode: 'queue', text: '空闲', attachments: [] }) + await submitAccepted(session, { mode: 'queue', text: '空闲', attachments: [] }) session.handleRunning(true) - session.beginSubmission({ mode: 'queue', text: '排队', attachments: [] }) - session.beginSubmission({ mode: 'steer', text: '纠偏', attachments: [] }) + await submitAccepted(session, { mode: 'queue', text: '排队', attachments: [] }) + await submitAccepted(session, { mode: 'steer', text: '纠偏', attachments: [] }) session.handleRunning(false) expect(session.getSnapshot().pendingSubmissions.map(({ text, placement }) => ({ text, placement }))).toEqual([ { text: '空闲', placement: 'transcript' }, @@ -107,12 +199,12 @@ describe('beginSubmission', () => { it('keeps rapid ordinary submissions in Chat until the running update arrives', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) - for (const text of ['A', 'B', 'C']) session.beginSubmission({ mode: 'queue', text, attachments: [] }) + for (const text of ['A', 'B', 'C']) await submitAccepted(session, { mode: 'queue', text, attachments: [] }) expect(session.getSnapshot().pendingSubmissions.map(input => input.placement)).toEqual([ 'transcript', 'transcript', 'transcript', ]) session.handleRunning(true) - session.beginSubmission({ mode: 'queue', text: 'D', attachments: [] }) + await submitAccepted(session, { mode: 'queue', text: 'D', attachments: [] }) expect(session.getSnapshot().pendingSubmissions.map(input => input.placement)).toEqual([ 'transcript', 'transcript', 'transcript', 'queued', ]) @@ -161,8 +253,8 @@ describe('prompt-coupled retirement', () => { it('an unidentified prompt failure leaves registered echoes alone', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) + await submitAccepted(session, { mode: 'queue', text: '还在', attachments: [] }) mock.remote.session.prompt.mockResolvedValue(err(new RemoteError('session/agent-busy', '忙', { reason: 'busy' }))) - session.beginSubmission({ mode: 'queue', text: '还在', attachments: [] }) await session.prompt([{ type: 'text', text: '另一个' }], 'queue') expect(session.getSnapshot().pendingSubmissions).toHaveLength(1) }) @@ -173,7 +265,7 @@ describe('observed retirement', () => { const session = await sessionBench(mock, start, SID) await session.open() const retirements: PendingSubmissionRetirement[] = [] - const handle = session.beginSubmission({ + const handle = await submitAccepted(session, { mode: 'queue', text: '发送', attachments: [{ type: 'image', value: { previewUrl: 'blob:p1' } }], @@ -193,7 +285,7 @@ describe('observed retirement', () => { const session = await sessionBench(mock, start, SID) await session.open() const onRetire = vi.fn() - const handle = session.beginSubmission({ mode: 'steer', text: 'accepted', attachments: [], onRetire }) + const handle = await submitAccepted(session, { mode: 'steer', text: 'accepted', attachments: [], onRetire }) const refs = [imageRef('claimed-image')] const message = queuedItem(handle.requestId, refs) session.projections.apply('inbox', { 'next-turn': [], 'next-step': [message] }, SessionSeq(0)) @@ -229,7 +321,7 @@ describe('observed retirement', () => { vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => frames.push(callback)) const onRetire = vi.fn() session.handleRunning(mode === 'steer') - const handle = session.beginSubmission({ mode, text: 'local input', attachments: [], onRetire }) + const handle = await submitAccepted(session, { mode, text: 'local input', attachments: [], onRetire }) const refs = [imageRef('idle-image'), fileRef('idle-file')] const message = queuedItem(handle.requestId, refs) const queued = { 'next-turn': [], 'next-step': [], [target]: [message] } @@ -277,10 +369,10 @@ describe('observed retirement', () => { const normalRetired = vi.fn() const queueRetired = vi.fn() const steerRetired = vi.fn() - const normal = session.beginSubmission({ mode: 'queue', text: 'opening', attachments: [], onRetire: normalRetired }) + const normal = await submitAccepted(session, { mode: 'queue', text: 'opening', attachments: [], onRetire: normalRetired }) session.handleRunning(true) - const queued = session.beginSubmission({ mode: 'queue', text: 'queued', attachments: [], onRetire: queueRetired }) - const steer = session.beginSubmission({ mode: 'steer', text: 'steering', attachments: [], onRetire: steerRetired }) + const queued = await submitAccepted(session, { mode: 'queue', text: 'queued', attachments: [], onRetire: queueRetired }) + const steer = await submitAccepted(session, { mode: 'steer', text: 'steering', attachments: [], onRetire: steerRetired }) const normalMessage = queuedItem(normal.requestId, [fileRef('opening-file')]) const queuedMessage = queuedItem(queued.requestId, [imageRef('queued-image')]) const steerMessage = queuedItem(steer.requestId, [imageRef('steer-image'), fileRef('steer-file')]) @@ -342,7 +434,7 @@ describe('observed retirement', () => { await session.open() session.handleRunning(true) const onRetire = vi.fn() - const handle = session.beginSubmission({ mode: 'steer', text: 'accepted', attachments: [], onRetire }) + const handle = await submitAccepted(session, { mode: 'steer', text: 'accepted', attachments: [], onRetire }) const refs = [imageRef('steer-image')] const message = queuedItem(handle.requestId, refs) const echo = session.getSnapshot().pendingSubmissions[0] @@ -376,9 +468,9 @@ describe('observed retirement', () => { session.handleRunning(target === 'next-step') const canceled = vi.fn() const rejected = vi.fn() - const first = session.beginSubmission({ mode: 'steer', text: 'cancel', attachments: [], onRetire: canceled }) - const second = session.beginSubmission({ mode: 'steer', text: 'reject', attachments: [], onRetire: rejected }) - const unclaimed = session.beginSubmission({ mode: 'steer', text: 'later', attachments: [] }) + const first = await submitAccepted(session, { mode: 'steer', text: 'cancel', attachments: [], onRetire: canceled }) + const second = await submitAccepted(session, { mode: 'steer', text: 'reject', attachments: [], onRetire: rejected }) + const unclaimed = await submitAccepted(session, { mode: 'steer', text: 'later', attachments: [] }) const foreign = createUserMessage({ source: { kind: 'user' }, content: [] }) await pushEvent(mock, { type: 'agent/inbox/spliced', seq: SessionSeq(0), time: 1, @@ -469,7 +561,7 @@ describe('observed retirement', () => { await session.open() session.handleRunning(target === 'next-step') const onRetire = vi.fn() - const handle = session.beginSubmission({ mode: 'steer', text: 'accepted', attachments: [], onRetire }) + const handle = await submitAccepted(session, { mode: 'steer', text: 'accepted', attachments: [], onRetire }) const refs = [imageRef('steer-image'), fileRef('steer-file')] const message = queuedItem(handle.requestId, refs) if (target === 'next-turn') { @@ -481,7 +573,7 @@ describe('observed retirement', () => { data: { target, start: 0, inserted: [message] }, }) } - const unconfirmed = session.beginSubmission({ mode: 'steer', text: 'not accepted yet', attachments: [] }) + const unconfirmed = await submitAccepted(session, { mode: 'steer', text: 'not accepted yet', attachments: [] }) const inbox = { 'next-turn': [], 'next-step': [], [target]: pending ? [message] : [] } const replacement = { ...historyValue([ev.turnEnd(SessionSeq(10), 2)], true), @@ -572,7 +664,7 @@ describe('observed retirement', () => { frames.push(fn) return frames.length }) - const handle = session.beginSubmission({ mode: 'queue', text: '帧', attachments: [] }) + const handle = await submitAccepted(session, { mode: 'queue', text: '帧', attachments: [] }) await pushEvent(mock, promptEvent(SessionSeq(0), handle.requestId)) expect(session.getSnapshot().pendingSubmissions).toHaveLength(1) expect(frames).toHaveLength(1) diff --git a/packages/api/session-controller/tests/session.client.spec.ts b/packages/api/session-controller/tests/session.client.spec.ts index 8d1838e40f..70c69ca033 100644 --- a/packages/api/session-controller/tests/session.client.spec.ts +++ b/packages/api/session-controller/tests/session.client.spec.ts @@ -15,7 +15,7 @@ import { ok, type RemoteMock } from '@deepseek-ai/dsh-remote-mock' import { createClientTest, type TestClient, webApp } from '@deepseek-ai/dsh-client-test-runtime/src/assembly/index.ts' import { Session } from '../src/client/sessions/session.ts' import { SessionEventStream } from '../src/client/transport.ts' -import type { SessionFollowRequest, SessionPage, SessionPageRequest } from '../src/types.ts' +import type { SessionFollowRequest, SessionEventsPage, SessionPageRequest } from '../src/types.ts' import { entries, ev, historyValue, plainTurn } from './event-script.client.ts' import { sessionBench } from './remote/bench.client.ts' import { @@ -122,7 +122,7 @@ describe('Session open', () => { it('stitches live frames landing right behind the opening snapshot, dropping the page overlap', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) - const gate = Promise.withResolvers() + const gate = Promise.withResolvers() const page = plainTurn(SessionSeq(10), 0, '早', '安') mock.stream(FOLLOW, async ([request], stream) => { stream.push(followSnapshot(await gate.promise, request as SessionFollowRequest)) @@ -243,7 +243,7 @@ describe('paging', () => { mock.stream(FOLLOW, followScript(history(newest, true))) await session.open() - const gate = Promise.withResolvers>() + const gate = Promise.withResolvers>() mock.remote.session.page.mockImplementation(pageRule(request => (request.beforeSeq === 12 ? history(middle, true) : history(oldest)))) mock.remote.session.page.mockReturnValueOnce(gate.promise) const jump = session.loadThrough(SessionSeq(0)) @@ -279,7 +279,7 @@ describe('paging', () => { mock.stream(FOLLOW, followScript(history(newest, true))) await session.open() const secondRequested = Promise.withResolvers() - const lastPage = Promise.withResolvers>() + const lastPage = Promise.withResolvers>() mock.remote.session.page.mockImplementation(pageRule((request) => { if (request.beforeSeq === 12) return history(middle, true) secondRequested.resolve(undefined) @@ -334,7 +334,7 @@ describe('paging', () => { mock.stream(FOLLOW, followScript(history(newest, true))) await session.open() const secondRequested = Promise.withResolvers() - const lastPage = Promise.withResolvers>() + const lastPage = Promise.withResolvers>() mock.remote.session.page.mockImplementation(pageRule((request) => { if (request.beforeSeq === 12) return history(plainTurn(SessionSeq(6), 1, 'middle', 'answer'), true) secondRequested.resolve(undefined) @@ -360,7 +360,7 @@ describe('paging', () => { mock.stream(FOLLOW, followScript(history(plainTurn(SessionSeq(12), 2, 'e', 'f'), true))) await session.open() - const gate = Promise.withResolvers>() + const gate = Promise.withResolvers>() mock.remote.session.page.mockImplementation(pageRule(history(oldest))) mock.remote.session.page.mockReturnValueOnce(gate.promise) const first = session.loadThrough(SessionSeq(6)) @@ -381,7 +381,7 @@ describe('paging', () => { await session.open() // A plain single-page pull holds the busy flag while the jump is refused. - const gate = Promise.withResolvers>() + const gate = Promise.withResolvers>() mock.remote.session.page.mockReturnValueOnce(gate.promise) const older = session.loadOlder() await session.loadThrough(SessionSeq(0)) // refused: must not park seq 0 anywhere @@ -409,7 +409,7 @@ describe('paging', () => { mock.stream(FOLLOW, followScript(history(plainTurn(SessionSeq(12), 2, 'x', 'y'), true))) await session.open() - const gate = Promise.withResolvers>() + const gate = Promise.withResolvers>() mock.remote.session.page.mockReturnValueOnce(gate.promise) const jump = session.loadThrough(SessionSeq(0)) // The address is rebuilt while the first page is in flight; the same follow script serves the new generation. @@ -459,7 +459,7 @@ describe('paging', () => { const session = await sessionBench(mock, start, SID) mock.stream(FOLLOW, followScript(history(plainTurn(SessionSeq(6), 1, 'x', 'y'), true))) await session.open() - const gate = Promise.withResolvers>() + const gate = Promise.withResolvers>() mock.remote.session.page.mockImplementation(pageRule(gate.promise)) const first = session.loadOlder() const second = session.loadOlder() @@ -484,7 +484,7 @@ describe('prompt and cancel errors', () => { expect(steered).toEqual({ ok: true, value: { accepted: true } }) expect(cancelled).toEqual({ ok: true, value: { accepted: true } }) expect(mock.log.requests(FOLLOW)).toEqual([ - { address: { kind: 'subagent', ...CHILD }, assistantStream: true, maxMessages: 500, turnWindow: { minMessages: 50, minTurns: 2 } }, + { address: { kind: 'subagent', ...CHILD }, activate: true, assistantStream: true, maxMessages: 500, turnWindow: { minMessages: 50, minTurns: 2 } }, ]) expect(mock.log.requests(PAGE)).toEqual([]) // The prompt mode crosses the wire as the request's delivery. @@ -593,7 +593,7 @@ describe('prompt and cancel errors', () => { expect(mock.log.requests('subagents/prompt')).toMatchObject([CHILD]) expect(mock.log.calls('subagents/interruptByParent').map(call => call.args)).toEqual([[SID, PARENT, 'continuable']]) expect(mock.log.requests(FOLLOW)).toEqual([ - { address: { kind: 'subagent', ...CHILD, mode: 'one-shot' }, assistantStream: true, maxMessages: 500, turnWindow: { minMessages: 50, minTurns: 2 } }, + { address: { kind: 'subagent', ...CHILD, mode: 'one-shot' }, activate: true, assistantStream: true, maxMessages: 500, turnWindow: { minMessages: 50, minTurns: 2 } }, ]) expect(mock.log.requests(PAGE)).toEqual([]) expect(mock.log.requests('session/cancel')).toEqual([]) @@ -613,15 +613,17 @@ describe('prompt and cancel errors', () => { ]) }) - it('publishes the first-prompt lifecycle synchronously before the Remote settles', async ({ mock, start }) => { + it('publishes the first-prompt lifecycle once the Host accepts the prompt', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) session.handleBlank(true) expect(session.getSnapshot()).toMatchObject({ blank: true, promptAttempted: false, awaitingFirstTurn: false, }) const inFlight = session.prompt([{ type: 'text', text: '要发的' }], 'queue') + // An unrelated update rebuilds the snapshot while the Host has not answered yet. + session.handleAgentError('unrelated live failure') expect(session.getSnapshot()).toMatchObject({ - blank: true, promptAttempted: true, awaitingFirstTurn: true, + blank: true, promptAttempted: false, awaitingFirstTurn: false, lastAgentError: 'unrelated live failure', }) const result = await inFlight expect(result.ok).toBe(true) @@ -642,9 +644,22 @@ describe('prompt and cancel errors', () => { const session = await sessionBench(mock, start, SID) session.handleBlank(false) const inFlight = session.prompt([{ type: 'text', text: '继续' }], 'queue') - expect(session.getSnapshot()).toMatchObject({ blank: false, promptAttempted: true, awaitingFirstTurn: false }) + expect(session.getSnapshot()).toMatchObject({ blank: false, promptAttempted: false, awaitingFirstTurn: false }) expect((await inFlight).ok).toBe(true) - expect(session.getSnapshot()).toMatchObject({ blank: false, awaitingFirstTurn: false }) + expect(session.getSnapshot()).toMatchObject({ blank: false, promptAttempted: true, awaitingFirstTurn: false }) + }) + + it('does not await a first turn that started before the Host receipt arrived', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + session.handleBlank(true) + const receipt = Promise.withResolvers<{ ok: true; value: { accepted: true } }>() + mock.remote.session.prompt.mockImplementationOnce(() => receipt.promise) + const inFlight = session.prompt([{ type: 'text', text: '很快' }], 'queue') + session.handleRunning(true) + session.handleRunning(false) + receipt.resolve({ ok: true, value: { accepted: true } }) + expect((await inFlight).ok).toBe(true) + expect(session.getSnapshot()).toMatchObject({ blank: false, promptAttempted: true, awaitingFirstTurn: false }) }) it('keeps an accepted first prompt converted when a later prompt is rejected', async ({ mock, start }) => { @@ -662,7 +677,7 @@ describe('prompt and cancel errors', () => { }) }) - it('keeps the attempted-first-prompt state when the Host rejects the prompt', async ({ mock, start }) => { + it('keeps a first prompt the Host rejects blank and unattempted', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) session.handleBlank(true) mock.remote.session.prompt.mockResolvedValue(err(new RemoteError('session/agent-busy', 'busy', { reason: 'x' }))) @@ -670,7 +685,7 @@ describe('prompt and cancel errors', () => { expect(result.ok).toBe(false) expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'session/agent-busy' } }) expect(session.getSnapshot()).toMatchObject({ - blank: true, promptAttempted: true, awaitingFirstTurn: true, + blank: true, promptAttempted: false, awaitingFirstTurn: false, }) }) @@ -684,9 +699,11 @@ describe('prompt and cancel errors', () => { expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'gateway/internal' } }) }) - it('reads session-authorized attachment bytes and keeps the opaque id on the wire', async ({ mock, start }) => { + it('sends the complete image reference and decodes the gateway response', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) - const result = await session.readAttachment('attachment-1' as never) + const attachment = { attachmentId: AttachmentId('attachment-1'), mediaType: 'image/png' as const, + bytes: 1, width: 1, height: 1, name: 'picture.png', originalDimensions: { width: 2, height: 2 } } + const result = await session.readAttachment(attachment) expect(result).toEqual({ ok: true, value: { @@ -695,7 +712,7 @@ describe('prompt and cancel errors', () => { }, }) expect(mock.log.requests('session/attachment')).toEqual([{ - sessionId: SID, attachmentId: 'attachment-1', + sessionId: SID, attachment, }]) }) @@ -703,7 +720,9 @@ describe('prompt and cancel errors', () => { const session = await sessionBench(mock, start, SID) const failure = new RemoteError('gateway/internal', 'attachment unavailable', {}) mock.remote.session.attachment.mockResolvedValueOnce(err(failure)) - await expect(session.readAttachment(AttachmentId('missing'))).resolves.toMatchObject({ ok: false, error: failure }) + await expect(session.readAttachment({ + attachmentId: AttachmentId('missing'), mediaType: 'image/png', bytes: 1, width: 1, height: 1, + })).resolves.toMatchObject({ ok: false, error: failure }) }) it('reports an unmatched command and forwards execution failures without opening history', async ({ mock, start }) => { @@ -874,7 +893,7 @@ describe('remaining branches', () => { const session = await sessionBench(mock, start, SID) mock.stream(FOLLOW, followScript(history(plainTurn(SessionSeq(0), 0, 'a', 'b')))) await session.open() - const gate = Promise.withResolvers>() + const gate = Promise.withResolvers>() mock.remote.session.page.mockImplementation(pageRule(gate.promise)) await pushEvent(mock, ev.user(SessionSeq(9), '洞一')) await pushEvent(mock, ev.user(SessionSeq(10), '洞二')) @@ -887,7 +906,7 @@ describe('remaining branches', () => { it('drops a stale opening without replacing the new generation error state', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) - const stale = Promise.withResolvers>() + const stale = Promise.withResolvers>() mock.stream(FOLLOW, followScript(() => stale.promise)) const opening = session.open() mock.stream(FOLLOW, followScript(history(plainTurn(SessionSeq(0), 0, 'a', 'b')))) @@ -899,7 +918,7 @@ describe('remaining branches', () => { it('drops a stale doOpen whose history resolved successfully after resync superseded it', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) - const stale = Promise.withResolvers>() + const stale = Promise.withResolvers>() mock.stream(FOLLOW, followScript(() => stale.promise)) const opening = session.open() mock.stream(FOLLOW, followScript(history(plainTurn(SessionSeq(6), 1, '新', '代')))) @@ -913,7 +932,7 @@ describe('remaining branches', () => { const session = await sessionBench(mock, start, SID) mock.stream(FOLLOW, followScript(history(plainTurn(SessionSeq(0), 0, 'a', 'b')))) await session.open() - const repairPull = Promise.withResolvers>() + const repairPull = Promise.withResolvers>() mock.remote.session.page.mockImplementation(pageRule(repairPull.promise)) await pushEvent(mock, ev.user(SessionSeq(9), '洞')) await vi.waitFor(() => { expect(mock.log.requests(PAGE)).toHaveLength(1) }) @@ -955,7 +974,7 @@ describe('resync', () => { mock.stream(FOLLOW, followScript(history(plainTurn(SessionSeq(0), 0, '旧', '窗')))) await session.open() const oldWindow = session.eventSource.getSnapshot() - const replacement = Promise.withResolvers() + const replacement = Promise.withResolvers() // The reconnect generation: its snapshot is gated, then two live frames land out of order right behind it. mock.stream(FOLLOW, async ([request], stream) => { stream.push(followSnapshot(await replacement.promise, request as SessionFollowRequest)) @@ -1014,7 +1033,7 @@ describe('resync', () => { it('drops a stale in-flight open superseded by resync (generation guard)', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) - const stale = Promise.withResolvers>() + const stale = Promise.withResolvers>() mock.stream(FOLLOW, followScript(() => stale.promise)) const firstOpen = session.open() mock.stream(FOLLOW, followScript(history(plainTurn(SessionSeq(6), 1, '新', '代')))) diff --git a/packages/api/session-controller/tests/sessions-service.client.spec.ts b/packages/api/session-controller/tests/sessions-service.client.spec.ts index d92a83198e..212320fdf6 100644 --- a/packages/api/session-controller/tests/sessions-service.client.spec.ts +++ b/packages/api/session-controller/tests/sessions-service.client.spec.ts @@ -12,7 +12,7 @@ import { createClientTest, webApp } from '@deepseek-ai/dsh-client-test-runtime/s import { ClientSessions, SessionCreateError, SessionForkError } from '../src/client/sessions/service.ts' import { scopeOf } from '../src/client/scope.ts' import type { - SessionAssistantStreamBaseline, SessionFollowFrame, SessionFollowRequest, + SessionAssistantStreamBaseline, SessionFollowFrame, SessionFollowRequest, SessionHistoryRecord, } from '../src/types.ts' import { FOLLOW, err, followScript, sessionWorld } from './remote/session.client.ts' @@ -174,7 +174,7 @@ describe('scope tree', () => { it('opens a conversation from follow projections without a second projection request', async ({ bench }) => { const b = bench() b.mock.stream(FOLLOW, followScript(ok({ - records: [], hasMore: false, + cursor: 0, records: [], hasMore: false, projections: { asOfSeq: 0, values: { subagentCatalog: [{ id: sid('child'), createdAt: 1, mode: 'one-shot', }] } }, @@ -277,7 +277,7 @@ describe('scope tree', () => { it('replaces an active assistant baseline on reconnect without duplicate chunks', async ({ bench }) => { const b = bench() const attemptId = LlmAttemptId('reconnect-attempt') - let records: never[] = [] + let records: SessionHistoryRecord[] = [] let assistantStreamBaseline: SessionAssistantStreamBaseline = { revision: 2, activeAttempt: { @@ -287,7 +287,7 @@ describe('scope tree', () => { }, } b.mock.stream(FOLLOW, followScript( - () => ok({ records, hasMore: false }), + () => ok({ cursor: records.at(-1)?.event.seq ?? -1, records, hasMore: false }), { assistantStream: () => assistantStreamBaseline }, )) await feedList(b, [{ id: 's1' }]) @@ -361,6 +361,7 @@ describe('scope tree', () => { }, } const history = ok({ + cursor: priorMessage.event.seq, records: [priorMessage] as never[], hasMore: false, }) @@ -437,7 +438,7 @@ describe('scope tree', () => { surfaceOp: 'append' as const, }, } - let records = [prior] as never[] + let records: SessionHistoryRecord[] = [prior] let assistantStreamBaseline: SessionAssistantStreamBaseline = { revision: 2, activeAttempt: { @@ -450,7 +451,7 @@ describe('scope tree', () => { }, } b.mock.stream(FOLLOW, followScript( - () => ok({ records, hasMore: false }), + () => ok({ cursor: records.at(-1)?.event.seq ?? -1, records, hasMore: false }), { assistantStream: () => assistantStreamBaseline }, )) await feedList(b, [{ id: 's1' }]) @@ -1002,10 +1003,10 @@ describe('fork', () => { expect(b.svc.binding(sid('child'))).toBeUndefined() expect(b.svc.retainInfo(sid('child')).getSnapshot().referenceCount).toBe(0) await Promise.resolve() + expect(b.svc.list.getSnapshot().byId[sid('child')]).not.toHaveProperty('parentId') expect(b.svc.list.getSnapshot().byId[sid('child')]).toMatchObject({ title: childTitle, displayTitle: childTitle, - parentId: 'source', }) }) diff --git a/packages/api/session-controller/tests/state-controller.host.spec.ts b/packages/api/session-controller/tests/state-controller.host.spec.ts new file mode 100644 index 0000000000..5fc74006ff --- /dev/null +++ b/packages/api/session-controller/tests/state-controller.host.spec.ts @@ -0,0 +1,480 @@ +import { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { createInboxStub } from '@deepseek-ai/dsh-agent-loop-testkit' +import { brandString } from '@deepseek-ai/dsh-brand' +import type AgentRegistry from '@deepseek-ai/dsh-agent' +import type TypertGatewayService from '@deepseek-ai/dsh-api-gateway' +import type { PendingRemoteEventInfo } from '@deepseek-ai/dsh-api-gateway' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import SessionStore, { SESSION_FORMAT_VERSION, SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session' +import type { SessionHeader } from '@deepseek-ai/dsh-session' +import type { SessionObservation } from '@deepseek-ai/dsh-session-query' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { HistoryController } from '../src/history/controller.ts' +import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' +import { StateController } from '../src/state/controller.ts' +import { StateListener } from '../src/state/listener.ts' +import type { SessionState, SessionRequestId } from '../src/types.ts' +import { installSessionReadTestServices } from './test-remote.ts' + +const roots: Context[] = [] +const aborters: AbortController[] = [] +const operations: Promise[] = [] +function cancellation(): AbortController { + const abort = new AbortController() + aborters.push(abort) + return abort +} +function tracked(promise: Promise): Promise { + operations.push(promise) + void promise.catch(() => undefined) + return promise +} +function deferred() { + let resolve!: (value: T) => void + const promise = new Promise((settle) => { resolve = settle }) + return { promise, resolve } +} +afterEach(async () => { + for (const abort of aborters.splice(0)) abort.abort() + await Promise.allSettled(operations.splice(0)) + await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) + vi.restoreAllMocks() + vi.useRealTimers() +}) + +async function fixture() { + const ctx = new Context() + roots.push(ctx) + await ctx.plugin(SessionStore) + installSessionReadTestServices(ctx) + const session = ctx.sessions.create(SessionId('state-target'), { meta: { cwd: '/state-test' } }) + let agent: Agent | undefined + const get = vi.fn(() => agent) + const agents: Partial = { get } + ctx.provide('agents', agents as AgentRegistry) + const pending: PendingRemoteEventInfo[] = [] + const pendingRead = vi.fn(() => pending) + const gateway: Partial = { getPendingRemoteEvents: pendingRead } + ctx.provide('typertGateway', gateway as TypertGatewayService) + const history = new HistoryController(ctx) + const output = vi.spyOn(history, 'assistantOutput').mockResolvedValue({ records: [], truncated: false }) + const controller = new StateController(ctx, history) + const abort = cancellation() + const request = { sessionId: session.id } + const live = (status: Agent['status'] = 'running', idle = Promise.resolve(undefined)) => { + const value = { + id: session.id, session, status, + inbox: createInboxStub(), + whenIdle: vi.fn(() => idle), + } + const partial: Partial = value + agent = partial as Agent + return value + } + const addPending = (event: string, id = session.id) => { + pending.push({ event, agentId: brandString(id) }) + } + return { + ctx, session, controller, history, output, abort, request, live, get, pending, pendingRead, addPending, + setAgent: (value: Agent | undefined) => { agent = value }, + } +} +const emptyState: SessionState = { cursor: -1, active: false, running: false, queue: null, pendingInput: [] } + +describe('StateController', () => { + it('re-reads a state whose cold read turned live', async () => { + const f = await fixture() + const agent = f.live('running') + // The first lookup misses; the Session is a live source by the time the cold read runs. + let lookups = 0 + f.get.mockImplementation(() => (lookups++ === 0 ? undefined : agent as never)) + const state = await f.controller.state(f.request, new AbortController().signal) + expect(state).toMatchObject({ active: true, running: true, queue: [] }) + expect(state.cursor).toBe(f.session.seq - 1) + expect(lookups).toBeGreaterThan(1) + }) + + it('rejects a live state read whose Session records no cwd', async () => { + const f = await fixture() + const session = f.ctx.sessions.create(SessionId('no-cwd-live')) + const partial: Partial = { + id: session.id, session, status: 'idle', inbox: createInboxStub(), whenIdle: vi.fn(() => Promise.resolve(undefined)), + } + f.setAgent(partial as Agent) + await expect(f.controller.state({ sessionId: session.id }, new AbortController().signal)) + .rejects.toMatchObject({ code: 'session/not-found' }) + }) + + it('rejects a cold state read whose stored header records no cwd', async () => { + const f = await fixture() + const header: SessionHeader = { + version: SESSION_FORMAT_VERSION, id: f.session.id, createdAt: 1, isSeeded: false, + } + const observation: SessionObservation = { + source: 'prepared', + header, + inheritedEventCount: SessionLogOffset(0), + events: [], + cursor: -1, + projections: { asOfSeq: -1, values: {} }, + retain: () => observation, + [Symbol.dispose]: () => {}, + } + vi.spyOn(f.history, 'usingObservation').mockImplementation(async (_request, _signal, callback) => + callback?.(observation)) + await expect(f.controller.state(f.request, new AbortController().signal)) + .rejects.toMatchObject({ code: 'session/not-found' }) + }) + + it('reads cold state without projections and reports classified, deduplicated pending input', async () => { + const f = await fixture() + const read = vi.spyOn(f.history, 'usingObservation') + f.addPending('approval/request') + f.addPending('user-questions/request') + f.addPending('fixture/request') + f.addPending('approval/request') + f.addPending('ignored', SessionId('other')) + expect(await f.controller.state(f.request, f.abort.signal)).toEqual({ ...emptyState, pendingInput: ['approval', 'question', 'other'] }) + expect(read).toHaveBeenCalledWith({ sessionId: f.session.id, projection: false }, f.abort.signal, expect.any(Function)) + }) + + it('preserves live queues, RPC identities and steering versus context placement', async () => { + const f = await fixture() + const queued = createUserMessage({ content: [{ type: 'text', text: 'queued' }], source: { kind: 'user' } }) + const steering = createUserMessage({ content: [{ type: 'text', text: 'steer' }], source: { kind: 'user', rpcId: 'rpc' as SessionRequestId } }) + const context = createUserMessage({ content: [{ type: 'text', text: 'context' }], source: { kind: 'user-approval' } }) + const agent = f.live() + agent.inbox.append('next-turn', queued) + agent.inbox.append('next-step', steering) + agent.inbox.append('next-step', context) + expect(await f.controller.state(f.request, f.abort.signal)).toEqual({ + cursor: -1, active: true, running: true, pendingInput: [], + queue: [ + { id: queued.id, placement: 'queued', content: queued.content }, + { id: steering.id, placement: 'steering', content: steering.content, rpcId: 'rpc' }, + { id: context.id, placement: 'context', content: context.content }, + ], + }) + }) + + it('rejects already cancelled state reads', async () => { + const f = await fixture() + f.abort.abort(new Error('cancelled')) + await expect(f.controller.state(f.request, f.abort.signal)).rejects.toThrow('cancelled') + }) + + it('observes complete replacements and closes a pending read on cancellation', async () => { + const f = await fixture() + const states = f.controller.observeState(f.request, f.abort.signal)[Symbol.asyncIterator]() + expect(await states.next()).toMatchObject({ value: emptyState }) + f.live() + const next = tracked(states.next()) + f.session.append('turn/start', { turn: 1 }) + expect(await next).toMatchObject({ value: { active: true, running: true, cursor: 0 } }) + const end = tracked(states.next()) + f.abort.abort() + expect(await end).toEqual({ done: true, value: undefined }) + await states.return?.() + }) + + it('returns inactive idle state and delegates the exact output window with caller signal', async () => { + const f = await fixture() + const result = await f.controller.wait({ ...f.request, afterSeq: 3, maxMessages: 2 }, f.abort.signal) + expect(result).toEqual({ reason: 'idle', state: emptyState, output: { records: [], truncated: false } }) + expect(f.output).toHaveBeenCalledWith(f.session.id, 3, -1, 2, f.abort.signal) + }) + + it('stops immediately for pending input even while the Agent runs', async () => { + const f = await fixture() + f.live() + f.addPending('approval/request') + expect(await f.controller.wait(f.request, f.abort.signal)).toMatchObject({ reason: 'input-required' }) + }) + + it('confirms an active idle Agent with whenIdle', async () => { + const f = await fixture() + const agent = f.live('idle') + expect(await f.controller.wait(f.request, f.abort.signal)).toMatchObject({ reason: 'idle', state: { active: true } }) + expect(agent.whenIdle).toHaveBeenCalledOnce() + }) + + it('polls pending input after one second without Gateway notifications', async () => { + const f = await fixture() + vi.useFakeTimers() + f.live() + const result = tracked(f.controller.wait(f.request, f.abort.signal)) + await vi.advanceTimersByTimeAsync(0) + expect(f.pendingRead).toHaveBeenCalledTimes(1) + f.addPending('user-questions/request') + await vi.advanceTimersByTimeAsync(999) + expect(f.pendingRead).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(1) + expect(await result).toMatchObject({ reason: 'input-required', state: { pendingInput: ['question'] } }) + expect(vi.getTimerCount()).toBe(0) + }) + + it('uses the latest accepted state on timeout and still reads output with the caller signal', async () => { + const f = await fixture() + vi.useFakeTimers() + f.live() + const result = tracked(f.controller.wait({ ...f.request, timeoutMs: 1500 }, f.abort.signal)) + await vi.advanceTimersByTimeAsync(1500) + expect(await result).toMatchObject({ reason: 'timeout', state: { running: true } }) + expect(f.output).toHaveBeenCalledWith(f.session.id, -1, -1, 50, f.abort.signal) + expect(f.abort.signal.aborted).toBe(false) + expect(vi.getTimerCount()).toBe(0) + }) + + it('responds to a standard event before the polling tick and races idle against new state', async () => { + const f = await fixture() + vi.useFakeTimers() + const idle = deferred() + f.live('idle', idle.promise) + const result = tracked(f.controller.wait(f.request, f.abort.signal)) + await vi.advanceTimersByTimeAsync(0) + f.addPending('approval/request') + f.session.append('turn/start', { turn: 1 }) + await vi.advanceTimersByTimeAsync(0) + expect(await result).toMatchObject({ reason: 'input-required', state: { cursor: 0 } }) + idle.resolve(undefined) + expect(vi.getTimerCount()).toBe(0) + }) + + it('propagates cancellation while waiting and cleans periodic reads', async () => { + const f = await fixture() + vi.useFakeTimers() + f.live() + const result = tracked(f.controller.wait(f.request, f.abort.signal)) + await vi.advanceTimersByTimeAsync(0) + f.abort.abort(new Error('caller cancelled')) + await expect(result).rejects.toThrow('caller cancelled') + expect(f.output).not.toHaveBeenCalled() + expect(vi.getTimerCount()).toBe(0) + }) + + it('propagates an idle-driver failure without treating it as a deadline', async () => { + const f = await fixture() + const idle = deferred() + const agent = f.live('idle', idle.promise) + agent.whenIdle.mockImplementation(() => Promise.reject(new Error('driver failed'))) + await expect(f.controller.wait(f.request, f.abort.signal)).rejects.toThrow('driver failed') + idle.resolve(undefined) + }) + + it('propagates a structured read failure raised before the deadline', async () => { + const f = await fixture() + const failure = deferred() + vi.spyOn(StateListener.prototype, 'observeStates').mockImplementation(async function* () { + await failure.promise + throw new RemoteError('gateway/internal', 'persistent read failed', {}) + }) + const result = tracked(f.controller.wait({ ...f.request, timeoutMs: 5_000 }, f.abort.signal)) + failure.resolve(undefined) + await expect(result).rejects.toMatchObject({ code: 'gateway/internal' }) + }) + + it('keeps a structured read failure raised after the deadline', async () => { + const f = await fixture() + vi.useFakeTimers() + let rejectRead!: (error: Error) => void + vi.spyOn(StateListener.prototype, 'observeStates').mockImplementation(async function* () { + await new Promise((_resolve, reject) => { rejectRead = reject }) + yield* [] + }) + const result = tracked(f.controller.wait({ ...f.request, timeoutMs: 20 }, f.abort.signal)) + await vi.advanceTimersByTimeAsync(20) + rejectRead(new RemoteError('gateway/internal', 'persistent read failed', {})) + await expect(result).rejects.toMatchObject({ code: 'gateway/internal' }) + expect(vi.getTimerCount()).toBe(0) + }) + + it('reports timeout when its first cold read never yields a state', async () => { + const f = await fixture() + vi.useFakeTimers() + vi.spyOn(f.ctx.sessionQuery, 'observeSession').mockImplementation((_id, options) => new Promise((_resolve, reject) => { + const abort = options?.signal + abort?.addEventListener('abort', () => { + const reason: unknown = abort.reason + reject(Object.assign(new Error('session observation was aborted'), { + code: 'SESSION_QUERY_ABORTED', cause: reason, + })) + }, { once: true }) + })) + const result = tracked(f.controller.wait({ ...f.request, timeoutMs: 20 }, f.abort.signal)) + await vi.advanceTimersByTimeAsync(20) + await expect(result).rejects.toMatchObject({ code: 'session/wait-timeout' }) + expect(f.output).not.toHaveBeenCalled() + expect(vi.getTimerCount()).toBe(0) + }) + + it('rejects a state stream that ends before a stopping observation', async () => { + const f = await fixture() + vi.spyOn(StateListener.prototype, 'observeStates').mockImplementation(async function* () {}) + await expect(f.controller.wait(f.request, f.abort.signal)).rejects.toMatchObject({ code: 'session/observation-ended' }) + }) + + it('settles an already-armed failed read when the preceding observation stops the wait', async () => { + const f = await fixture() + vi.spyOn(StateListener.prototype, 'observeStates').mockImplementation(async function* () { + yield { state: emptyState, revision: 0 } + throw new Error('next read failed') + }) + expect(await f.controller.wait(f.request, f.abort.signal)).toMatchObject({ reason: 'idle' }) + }) + + it('ignores a yielded state invalidated before wait accepts it', async () => { + const f = await fixture() + vi.spyOn(StateListener.prototype, 'observeStates').mockImplementation(async function* () { + yield { state: { ...emptyState, running: true }, revision: 0 } + yield { state: emptyState, revision: 1 } + }) + vi.spyOn(StateListener.prototype, 'isCurrent').mockReturnValueOnce(false).mockReturnValue(true) + expect(await f.controller.wait(f.request, f.abort.signal)).toMatchObject({ reason: 'idle', state: emptyState }) + }) + + it('times out with the last accepted state, not a later invalidated sample', async () => { + const f = await fixture() + vi.useFakeTimers() + const accepted = { ...emptyState, running: true } + const stale = { ...emptyState, running: true, cursor: 7 } + const never = deferred() + vi.spyOn(StateListener.prototype, 'observeStates').mockImplementation(async function* () { + yield { state: accepted, revision: 0 } + yield { state: stale, revision: 0 } + await never.promise + yield* [] + }) + vi.spyOn(StateListener.prototype, 'isCurrent').mockReturnValueOnce(true).mockReturnValue(false) + const result = tracked(f.controller.wait({ ...f.request, timeoutMs: 20 }, f.abort.signal)) + await vi.advanceTimersByTimeAsync(20) + never.resolve(undefined) + await expect(result).resolves.toMatchObject({ reason: 'timeout', state: { cursor: -1 } }) + }) + + it.each(['missing-agent', 'different-session'] as const)('retries active state when its owner is %s', async (condition) => { + const f = await fixture() + const agent = f.live('idle') + if (condition === 'missing-agent') f.setAgent(undefined) + else Object.assign(agent, { session: f.ctx.sessions.create(SessionId('replacement')) }) + vi.spyOn(StateListener.prototype, 'observeStates').mockImplementation(async function* () { + yield { state: { ...emptyState, active: true, queue: [] }, revision: 0 } + yield { state: emptyState, revision: 0 } + }) + expect(await f.controller.wait(f.request, f.abort.signal)).toMatchObject({ reason: 'idle', state: emptyState }) + expect(agent.whenIdle).not.toHaveBeenCalled() + }) + + it.each(['revision', 'agent', 'session'] as const)('rechecks %s after the idle promise settles', async (changed) => { + const f = await fixture() + const idle = deferred() + const entered = deferred() + const next = deferred() + const agent = f.live('idle', idle.promise) + agent.whenIdle.mockImplementation(() => { entered.resolve(undefined); return idle.promise }) + vi.spyOn(StateListener.prototype, 'observeStates').mockImplementation(async function* () { + yield { state: { ...emptyState, active: true, queue: [] }, revision: 0 } + await next.promise + yield { state: emptyState, revision: 0 } + }) + const rechecked = deferred() + let checks = 0 + vi.spyOn(StateListener.prototype, 'isCurrent').mockImplementation(() => { + checks++ + if (checks === 2) rechecked.resolve(undefined) + return !(changed === 'revision' && checks === 2) + }) + const result = tracked(f.controller.wait(f.request, f.abort.signal)) + try { + await entered.promise + if (changed === 'agent') f.setAgent(undefined) + if (changed === 'session') Object.assign(agent, { session: f.ctx.sessions.create(SessionId('new-session')) }) + idle.resolve(undefined) + await rechecked.promise + next.resolve(undefined) + expect(await result).toMatchObject({ reason: 'idle', state: emptyState }) + } finally { + idle.resolve(undefined) + next.resolve(undefined) + f.abort.abort() + await Promise.allSettled([result]) + } + }) + + it.each([ + { afterSeq: -2 }, { afterSeq: -0 }, { afterSeq: 1.5 }, + { maxMessages: 0 }, { maxMessages: 1.5 }, + { timeoutMs: 0 }, { timeoutMs: 2147483648 }, { timeoutMs: 1.5 }, + ])('rejects unsupported wait bounds %j', async (bounds) => { + const f = await fixture() + await expect(f.controller.wait({ ...f.request, ...bounds }, f.abort.signal)).rejects.toMatchObject({ code: 'gateway/bad-request' }) + }) +}) + +describe('StateListener', () => { + it('discards an async stale read and coalesces repeated invalidations', async () => { + const f = await fixture() + const first = deferred() + const reading = deferred() + const read = vi.fn() + .mockImplementationOnce(() => { reading.resolve(undefined); return first.promise }) + .mockResolvedValue({ ...emptyState, cursor: 1 }) + using listener = new StateListener(f.ctx, f.session.id, f.abort.signal, read) + const states = listener.observeStates() + const pending = tracked(states.next()) + await reading.promise + f.session.append('turn/start', { turn: 1 }) + f.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + first.resolve(emptyState) + expect(await pending).toEqual({ done: false, value: { state: { ...emptyState, cursor: 1 }, revision: 2 } }) + expect(read).toHaveBeenCalledTimes(2) + expect(listener.isCurrent(0)).toBe(false) + expect(listener.isCurrent(2)).toBe(true) + await states.return(undefined) + expect(listener.isCurrent(2)).toBe(false) + }) + + it('ignores other Sessions and ends when its Context is disposed', async () => { + const f = await fixture() + const read = vi.fn(async () => emptyState) + const listener = new StateListener(f.ctx, f.session.id, f.abort.signal, read) + const states = listener.observeStates() + await states.next() + const pending = tracked(states.next()) + f.ctx.sessions.create(SessionId('unrelated')) + expect(read).toHaveBeenCalledOnce() + await f.ctx.fiber.dispose() + expect(await pending).toEqual({ done: true, value: undefined }) + listener[Symbol.dispose]() + }) + + it('invalidates for each Agent lifecycle notification', async () => { + const f = await fixture() + f.live('idle') + const agent = f.get()! + using listener = new StateListener(f.ctx, f.session.id, f.abort.signal, async () => emptyState) + const states = listener.observeStates() + await states.next() + for (const emit of [ + () => { f.ctx.emit('agent/status', { agent, status: 'running' }) }, + () => { f.ctx.emit('agent/created', { agent, source: 'startup' }) }, + () => { f.ctx.emit('agent/disposed', { agent }) }, + ]) { + const pending = tracked(states.next()) + emit() + expect(await pending).toMatchObject({ done: false, value: { state: emptyState } }) + } + await states.return(undefined) + }) + + it('rejects cancelled construction and contains setup failure by removing abort listeners', async () => { + const f = await fixture() + f.abort.abort() + expect(() => new StateListener(f.ctx, f.session.id, f.abort.signal, async () => emptyState)).toThrow() + const abort = cancellation() + const remove = vi.spyOn(abort.signal, 'removeEventListener') + vi.spyOn(f.ctx, 'on').mockImplementation(() => { throw new Error('registration failed') }) + expect(() => new StateListener(f.ctx, f.session.id, abort.signal, async () => emptyState)).toThrow('registration failed') + expect(remove).toHaveBeenCalledWith('abort', expect.any(Function)) + }) +}) diff --git a/packages/api/session-controller/tests/subagent-catalog.host.spec.ts b/packages/api/session-controller/tests/subagent-catalog.host.spec.ts index 9534b8b66d..36216a1f1c 100644 --- a/packages/api/session-controller/tests/subagent-catalog.host.spec.ts +++ b/packages/api/session-controller/tests/subagent-catalog.host.spec.ts @@ -105,7 +105,7 @@ describe('SessionController subagent catalog', () => { kind: 'sequenced', values: { subagentCatalog: [{ id: CHILD, mode: 'continuable', label: 'worker' }] }, }) expect(stat).toHaveBeenCalledWith(PARENT, { signal }) - expect(observe).toHaveBeenCalledWith(PARENT, { signal }) + expect(observe).toHaveBeenCalledWith(PARENT, { signal, projectionMode: 'all' }) expect(open).toHaveBeenCalledWith(PARENT, 'read', { signal }) expect(resume).not.toHaveBeenCalled() expect(ctx.sessions.get(PARENT)).toBeUndefined() diff --git a/packages/api/session-controller/tests/test-remote.ts b/packages/api/session-controller/tests/test-remote.ts index 114e15734d..145b48f5c3 100644 --- a/packages/api/session-controller/tests/test-remote.ts +++ b/packages/api/session-controller/tests/test-remote.ts @@ -51,7 +51,7 @@ import type { SessionOpenWorkspacePathRequest, SessionOpenWorkspacePathValue, SessionWorkspacePathApplication, - SessionPage, + SessionEventsPage, SessionPageRequest, SessionPromptRequest, SessionPromptValue, @@ -66,7 +66,7 @@ import type { SessionUpdateQueueValue, } from '../src/types.ts' -/** Direct test face matching the generated `ctx.remote.session` unary methods. */ +/** Direct test face for the generated `ctx.remote.session` unary methods these tests exercise. */ export interface TestSessionRemote { workspacePathApplications( request: { readonly path: string }, signal?: AbortSignal, @@ -87,7 +87,7 @@ export interface TestSessionRemote { request: SessionOpenWorkspacePathRequest, signal?: AbortSignal, ): Promise> - page(request: SessionPageRequest, signal?: AbortSignal): Promise> + page(request: SessionPageRequest, signal?: AbortSignal): Promise> projections(request: SessionProjectionsRequest, signal?: AbortSignal): Promise> follow(request: SessionFollowRequest, signal?: AbortSignal): AsyncIterable control(signal?: AbortSignal): AsyncIterable @@ -388,6 +388,7 @@ export async function createSessionTestRemote( signal, ), page: (request, signal = new AbortController().signal) => remoteResult( + // oxlint-disable-next-line typescript/no-deprecated -- Test face keeps the legacy page entry covered. () => direct.page(request, signal), signal, ), diff --git a/packages/api/session-controller/tests/transport.client.spec.ts b/packages/api/session-controller/tests/transport.client.spec.ts index 87d8fd7479..2c60701f80 100644 --- a/packages/api/session-controller/tests/transport.client.spec.ts +++ b/packages/api/session-controller/tests/transport.client.spec.ts @@ -25,7 +25,7 @@ import type { SessionFollowFrame, SessionFollowRequest, SessionHistoryRecord, - SessionPage, + SessionEventsPage, SessionPageRequest, SessionWireEvent, } from '../src/types.ts' @@ -44,8 +44,8 @@ function entry(seq: number): SessionEventEntry { return { type: 'event', event: { type: 'turn/start', seq, time: seq, data: { turn: seq } } } } -function page(records: readonly SessionHistoryRecord[], hasMore = false): SessionPage { - return { records, hasMore } +function page(records: readonly SessionHistoryRecord[], hasMore = false): SessionEventsPage { + return { cursor: records.at(-1)?.event?.seq ?? -1, records, hasMore } } function snapshot( @@ -102,7 +102,7 @@ class ScriptedSessionRemote implements SessionTransportRemote { constructor( private readonly generations: FollowGeneration[], - private readonly pages: RemoteResult[], + private readonly pages: RemoteResult[], private readonly controlFrames: readonly SessionControlFrame[] = [], private readonly holdControl = true, ) {} @@ -126,7 +126,7 @@ class ScriptedSessionRemote implements SessionTransportRemote { } } - page(request: SessionPageRequest): Promise> { + page(request: SessionPageRequest): Promise> { this.pageRequests.push(request) const result = this.pages.shift() if (result === undefined) throw new Error('no scripted Session page') @@ -326,7 +326,7 @@ describe('Session Client stream adapters', () => { await stream.open({}) await vi.waitFor(() => { expect(changes).toHaveLength(2) }) - expect(remote.followRequests).toEqual([{ address: ADDRESS, assistantStream: true }]) + expect(remote.followRequests).toEqual([{ address: ADDRESS, activate: true, assistantStream: true }]) expect(changes).toMatchObject([ { type: 'replace', page: { assistantStream: baseline } }, { type: 'assistant-stream', frame }, @@ -382,7 +382,7 @@ describe('Session Client stream adapters', () => { code: 'gateway/internal', message: 'session event stream emitted an entry before its opening cursor', }) - expect(remote.followRequests).toEqual([{ address: ADDRESS, assistantStream: true }]) + expect(remote.followRequests).toEqual([{ address: ADDRESS, activate: true, assistantStream: true }]) } finally { await stream.dispose() } @@ -547,7 +547,7 @@ describe('Session Client stream adapters', () => { await stream.prepend({ beforeSeq: 2, maxMessages: 500, turnWindow: { minMessages: 50, minTurns: 2 } }) expect(remote.followRequests).toEqual([{ - address: ADDRESS, assistantStream: true, maxMessages: 500, turnWindow: { minMessages: 50, minTurns: 2 }, + address: ADDRESS, activate: true, assistantStream: true, maxMessages: 500, turnWindow: { minMessages: 50, minTurns: 2 }, }]) expect(remote.pageRequests).toEqual([ { address: ADDRESS, throughSeq: 4, beforeSeq: 2, maxMessages: 500, turnWindow: { minMessages: 50, minTurns: 2 } }, @@ -585,8 +585,8 @@ describe('Session Client stream adapters', () => { await vi.waitFor(() => { expect(remote.followRequests).toHaveLength(2) }) expect(remote.followRequests).toEqual([ - { address: ADDRESS, assistantStream: true, maxMessages: 500, turnWindow: { minMessages: 50, minTurns: 2 } }, - { address: ADDRESS, assistantStream: true, maxMessages: 500, turnWindow: { minMessages: 50, minTurns: 2 } }, + { address: ADDRESS, activate: true, assistantStream: true, maxMessages: 500, turnWindow: { minMessages: 50, minTurns: 2 } }, + { address: ADDRESS, activate: true, assistantStream: true, maxMessages: 500, turnWindow: { minMessages: 50, minTurns: 2 } }, ]) expect(remote.pageRequests).toEqual([]) expect(changes.map(change => change.type)).toEqual(['replace', 'append', 'replace']) @@ -616,8 +616,8 @@ describe('Session Client stream adapters', () => { finish.resolve(undefined) await vi.waitFor(() => { expect(remote.followRequests).toHaveLength(2) }) expect(remote.followRequests).toEqual([ - { address: ADDRESS, assistantStream: true }, - { address: ADDRESS, assistantStream: true }, + { address: ADDRESS, activate: true, assistantStream: true }, + { address: ADDRESS, activate: true, assistantStream: true }, ]) expect(remote.pageRequests).toEqual([]) await stream.dispose() diff --git a/packages/api/session-controller/tests/transport.host.spec.ts b/packages/api/session-controller/tests/transport.host.spec.ts index e48b114c91..8a3df2ae43 100644 --- a/packages/api/session-controller/tests/transport.host.spec.ts +++ b/packages/api/session-controller/tests/transport.host.spec.ts @@ -5,8 +5,9 @@ import type { Session, SessionEvent, SessionHeader, SurfaceIntent } from '@deeps import type { SessionObservation } from '@deepseek-ai/dsh-session-query' import { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent' import { subagentIdentityProjectionDefinition } from '@deepseek-ai/dsh-subagent/src/projection.ts' -import { describe, expect, it, vi } from 'vitest' -import { SessionHistoryController } from '../src/history.ts' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { HistoryController } from '../src/history/controller.ts' +import { WebController } from '../src/web/controller.ts' import { installSessionReadTestServices, testSessionPersistence } from './test-remote.ts' const signal = (): AbortSignal => new AbortController().signal @@ -72,22 +73,39 @@ function deferred(): Deferred { return { promise, resolve } } -async function setup(): Promise<{ ctx: Context; transport: SessionHistoryController }> { +const roots = new Set() +afterEach(async () => { + await Promise.all([...roots].map(ctx => ctx.fiber.dispose())) + roots.clear() +}) + +function controllers( + ctx: Context, promote: (observation: SessionObservation) => void = (observation) => { observation[Symbol.dispose]() }, +): { + history: HistoryController + web: WebController +} { + roots.add(ctx.root) + installSessionReadTestServices(ctx) + const history = new HistoryController(ctx) + return { history, web: new WebController(ctx, history, promote) } +} + +async function setup(): Promise<{ ctx: Context; history: HistoryController; web: WebController }> { const ctx = new Context() await ctx.plugin(SessionStore) installSessionReadTestServices(ctx) await ctx.sessionProjections.register(subagentIdentityProjectionDefinition) - const transport = new SessionHistoryController(ctx, (observation) => { observation[Symbol.dispose]() }) - return { ctx, transport } + return { ctx, ...controllers(ctx) } } -describe('SessionHistoryController', () => { +describe('Session history and Web follow', () => { it('opens at the current cursor and follows later events from an ordinary Session', async () => { - const { ctx, transport } = await setup() + const { ctx, history, web } = await setup() const session = ctx.sessions.create(SessionId('ordinary'), { meta: { cwd: '/workspace' } }) session.append('turn/start', { turn: 1 }) const abort = new AbortController() - const iterator = transport.follow( + const iterator = web.follow( { address: { kind: 'session', sessionId: session.id } }, abort.signal, )[Symbol.asyncIterator]() @@ -99,7 +117,7 @@ describe('SessionHistoryController', () => { value: { type: 'event', event: { type: 'turn/end', seq: 1 } }, }) - const page = await transport.page( + const page = await history.events( { address: { kind: 'session', sessionId: session.id }, throughSeq: 1 }, new AbortController().signal, ) @@ -113,16 +131,16 @@ describe('SessionHistoryController', () => { const ctx = new Context() await ctx.plugin(SessionStore) installSessionReadTestServices(ctx) - let transport!: SessionHistoryController + let web!: WebController const owner = ctx.plugin(Object.assign( (inner: Context) => { - transport = new SessionHistoryController(inner, (observation) => { observation[Symbol.dispose]() }) + web = controllers(inner).web }, { inject: ['sessions', 'sessionQuery'] }, )) await owner.await() const session = ctx.sessions.create(SessionId('controller-unload'), { meta: { cwd: '/workspace' } }) - const iterator = transport.follow( + const iterator = web.follow( { address: { kind: 'session', sessionId: session.id } }, new AbortController().signal, )[Symbol.asyncIterator]() @@ -138,13 +156,13 @@ describe('SessionHistoryController', () => { }) it('reconnects with a complete replacement snapshot before later live events', async () => { - const { ctx, transport } = await setup() + const { ctx, web } = await setup() const session = ctx.sessions.create(SessionId('resume'), { meta: { cwd: '/workspace' } }) session.append('turn/start', { turn: 1 }) session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) session.append('turn/start', { turn: 2 }) const abort = new AbortController() - const iterator = transport.follow({ + const iterator = web.follow({ address: { kind: 'session', sessionId: session.id }, }, abort.signal)[Symbol.asyncIterator]() @@ -168,7 +186,7 @@ describe('SessionHistoryController', () => { }) it('subscribes before a cold read and ignores unrelated and replayed buffered events', async () => { - const { ctx, transport } = await setup() + const { ctx, web } = await setup() const sessionId = SessionId('cold-race') const header: SessionHeader = { version: SESSION_FORMAT_VERSION, @@ -187,7 +205,7 @@ describe('SessionHistoryController', () => { inspect: () => inspected.promise, }) as never) const abort = new AbortController() - const iterator = transport.follow({ address: { kind: 'session', sessionId } }, abort.signal) + const iterator = web.follow({ address: { kind: 'session', sessionId } }, abort.signal) [Symbol.asyncIterator]() const opening = iterator.next() @@ -220,9 +238,9 @@ describe('SessionHistoryController', () => { } const observed = deferred() ctx.provide('sessionQuery', { observeSession: () => observed.promise } as never) - const transport = new SessionHistoryController(ctx, vi.fn()) + const { web } = controllers(ctx, vi.fn()) const abort = new AbortController() - const iterator = transport.follow({ address: { kind: 'session', sessionId } }, abort.signal) + const iterator = web.follow({ address: { kind: 'session', sessionId } }, abort.signal) [Symbol.asyncIterator]() const opening = iterator.next() @@ -256,11 +274,11 @@ describe('SessionHistoryController', () => { const ctx = new Context() await ctx.plugin(SessionStore) installSessionReadTestServices(ctx) - let transport!: SessionHistoryController + let web!: WebController let agentCtx!: Context await ctx.plugin(Object.assign( (inner: Context) => { - transport = new SessionHistoryController(inner, (observation) => { observation[Symbol.dispose]() }) + web = controllers(inner).web }, { inject: ['sessions', 'sessionQuery'] }, )) @@ -279,7 +297,7 @@ describe('SessionHistoryController', () => { const seed = [event('fixture/start', SessionSeq(0))] cold(ctx, header, seed) const abort = new AbortController() - const iterator = transport.follow({ address: { kind: 'session', sessionId } }, abort.signal) + const iterator = web.follow({ address: { kind: 'session', sessionId } }, abort.signal) [Symbol.asyncIterator]() await expect(iterator.next()).resolves.toMatchObject({ done: false, value: { type: 'snapshot', cursor: 0 } }) @@ -322,7 +340,7 @@ describe('SessionHistoryController', () => { isSeeded: false, } cold(replay.ctx, replayHeader, [event('fixture/start', SessionSeq(0)), event('fixture/gap', SessionSeq(2))]) - const replayed = replay.transport.follow({ + const replayed = replay.web.follow({ address: { kind: 'session', sessionId: replayId }, }, signal())[Symbol.asyncIterator]() await expect(replayed.next()).rejects.toMatchObject({ code: 'SESSION_QUERY_CORRUPT_SESSION' }) @@ -331,7 +349,7 @@ describe('SessionHistoryController', () => { const session = live.ctx.sessions.create(SessionId('live-gap'), { meta: { cwd: '/workspace' } }) append(session, 'fixture/start', {}) live.ctx.provide('agents', { get: () => ({ id: session.id }) } as never) - const followed = live.transport.follow({ + const followed = live.web.follow({ address: { kind: 'session', sessionId: session.id }, }, signal())[Symbol.asyncIterator]() await expect(followed.next()).resolves.toMatchObject({ done: false, value: { type: 'snapshot', cursor: 0 } }) @@ -345,21 +363,21 @@ describe('SessionHistoryController', () => { }) it('opens an empty source at cursor -1', async () => { - const { ctx, transport } = await setup() + const { ctx, history, web } = await setup() const session = ctx.sessions.create(SessionId('empty-follow'), { meta: { cwd: '/workspace' } }) const abort = new AbortController() - const iterator = transport.follow({ + const iterator = web.follow({ address: { kind: 'session', sessionId: session.id }, }, abort.signal)[Symbol.asyncIterator]() await expect(iterator.next()).resolves.toMatchObject({ done: false, value: { type: 'snapshot', cursor: -1 } }) - await expect(transport.page({ + await expect(history.events({ address: { kind: 'session', sessionId: session.id }, throughSeq: -1, }, signal())).resolves.toMatchObject({ records: [], hasMore: false }) abort.abort() await expect(iterator.next()).resolves.toMatchObject({ done: true }) }) - it('publishes an empty projection baseline when the query has no registry', async () => { + it('fails explicitly when a projected observation omits its baseline', async () => { const ctx = new Context() await ctx.plugin(SessionStore) const sessionId = SessionId('projectionless-follow') @@ -380,19 +398,83 @@ describe('SessionHistoryController', () => { retain: vi.fn(), [Symbol.dispose]: vi.fn(), } satisfies SessionObservation), } as never) - const history = new SessionHistoryController(ctx, vi.fn()) + const { web } = controllers(ctx, vi.fn()) const abort = new AbortController() - const iterator = history.follow({ address: { kind: 'session', sessionId } }, abort.signal) + const iterator = web.follow({ address: { kind: 'session', sessionId } }, abort.signal) [Symbol.asyncIterator]() - await expect(iterator.next()).resolves.toMatchObject({ - value: { type: 'snapshot', projections: { asOfSeq: -1, values: {} } }, - }) + await expect(iterator.next()).rejects.toMatchObject({ code: 'session/projections-unavailable' }) abort.abort() await expect(iterator.next()).resolves.toMatchObject({ done: true }) await ctx.fiber.dispose() }) + it('does not activate a prepared Session when the request omits activate', async () => { + const ctx = new Context() + await ctx.plugin(SessionStore) + const sessionId = SessionId('passive-activation-default') + const header: SessionHeader = { + version: SESSION_FORMAT_VERSION, id: sessionId, createdAt: 1, cwd: '/workspace', isSeeded: false, + } + const disposeSource = vi.fn() + const source: SessionObservation = { + source: 'prepared', + header, + inheritedEventCount: SessionLogOffset(0), + events: [], + cursor: -1, + projections: { asOfSeq: -1, values: {} }, + retain: () => source, + [Symbol.dispose]: disposeSource, + } + ctx.provide('sessionQuery', { observeSession: () => Promise.resolve(source) } as never) + const promote = vi.fn() + const { web } = controllers(ctx, promote) + const abort = new AbortController() + const iterator = web.follow({ address: { kind: 'session', sessionId } }, abort.signal)[Symbol.asyncIterator]() + await expect(iterator.next()).resolves.toMatchObject({ value: { type: 'snapshot' } }) + expect(promote).not.toHaveBeenCalled() + abort.abort() + await expect(iterator.next()).resolves.toMatchObject({ done: true }) + expect(disposeSource).toHaveBeenCalled() + await ctx.fiber.dispose() + }) + + it('starts activation for a consumer that stops after the opening snapshot', async () => { + const ctx = new Context() + await ctx.plugin(SessionStore) + const sessionId = SessionId('activation-after-opening') + const header: SessionHeader = { + version: SESSION_FORMAT_VERSION, id: sessionId, createdAt: 1, cwd: '/workspace', isSeeded: false, + } + const disposed: string[] = [] + const promotion: SessionObservation = { + source: 'prepared', + header, + inheritedEventCount: SessionLogOffset(0), + events: [], + cursor: -1, + projections: { asOfSeq: -1, values: {} }, + retain: vi.fn(), + [Symbol.dispose]: () => { disposed.push('promotion') }, + } + const source: SessionObservation = { + ...promotion, + retain: () => promotion, + [Symbol.dispose]: () => { disposed.push('source') }, + } + ctx.provide('sessionQuery', { observeSession: () => Promise.resolve(source) } as never) + const promote = vi.fn((observation: SessionObservation) => { observation[Symbol.dispose]() }) + const { web } = controllers(ctx, promote) + const iterator = web.follow({ address: { kind: 'session', sessionId }, activate: true }, signal()) + [Symbol.asyncIterator]() + await expect(iterator.next()).resolves.toMatchObject({ value: { type: 'snapshot' } }) + await iterator.return?.(undefined) + expect(promote).toHaveBeenCalledOnce() + expect(disposed).toContain('promotion') + await ctx.fiber.dispose() + }) + it('disposes a retained promotion when background activation rejects synchronously', async () => { const ctx = new Context() await ctx.plugin(SessionStore) @@ -412,18 +494,17 @@ describe('SessionHistoryController', () => { ctx.provide('sessionQuery', { observeSession: () => Promise.resolve(source), } as never) - const history = new SessionHistoryController(ctx, () => { throw new Error('activation failed') }) - const iterator = history.follow({ address: { kind: 'session', sessionId } }, signal()) + const { web } = controllers(ctx, () => { throw new Error('activation failed') }) + const iterator = web.follow({ address: { kind: 'session', sessionId }, activate: true }, signal()) [Symbol.asyncIterator]() - await expect(iterator.next()).resolves.toMatchObject({ value: { type: 'snapshot' } }) await expect(iterator.next()).rejects.toThrow('activation failed') expect(disposePromotion).toHaveBeenCalledOnce() await ctx.fiber.dispose() }) it('requires the durable parent and mode for a direct subagent address', async () => { - const { ctx, transport } = await setup() + const { ctx, history } = await setup() const parentSessionId = SessionId('parent') const childSessionId = SessionId('child') ctx.sessions.create(parentSessionId, { meta: { cwd: '/workspace' } }) @@ -437,7 +518,7 @@ describe('SessionHistoryController', () => { })) const signal = new AbortController().signal - await expect(transport.page({ + await expect(history.events({ address: { kind: 'subagent', parentSessionId, @@ -448,17 +529,17 @@ describe('SessionHistoryController', () => { }, signal)).resolves.toMatchObject({ records: [{ type: 'event', event: { type: 'subagent/descriptor' } }], }) - await expect(transport.page({ + await expect(history.events({ address: { kind: 'subagent', parentSessionId, childSessionId, mode: 'unknown' }, throughSeq: 0, }, signal)).resolves.toMatchObject({ records: [{ type: 'event', event: { type: 'subagent/descriptor' } }], }) - await expect(transport.page({ + await expect(history.events({ address: { kind: 'subagent', parentSessionId: SessionId('other-parent'), childSessionId, mode: 'unknown' }, throughSeq: 0, }, signal)).rejects.toMatchObject({ code: 'subagent/unauthorized' }) - await expect(transport.page({ + await expect(history.events({ address: { kind: 'subagent', parentSessionId: SessionId('other-parent'), @@ -467,7 +548,7 @@ describe('SessionHistoryController', () => { }, throughSeq: 0, }, signal)).rejects.toMatchObject({ code: 'subagent/unauthorized' }) - await expect(transport.page({ + await expect(history.events({ address: { kind: 'subagent', parentSessionId, @@ -476,14 +557,14 @@ describe('SessionHistoryController', () => { }, throughSeq: 0, }, signal)).rejects.toMatchObject({ code: 'subagent/unauthorized' }) - await expect(transport.page({ + await expect(history.events({ address: { kind: 'session', sessionId: childSessionId }, throughSeq: 0, }, signal)).rejects.toMatchObject({ code: 'session/agent-busy' }) }) it('preserves a cold inspection failure for the Gateway error branch', async () => { - const { ctx, transport } = await setup() + const { ctx, history } = await setup() const sessionId = SessionId('corrupt-cold') const failure = new Error('cold log is corrupt') const header: SessionHeader = { version: SESSION_FORMAT_VERSION, id: sessionId, createdAt: 1, isSeeded: false, cwd: '/workspace' } @@ -492,7 +573,7 @@ describe('SessionHistoryController', () => { inspect: () => Promise.reject(failure), }) as never) - await expect(transport.page({ + await expect(history.events({ address: { kind: 'session', sessionId }, throughSeq: -1, }, new AbortController().signal)).rejects.toMatchObject({ @@ -502,7 +583,7 @@ describe('SessionHistoryController', () => { }) it('rejects malformed page and follow cursors at the service boundary', async () => { - const { ctx, transport } = await setup() + const { ctx, history, web } = await setup() const session = ctx.sessions.create(SessionId('validation'), { meta: { cwd: '/workspace' } }) const address = { kind: 'session' as const, sessionId: session.id } for (const request of [ @@ -521,9 +602,9 @@ describe('SessionHistoryController', () => { { address, throughSeq: -1, turnWindow: { minMessages: 50, minTurns: 0 } }, { address, throughSeq: -1, turnWindow: { minMessages: 50, minTurns: 1.5 } }, ]) { - await expect(transport.page(request, signal())).rejects.toMatchObject({ code: 'gateway/bad-request' }) + await expect(history.events(request, signal())).rejects.toMatchObject({ code: 'gateway/bad-request' }) } - await expect(transport.page({ address, throughSeq: 0 }, signal())) + await expect(history.events({ address, throughSeq: 0 }, signal())) .rejects.toMatchObject({ code: 'gateway/bad-request' }) const corrupt = await setup() @@ -533,11 +614,11 @@ describe('SessionHistoryController', () => { { version: SESSION_FORMAT_VERSION, id: corruptId, createdAt: 1, cwd: '/workspace', isSeeded: false }, [event('fixture/start', SessionSeq(0)), event('fixture/gap', SessionSeq(2))], ) - await expect(corrupt.transport.page({ + await expect(corrupt.history.events({ address: { kind: 'session', sessionId: corruptId }, throughSeq: 1, }, signal())).rejects.toMatchObject({ code: 'SESSION_QUERY_CORRUPT_SESSION' }) for (const maxMessages of [0, 0.5]) { - const iterator = transport.follow({ address, maxMessages }, signal())[Symbol.asyncIterator]() + const iterator = web.follow({ address, maxMessages }, signal())[Symbol.asyncIterator]() await expect(iterator.next()).rejects.toMatchObject({ code: 'gateway/bad-request' }) } for (const turnWindow of [ @@ -547,15 +628,15 @@ describe('SessionHistoryController', () => { { minMessages: 50, minTurns: 0 }, { minMessages: 50, minTurns: 1.5 }, ]) { - const iterator = transport.follow({ address, turnWindow }, signal())[Symbol.asyncIterator]() + const iterator = web.follow({ address, turnWindow }, signal())[Symbol.asyncIterator]() await expect(iterator.next()).rejects.toMatchObject({ code: 'gateway/bad-request' }) } }) it('reports missing ordinary and subagent sources without fabricating inspection failures', async () => { - const { ctx, transport } = await setup() + const { ctx, history } = await setup() const ordinary = { kind: 'session' as const, sessionId: SessionId('missing') } - await expect(transport.page({ address: ordinary, throughSeq: -1 }, signal())) + await expect(history.events({ address: ordinary, throughSeq: -1 }, signal())) .rejects.toMatchObject({ code: 'session/not-found' }) const inspect = vi.fn(() => Promise.resolve(undefined)) @@ -565,9 +646,9 @@ describe('SessionHistoryController', () => { stat, inspect, }) as never) - await expect(transport.page({ address: ordinary, throughSeq: -1 }, signal())) + await expect(history.events({ address: ordinary, throughSeq: -1 }, signal())) .rejects.toMatchObject({ code: 'session/not-found' }) - await expect(transport.page({ + await expect(history.events({ address: { kind: 'subagent', parentSessionId: SessionId('parent'), @@ -594,7 +675,7 @@ describe('SessionHistoryController', () => { events: [], }), }) as never) - await expect(first.transport.page({ address, throughSeq: -1 }, signal())) + await expect(first.history.events({ address, throughSeq: -1 }, signal())) .rejects.toMatchObject({ code: 'session/not-found' }) const second = await setup() @@ -608,7 +689,7 @@ describe('SessionHistoryController', () => { events: [], }), }) as never) - await expect(second.transport.page({ address, throughSeq: -1 }, signal())) + await expect(second.history.events({ address, throughSeq: -1 }, signal())) .rejects.toMatchObject({ code: 'session/not-found' }) }) @@ -623,7 +704,7 @@ describe('SessionHistoryController', () => { isSeeded: false, } cold(ordinaryBench.ctx, ordinaryHeader, [event('turn/start', SessionSeq(0), { turn: 1 })]) - await expect(ordinaryBench.transport.page({ + await expect(ordinaryBench.history.events({ address: { kind: 'session', sessionId: ordinaryId }, throughSeq: 0, }, signal())).resolves.toMatchObject({ @@ -649,18 +730,18 @@ describe('SessionHistoryController', () => { } const missing = await setup() cold(missing.ctx, childHeader, []) - await expect(missing.transport.page({ address: childAddress, throughSeq: -1 }, signal())) + await expect(missing.history.events({ address: childAddress, throughSeq: -1 }, signal())) .rejects.toMatchObject({ code: 'subagent/catalog-diagnostic', details: { reason: 'corrupt' } }) const corrupt = await setup() cold(corrupt.ctx, childHeader, [event('subagent/descriptor', SessionSeq(0), { version: 'bad' })]) - await expect(corrupt.transport.page({ address: childAddress, throughSeq: 0 }, signal())) + await expect(corrupt.history.events({ address: childAddress, throughSeq: 0 }, signal())) .rejects.toMatchObject({ code: 'subagent/catalog-diagnostic', details: { reason: 'corrupt' } }) const ordinaryChild = await setup() const { origin: _origin, ...ordinaryChildHeader } = childHeader cold(ordinaryChild.ctx, ordinaryChildHeader, []) - await expect(ordinaryChild.transport.page({ address: childAddress, throughSeq: -1 }, signal())) + await expect(ordinaryChild.history.events({ address: childAddress, throughSeq: -1 }, signal())) .rejects.toMatchObject({ code: 'subagent/unauthorized' }) }) @@ -689,9 +770,9 @@ describe('SessionHistoryController', () => { retain: vi.fn(), [Symbol.dispose]: vi.fn(), } as unknown as SessionObservation), } as never) - const history = new SessionHistoryController(ctx, vi.fn()) + const { history } = controllers(ctx, vi.fn()) - await expect(history.page({ + await expect(history.events({ address: { kind: 'subagent', parentSessionId, @@ -710,7 +791,7 @@ describe('SessionHistoryController', () => { const session = ordinary.ctx.sessions.create(SessionId('projected'), { meta: { cwd: '/workspace' } }) session.append('turn/start', { turn: 1 }) const ordinarySnapshot = vi.spyOn(ordinary.ctx.sessionProjections, 'snapshot') - const ordinaryPage = await ordinary.transport.page({ + const ordinaryPage = await ordinary.history.events({ address: { kind: 'session', sessionId: session.id }, throughSeq: 0, }, signal()) @@ -727,7 +808,7 @@ describe('SessionHistoryController', () => { mode: 'continuable', provider: 'test', label: 'child', })) const childSnapshot = vi.spyOn(child.ctx.sessionProjections, 'snapshot') - const page = await child.transport.page({ + const page = await child.history.events({ address: { kind: 'subagent', parentSessionId, @@ -741,7 +822,7 @@ describe('SessionHistoryController', () => { }) it('keeps message-aligned pagination contiguous across replacement source-event references', async () => { - const { ctx, transport } = await setup() + const { ctx, history } = await setup() const session = ctx.sessions.create(SessionId('pagination'), { meta: { cwd: '/workspace' } }) session.append('turn/start', { turn: 1 }) append(session, 'user/message', { content: [], source: { kind: 'user' } }, { surfaceOp: 'append' }) @@ -754,27 +835,27 @@ describe('SessionHistoryController', () => { sourceEventSeqs: [SessionSeq(1), firstReply.seq, SessionSeq(3), SessionSeq(4), summary.seq], }) - const page = await transport.page({ + const page = await history.events({ address: { kind: 'session', sessionId: session.id }, throughSeq: replacement.seq, maxMessages: 2, }, signal()) expect(page.records.map(entry => entry.event.seq)) .toEqual([3, 4, 5, replacement.seq]) expect(page.hasMore).toBe(true) - const before = await transport.page({ + const before = await history.events({ address: { kind: 'session', sessionId: session.id }, throughSeq: replacement.seq, beforeSeq: 3, maxMessages: 1, }, signal()) expect(before.records.map(entry => entry.event.seq)).toEqual([2]) }) it('keeps cited source events in the page that owns their appended message', async () => { - const { ctx, transport } = await setup() + const { ctx, history } = await setup() const session = ctx.sessions.create(SessionId('pagination-sources'), { meta: { cwd: '/workspace' } }) const source = append(session, 'fixture/source', {}) append(session, 'user/message', { content: [], source: { kind: 'plugin' } }, { surfaceOp: 'append', sourceEventSeqs: [source.seq], }) - const page = await transport.page({ + const page = await history.events({ address: { kind: 'session', sessionId: session.id }, throughSeq: 1, maxMessages: 1, }, signal()) expect(page.records.map(entry => entry.event.seq)).toEqual([0, 1]) diff --git a/packages/api/session-controller/tsconfig.host.json b/packages/api/session-controller/tsconfig.host.json index 8a5fa75166..acadf82099 100644 --- a/packages/api/session-controller/tsconfig.host.json +++ b/packages/api/session-controller/tsconfig.host.json @@ -16,12 +16,24 @@ "src/control.ts", "src/file-references.ts", "src/history.ts", + "src/history/controller.ts", + "src/history/listener.ts", + "src/history/assistant-stream.ts", + "src/state/controller.ts", + "src/state/listener.ts", + "src/web/controller.ts", "src/list.ts", "src/media-references.ts", "src/archived-session-gate.ts", "src/skill-catalog.ts" ], "references": [ + { + "path": "../gateway/tsconfig.host.json" + }, + { + "path": "../../util/timeout" + }, { "path": "../../../vendor/cordis" }, diff --git a/packages/api/settings-controller/locale/de.json b/packages/api/settings-controller/locale/de.json new file mode 100644 index 0000000000..f27d4899d3 --- /dev/null +++ b/packages/api/settings-controller/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Lese- und Schreibschnittstelle einrichten", + "description": "Bieten Sie dem Kunden die Möglichkeit, verschiedene Einstellungen zu lesen und zu ändern." + } +} diff --git a/packages/api/settings-controller/locale/es.json b/packages/api/settings-controller/locale/es.json new file mode 100644 index 0000000000..39d21f44e7 --- /dev/null +++ b/packages/api/settings-controller/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Configurar la interfaz de lectura y escritura", + "description": "Proporcionar al cliente la capacidad de leer y modificar varias configuraciones." + } +} diff --git a/packages/api/settings-controller/locale/fr.json b/packages/api/settings-controller/locale/fr.json new file mode 100644 index 0000000000..7fe6fcd1d9 --- /dev/null +++ b/packages/api/settings-controller/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Configurer l'interface de lecture et d'écriture", + "description": "Offrir au client la possibilité de lire et de modifier divers paramètres." + } +} diff --git a/packages/api/settings-controller/locale/pt.json b/packages/api/settings-controller/locale/pt.json new file mode 100644 index 0000000000..46507f0ae7 --- /dev/null +++ b/packages/api/settings-controller/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Configurar interface de leitura e gravação", + "description": "Forneça ao cliente a capacidade de ler e modificar várias configurações." + } +} diff --git a/packages/api/settings-controller/locale/ru.json b/packages/api/settings-controller/locale/ru.json new file mode 100644 index 0000000000..a24ae67e2d --- /dev/null +++ b/packages/api/settings-controller/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Настройка интерфейса чтения и записи", + "description": "Предоставьте клиенту возможность читать и изменять различные настройки." + } +} diff --git a/packages/api/settings-controller/package.json b/packages/api/settings-controller/package.json index 260193276a..1a01d513c4 100644 --- a/packages/api/settings-controller/package.json +++ b/packages/api/settings-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-settings-controller", "description": "Remote owner for the configuration surfaces over the settings-domain seams", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, diff --git a/packages/api/terminal-controller/locale/de.json b/packages/api/terminal-controller/locale/de.json new file mode 100644 index 0000000000..40a84f00ec --- /dev/null +++ b/packages/api/terminal-controller/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Terminal-Steuerungsschnittstelle", + "description": "Bietet Clients die Möglichkeit, Sitzungsterminals zu erstellen, einzugeben, zu lesen und wiederherzustellen." + } +} diff --git a/packages/api/terminal-controller/locale/es.json b/packages/api/terminal-controller/locale/es.json new file mode 100644 index 0000000000..89251b9b70 --- /dev/null +++ b/packages/api/terminal-controller/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "interfaz de control terminal", + "description": "Proporciona a los clientes la capacidad de crear, ingresar, leer y restaurar terminales de sesión." + } +} diff --git a/packages/api/terminal-controller/locale/fr.json b/packages/api/terminal-controller/locale/fr.json new file mode 100644 index 0000000000..e016120a32 --- /dev/null +++ b/packages/api/terminal-controller/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "interface de contrôle des terminaux", + "description": "Fournit aux clients la possibilité de créer, saisir, lire et restaurer des terminaux de session." + } +} diff --git a/packages/api/terminal-controller/locale/pt.json b/packages/api/terminal-controller/locale/pt.json new file mode 100644 index 0000000000..3e2aa9afb6 --- /dev/null +++ b/packages/api/terminal-controller/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "interface de controle de terminal", + "description": "Fornece aos clientes a capacidade de criar, inserir, ler e restaurar terminais de sessão." + } +} diff --git a/packages/api/terminal-controller/locale/ru.json b/packages/api/terminal-controller/locale/ru.json new file mode 100644 index 0000000000..c2c8651003 --- /dev/null +++ b/packages/api/terminal-controller/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "интерфейс управления терминалом", + "description": "Предоставляет клиентам возможность создавать, вводить, читать и восстанавливать сеансовые терминалы." + } +} diff --git a/packages/api/terminal-controller/package.json b/packages/api/terminal-controller/package.json index 1ac43492f5..a7e7ca3a0e 100644 --- a/packages/api/terminal-controller/package.json +++ b/packages/api/terminal-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-terminal-controller", "description": "Session-owned interactive terminals with shell discovery, screen recovery and typed Remote control", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, diff --git a/packages/api/workspace-controller/locale/de.json b/packages/api/workspace-controller/locale/de.json new file mode 100644 index 0000000000..f36dfe99d3 --- /dev/null +++ b/packages/api/workspace-controller/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Schnittstelle zur Arbeitsbereichssteuerung", + "description": "Bietet Clients Arbeitsbereichsvorgänge und einen Status, der bei erneuter Verbindung wiederhergestellt werden kann." + } +} diff --git a/packages/api/workspace-controller/locale/es.json b/packages/api/workspace-controller/locale/es.json new file mode 100644 index 0000000000..3a451aba01 --- /dev/null +++ b/packages/api/workspace-controller/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Interfaz de control del espacio de trabajo", + "description": "Proporciona a los clientes operaciones en el espacio de trabajo y un estado que se puede restaurar tras la reconexión." + } +} diff --git a/packages/api/workspace-controller/locale/fr.json b/packages/api/workspace-controller/locale/fr.json new file mode 100644 index 0000000000..d6b5f2a527 --- /dev/null +++ b/packages/api/workspace-controller/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Interface de contrôle de l'espace de travail", + "description": "Fournit aux clients des opérations d’espace de travail et un état qui peut être restauré lors de la reconnexion." + } +} diff --git a/packages/api/workspace-controller/locale/pt.json b/packages/api/workspace-controller/locale/pt.json new file mode 100644 index 0000000000..0564e0743f --- /dev/null +++ b/packages/api/workspace-controller/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Interface de controle do espaço de trabalho", + "description": "Fornece aos clientes operações de espaço de trabalho e um estado que pode ser restaurado após a reconexão." + } +} diff --git a/packages/api/workspace-controller/locale/ru.json b/packages/api/workspace-controller/locale/ru.json new file mode 100644 index 0000000000..19da086fb1 --- /dev/null +++ b/packages/api/workspace-controller/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Интерфейс управления рабочей областью", + "description": "Предоставляет клиентам операции в рабочей области и состояние, которое можно восстановить при повторном подключении." + } +} diff --git a/packages/api/workspace-controller/package.json b/packages/api/workspace-controller/package.json index 142b9dfbf3..802e26fb0e 100644 --- a/packages/api/workspace-controller/package.json +++ b/packages/api/workspace-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-workspace-controller", "description": "Workspace Remote commands and reconnect-safe state transport", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, diff --git a/packages/api/workspace-files/locale/de.json b/packages/api/workspace-files/locale/de.json new file mode 100644 index 0000000000..60f31b3a27 --- /dev/null +++ b/packages/api/workspace-files/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Workspace-Dateischnittstelle", + "description": "Bietet das Lesen von Arbeitsbereichsdateien, das Auflisten von Verzeichnissen und die Aktualisierung von Dateiinformationen." + } +} diff --git a/packages/api/workspace-files/locale/es.json b/packages/api/workspace-files/locale/es.json new file mode 100644 index 0000000000..91db1da1f2 --- /dev/null +++ b/packages/api/workspace-files/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Interfaz de archivos del espacio de trabajo", + "description": "Proporciona lectura de archivos del espacio de trabajo, listado de directorios y actualizaciones de información de archivos." + } +} diff --git a/packages/api/workspace-files/locale/fr.json b/packages/api/workspace-files/locale/fr.json new file mode 100644 index 0000000000..490d88dcbf --- /dev/null +++ b/packages/api/workspace-files/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Interface de fichier de l'espace de travail", + "description": "Fournit la lecture des fichiers de l'espace de travail, la liste des répertoires et les mises à jour des informations sur les fichiers." + } +} diff --git a/packages/api/workspace-files/locale/pt.json b/packages/api/workspace-files/locale/pt.json new file mode 100644 index 0000000000..e0d49a666d --- /dev/null +++ b/packages/api/workspace-files/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Interface de arquivo do espaço de trabalho", + "description": "Fornece leitura de arquivos do espaço de trabalho, listagem de diretórios e atualizações de informações de arquivos." + } +} diff --git a/packages/api/workspace-files/locale/ru.json b/packages/api/workspace-files/locale/ru.json new file mode 100644 index 0000000000..3d514ad55b --- /dev/null +++ b/packages/api/workspace-files/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Файловый интерфейс рабочей области", + "description": "Обеспечивает чтение файлов рабочей области, список каталогов и обновление информации о файлах." + } +} diff --git a/packages/api/workspace-files/package.json b/packages/api/workspace-files/package.json index ca8ac9b61e..4d1e0ca86a 100644 --- a/packages/api/workspace-files/package.json +++ b/packages/api/workspace-files/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-workspace-files", "description": "Workspace file service and Client resource provider: bounded reads, directory listing, and live metadata over the workspaceFiles Remote namespace", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, diff --git a/packages/attachment/attachment-local/README.i18n.yaml b/packages/attachment/attachment-local/README.i18n.yaml index be08b2fdbd..2caf5e3785 100644 --- a/packages/attachment/attachment-local/README.i18n.yaml +++ b/packages/attachment/attachment-local/README.i18n.yaml @@ -36,8 +36,8 @@ en: dcd9857653645420 zh: a27259a09f17465d /deepseek-ai-dsh-attachment-local/understand-the-implementation/write-and-read-paths: - en: 62ea104a00a7fdb8 - zh: b08575274ca244b4 + en: 4cbbe8a1466ed46f + zh: 49d2d118501867d3 /deepseek-ai-dsh-attachment-local/understand-the-implementation/source-map: en: 05af85aa85934d01 zh: 1c89e80d496dc0a3 diff --git a/packages/attachment/attachment-local/README.md b/packages/attachment/attachment-local/README.md index 4844be3670..b27ac0c75a 100644 --- a/packages/attachment/attachment-local/README.md +++ b/packages/attachment/attachment-local/README.md @@ -83,6 +83,8 @@ This section explains the durability and verification design behind the storage, Objects land at `/attachments/v1/objects//`; equal bytes deduplicate to one object and one `sha256:` id. Before the first write, the process syncs every ancestor directory of the home down to the filesystem root once, so a directory another process created but has not yet synced is never mistaken for a safe boundary. Writes then stage bytes in `v1/tmp`, sync the temporary file, publish with an atomic exclusive hard link, and sync the publication directories — on Windows, filesystem metadata journaling owns entry durability. Once the save resolves, the reported reference is durable. +Image reads receive a complete reference with a canonical `sha256:` ID, derive the object path within this storage tree, verify the complete digest, and probe the image header. The actual format, byte length, width, and height must match the supplied reference. The returned reference preserves optional `name` and `originalDimensions` as caller-supplied display information; these fields are not verified against the object. Reads neither consult Session history nor reapply admission limits; a missing object or failed verification rejects the read. + Admission accepts up to 20 images and 200 MiB of source bytes per message; one source may use up to 50 MiB, 64 million pixels, and 65,535 pixels per side. It applies orientation, removes metadata and color profiles, and normalizes under a 2048×2048 total-pixel budget, an 8192-pixel long edge, and a 4 MiB encoded-byte target. Extreme aspect ratios therefore retain their short-edge resolution. Clean single-frame 8-bit sRGB/sRGBA PNG, JPEG, or WebP input already within those limits passes through byte-identically; GIF, animation, metadata, orientation, 16-bit PNG, and incompatible color spaces force conversion. Request versions live below `/cache/attachments/request-images/`, resolved by `dshCachePath`; an explicit `dshHome` setting applies to both cache and durable storage. Clearing this cache between requests preserves durable attachments, and later reads regenerate the variants. `readImageRequest` scales without enlargement to the route-chosen target, resizing by the long edge only so the encoder derives the short edge as the route predicts, then applies a separate encoded-byte target through the same alpha routing and quality ladder. Its cache identity includes the attachment id, transform version, target dimensions, byte target, and fixed encoder settings; cached bytes are header-probed for format, 8-bit sRGB/sRGBA, dimensions, and alpha facts, and a mismatch regenerates the entry. Concurrent callers share one transform and cache write, while cancellation stops shared work only when no waiter remains. `imageHostPath` derives the normalized object's host path, and the mounted filesystem may map that path into its execution world without writing it to durable history. diff --git a/packages/attachment/attachment-local/README.zh.md b/packages/attachment/attachment-local/README.zh.md index a079785984..a0663aaebe 100644 --- a/packages/attachment/attachment-local/README.zh.md +++ b/packages/attachment/attachment-local/README.zh.md @@ -83,6 +83,8 @@ kind: "package-reference" 对象存放在 `/attachments/v1/objects//`;相同字节会去重为同一个对象和同一个 `sha256:` 标识符。首次写入前,进程会把 home 的每个祖先目录逐级同步到文件系统根目录,因此绝不会把另一个进程已创建但尚未同步的目录误认为安全边界。随后,写入过程把字节暂存到 `v1/tmp`、同步临时文件、以原子且排他的硬链接发布,并同步发布目录——在 Windows 上,文件系统元数据日志负责目录项持久性。保存操作完成后,返回的引用已具备持久性。 +图片读取接收包含规范 `sha256:` ID 的完整引用,在该存储目录内推导对象路径,校验完整摘要,并探测图片文件头。实际格式、字节数、宽度和高度必须与传入引用一致。返回的引用把可选的 `name` 和 `originalDimensions` 作为调用方提交的显示信息原样保留,不根据对象校验这两个字段。读取不查询 Session 历史,也不重新应用准入限制;对象缺失或校验失败都会拒绝读取。 + 准入允许每条消息最多 20 张图片与 200 MiB 源字节;单个源图最多 50 MiB、6400 万像素与单边 65,535 像素。系统应用方向、移除元数据与色彩配置,并把规范化结果限制在 2048×2048 总像素预算、8192 像素长边和 4 MiB 编码字节目标内,因此,即使宽高比极端,图片也会保留短边分辨率。已经满足限制的干净、单帧、8-bit sRGB/sRGBA PNG、JPEG 或 WebP 会逐字节直通;GIF、动画、元数据、方向、16-bit PNG 与不兼容色彩空间会触发转换。 请求版本位于由 `dshCachePath` 解析的 `/cache/attachments/request-images/`;显式 `dshHome` 设置同时适用于缓存与持久存储。在两次请求之间清空此缓存会保留持久附件,后续读取会重新生成请求版本。`readImageRequest` 在不放大的前提下缩放到路由选定的目标尺寸,缩放只按长边给定,短边由编码器按路由预测的方式推出,随后通过相同的 alpha 路由与质量阶梯应用独立编码字节目标。缓存身份包含附件 id、变换版本、目标尺寸、字节目标与固定编码参数;缓存字节会先通过文件头探测格式、8-bit sRGB/sRGBA、尺寸与 alpha 信息,不匹配时重新生成。并发调用方共享一次变换与缓存写入,且只在没有等待方时由取消停止共享工作。`imageHostPath` 派生规范化对象的宿主路径,挂载的文件系统可以把该路径映射进执行世界,而不会写入持久历史。 diff --git a/packages/attachment/attachment-local/locale/de.json b/packages/attachment/attachment-local/locale/de.json new file mode 100644 index 0000000000..1095b25bb2 --- /dev/null +++ b/packages/attachment/attachment-local/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Lokaler Anhangsspeicher", + "description": "Speichern Sie Anhänge wie Bilder in der Sitzung und lesen Sie sie entsprechend der Inhaltskennung." + } +} diff --git a/packages/attachment/attachment-local/locale/es.json b/packages/attachment/attachment-local/locale/es.json new file mode 100644 index 0000000000..59ca4b5d35 --- /dev/null +++ b/packages/attachment/attachment-local/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Almacenamiento de archivos adjuntos locales", + "description": "Guarde archivos adjuntos como imágenes de la sesión y léalos según el identificador de contenido." + } +} diff --git a/packages/attachment/attachment-local/locale/fr.json b/packages/attachment/attachment-local/locale/fr.json new file mode 100644 index 0000000000..cb5019bfc5 --- /dev/null +++ b/packages/attachment/attachment-local/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Stockage local des pièces jointes", + "description": "Enregistrez les pièces jointes telles que les images dans la session et lisez-les en fonction de l'identifiant du contenu." + } +} diff --git a/packages/attachment/attachment-local/locale/pt.json b/packages/attachment/attachment-local/locale/pt.json new file mode 100644 index 0000000000..030a96aed5 --- /dev/null +++ b/packages/attachment/attachment-local/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Armazenamento local de anexos", + "description": "Salve anexos como fotos na sessão e leia-os de acordo com o identificador de conteúdo." + } +} diff --git a/packages/attachment/attachment-local/locale/ru.json b/packages/attachment/attachment-local/locale/ru.json new file mode 100644 index 0000000000..d452d5a8f5 --- /dev/null +++ b/packages/attachment/attachment-local/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Локальное хранилище вложений", + "description": "Сохраняйте вложения, например изображения, в сеансе и читайте их в соответствии с идентификатором контента." + } +} diff --git a/packages/attachment/attachment-local/package.json b/packages/attachment/attachment-local/package.json index b8163bbe34..6ad5b54083 100644 --- a/packages/attachment/attachment-local/package.json +++ b/packages/attachment/attachment-local/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-attachment-local", "description": "Private content-addressed DSH_HOME attachment storage", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, diff --git a/packages/attachment/attachment-local/src/store.ts b/packages/attachment/attachment-local/src/store.ts index 7fab679e34..88ab2c9d27 100644 --- a/packages/attachment/attachment-local/src/store.ts +++ b/packages/attachment/attachment-local/src/store.ts @@ -423,7 +423,7 @@ export async function saveImageFile( /** * Read and verify one content-addressed image. * @param root - absolute `DSH_HOME/attachments/v1` root. - * @param ref - reference recorded in the session log. + * @param ref - supplied image reference; display fields are returned unchanged. * @param signal - optional cancellation for filesystem and verification work. * @returns verified bytes and reference. * @throws the signal reason when aborted, or an AttachmentError when verification fails. diff --git a/packages/attachment/attachment-local/tests/store.spec.ts b/packages/attachment/attachment-local/tests/store.spec.ts index 82c2b9f3ba..6e7ff4b011 100644 --- a/packages/attachment/attachment-local/tests/store.spec.ts +++ b/packages/attachment/attachment-local/tests/store.spec.ts @@ -148,6 +148,21 @@ describe('local attachment store', () => { await expect(readImageFile(storageRoot, first)).resolves.toEqual({ ref: first, data: PNG }) }) + it.each([ + { mediaType: 'image/jpeg' }, { bytes: PNG.byteLength + 1 }, { width: 2 }, { height: 2 }, + ] as const)('rejects supplied metadata that differs from stored bytes: %j', async (mismatch) => { + const storageRoot = await root() + const saved = await saveImageFile(storageRoot, { data: PNG, mediaType: 'image/png' }, LIMITS, POLICY) + await expect(readImageFile(storageRoot, { ...saved, ...mismatch })).rejects.toMatchObject({ code: 'ATTACHMENT_CORRUPT' }) + }) + + it('preserves supplied display fields while verifying stored image facts', async () => { + const storageRoot = await root() + const saved = await saveImageFile(storageRoot, { data: PNG, mediaType: 'image/png' }, LIMITS, POLICY) + const supplied = { ...saved, name: 'display.png', originalDimensions: { width: 8, height: 8 } } + await expect(readImageFile(storageRoot, supplied)).resolves.toEqual({ ref: supplied, data: PNG }) + }) + it('rejects publication when the supplied digest does not match the staged bytes', async () => { const storageRoot = await root() const target = join(storageRoot, 'objects', '00', 'mismatch') diff --git a/packages/attachment/attachment/README.i18n.yaml b/packages/attachment/attachment/README.i18n.yaml index b2b7ba57ad..125d96125d 100644 --- a/packages/attachment/attachment/README.i18n.yaml +++ b/packages/attachment/attachment/README.i18n.yaml @@ -27,8 +27,8 @@ en: 8a0fa64e84aa4450 zh: ed2ac44ef20250d4 /deepseek-ai-dsh-attachment/use-this-package/reuse-images-across-the-session: - en: c99e4e088be92c4f - zh: 34997ecb9a420d08 + en: ede9266988e20f19 + zh: 6264c601ec62975d /deepseek-ai-dsh-attachment/use-this-package/what-can-go-wrong: en: b35e2f7f17269ae1 zh: 57cf0ef9fee6c7e1 @@ -36,8 +36,8 @@ en: 25d9c7d6c0899d23 zh: ad8380d14810ff1c /deepseek-ai-dsh-attachment/understand-the-implementation/design-decisions: - en: af7deef72fd2fa93 - zh: f217d52ce3971135 + en: 6315b2d1fb12f0ca + zh: c3f99f4c0850fb44 /deepseek-ai-dsh-attachment/understand-the-implementation/service-operations: en: b94d13fe133d8ce6 zh: dd4064d20d510afc diff --git a/packages/attachment/attachment/README.md b/packages/attachment/attachment/README.md index 2acdc13c42..0e0c2bc05f 100644 --- a/packages/attachment/attachment/README.md +++ b/packages/attachment/attachment/README.md @@ -45,7 +45,7 @@ Commands declaring attachment input receive images and generic files in selectio ### Reuse images across the session -Saved normalized images stay in conversation history and are projected into deterministic, route-sized request versions in later turns; after a restart, a resumed session shows and reuses the same images. When the current execution filesystem maps the stored host object, the request descriptor also carries a read-only process path that the model can inspect. When history or a request version is read back, the stored bytes are checked against what was recorded, so a missing, corrupted, or swapped image surfaces as an error rather than wrong bytes. +Saved normalized images stay in conversation history and are projected into deterministic, route-sized request versions in later turns; after a restart, a resumed session shows and reuses the same images. When the current execution filesystem maps the stored host object, the request descriptor also carries a read-only process path that the model can inspect. History image reads and request projections verify the stored object against the full image reference, including its digest, format, byte length, and dimensions. Missing, corrupted, or swapped images fail explicitly. ### What can go wrong @@ -65,7 +65,7 @@ This section explains the design decisions behind the seam and the service opera - **Normalize and persist before event.** Every source is prepared and verified before the batch publishes in order, so the session log never references a partial or failed normalization. - **Immutable and retention-neutral.** Objects are immutable once published; resumed and forked sessions may share them, so reference-aware garbage collection is deferred rather than tied to any one session's deletion. -- **Verify on read.** Reads check bytes and metadata against the logged reference before returning them, and request projections fully decode cached bytes, so a missing, corrupted, or swapped object fails closed. +- **Verify on read.** Reads verify the immutable object against the supplied reference without consulting a Session. Optional display names and pre-normalization dimensions pass through as caller-supplied display information; the stored bytes do not verify these fields. - **Role-neutral image blocks.** The `ImageBlock` content block in `dsh-llm` carries an `ImageAttachmentRef`; provider adapters resolve it into deterministic request versions at an explicit route-chosen target size and byte target, while execution filesystems may map the immutable host object to a model-readable process path. - **Error routing by code.** `AttachmentError` re-implements the `HarnessError` shape instead of extending it because the base lives in `dsh-llm`, which depends on this package; consumers use `isAttachmentError` and route on `code`, never on the prototype chain. - **Files are verbatim, images are normalized.** `saveFile` commits an existing byte array, `saveFileStream` commits bounded chunks with backpressure and cancellation, `readFileStream` verifies and returns bounded chunks, and `fileHostPath` locates the stored object for read-on-demand projection; neither file write path applies admission limits. The image path keeps its separate normalization, limits, and request-version pipeline. The `FileBlock` content block in `dsh-llm` carries a `FileAttachmentRef`, and request assembly projects it to deterministic handle text for every route. diff --git a/packages/attachment/attachment/README.zh.md b/packages/attachment/attachment/README.zh.md index 06cbe5631a..9c9d2c7fb5 100644 --- a/packages/attachment/attachment/README.zh.md +++ b/packages/attachment/attachment/README.zh.md @@ -45,7 +45,7 @@ kind: "package-reference" ### 在整个会话中复用图片 -已保存的规范化图片会保留在对话历史中,并在后续轮次投影为确定性的路由尺寸请求版本;重启后,恢复的会话会显示并复用相同的图片。当前执行文件系统可以映射已存宿主对象时,请求描述符还会携带模型可检查的只读进程路径。回读历史或请求版本时,已存储的字节会与记录的内容比对,因此缺失、损坏或被替换的图片会以错误形式呈现,而不是错误的字节。 +已保存的规范化图片会保留在对话历史中,并在后续轮次投影为确定性的路由尺寸请求版本;重启后,恢复的会话会显示并复用相同的图片。当前执行文件系统可以映射已存宿主对象时,请求描述符还会携带模型可检查的只读进程路径。历史图片读取和请求投影会把存储对象与完整图片引用中的摘要、格式、字节数和尺寸比对。图片缺失、损坏或被替换时会明确失败。 ### 可能出什么问题 @@ -65,7 +65,7 @@ kind: "package-reference" - **事件前完成规范化与持久化。** 每个源图都会在批次按序发布前完成准备与校验,因此会话日志绝不会引用部分完成或规范化失败的对象。 - **不可变且保留策略中立。** 对象一经发布即不可变;恢复和 fork 后的会话可能共享它们,因此引用感知的垃圾回收被推迟,而不是与任何单个会话的删除绑定。 -- **读取时校验。** 读取在返回前把字节和元数据与记录的引用比对,请求投影还会完整解码缓存字节,因此缺失、损坏或被替换的对象不会通过校验。 +- **读取时校验。** 读取会把不可变对象与传入引用比对,无需查询 Session。可选的显示名称和规范化前尺寸作为调用方提交的显示信息原样返回;存储字节不校验这两个字段。 - **角色无关的图片块。** `dsh-llm` 中的 `ImageBlock` 内容块携带 `ImageAttachmentRef`;提供方适配器按路由显式选定的目标尺寸与字节目标把引用解析为确定性请求版本,执行文件系统则可以把不可变宿主对象映射为模型可读的进程路径。 - **按错误码路由。** `AttachmentError` 重新实现 `HarnessError` 的结构而不是继承它,因为基类位于 `dsh-llm`,而后者依赖本包;消费方用 `isAttachmentError` 识别错误并按 `code` 路由,绝不依赖原型链。 - **文件原样,图片规范化。**`saveFile` 提交已有字节数组,`saveFileStream` 以背压和取消语义提交有界分块,`readFileStream` 校验并返回有界分块,`fileHostPath` 定位存储对象供按需读取投影;两种文件写入路径都不设准入限制。图片路径保留其独立的规范化、限额与请求版本流水线。`dsh-llm` 中的 `FileBlock` 内容块承载 `FileAttachmentRef`,请求组装会为每条路由将其投影为确定性的句柄文本。 diff --git a/packages/attachment/attachment/package.json b/packages/attachment/attachment/package.json index 65958a9643..7ef5c29d66 100644 --- a/packages/attachment/attachment/package.json +++ b/packages/attachment/attachment/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-attachment", "description": "Durable immutable attachment storage seam for the DeepSeek Harness", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, diff --git a/packages/attachment/attachment/src/index.ts b/packages/attachment/attachment/src/index.ts index ba7f567884..802df0cb6b 100644 --- a/packages/attachment/attachment/src/index.ts +++ b/packages/attachment/attachment/src/index.ts @@ -186,8 +186,8 @@ export abstract class AttachmentStore extends Service { abstract saveImage(input: SaveImageAttachment): Promise /** - * Read one image and verify that bytes still match the recorded reference. - * @param ref - durable reference from the session log. + * Read one image and verify its ID, format, byte length, and dimensions against the supplied reference. + * @param ref - supplied image reference; name and originalDimensions are preserved without file verification. * @param signal - optional cancellation for backend read and verification work. * @returns the verified bytes and normalized attachment reference. * @throws the signal reason when aborted, or a storage error when verification fails. @@ -240,7 +240,7 @@ export abstract class AttachmentStore extends Service { * Read and verify one verbatim stored file as bounded chunks. Providers must * not collect the complete file in memory. Backends without verbatim file * reads keep this default rejection. - * @param ref - durable reference from the session log. + * @param ref - durable file reference from the session log. * @param signal - optional cancellation for backend reads and verification work. * @returns exact file bytes in order; integrity failures reject the iteration. */ diff --git a/packages/boot/README.i18n.yaml b/packages/boot/README.i18n.yaml index 8ecc1fc6e8..0a33b9fd4f 100644 --- a/packages/boot/README.i18n.yaml +++ b/packages/boot/README.i18n.yaml @@ -15,8 +15,8 @@ en: 09848f4d056e4fc1 zh: 8df6139cff0288f6 /boot-shared-app-bin-boot-glue/packages: - en: 71736c39fd71952c - zh: 2033a18debd8a2d8 + en: 358a944a024ffeb1 + zh: f430e25832085068 /boot-shared-app-bin-boot-glue/related-documentation: en: 77af4b40ee7b98a3 zh: e9b4e817823b973d diff --git a/packages/boot/README.md b/packages/boot/README.md index d3d6610d1c..04e4325fe3 100644 --- a/packages/boot/README.md +++ b/packages/boot/README.md @@ -23,12 +23,11 @@ The boot group launches profile applications and manages their installed composi | Package | Role | ctx key | |---|---|---| | [`app-boot`](app-boot/README.md) | Boots a dsh app from a `cordis.yml`: loads `.env`, applies profile and patch layers, and reports startup failures clearly | (library for the bins) | -| [`official-bundles`](official-bundles/README.md) | Lists the bundles the installation ships in profile templates, offers switched off, installs on demand, or retires | (library) | | [`cmdline`](cmdline/README.md) | Lets the app own its flags, `--help`, and exit code; passes everything after the launcher's flags through verbatim | `cmdlineArgs`, `appExit` | | [`hmr`](hmr/README.md) | Coordinates module and configuration reloads with package mutations | `hmr` | | [`config-editor`](config-editor/README.md) | Persists active profile configuration through Loader reconciliation | `configEditor` | | [`plugin-manager`](plugin-manager/README.md) | Manages current-profile plugins and bundle packages through shared CLI operations | `pluginManager` | -| [`plugin-market`](plugin-market/README.md) | Reads the plugin market indexes the user configures for Discover and the `plugin_market` tool | `pluginMarket` | +| [`plugin-market`](plugin-market/README.md) | Reads the plugin indexes the user configures for Discover and the `plugin_market` tool | `pluginMarket` | ## Related documentation diff --git a/packages/boot/README.zh.md b/packages/boot/README.zh.md index 12c9b32d7d..afdee696e2 100644 --- a/packages/boot/README.zh.md +++ b/packages/boot/README.zh.md @@ -23,12 +23,11 @@ boot 组负责启动 profile 应用并管理其已安装组合。`app-boot` 解 | 包 | 职责 | ctx 键 | |---|---|---| | [`app-boot`](app-boot/README.zh.md) | 从 `cordis.yml` 启动 dsh 应用:加载 `.env`、应用 profile 与 patch 层,并清晰报告启动失败 | (供各 bin 使用的库) | -| [`official-bundles`](official-bundles/README.zh.md) | 列出安装随附于 profile 模板、默认关闭提供、按需安装或已退役的组合包 | (库) | | [`cmdline`](cmdline/README.zh.md) | 让应用持有自己的 flag、`--help` 与退出码;启动器自身 flag 之后的一切原样传入 | `cmdlineArgs`、`appExit` | | [`hmr`](hmr/README.zh.md) | 协调模块与配置重载,并与包修改互斥执行 | `hmr` | | [`config-editor`](config-editor/README.zh.md) | 通过 Loader 应用并持久化当前 profile 配置 | `configEditor` | | [`plugin-manager`](plugin-manager/README.zh.md) | 通过共享 CLI 操作管理当前 profile 插件与组合包 | `pluginManager` | -| [`plugin-market`](plugin-market/README.zh.md) | 读取用户配置的插件市场索引,供发现页和 `plugin_market` 工具使用 | `pluginMarket` | +| [`plugin-market`](plugin-market/README.zh.md) | 读取用户配置的插件索引,供发现页和 `plugin_market` 工具使用 | `pluginMarket` | ## 相关文档 diff --git a/packages/boot/app-boot/README.i18n.yaml b/packages/boot/app-boot/README.i18n.yaml index 7170485221..9ce0beae8e 100644 --- a/packages/boot/app-boot/README.i18n.yaml +++ b/packages/boot/app-boot/README.i18n.yaml @@ -24,8 +24,8 @@ en: 65bf2834b81f87da zh: c864ac60a3005b99 /deepseek-ai-dsh-app-boot/use-this-package/profiles: - en: 0a1b5f4f40d835a7 - zh: d8f4b54160aa033b + en: a9c82cd220ae8d59 + zh: 8c7c1c97efcdfc25 /deepseek-ai-dsh-app-boot/use-this-package/previewing-the-effective-configuration: en: 646a0ccdd7881ad1 zh: e3696acb1573dd7b @@ -33,8 +33,8 @@ en: c4a301652b851ce9 zh: 784871e19cd9db0a /deepseek-ai-dsh-app-boot/use-this-package/reading-plugin-display-metadata: - en: b737278c1bc065e7 - zh: f42bdbfe267581d1 + en: 91d80c444ac0cfe5 + zh: e7db496043528ffb /deepseek-ai-dsh-app-boot/use-this-package/startup-and-reload-failures: en: dc13dfa1f79292e4 zh: d51682ced7a18ac2 @@ -42,8 +42,8 @@ en: f4a2695cb4c8a570 zh: 89837235d2f376cf /deepseek-ai-dsh-app-boot/understand-the-implementation/design-notes: - en: 9ecb744556705fd1 - zh: d83aaf2ebb91d0fc + en: 6eba01e24a2a68ab + zh: 64af424489087ec7 /deepseek-ai-dsh-app-boot/understand-the-implementation/helper-behavior: en: 6fa850d1bb000d0e zh: aa83a40a9d3db295 diff --git a/packages/boot/app-boot/README.md b/packages/boot/app-boot/README.md index 53c72680be..4d30457f81 100644 --- a/packages/boot/app-boot/README.md +++ b/packages/boot/app-boot/README.md @@ -53,7 +53,9 @@ Before a profile imports a plugin, DSH checks its declared DSH requirement again Admission happens only at composition boundaries DSH owns, and a denied row is denied in the launcher's own copy of the composition: no profile patch layer, dependency manifest, or bundle list changes. `prepareProfilePatches` composes over the launcher's empty profile root and runs while the root Include is mounted and on every profile recomposition, so a denied plugin never imports its module. `prepareProfileEntries` does the same for a preset's rows. A denied ordinary row becomes a detached `disabled: true` row; a native group stays mounted and its denied children do not load; a native Include that reaches a denied plugin is omitted whole, because its file is never rewritten. A row denied by policy keeps its configured `disabled` value in the profile, and every refusal is reported with the package, versions, and risk. A bundle is not a row, so `loadProfileDirectory` checks each bundle's own DSH requirement when it loads the profile's bundle layers, at startup and on every recomposition; an incompatible bundle without an exemption is skipped like an unreadable one and listed in `skippedBundles`. These boundaries do not cover plugins another embedder mounts through its own `ctx.plugin` call. Two edits made directly to files during a session are judged only at the next recomposition or startup: a running plugin's own `package.json` DSH requirement, and an entry-list file the Loader reads itself, such as the launcher's root config or a nested `cordis:include` file. `--dump-config` reports the configured composition, so a denied plugin row still appears there while a denied bundle contributes no rows, and `--dump-config-schema` imports each composed module to read its schema; run it only against a profile whose plugins you already trust. -Exact-version exemptions live in the profile's own `compatibility.json`, not in its `package.json`, so an exemption write never touches the dependency manifest, the bundle list, or Cordis patch files. It maps exact `package-name@version` keys to lists of exact DSH runtime versions; neither a plugin upgrade nor a DSH upgrade inherits permission. A missing file means no exemptions. A malformed one never stops the profile from starting: records the reader accepts still apply, each rejected record is reported on stderr beside the plugin denials, and the file is then treated as read-only, so a grant or revocation refuses and asks the user to repair it by hand instead of overwriting their content. [Plugin Manager](../plugin-manager/README.md#version-compatibility-and-exemptions) owns the grant, revocation, and risk confirmation each change requires. +Exact-version exemptions live in the profile's own `compatibility.json`, not in its `package.json`, so an exemption write never touches the dependency manifest, the bundle list, or Cordis patch files. It maps exact `package-name@version` keys to lists of exact DSH runtime versions; neither a plugin upgrade nor a DSH upgrade inherits permission. A missing file means no exemptions. A malformed one never stops the profile from starting: records the reader accepts still apply, each rejected record is reported on stderr beside the plugin denials, and the file is then treated as read-only, so a grant or revocation refuses and asks the user to repair it by hand instead of overwriting their content. [Plugin Manager](../plugin-manager/README.md#version-compatibility-and-exemptions) owns the grant, revocation, and risk confirmation each change requires. `validatePluginVersionExemption(packageVersion, runtimeVersion)` validates canonical exact identities without granting permission; invalid identities throw. + +A bundle may declare `dsh.bundle.platforms` as a nonempty list of Node Host platform names, such as `["darwin"]`. The launcher validates this declaration before reading the bundle patch. An unsupported Host skips the entire layer, retains its saved selection, and reports the reason through `skippedBundles`; other layers remain effective. Omission permits every platform. Values must be Node platform names; aliases such as `macos` are invalid. Browser clients do not determine Host support. Your machine-local preferences also live in the Harness home: @@ -86,7 +88,7 @@ The projector preserves native omission behavior by checking literal defaults ag Use `readPluginMeta(specifier, parentURL)` or `ctx.pluginPackages.metaOf(specifier, parentURL)` to read installed package display text without importing or activating the plugin. Lookup uses the complete package specifier and the caller's resolution base, respecting Node exports. File paths and file URLs return no metadata without resolving resources. For a package-root specifier, missing locale fields fall back to the accessible `package.json`; a subpath specifier never reads a `package.json`. Malformed metadata returns an `error` diagnostic. Results retain translations for Client-side language selection. The reader also loads an image data URL, even when locale text is complete: a package root uses its manifest `icon`, or `/icon` when that field is omitted; a subpath uses `/icon`. An icon error preserves valid text alongside the diagnostic. See [Plugin display metadata](../../../docs/cookbook/adding-a-package.md#plugin-display-metadata) for the author format. -The profile templates, installation-owned profile tuples, and retired bundle list that app-boot applies live in [`@deepseek-ai/dsh-official-bundles`](../official-bundles/README.md), together with the installation's default, optional, and on-demand bundle lists. +The profile templates, installation-owned profile tuples, and retired bundle list that app-boot applies live in [`@deepseek-ai/dsh-official-bundles`](../../util/official-bundles/README.md), together with the installation's default, optional, and on-demand bundle lists. ### Startup and reload failures @@ -143,7 +145,9 @@ This section explains how the outcomes above are realized and points at the code - **One rejection checkpoint.** `inactiveEntries` keeps the exact reasons it folds into the boot diagnostic visible through the next process rejection checkpoint, so `installFailLoud` coalesces Loader's duplicate notification while unrelated unhandled rejections remain fatal. - **Two-stage failure labels.** Outside startup audit failures, `boot()` distinguishes `host preparation failed` — `prepare` threw before any config-tree entry mounted — from `plugin tree failed to load`, and appends the deepest plugin error's stack. Plugin diagnostics retain nested causes and aggregate member failures; cyclic causes stop traversal without replacing the original error. -The startup error also retains inactive-entry metadata and raw startup warning/error records without retaining the Loader tree. Its `entries` and `startup` fields are non-enumerable: direct access and full diagnostic reports retain them, while ordinary error inspection omits them. Pending-only failures have no `cause`; failures with recorded errors retain their original values in an `AggregateError`. Import errors are collected through the logger before the Loader mounts because no failed Fiber exists for those imports. The temporary exporter is removed when boot settles. +The startup error also retains inactive-entry metadata and raw startup warning/error records without retaining the Loader tree. Its `entries`, `startup`, and `composition` fields are non-enumerable: direct access and full diagnostic reports retain them, while ordinary error inspection omits them. Pending-only failures have no `cause`; failures with recorded errors retain their original values in an `AggregateError`. Import errors are collected through the logger before the Loader mounts because no failed Fiber exists for those imports. The temporary exporter is removed when boot settles. + +The package exports `StartupCompositionDiagnostic`, `StartupPluginState`, and `StartupServiceState` for typed consumers. Before disposal, `composition` captures up to 256 configured plugin rows and 256 missing-service observations, with omission counts. Rows include module, available package version, state and Loader source URL; configuration values are excluded. Registered providers include their state and whether their scope matches the consumer. An empty provider list means ownership is unknown: disabled or failed plugins may never have registered. The Loader source does not identify which overlay last changed a row. Metadata lookup failures leave the version unknown; snapshot failure preserves the original startup error. ### Helper behavior diff --git a/packages/boot/app-boot/README.zh.md b/packages/boot/app-boot/README.zh.md index a22b7eabab..a4d8554ca5 100644 --- a/packages/boot/app-boot/README.zh.md +++ b/packages/boot/app-boot/README.zh.md @@ -53,7 +53,9 @@ profile 导入插件前,DSH 会将其声明的 DSH 版本要求与 `getDshRunt 检查只发生在 DSH 自己持有的组合入口,改写的是启动器自己的那份组合:profile 的 patch 层、依赖清单与组合包列表都不会改变。`prepareProfilePatches` 在启动器的空 profile 根之上组合,并在挂载根 Include 时以及每次 profile 重新组合时执行,因此被拒绝的插件永远不会导入其模块;`prepareProfileEntries` 对 preset 行做同样的事。被拒绝的普通行会变成游离的 `disabled: true` 行;原生 group 保持挂载,其被拒绝的子行不会加载;若某个原生 Include 会到达被拒绝的插件,则整体省略该 Include,因为它的文件不会被改写。被策略拒绝的行在 profile 中保留其配置的 `disabled` 值,每次拒绝都会报告包名、版本与风险。组合包本身不是行,因此 `loadProfileDirectory` 在启动和每次重新组合加载 profile 的组合包层时,检查每个组合包自己声明的 DSH 版本要求;没有豁免的不兼容组合包会像无法读取的组合包一样被跳过,并列入 `skippedBundles`。这些入口不覆盖其他嵌入方通过自己的 `ctx.plugin` 调用挂载的插件。会话中直接改文件的两类编辑只在下一次重新组合或启动时才被判定:正在运行的插件自己的 `package.json` DSH 版本要求,以及 Loader 自己读取的入口清单文件(如启动器的根配置或嵌套的 `cordis:include` 文件)。`--dump-config` 报告的是配置出的组合,因此被拒绝的插件行仍会出现在其中,而被拒绝的组合包不提供任何行;`--dump-config-schema` 会导入每个组合模块以读取其 schema,请只对已经信任其插件的 profile 运行。 -精确版本豁免保存在 profile 自己的 `compatibility.json` 中,而不是 `package.json`,因此写豁免不会触及依赖清单、组合包列表或 Cordis patch 文件。它把精确的 `package-name@version` 键映射到精确 DSH 运行时版本列表;插件升级和 DSH 升级都不继承授权。文件缺失表示没有豁免。文件损坏绝不会阻止 profile 启动:读取器接受的记录仍然生效,每条被拒绝的记录会与插件拒绝信息一起输出到 stderr,此后该文件被视为只读,因此授予或撤销会拒绝执行并要求用户手工修复,而不是覆盖用户的内容。[插件管理器](../plugin-manager/README.zh.md#version-compatibility-and-exemptions)负责每次变更所需的授权、撤销与风险确认。 +精确版本豁免保存在 profile 自己的 `compatibility.json` 中,而不是 `package.json`,因此写豁免不会触及依赖清单、组合包列表或 Cordis patch 文件。它把精确的 `package-name@version` 键映射到精确 DSH 运行时版本列表;插件升级和 DSH 升级都不继承授权。文件缺失表示没有豁免。文件损坏绝不会阻止 profile 启动:读取器接受的记录仍然生效,每条被拒绝的记录会与插件拒绝信息一起输出到 stderr,此后该文件被视为只读,因此授予或撤销会拒绝执行并要求用户手工修复,而不是覆盖用户的内容。[插件管理器](../plugin-manager/README.zh.md#version-compatibility-and-exemptions)负责每次变更所需的授权、撤销与风险确认。`validatePluginVersionExemption(packageVersion, runtimeVersion)` 校验规范的精确身份而不授予权限;身份非法时抛出错误。 + +组合包可以用 `dsh.bundle.platforms` 声明非空的 Node Host 平台名称列表,例如 `["darwin"]`。启动器在读取组合包 patch 前验证此声明。Host 不受支持时会跳过整个配置层,保留已保存的选择,并通过 `skippedBundles` 报告原因;其他配置层继续生效。省略此字段时允许所有平台。值必须是 Node 平台名,`macos` 等别名无效。浏览器所在机器的平台不决定 Host 是否受支持。 你的机器本地偏好同样位于 harness home 中: @@ -86,7 +88,7 @@ profile 导入插件前,DSH 会将其声明的 DSH 版本要求与 `getDshRunt 使用 `readPluginMeta(specifier, parentURL)` 或 `ctx.pluginPackages.metaOf(specifier, parentURL)` 读取已安装包的展示文本,无需导入或激活插件。查询使用完整包标识与调用方的解析基准,并遵循 Node exports。文件路径与文件 URL 不解析资源,直接返回无元信息。包根标识缺失的 locale 字段回退到可访问的 `package.json`;子路径标识从不读取 `package.json`。格式错误的元信息返回 `error` 诊断。结果保留翻译,由 Client 选择语言。即使 locale 文本完整,读取器也会加载图片 data URL:包根使用清单 `icon`,省略该字段时使用 `<包名>/icon`;子路径使用 `<标识>/icon`。图标出错时,保留有效文本并附上诊断。作者格式见[插件展示元信息](../../../docs/cookbook/adding-a-package.zh.md#plugin-display-metadata)。 -app-boot 应用的 profile 模板、安装方拥有的 profile 组合包元组和已退役组合包列表位于 [`@deepseek-ai/dsh-official-bundles`](../official-bundles/README.zh.md),安装方的默认、可选和按需组合包列表也在该包中。 +app-boot 应用的 profile 模板、安装方拥有的 profile 组合包元组和已退役组合包列表位于 [`@deepseek-ai/dsh-official-bundles`](../../util/official-bundles/README.zh.md),安装方的默认、可选和按需组合包列表也在该包中。 ### 启动与重载失败 @@ -143,7 +145,9 @@ Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如 - **单一 rejection 检查点。** `inactiveEntries` 把折入启动诊断的确切原因保持到下一个进程级 rejection 检查点可见,使 `installFailLoud` 能合并 Loader 的重复通知,而所有无关的未处理 rejection 仍然致命。 - **两阶段失败标签。** 除启动审计失败外,`boot()` 区分 `host preparation failed`(`prepare` 在任何配置树条目挂载前抛出)与 `plugin tree failed to load`,并追加最深层插件错误的堆栈。插件诊断保留嵌套原因和聚合错误中的各项失败;原因链出现循环时会停止遍历,但不会替换原始错误。 -启动错误还保留未激活条目的元数据和原始启动警告、错误记录,不保留 Loader tree。其 `entries` 和 `startup` 字段不可枚举:直接访问和完整诊断报告保留这些字段,常规错误检查输出则省略它们。只有等待条目时没有 `cause`;存在已记录错误时,`AggregateError` 保留其原始值。收集器在 Loader 挂载前通过 logger 收集导入错误,因为这些导入尚无 failed Fiber。启动结算后会移除临时 exporter。 +启动错误还保留未激活条目的元数据和原始启动警告、错误记录,不保留 Loader tree。其 `entries`、`startup` 和 `composition` 字段不可枚举:直接访问和完整诊断报告保留这些字段,常规错误检查输出则省略它们。只有等待条目时没有 `cause`;存在已记录错误时,`AggregateError` 保留其原始值。收集器在 Loader 挂载前通过 logger 收集导入错误,因为这些导入尚无 failed Fiber。启动结算后会移除临时 exporter。 + +包导出 `StartupCompositionDiagnostic`、`StartupPluginState` 和 `StartupServiceState`,供消费者按名引用。释放前,`composition` 捕获最多 256 个配置插件条目和 256 个缺失服务观测,并记录省略数量。条目包含模块、可取得的包版本、状态和 Loader 来源 URL,不含配置值。已注册提供者包含其状态及作用域是否与消费者一致。提供者列表为空表示归属未知:被禁用或失败的插件可能从未注册服务。Loader 来源不代表最后修改该条目的 overlay。元数据查询失败时版本标为未知;快照失败保留原始启动错误。 ### Helper 行为 diff --git a/packages/boot/app-boot/package.json b/packages/boot/app-boot/package.json index 1db32358de..07e9757746 100644 --- a/packages/boot/app-boot/package.json +++ b/packages/boot/app-boot/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-app-boot", "description": "Shared boot glue for the app bins: .env loading, fail-loud Loader guards, snapshot-aware config resolution, and the Loader boot sequence", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, diff --git a/packages/boot/app-boot/src/bundle-platform.ts b/packages/boot/app-boot/src/bundle-platform.ts new file mode 100644 index 0000000000..ba9ab28968 --- /dev/null +++ b/packages/boot/app-boot/src/bundle-platform.ts @@ -0,0 +1,32 @@ +/** Host operating-system admission for optional bundle layers. */ + +const NODE_PLATFORMS: readonly string[] = Object.freeze([ + 'aix', 'android', 'darwin', 'freebsd', 'haiku', 'linux', 'openbsd', 'sunos', 'win32', 'cygwin', 'netbsd', +] satisfies NodeJS.Platform[]) + +/** A valid bundle declaration excludes the operating system running DSH. */ +export class UnsupportedBundlePlatformError extends Error { + /** + * @param platforms Node platform names supported by the bundle. + * @param platform Operating system of the DSH Host. + */ + constructor(platforms: readonly string[], platform: string) { + super(`Bundle supports Host platforms ${platforms.join(', ')}; the DSH Host is running ${platform}`) + this.name = 'UnsupportedBundlePlatformError' + } +} + +/** + * Validate package metadata and reject an unsupported Host before selecting or composing a bundle. + * @param platforms The optional `dsh.bundle.platforms` field read from package.json. + * @param platform Operating system of the DSH Host, from Node's `process.platform`. + * @throws When the declaration is malformed or excludes the Host; omission allows every platform. + */ +export function assertBundlePlatform(platforms: unknown, platform: string): void { + if (platforms === undefined) return + if (!Array.isArray(platforms) || platforms.length === 0 + || !platforms.every((value): value is string => typeof value === 'string' && NODE_PLATFORMS.includes(value))) { + throw new Error('dsh.bundle.platforms must be a nonempty list of Node platform names') + } + if (!platforms.includes(platform)) throw new UnsupportedBundlePlatformError(platforms, platform) +} diff --git a/packages/boot/app-boot/src/index.ts b/packages/boot/app-boot/src/index.ts index fb68e4ba08..acab24ebe4 100644 --- a/packages/boot/app-boot/src/index.ts +++ b/packages/boot/app-boot/src/index.ts @@ -9,6 +9,8 @@ import { pathToFileURL } from 'node:url' import { readFileSync } from 'node:fs' import { inspect, parseEnv } from 'node:util' +import { captureStartupComposition, type StartupCompositionDiagnostic } from './startup-diagnostics.ts' +export type { StartupCompositionDiagnostic, StartupPluginState, StartupServiceState } from './startup-diagnostics.ts' import { basename, dirname, isAbsolute, resolve } from 'node:path' import * as yaml from 'js-yaml' import { Context, type Fiber, type FiberState } from '@deepseek-ai/cordis' @@ -22,7 +24,7 @@ export { sanitizeProfile } from './profile-sanitize.ts' export { getDshRuntimeVersion, evaluatePluginCompatibility, pluginCompatibilityWarning, type PluginCompatibility } from './plugin-compatibility.ts' export { PROFILE_COMPATIBILITY_FILENAME, readProfileCompatibility, readProfileVersionExemptions, - setProfileVersionExemption, type ProfileCompatibility, + setProfileVersionExemption, validatePluginVersionExemption, type ProfileCompatibility, } from './profile-compatibility.ts' import { prepareProfilePatches } from './compatibility-preflight.ts' import { ProfileRuntimeResolution, type RuntimeResolution } from './profile.ts' @@ -54,6 +56,7 @@ declare module '@deepseek-ai/cordis' { } } +export { assertBundlePlatform, UnsupportedBundlePlatformError } from './bundle-platform.ts' export { composeEntries, createRuntimeResolution, @@ -1002,6 +1005,8 @@ interface StartupLogRecord { /** Startup audit failure with non-enumerable metadata and original failures as its cause. */ export class StartupError extends Error { + /** Plugin states captured before disposal, excluding configuration values. */ + composition?: StartupCompositionDiagnostic /** Root configuration and startup logs, attached by boot after disposal. */ startup?: { configurationPath: string; messages: readonly StartupLogRecord[] } @@ -1015,6 +1020,7 @@ export class StartupError extends Error { Object.defineProperties(this, { entries: { enumerable: false }, startup: { enumerable: false }, + composition: { enumerable: false }, }) } } @@ -1237,6 +1243,11 @@ export async function boot( await auditStartupEntries(ctx, binName) return ctx } catch (cause) { + if (cause instanceof StartupError) { + try { cause.composition = captureStartupComposition(ctx) } catch (error) { + ctx.logger.warn('Startup composition diagnostic unavailable', error) + } + } // Root-fiber disposal contains cleanup failures per observer (Cordis // fiber.ts hardening) and a repeated call returns the settled single-shot // result, so this await cannot reject and replace `cause`. diff --git a/packages/boot/app-boot/src/profile-plugins.ts b/packages/boot/app-boot/src/profile-plugins.ts index 1cd55e9135..268d000f5a 100644 --- a/packages/boot/app-boot/src/profile-plugins.ts +++ b/packages/boot/app-boot/src/profile-plugins.ts @@ -1,6 +1,7 @@ /** Installed profile dependencies and their bundle activation after package-manager operations. */ import { join } from 'node:path' +import { assertBundlePlatform } from './bundle-platform.ts' import { readProfileManifest, resolveBundleDir, writeProfileManifest, type ProfileManifest } from './profile.ts' /** Profile directory and installation used by the shared bundle resolver. */ @@ -97,6 +98,8 @@ export function writeProfileBundles( * template entries retain their order and duplicates. New bundle dependencies activate automatically. * @param options - location, inventory captured before pnpm, and whether explicitly disabled bundles remain disabled. * @returns updated inventory and newly added ordinary dependencies for caller-owned warnings. + * @throws If a new selection has invalid platform metadata or excludes the Host. Installed dependencies + * remain; no bundle selection changes are written. */ export function reconcileProfilePlugins(options: ProfilePluginLocation & { readonly before: ProfilePluginInventory @@ -112,7 +115,10 @@ export function reconcileProfilePlugins(options: ProfilePluginLocation & { const previous = after.manifest.dsh?.profile?.bundles ?? [] const bundles = previous.filter(name => !(beforeNames.has(name) || afterNames.has(name)) || bundleNames.has(name)) for (const dependency of after.dependencies) { - if (dependency.bundle && !disabled.has(dependency.name) && !bundles.includes(dependency.name)) bundles.push(dependency.name) + if (dependency.bundle && !disabled.has(dependency.name) && !bundles.includes(dependency.name)) { + assertBundlePlatform(bundleManifest(options, dependency.name)?.dsh?.bundle?.platforms, process.platform) + bundles.push(dependency.name) + } } const changed = bundles.length !== previous.length || bundles.some((name, index) => name !== previous[index]) const manifest = changed ? writeProfileBundles(options.profileDir, after.manifest, bundles) : after.manifest diff --git a/packages/boot/app-boot/src/profile.ts b/packages/boot/app-boot/src/profile.ts index 1472e06c64..32719f2484 100644 --- a/packages/boot/app-boot/src/profile.ts +++ b/packages/boot/app-boot/src/profile.ts @@ -29,6 +29,7 @@ import { applyEntryPatches, type PatchOptions } from '@deepseek-ai/cordis-plugin import { resolveDshHome } from '@deepseek-ai/dsh-home-paths' import type { DshBundleManifest, DshPackageManifest } from '@deepseek-ai/dsh-package-manifest' import { INSTALLATION_OWNED_PROFILE_TUPLES, PROFILE_TEMPLATES, RETIRED_BUNDLES } from '@deepseek-ai/dsh-official-bundles' +import { assertBundlePlatform } from './bundle-platform.ts' import { evaluatePluginCompatibility, pluginCompatibilityWarning } from './plugin-compatibility.ts' import { readProfileVersionExemptions } from './profile-compatibility.ts' import { loadOverlayPatches } from './index.ts' @@ -665,7 +666,8 @@ export function resolveBundleDir( * the shared Harness home. This is used by application-owned profiles whose * package project and lifecycle belong to that application. * Retired bundles are removed from the stored bundle list first, rewriting the - * manifest when it listed one. Unreadable bundles, and bundles whose own dsh requirements the profile does not exempt, are skipped + * manifest when it listed one. Unreadable bundles, unsupported Host platforms, and bundles whose own dsh requirements + * the profile does not exempt are skipped * without changing the manifest and listed in `skippedBundles`; nothing is printed. * @param binName - the diagnostic prefix on thrown errors. * @param dir - absolute profile package directory. @@ -692,6 +694,7 @@ export function loadProfileDirectory( if (bundle === undefined) { throw new Error(`${binName}: profile bundle ${JSON.stringify(packageName)} declares no dsh.bundle in its package.json`) } + assertBundlePlatform(bundle.platforms, process.platform) // A bundle is not a plugin row, so row admission never reads its own dsh requirements. const issue = evaluatePluginCompatibility(bundleManifest, exemptions) if (issue !== undefined && !issue.exempted) throw new Error(pluginCompatibilityWarning(issue)) @@ -711,8 +714,8 @@ export function loadProfileDirectory( /** * Load a profile: resolve every `dsh.profile.bundles` entry to its patch - * layer and parse the profile's own patch file. Unreadable or incompatible bundles - * are skipped and listed in `skippedBundles`; profile manifest and user patch errors still throw. + * layer and parse the profile's own patch file. Unreadable bundles, unsupported Host platforms, + * and incompatible bundles are skipped and listed in `skippedBundles`; profile manifest and user patch errors still throw. * @param binName - the diagnostic prefix on thrown errors. * @param name - the profile name. * @param installAnchor - absolute path of the dsh app's package.json (first resolution anchor). diff --git a/packages/boot/app-boot/src/startup-diagnostics.ts b/packages/boot/app-boot/src/startup-diagnostics.ts new file mode 100644 index 0000000000..7982ccc111 --- /dev/null +++ b/packages/boot/app-boot/src/startup-diagnostics.ts @@ -0,0 +1,104 @@ +/** Configuration-free snapshots captured before a failed startup disposes its plugins. */ + +import { Context, type FiberState } from '@deepseek-ai/cordis' +import type { Entry } from '@deepseek-ai/cordis-plugin-loader' +import type {} from './profile-resolution/service.ts' + +/** One configured entry at the time startup failed. */ +export interface StartupPluginState { + readonly id: string + readonly module: string + readonly version: string + readonly state: 'disabled' | 'active' | 'pending' | 'failed' | 'disposed' | 'loading' | 'unloading' + /** Loader source URL; individual overlay ownership may be unavailable. */ + readonly source: string + readonly missing: readonly string[] +} + +/** Observed registrations for one service missing from a consumer. */ +export interface StartupServiceState { + readonly consumer: string + readonly service: string + /** Empty means no registration was observed, not that no configured plugin can provide it. */ + readonly providers: readonly { + readonly entry: string + readonly state: string + readonly visibility: 'same-scope' | 'other-scope' + }[] +} + +/** Bounded startup state without plugin config, service values, or logger arguments. */ +export interface StartupCompositionDiagnostic { + readonly plugins: readonly StartupPluginState[] + readonly services: readonly StartupServiceState[] + readonly omittedPlugins: number + readonly omittedServices: number +} + +function stateName(state: FiberState): StartupPluginState['state'] { + const names: Record = { + 0: 'pending', 1: 'loading', 2: 'active', 3: 'failed', 4: 'disposed', 5: 'unloading', + } + return names[state] +} + +function pluginState(ctx: Context, entry: Entry): StartupPluginState { + let state: StartupPluginState['state'] + try { + state = entry.disabled ? 'disabled' : entry.fiber === undefined ? 'failed' : stateName(entry.fiber.state) + } catch (_error) { + // The activation diagnostic owns the disabled-expression error. + state = 'failed' + } + let version = 'unknown' + const source = entry.parent.tree.ctx.baseUrl + try { + if (source !== undefined) version = ctx.get('pluginPackages')?.packageOf(entry.options.name, source)?.version ?? 'unknown' + } catch (_error) { + // Missing or damaged metadata must not replace the startup failure. + } + const fiber = entry.fiber + return { + id: entry.id, module: entry.options.name, version, state, source: source ?? 'unknown', + missing: state === 'pending' && fiber !== undefined + ? Object.keys(fiber.inject).filter(name => fiber.ctx.get(name) === undefined) : [], + } +} + +/** + * Capture Loader state and registered service ownership before teardown. + * Providers that never registered cannot be inferred from their package names. + * @param ctx - Live application context with its Loader still mounted. + * @returns At most 256 plugin rows and 256 missing-service observations, with omission counts. + */ +export function captureStartupComposition(ctx: Context): StartupCompositionDiagnostic { + const entries = [...ctx.loader.entries()] + const rows = entries.map(entry => ({ entry, state: pluginState(ctx, entry) })) + // Inactive rows precede healthy rows so bounded reports retain the failure context. + rows.sort((a, b) => Number(a.state.state === 'active') - Number(b.state.state === 'active')) + const services: StartupServiceState[] = [] + let omittedServices = 0 + const store = ctx.reflect.store + for (const { entry, state } of rows) { + const fiber = entry.fiber + if (fiber === undefined) continue + for (const service of state.missing) { + if (services.length === 256) { omittedServices++; continue } + const scope = fiber.ctx[Context.isolate][service] + const providers: StartupServiceState['providers'][number][] = [] + for (const key of Object.getOwnPropertySymbols(store)) { + const impl = store[key] + if (impl?.name !== service) continue + providers.push({ + entry: impl.fiber.entry?.id ?? 'unknown', state: stateName(impl.fiber.state), + visibility: key === scope ? 'same-scope' : 'other-scope', + }) + } + services.push({ consumer: state.id, service, providers }) + } + } + return { + plugins: rows.slice(0, 256).map(row => row.state), services, + omittedPlugins: Math.max(0, rows.length - 256), omittedServices, + } +} diff --git a/packages/boot/app-boot/tests/bundle-platform.spec.ts b/packages/boot/app-boot/tests/bundle-platform.spec.ts new file mode 100644 index 0000000000..eaaa76c690 --- /dev/null +++ b/packages/boot/app-boot/tests/bundle-platform.spec.ts @@ -0,0 +1,18 @@ +/** Bundle declarations admit the Host operating system independently of browser clients. */ +import { expect, it } from 'vitest' +import { assertBundlePlatform, UnsupportedBundlePlatformError } from '../src/bundle-platform.ts' + +it.each(['darwin', 'win32', 'linux'])('allows undeclared platforms and an explicit %s Host', (platform) => { + expect(() => { assertBundlePlatform(undefined, platform) }).not.toThrow() + expect(() => { assertBundlePlatform([platform], platform) }).not.toThrow() + expect(() => { assertBundlePlatform(['darwin', 'win32', 'linux'], platform) }).not.toThrow() +}) + +it.each(['win32', 'linux'])('rejects macOS-only bundles on %s Hosts', (platform) => { + expect(() => { assertBundlePlatform(['darwin'], platform) }).toThrow(UnsupportedBundlePlatformError) + expect(() => { assertBundlePlatform(['darwin'], platform) }).toThrow(`the DSH Host is running ${platform}`) +}) + +it.each([null, true, 'darwin', [], [1], [''], ['Darwin'], [' darwin'], ['macos'], ['darwin', 'linxu'], ['darwin', false]].map(platforms => ({ platforms })))('rejects malformed platform metadata $platforms', ({ platforms }) => { + expect(() => { assertBundlePlatform(platforms, 'darwin') }).toThrow('dsh.bundle.platforms must be a nonempty list') +}) diff --git a/packages/boot/app-boot/tests/profile-plugins.spec.ts b/packages/boot/app-boot/tests/profile-plugins.spec.ts index 04950b4812..223754fc71 100644 --- a/packages/boot/app-boot/tests/profile-plugins.spec.ts +++ b/packages/boot/app-boot/tests/profile-plugins.spec.ts @@ -31,6 +31,18 @@ function installed(location: ProfilePluginLocation, name: string, bundle = true) }) } +it('refuses automatic activation on an unsupported Host without changing the bundle selection', () => { + const location = fixture() + const before = readProfilePlugins(location) + writeManifest(location.profileDir, { dependencies: { restricted: '1.0.0' }, dsh: { profile: { bundles: [] } } }) + writeManifest(join(location.profileDir, 'node_modules/restricted'), { name: 'restricted', dsh: { bundle: { + patch: 'unused.yml', platforms: [process.platform === 'darwin' ? 'win32' : 'darwin'], + } } }) + const saved = readFileSync(join(location.profileDir, 'package.json'), 'utf8') + expect(() => reconcileProfilePlugins({ ...location, before, preserveDisabled: true })).toThrow('Host is running') + expect(readFileSync(join(location.profileDir, 'package.json'), 'utf8')).toBe(saved) +}) + describe('profile plugin inventory', () => { it('uses dependency alias keys, installed versions, and the loader installation precedence', () => { const location = fixture() diff --git a/packages/boot/app-boot/tests/profile.spec.ts b/packages/boot/app-boot/tests/profile.spec.ts index 390e888050..0a67d476e1 100644 --- a/packages/boot/app-boot/tests/profile.spec.ts +++ b/packages/boot/app-boot/tests/profile.spec.ts @@ -47,7 +47,7 @@ const tmp = (): string => { /** Stage a fake installed app: package.json with deps and a node_modules holding bundles. */ function stageInstallation( - bundles: Record }>, + bundles: Record; platforms?: string[] }>, appName = 'dsh-app', ): string { const root = tmp() @@ -64,7 +64,7 @@ function stageInstallation( type: 'module', main: './index.js', dependencies: spec.deps ?? {}, - ...spec.patch === undefined ? {} : { dsh: { bundle: { patch: './cordis.patch.yml' } } }, + ...spec.patch === undefined ? {} : { dsh: { bundle: { patch: './cordis.patch.yml', ...spec.platforms === undefined ? {} : { platforms: spec.platforms } } } }, })) writeFileSync(join(dir, 'index.js'), `export const packageName = ${JSON.stringify(name)}\n`) if (spec.patch !== undefined) writeFileSync(join(dir, 'cordis.patch.yml'), spec.patch) @@ -76,6 +76,24 @@ function stageInstallation( return join(appDir, 'package.json') } +it('skips an unsupported saved bundle before composing any runtime overrides and retains the selection', () => { + const unsupported = process.platform === 'darwin' ? 'win32' : 'darwin' + const anchor = stageInstallation({ + base: { patch: '- insert:\n - id: ptc-runtime\n name: runtime\n config: { executionMode: isolated }\n' }, + restricted: { platforms: [unsupported], patch: '- id: ptc-runtime\n config: { executionMode: persistent-in-memory }\n' }, + }) + const dir = join(tmp(), 'profile') + initProfile(dir, ['base', 'restricted']) + const before = readFileSync(join(dir, 'package.json'), 'utf8') + const profile = loadProfileDirectory('test', dir, anchor) + expect(profile.layers.map(layer => layer.packageName)).toEqual(['base']) + expect(profile.skippedBundles).toHaveLength(1) + expect(profile.skippedBundles[0]?.packageName).toBe('restricted') + expect(profile.skippedBundles[0]?.reason).toContain(`Host is running ${process.platform}`) + expect(composeEntries(profile.layers.map(layer => layer.patches))).toMatchObject([{ id: 'ptc-runtime', config: { executionMode: 'isolated' } }]) + expect(readFileSync(join(dir, 'package.json'), 'utf8')).toBe(before) +}) + /** Represent one resolved external bundle as a loaded profile layer. */ function stageProfile(home: string, name: string, bundleAnchor: string): Profile { const dir = resolveProfileDir(name, home) diff --git a/packages/boot/app-boot/tests/startup-diagnostics.spec.ts b/packages/boot/app-boot/tests/startup-diagnostics.spec.ts new file mode 100644 index 0000000000..9d55d4808b --- /dev/null +++ b/packages/boot/app-boot/tests/startup-diagnostics.spec.ts @@ -0,0 +1,133 @@ +import { mkdtemp, writeFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, expectTypeOf, it } from 'vitest' +import { boot, StartupError, type StartupCompositionDiagnostic, type StartupPluginState, type StartupServiceState } from '../src/index.ts' +import { captureStartupComposition } from '../src/startup-diagnostics.ts' + +const roots: string[] = [] +afterEach(async () => { + await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) +}) + +async function configuration(): Promise { + const root = await mkdtemp(join(tmpdir(), 'dsh-startup-diagnostic-')) + roots.push(root) + await writeFile(join(root, 'consumer.mjs'), 'export const inject = ["agents"]; export function apply() {}\n') + await writeFile(join(root, 'provider.mjs'), 'export function apply(ctx) { ctx.provide("agents", {}) }\n') + await writeFile(join(root, 'cordis.yml'), [ + '- id: agent', ' name: ./provider.mjs', ' disabled: true', + ' config:', ' privateValue: do-not-export-this', + '- id: agent-loop', ' name: ./consumer.mjs', '', + ].join('\n')) + return join(root, 'cordis.yml') +} + +it('retains disabled and waiting entries after the real Loader has been disposed', async () => { + const error: unknown = await boot('diagnostic-test', await configuration()).catch((failure: unknown) => failure) + expect(error).toBeInstanceOf(StartupError) + if (!(error instanceof StartupError)) throw error + expect(error.composition?.plugins).toEqual(expect.arrayContaining([ + expect.objectContaining({ module: './provider.mjs', state: 'disabled', version: 'unknown' }), + expect.objectContaining({ module: './consumer.mjs', state: 'pending', missing: ['agents'] }), + ])) + expect(error.composition?.services).toEqual([ + expect.objectContaining({ service: 'agents', providers: [] }), + ]) + expect(JSON.stringify(error.composition)).not.toContain('do-not-export-this') +}) + +it('preserves the startup failure when the Loader is already unavailable to diagnostic capture', async () => { + const failure = new StartupError('startup was interrupted', []) + const result: unknown = await boot('diagnostic-test', await configuration(), undefined, async (ctx) => { + await ctx.fiber.dispose() + throw failure + }).catch((error: unknown) => error) + expect(result).toBe(failure) + expect(failure.composition).toBeUndefined() + expect(failure.startup?.messages.some(message => message.args[0] === 'Startup composition diagnostic unavailable')).toBe(true) +}) + +it('identifies a registered provider that is isolated from the waiting consumer', async () => { + const error: unknown = await boot('diagnostic-test', await configuration(), undefined, async (ctx) => { + await ctx.isolate('agents').plugin({ + name: 'isolated-agent-provider', + apply(provider) { provider.reflect.provide('agents', {}) }, + }) + }).catch((failure: unknown) => failure) + expect(error).toBeInstanceOf(StartupError) + if (!(error instanceof StartupError)) throw error + expect(error.composition?.services).toEqual([ + expect.objectContaining({ service: 'agents', providers: [{ entry: 'unknown', state: 'active', visibility: 'other-scope' }] }), + ]) +}) + +it('reports omitted plugin and missing-service counts instead of silently dropping rows', async () => { + const config = await configuration() + const root = roots.at(-1)! + const services = Array.from({ length: 257 }, (_, index) => `missing${index}`) + await writeFile(join(root, 'consumer.mjs'), `export const inject = ${JSON.stringify(services)}; export function apply() {}\n`) + await writeFile(config, [ + '- id: agent-loop\n name: ./consumer.mjs', + ...Array.from({ length: 257 }, (_, index) => `- id: disabled-${index}\n name: ./provider.mjs\n disabled: true`), '', + ].join('\n')) + const error: unknown = await boot('diagnostic-test', config).catch((failure: unknown) => failure) + if (!(error instanceof StartupError)) throw error + expect(error.composition?.plugins).toHaveLength(256) + expect(error.composition?.omittedPlugins).toBeGreaterThanOrEqual(2) + expect(error.composition?.services).toHaveLength(256) + expect(error.composition?.omittedServices).toBe(1) +}) + +it('reports a registered same-scope provider whose value is unavailable', async () => { + const config = await configuration() + await writeFile(join(roots.at(-1)!, 'provider.mjs'), 'export function apply(ctx) { ctx.provide("agents", undefined) }\n') + await writeFile(join(roots.at(-1)!, 'consumer.mjs'), 'export const inject = ["agents", "unprovided"]; export function apply() {}\n') + await writeFile(config, '- id: agent\n name: ./provider.mjs\n- id: agent-loop\n name: ./consumer.mjs\n') + const error: unknown = await boot('diagnostic-test', config) + .catch((failure: unknown) => failure) + if (!(error instanceof StartupError)) throw error + expect(error.composition?.services[0]?.providers).toMatchObject([ + { state: 'active', visibility: 'same-scope' }, + ]) + expect(error.composition?.services[0]?.providers[0]?.entry).toContain('agent') +}) + +it('retains the Loader disablement after disposal and reports missing source metadata', async () => { + const config = await configuration() + await writeFile(config, '- id: agent\n name: ./provider.mjs\n') + const ctx = await boot('diagnostic-test', config) + try { + const entry = [...ctx.loader.entries()].find(row => row.options.id === 'agent')! + await entry.fiber!.dispose() + Object.defineProperty(entry.parent.tree.ctx, 'baseUrl', { value: undefined, configurable: true }) + const snapshot = captureStartupComposition(ctx) + expect(snapshot.plugins).toContainEqual(expect.objectContaining({ module: './provider.mjs', state: 'disabled', source: 'unknown' })) + } finally { + await ctx.fiber.dispose() + } +}) + +it.each(['same-scope', 'other-scope'] as const)('attributes a nested %s provider to its Loader entry', async (visibility) => { + const config = await configuration() + const parent = visibility === 'same-scope' ? 'ctx' : 'ctx.isolate("agents")' + await writeFile(join(roots.at(-1)!, 'consumer.mjs'), 'export const inject = ["agents", "unprovided"]; export function apply() {}\n') + await writeFile(join(roots.at(-1)!, 'provider.mjs'), `export async function apply(ctx) { await ${parent}.plugin({ name: "nested-provider", apply(child) { child.provide("agents", undefined) } }) }\n`) + await writeFile(config, '- id: agent\n name: ./provider.mjs\n- id: agent-loop\n name: ./consumer.mjs\n') + const failure: unknown = await boot('diagnostic-test', config).then(async (ctx) => { + await ctx.fiber.dispose() + throw new Error('Expected the missing service to prevent startup') + }, (error: unknown) => error) + if (!(failure instanceof StartupError)) throw failure + const owner = failure.composition?.plugins.find(plugin => plugin.module === './provider.mjs') + expect(owner).toBeDefined() + expect(failure.composition?.services[0]?.providers).toEqual([ + { entry: owner!.id, state: 'active', visibility }, + ]) +}) + +it('exports the named types used by startup composition diagnostics', () => { + expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf() +}) diff --git a/packages/boot/app-boot/tsconfig.json b/packages/boot/app-boot/tsconfig.json index c1dcee4ba2..b5b42ed67a 100644 --- a/packages/boot/app-boot/tsconfig.json +++ b/packages/boot/app-boot/tsconfig.json @@ -27,7 +27,7 @@ "path": "../../util/home-paths" }, { - "path": "../official-bundles" + "path": "../../util/official-bundles" }, { "path": "../../util/package-manifest" diff --git a/packages/boot/cmdline/package.json b/packages/boot/cmdline/package.json index 95ca31e410..804bb2bc11 100644 --- a/packages/boot/cmdline/package.json +++ b/packages/boot/cmdline/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-cmdline", "description": "Immutable command-line handoff from a dsh launcher to any app plugin that injects cmdlineArgs", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, diff --git a/packages/boot/config-editor/locale/de.json b/packages/boot/config-editor/locale/de.json new file mode 100644 index 0000000000..d72e2c7250 --- /dev/null +++ b/packages/boot/config-editor/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Plug-in-Konfigurationseditor", + "description": "Speichern Sie die Plug-in-Konfiguration und übernehmen Sie Änderungen auf die aktuell ausgeführte Konfiguration." + } +} diff --git a/packages/boot/config-editor/locale/es.json b/packages/boot/config-editor/locale/es.json new file mode 100644 index 0000000000..a2448c1f5d --- /dev/null +++ b/packages/boot/config-editor/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Editor de configuración de complementos", + "description": "Guarde la configuración del complemento y aplique los cambios a la configuración en ejecución actual." + } +} diff --git a/packages/boot/config-editor/locale/fr.json b/packages/boot/config-editor/locale/fr.json new file mode 100644 index 0000000000..f2b3eb621d --- /dev/null +++ b/packages/boot/config-editor/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Éditeur de configuration de plug-in", + "description": "Enregistrez la configuration du plug-in et appliquez les modifications à la configuration en cours d'exécution." + } +} diff --git a/packages/boot/config-editor/locale/pt.json b/packages/boot/config-editor/locale/pt.json new file mode 100644 index 0000000000..8f2a80a8aa --- /dev/null +++ b/packages/boot/config-editor/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Editor de configuração de plug-ins", + "description": "Salve a configuração do plug-in e aplique as alterações à configuração em execução atual." + } +} diff --git a/packages/boot/config-editor/locale/ru.json b/packages/boot/config-editor/locale/ru.json new file mode 100644 index 0000000000..b14ff9c92c --- /dev/null +++ b/packages/boot/config-editor/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Редактор конфигурации плагина", + "description": "Сохраните конфигурацию плагина и примените изменения к текущей работающей конфигурации." + } +} diff --git a/packages/boot/config-editor/package.json b/packages/boot/config-editor/package.json index 4b41336ae3..d8bfc04659 100644 --- a/packages/boot/config-editor/package.json +++ b/packages/boot/config-editor/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-config-editor", "description": "Persist plugin configuration through profile patches and Loader reconciliation", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, diff --git a/packages/boot/hmr/locale/de.json b/packages/boot/hmr/locale/de.json new file mode 100644 index 0000000000..45ffdf967a --- /dev/null +++ b/packages/boot/hmr/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Hmr", + "description": "Laden Sie den Plugin-Code und die Konfiguration neu, während die App ausgeführt wird." + } +} diff --git a/packages/boot/hmr/locale/es.json b/packages/boot/hmr/locale/es.json new file mode 100644 index 0000000000..06af2d1b51 --- /dev/null +++ b/packages/boot/hmr/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "hmr", + "description": "Vuelva a cargar el código y la configuración del complemento mientras la aplicación se está ejecutando." + } +} diff --git a/packages/boot/hmr/locale/fr.json b/packages/boot/hmr/locale/fr.json new file mode 100644 index 0000000000..096306a34e --- /dev/null +++ b/packages/boot/hmr/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "hum", + "description": "Rechargez le code et la configuration du plugin pendant que l'application est en cours d'exécution." + } +} diff --git a/packages/boot/hmr/locale/pt.json b/packages/boot/hmr/locale/pt.json new file mode 100644 index 0000000000..b9ee71fba2 --- /dev/null +++ b/packages/boot/hmr/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "hum", + "description": "Recarregue o código e a configuração do plugin enquanto o aplicativo estiver em execução." + } +} diff --git a/packages/boot/hmr/locale/ru.json b/packages/boot/hmr/locale/ru.json new file mode 100644 index 0000000000..0ed5dc0fdc --- /dev/null +++ b/packages/boot/hmr/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "хмр", + "description": "Перезагрузите код и конфигурацию плагина во время работы приложения." + } +} diff --git a/packages/boot/hmr/package.json b/packages/boot/hmr/package.json index a4efcfe4c6..93fa7fb127 100644 --- a/packages/boot/hmr/package.json +++ b/packages/boot/hmr/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-hmr", "description": "Coordinated module and profile configuration hot reload", - "version": "0.2.1-rc.2", + "version": "0.2.1-rc.3", "publishConfig": { "access": "public" }, diff --git a/packages/boot/official-bundles/README.md b/packages/boot/official-bundles/README.md deleted file mode 100644 index 7fb4babfa0..0000000000 --- a/packages/boot/official-bundles/README.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -description: "Installation-owned lists of official dsh bundles: shipped profile templates, the default bundle list, and the optional, on-demand, and retired bundles." -kind: "package-library" ---- - -# @deepseek-ai/dsh-official-bundles - -English | [中文](README.zh.md) - -## Summary - -`@deepseek-ai/dsh-official-bundles` holds the bundle package names the dsh installation decides on: which bundles each shipped profile starts with, which bundles it ships switched off, which official bundles install on request, and which bundles earlier releases shipped and profiles drop. [`dsh-app-boot`](../app-boot/README.md) applies these lists when it loads a profile; the plugin manager, the CLI, Desktop, the WebWorker image packer, and repository checks read them directly. The package holds data only, so adding or removing a bundle leaves app-boot untouched. Use it as a direct library dependency, not through `cordis.yml`. - -## Table of Contents - -- [Use this package](#use-this-package) -- [Understand the implementation](#understand-the-implementation) -- [Further Exploration](#further-exploration) -- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) -- [Dev Note](#dev-note) - ------ - - -## Use this package - -Edit this package when the installation's bundle selection changes; read it wherever code must agree with the launcher about that selection. - -### Profile templates - -`PROFILE_TEMPLATES` maps each shipped profile name (`web`, `headless`, `acp`, `sdk`, `sdk-minimal`) to its ordered bundle layer list. App-boot initializes a missing shipped profile from its template, and `dsh --profile --from-default-profile