Compare commits

..
Author SHA1 Message Date
cflmy 2aab24cccf docs: record the catalog empty-home negative 2026-11-29 12:52:51 +08:00
cflmy 86c10416dd docs: record the five-group ecosystem catalog browser evidence 2026-11-29 12:39:44 +08:00
cflmy 56ff79cf01 docs: record reader candidate CI evidence 2026-11-29 12:33:40 +08:00
cflmy 01afaf2ce4 feat: embed the View read-only reader
Add a single bridge that runs the public View export --embed command, checks
the manifest, producer and package digests, caches the package by source,
View, CLI, theme and anchor identity, and serves it to a sandboxed same-origin
frame. Expose workspace and knowledge reading in the workbench and keep
execution, approval and evidence in the existing MQDH/CLI flow.
2026-11-29 12:21:48 +08:00
cflmy bc4bb48e61 fix: expose capability imports in the market projection
The project view reads recorded imports from the capability projection; keep
that field in the public view and cover it in the import test. Record the real
browser import, lock and uninstall-refusal flow.
2026-11-29 10:48:59 +08:00
cflmy b0f39dad94 docs: record final market CI evidence 2026-11-29 10:32:51 +08:00
cflmy 629cff0301 feat: add the dynamic extension market and capability control
Replace the fixed component candidate enumeration with a user-configurable
market projection over Gitea topics and local directories. Install verified
payloads into a user-level capability store, require explicit activation and
scope enablement before a model can see them, and gate project import through
the published CLI add/lock commands. Update the ecosystem catalog, bootstrap
default tool installation, and status evidence.
2026-11-29 10:20:41 +08:00
cflmy 8b7b56e983 feat: make trusted ecosystem candidates installable
Tool candidates from the authoritative Release can be installed directly after\nexplicit confirmation; Runtime candidates switch through the existing install\ntransaction. Std remains Bundle-only, Ext remains project-scoped, and no\narbitrary URL/marketplace is introduced. Documents the discovery/authorization\nsplit in ECOSYSTEM.md and updates CAT-01.
2026-11-29 08:50:57 +08:00
cflmy 0b47cf05fd test: skip real bootstrap when the platform is outside the release contract
CI bookworm reports glibc 2.36; the published CLI declares 2.39. Bootstrap\nmust refuse that platform, so the gated test skips with the real reason and\nremains covered on a supported host. Records the split in STATUS.
2026-11-28 23:55:00 +08:00
cflmy 682032c769 feat: capture CLI and routed workbench failures as diagnostics
CLI check/execution failures from marqdo_program and unexpected Web API failures are persisted as local redacted reports, routed to the owning area (cli/knowledge/ecosystem/bootstrap/update/web). Submission remains explicit.
2026-11-28 23:41:03 +08:00
cflmy 3033d37b93 feat: add the read-only ecosystem catalog
Project Runtime, Tool, Std, Ext and Knowledge in a fixed order from real\nservices. Ext exposes marqdo.yaml/marqdo.lock identity without a second parser;\nsemantic validation and trusted candidate discovery are explicit user actions.\nNo page open/filter action downloads, installs or executes.\n\nAdds /mqdh/api/ecosystem/candidates and /mqdh/api/ecosystem/project-check,\npublic std:<relative> import projection, unit tests and CAT/READER status.
2026-11-28 23:39:42 +08:00
cflmy 980e07dfae build: pin the DSH upstream identity in the package manifest
The tag-only package lane cannot rely on an upstream git remote. Record the\ntested DSH baseline in packages/marqdo/harness/package.json and let the release\nmanifest/evidence fall back to it, so a clean clone still produces a complete\nmanifest. UPSTREAM.md documents the single record and update rule.
2026-11-28 23:14:48 +08:00
cflmy 475e774536 ci: scope the shared-egress gate to Node-side sources
The browser API client in src/web/assets.ts must use fetch; the gate now only rejects Node-side product sources that bypass src/network. CI passes end-to-end with real Release install and Bootstrap.
2026-11-28 23:12:51 +08:00
cflmy 307a44d6f1 docs: record egress, bootstrap, diagnostics and distribution evidence 2026-11-28 23:10:55 +08:00
cflmy 5f56c23455 feat: add unified egress, bootstrap, diagnostics and app distribution
Implements the four follow-up design issues for MQDH:\n\n- network: one policy/proxy/mirror/offline/audit client for product egress\n- bootstrap: first-run state machine, default Tools, real smoke, doctor/repair\n- diagnostics: local redacted reports and explicit Gitea issue submission\n- distribution: release manifest, user install tree, update/rollback, installer\n\nThe product CLI exposes bootstrap/doctor/repair/report/update/network and the\n/mqdh workbench renders the same services. Marqdo runtime artifacts remain\ndownloaded from trusted releases; unsupported platforms and unrun gates stay\nUNVERIFIED in docs/mqdh/STATUS.md.
2026-11-28 23:07:07 +08:00
cflmy 9b6acf0569 refactor: rename the product abbreviation to MQDH
Rename the downstream identity consistently: MQDH_HOME and MQDH_* env
vars, @marqdo/mqdh-harness, @marqdo/mqdh-bundle, the mqdh profile and
launcher, /mqdh routes, marqdo.mqdh.* schemas, docs/mqdh, CI variables and
all user-facing prose. Product name remains Marqdo Harness; command is
mqdh. No behavior change; 29 tests and the host typecheck pass.

Part of marqdo#25.
2026-11-28 16:34:44 +08:00
cflmy ee482a23c2 ci: skip upstream git-hook installation in submodule CI
The upstream install script refuses extensions.worktreeConfig when a
submodule keeps core.worktree in its common config. Its documented CI skip
path is CI=true; hooks are not needed in the pipeline. This keeps the
independent app CI and the root Node lane installable from a submodule.

Part of marqdo#25 (S09).
2026-11-28 11:03:08 +08:00
cflmy 44282ead84 docs: record the independent-clone build evidence
A depth-1 clone of origin/main installs the frozen lockfile and builds all
10 gates, so R04 is verified rather than inferred from the development
checkout. The parent pipeline's candidate-manifest bug is recorded as
fixed with its rerun still pending.

Part of marqdo#25.
2026-11-28 10:54:53 +08:00
cflmy 210ac86b0b feat: save a reviewed completed run as static knowledge
Add the reviewed outcome flow: a completed, fresh run can be confirmed
into a static knowledge document that records applicability, executable
asset identity, run/evidence id and boundaries. The generated document has
no @exec region and grants no execution permission; it enters the same
private knowledge index and can be searched later.

Expose it as POST /mdh/api/runs/<id>/candidate with explicit confirmation
and a workbench button, and cover the policy in tests. Record the View
result-binding gap as marqdo-view#15 instead of rendering results here.

Part of marqdo#25 (MDH-07, K07).
2026-11-28 10:52:32 +08:00
cflmy d28c5e4051 types: make the downstream package strict-clean in the host aggregate
Register the package sources in the host typecheck program and fix the
strict findings: explicit Error.name overrides, exact optional properties,
index/array narrowing and the webserver route auth field. No behavior
change; the same 28 tests pass and the host aggregate reports 0 errors.

Part of marqdo#25.
2026-11-28 10:46:25 +08:00
cflmy 25fc24eea4 feat: add Marqdo Harness product services and workbench
Implement the downstream product in `packages/marqdo`:

- `@marqdo/mdh-harness`: application home layout, atomic writes, locks,
  bounded fixed-argv processes, safe tar extraction, Observation 1 and
  ValueWire validation;
- trusted Gitea release discovery, SHA-256/platform/Bundle verification,
  transactional environment install, rollback and cleanup, CLI Tool changes;
- private knowledge collections with strict import policy, the official
  `marqdo-knowledge` compile/query adapter and a disclosed locator fallback;
- Analysis 3 parsing, approved run/call execution, evidence and staleness;
- the six model operations (find/read/check/program/ecosystem/knowledge_search);
- the `/mdh` workbench over the existing web server with a same-origin fence;
- `mdh` launcher, CI/package/upstream scripts and a Woodpecker pipeline.

Tests: 28 node:test cases (27 PASS, one network-gated install test also PASS
with MDH_TEST_INSTALL=1). Product install/workbench evidence is recorded in
docs/mdh/evidence.

Part of marqdo#25 (MDH-03..MDH-08).
2026-11-28 10:41:39 +08:00
cflmy 2d4eef4fe0 fork: establish the Marqdo Harness downstream baseline
- keep the full DSH history, MIT license and third-party notices;
- remove upstream publish/upload/desktop packaging workflows so downstream
  CI cannot trigger official credentials or channels;
- exclude the downstream `packages/marqdo/*` packages from the upstream
  bundling graph (they run as TypeScript through Node's type stripping);
- declare app-boot's production peer for the deployed launcher;
- document the product architecture, gates, upstream policy, modification
  log and the M0/M1-M6 evidence.

Upstream: deepseek-harness 4b399c39a6.
Part of marqdo#25 (MDH-00/MDH-02).
2026-11-28 10:41:04 +08:00
6154 changed files with 53502 additions and 253071 deletions

No files matched your search

-6
View File
@@ -2389,9 +2389,6 @@
"process/2026-09-23-section-keyed-translation-pairing-records.i18n.yaml": "sha256:ec07cef0e6b9628c81ae62ff772821b7dc659c07bd01a451a561b37a96f423e4",
"process/2026-09-23-section-keyed-translation-pairing-records.md": "sha256:990d5c3c0d3fbcf43327997ece13879119a1e36a9841f7797a8a2a675c932f57",
"process/2026-09-23-section-keyed-translation-pairing-records.zh.md": "sha256:befcb9915ff0020d1153d596ed85b0a09a7cac6541ec7af0ac93ab96dc62263f",
"process/2026-10-20-weighted-approval-status-gate-with-check-run-label.i18n.yaml": "sha256:138c15baa1593ffdce5222f93ceab46ad97fa9bcc2c96586b1832cd4d83cf975",
"process/2026-10-20-weighted-approval-status-gate-with-check-run-label.md": "sha256:88d3493b2236f92c5195f8e81fca2d58e2c102bcdd0a2fd8111de23197bce226",
"process/2026-10-20-weighted-approval-status-gate-with-check-run-label.zh.md": "sha256:8ea2cae25eee736d59f21ee5160184893f91b32d690d773c4d55e0df24cbe828",
"simplification/2026-06-19-drop-mutable-session-summary.i18n.yaml": "sha256:43fe5daadc1491f94a3e34595182cad1591f76b64e1f13b48811b80fd7e53b94",
"simplification/2026-06-19-drop-mutable-session-summary.md": "sha256:01647a5a14aa4e195328d4d39c6d80eb0723739e5a543115314716b280a93560",
"simplification/2026-06-19-drop-mutable-session-summary.zh.md": "sha256:22389e0c29158b1f7a5a43ed6073f8795bb87cf51c04cf83be055359cd65c9f5",
@@ -2773,9 +2770,6 @@
"testing/2026-09-12-connection-and-compaction-fixture-preconditions.i18n.yaml": "sha256:1740bca0aafb2f91dad66b870917a78ec8d50243b20f21f872cc005229231b65",
"testing/2026-09-12-connection-and-compaction-fixture-preconditions.md": "sha256:959da865d7740bfde03dcc4a5a1bd67e80c7595807e035d6499af738a6efcde4",
"testing/2026-09-12-connection-and-compaction-fixture-preconditions.zh.md": "sha256:c00055c634f579ee80e910cc89de742ce1db90e43b407356f9fdc12a7ccab66d",
"testing/2026-09-14-desktop-installed-update-materials.i18n.yaml": "sha256:f45fe477693dc4d9dc2a79537cef0c2b0cb930fecc5154e62b96645cd1a39ce8",
"testing/2026-09-14-desktop-installed-update-materials.md": "sha256:b35f7ffaa8b1e6322d0ac95253430aa5004e4ea2fc94691b604c1660c9dbbb18",
"testing/2026-09-14-desktop-installed-update-materials.zh.md": "sha256:f1ea8825dc63336ef960815681f40a1e02dccf53611893f5c425682e9ae64f48",
"testing/2026-09-26-web-conversation-clock-fixture-day.i18n.yaml": "sha256:1e57f76a30c07fd343ce22be7ea9454e5beb8cc3979b7709d2f55423b1c7d2c0",
"testing/2026-09-26-web-conversation-clock-fixture-day.md": "sha256:a918c35b1b4e69b766b02883218bd1280d161392c4ca2f359d45dbe1cbfcfce8",
"testing/2026-09-26-web-conversation-clock-fixture-day.zh.md": "sha256:910eff4bae8075dd576726ccb3bc7cfd1f8bb5a970c543e1b9c986494a09749f",
@@ -1,6 +0,0 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/archived/process/2026-10-20-weighted-approval-status-gate-with-check-run-label.md
2026-10-20-weighted-approval-status-gate-with-check-run-label.md: 35f228dbb99a0dbaf4c6af40cf0e61edd05eb3ed
2026-10-20-weighted-approval-status-gate-with-check-run-label.zh.md: 22b194cd41893499ad5b3fc33a8cbc6b4d8b9975
@@ -1,6 +0,0 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/archived/testing/2026-09-14-desktop-installed-update-materials.md
2026-09-14-desktop-installed-update-materials.md: 7270767033f7701b483fbf4c544b0b88ee08199c
2026-09-14-desktop-installed-update-materials.zh.md: 055e1af865ab0ec8f1cc21d9601c5d33083b8a2d
@@ -24,8 +24,8 @@
en: 26e4b71366bebd1b
zh: 10598e12b28c586e
/agent-note-cooperative-tool-cancellation-at-the-registry-boundary/verification:
en: 4911064d1a23aaa8
zh: 59196f7291618eda
en: 983da6d0c09f5c10
zh: ca7c86117a1a4d5f
/agent-note-cooperative-tool-cancellation-at-the-registry-boundary/alternatives-considered:
en: c4d86feb135d2ac4
zh: 67c56c0bc2213949
@@ -46,7 +46,7 @@ This decision requires cancellation at the tool invocation boundary only. Making
## Verification
[`execution-signal-types.spec.ts`](../../../../packages/core/tools/tests/execution-signal-types.spec.ts) proves the required exact signal types, readonly observer and tool views, mutable-but-required around-dispatch view, and `defineTool()` inference. [`tools.spec.ts`](../../../../packages/core/tools/tests/tools.spec.ts) covers pre-aborted materialization, phase skipping, policy and wrapper races, body invocation classification, caller-signal fusion, error precedence, context retention, and quiescent drainage. [`tool-calls.spec.ts`](../../../../packages/core/agent-loop/tests/tool-calls.spec.ts) and [`contract-regressions.spec.ts`](../../../../packages/core/agent-loop/tests/contract-regressions.spec.ts) cover balanced durable results for undispatched siblings. [`ptc.spec.ts`](../../../../packages/core/tool-registry-ptc/tests/ptc.spec.ts) and first-party integration suites cover explicit forwarding, while [`timeout-policy.spec.ts`](../../../../packages/guard/timeout-policy/tests/timeout-policy.spec.ts) preserves timeout ownership.
[`execution-signal-types.spec.ts`](../../../../packages/core/tools/tests/execution-signal-types.spec.ts) proves the required exact signal types, readonly observer and tool views, mutable-but-required around-dispatch view, and `defineTool()` inference. [`tools.spec.ts`](../../../../packages/core/tools/tests/tools.spec.ts) covers pre-aborted materialization, phase skipping, policy and wrapper races, body invocation classification, caller-signal fusion, error precedence, context retention, and quiescent drainage. [`tool-calls.spec.ts`](../../../../packages/core/agent-loop/tests/tool-calls.spec.ts) and [`contract-regressions.spec.ts`](../../../../packages/core/agent-loop/tests/contract-regressions.spec.ts) cover balanced durable results for undispatched siblings. [`ptc.spec.ts`](../../../../packages/core/tool-executor-ptc/tests/ptc.spec.ts) and first-party integration suites cover explicit forwarding, while [`timeout-policy.spec.ts`](../../../../packages/guard/timeout-policy/tests/timeout-policy.spec.ts) preserves timeout ownership.
No registry test can prove that arbitrary third-party same-process code observes the signal or stops in bounded time. Capability tests continue to prove cancellation and quiescence at the boundary that owns each side effect.
@@ -46,7 +46,7 @@ Status: implemented
## 验证
[`execution-signal-types.spec.ts`](../../../../packages/core/tools/tests/execution-signal-types.spec.ts) 证明必填的精确信号类型、观察者与工具的只读视图、环绕调度可替换但不可删除的视图,以及 `defineTool()` 推断。[`tools.spec.ts`](../../../../packages/core/tools/tests/tools.spec.ts) 覆盖进入时已中止的物化与阶段跳过、策略和包装层竞态、工具主体调用分类、调用方信号融合、错误优先级、上下文保留和完全停稳。[`tool-calls.spec.ts`](../../../../packages/core/agent-loop/tests/tool-calls.spec.ts) 与 [`contract-regressions.spec.ts`](../../../../packages/core/agent-loop/tests/contract-regressions.spec.ts) 覆盖为未调度的同批调用补齐持久化结果。[`ptc.spec.ts`](../../../../packages/core/tool-registry-ptc/tests/ptc.spec.ts) 和第一方集成测试覆盖显式转发,[`timeout-policy.spec.ts`](../../../../packages/guard/timeout-policy/tests/timeout-policy.spec.ts) 保持超时归属。
[`execution-signal-types.spec.ts`](../../../../packages/core/tools/tests/execution-signal-types.spec.ts) 证明必填的精确信号类型、观察者与工具的只读视图、环绕调度可替换但不可删除的视图,以及 `defineTool()` 推断。[`tools.spec.ts`](../../../../packages/core/tools/tests/tools.spec.ts) 覆盖进入时已中止的物化与阶段跳过、策略和包装层竞态、工具主体调用分类、调用方信号融合、错误优先级、上下文保留和完全停稳。[`tool-calls.spec.ts`](../../../../packages/core/agent-loop/tests/tool-calls.spec.ts) 与 [`contract-regressions.spec.ts`](../../../../packages/core/agent-loop/tests/contract-regressions.spec.ts) 覆盖为未调度的同批调用补齐持久化结果。[`ptc.spec.ts`](../../../../packages/core/tool-executor-ptc/tests/ptc.spec.ts) 和第一方集成测试覆盖显式转发,[`timeout-policy.spec.ts`](../../../../packages/guard/timeout-policy/tests/timeout-policy.spec.ts) 保持超时归属。
任何注册表测试都无法证明任意第三方同进程代码会观察信号或在有界时间内停止。各能力的测试仍需在拥有相应副作用的边界证明取消与完全停稳。
@@ -15,8 +15,8 @@
en: 6af228b03e5e533f
zh: 276a522af6be5d7a
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/one-module-system-one-plugin-governor:
en: 51df5a30c9337f22
zh: f4533cd731c86890
en: 5f5daec51b20db77
zh: e4d6f78fc1b4b835
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/combo-external-script-arrival-and-source-maps:
en: 04b9f0138b5d2288
zh: 2a749db57f6e7a10
@@ -34,7 +34,7 @@ The web kernel remains framework-free and imports no dynamic package value. Modu
The browser mirrors the host's division of labor. `dsh-client-modules` (`ClientModuleSystem`) takes the module-system seat that Node's internal ESM loader holds host-side; the same vendored `@cordisjs/plugin-loader` keeps the governance seat on both sides. The line between them in one sentence: **the module system owns module identity and bytes — how code arrives, registers, and becomes an exports; the Loader owns plugin lifecycle — when a plugin mounts, what it waits for, and how it is torn down.**
`ClientModuleSystem` is a lazy CJS table. Executing a bundle only **registers** its factory — an entry calls `window.__ModuleLoader__.load({ id, factory })`, while a chunk also supplies its generated filename — and nothing else happens. JavaScript module body side effects live inside the factory closure and run at materialization: the first `require`/import of that id, memoized after that. Import and prefetch recursively register declared dynamic requests before their consumer; a factory then materializes any registered-but-unmaterialized request synchronously. The callable `require` resolves synchronous module-table requests; its `require.async` operation returns a Promise that loads, registers, and materializes one package-local chunk. The shared tsdown preset compiles source `import()` expressions for package-local chunks to that distinct operation. A factory may also synchronously require a chunk of its own package that is already registered; the chunk registration and request rules are in [package-local chunk dependencies](2026-11-26-package-local-chunk-dependencies.md). The table resolves through a fixed branch order: seed word → memoized record → graph-row classic-script registration → registered-factory materialization → loud throw. The modules factory is the bootstrap exception: the HTML facade materializes it first, and construction places those same exports directly in the memoized table. That final throw is the runtime mirror of the build-time purity gate. The system also keeps per-module bookkeeping — owner identity, optional opaque metadata producers, and observed require edges — and exposes the two verbs HMR needs: `prefetch(id)` (register the requested dynamic factories and the row's own factory; concurrent arrivals share one task) and `invalidate(id)` (advance the owner generation and drop a non-bootstrap package's entry and chunk factories and records so the next arrival reloads them). A chunk request captured under an older generation cannot populate the new generation.
`ClientModuleSystem` is a lazy CJS table. Executing a bundle only **registers** its factory — an entry calls `window.__ModuleLoader__.load({ id, factory })`, while a chunk also supplies its generated filename — and nothing else happens. JavaScript module body side effects live inside the factory closure and run at materialization: the first `require`/import of that id, memoized after that. Import and prefetch recursively register declared dynamic requests before their consumer; a factory then materializes any registered-but-unmaterialized request synchronously. The callable `require` resolves synchronous module-table requests; its `require.async` operation returns a Promise that loads, registers, and materializes one package-local chunk. The shared tsdown preset compiles source `import()` expressions for package-local chunks to that distinct operation. The supported output is self-contained: an entry or chunk cannot synchronously require another relative `client*.js` output. The table resolves through a fixed branch order: seed word → memoized record → graph-row classic-script registration → registered-factory materialization → loud throw. The modules factory is the bootstrap exception: the HTML facade materializes it first, and construction places those same exports directly in the memoized table. That final throw is the runtime mirror of the build-time purity gate. The system also keeps per-module bookkeeping — owner identity, optional opaque metadata producers, and observed require edges — and exposes the two verbs HMR needs: `prefetch(id)` (register the requested dynamic factories and the row's own factory; concurrent arrivals share one task) and `invalidate(id)` (advance the owner generation and drop a non-bootstrap package's entry and chunk factories and records so the next arrival reloads them). A chunk request captured under an older generation cannot populate the new generation.
The vendored Loader consumes the module system through its `internal` contract — the only call site is `tree.import` — and owns everything entry-shaped: entry creation, fiber activation through cordis service waiting (PENDING until injected services exist, cascading when a service is provided), update/refresh, teardown. The governance code is byte-identical to the host side, per vendor policy. Browserization is compile-time mapping in the shell's vite config: a `node:module` stub alias plus `process.*` defines make `ModuleLoader.fromInternal()` return undefined — exactly the empty slot the shell fills. The module system mounts as `ctx.modules`.
@@ -34,7 +34,7 @@ Web 内核保持不依赖框架,也不 import 任何动态包实体。Modules
浏览器复刻 host 侧的分工。`dsh-client-modules`(`ClientModuleSystem`)坐上 host 侧由 Node 内部 ESM loader 占据的模块系统席位;同一份 vendored `@cordisjs/plugin-loader` 在两侧都坐治理席。二者的分界线一句话说尽:**模块系统拥有模块身份与字节——代码怎么到达、怎么登记、怎么变成导出内容;Loader 拥有插件生命周期——插件何时挂载、等待什么、如何拆除。**
`ClientModuleSystem` 是一张 lazy CJS 表。执行 bundle 只**登记**其 factory——入口调用 `window.__ModuleLoader__.load({ id, factory })`,chunk 还会提供其生成文件名——此外什么都不发生。JavaScript 模块体副作用位于 factory 闭包里,在物化时运行:物化即该 id 的首次 `require`/import,此后记忆化。Import 和 prefetch 会先递归登记已声明的动态请求,再登记消费者;随后 factory 会同步物化任何已登记但尚未物化的请求。可调用的 `require` 解析同步模块表请求;其 `require.async` 操作返回 Promise,负责加载、登记并物化一个包内 chunk。共享 tsdown 预设把源码中针对包内 chunk 的 `import()` 表达式编译到这个独立操作。factory 也可以同步 require 本包已登记的 chunk;chunk 登记与请求的规则见[包内分片之间的依赖](2026-11-26-package-local-chunk-dependencies.zh.md)。模块表按固定分支顺序解析:seed word → 记忆化记录 → graph row classic-script 登记 → 已登记 factory 物化 → 大声抛错。Modules factory 是自举例外:HTML facade 先物化它,构造过程再把同一 exports 直接写入记忆化表。最后这一抛是构建期纯度门禁在运行时的镜像。系统还保管逐模块簿记——owner 身份、可选且不求值的元信息函数、观测到的 require 边——并暴露 HMR(热模块替换)需要的两个动词:`prefetch(id)`(登记所请求的动态 factory 和本 row 自身的 factory;并发到达共享一个任务)与 `invalidate(id)`(推进 owner 代次并丢弃非 bootstrap 包的入口和 chunk factory 及记录,让下次到达重新加载它们)。在旧代次捕获的 chunk 请求不能填充新代次。
`ClientModuleSystem` 是一张 lazy CJS 表。执行 bundle 只**登记**其 factory——入口调用 `window.__ModuleLoader__.load({ id, factory })`,chunk 还会提供其生成文件名——此外什么都不发生。JavaScript 模块体副作用位于 factory 闭包里,在物化时运行:物化即该 id 的首次 `require`/import,此后记忆化。Import 和 prefetch 会先递归登记已声明的动态请求,再登记消费者;随后 factory 会同步物化任何已登记但尚未物化的请求。可调用的 `require` 解析同步模块表请求;其 `require.async` 操作返回 Promise,负责加载、登记并物化一个包内 chunk。共享 tsdown 预设把源码中针对包内 chunk 的 `import()` 表达式编译到这个独立操作。受支持的产物必须自包含:入口或 chunk 不能同步 require 另一个相对 `client*.js` 产物。模块表按固定分支顺序解析:seed word → 记忆化记录 → graph row classic-script 登记 → 已登记 factory 物化 → 大声抛错。Modules factory 是自举例外:HTML facade 先物化它,构造过程再把同一 exports 直接写入记忆化表。最后这一抛是构建期纯度门禁在运行时的镜像。系统还保管逐模块簿记——owner 身份、可选且不求值的元信息函数、观测到的 require 边——并暴露 HMR(热模块替换)需要的两个动词:`prefetch(id)`(登记所请求的动态 factory 和本 row 自身的 factory;并发到达共享一个任务)与 `invalidate(id)`(推进 owner 代次并丢弃非 bootstrap 包的入口和 chunk factory 及记录,让下次到达重新加载它们)。在旧代次捕获的 chunk 请求不能填充新代次。
vendored Loader 经其 `internal` 约定消费模块系统——唯一调用点是 `tree.import`——并拥有一切 entry 形状的事务:entry 创建、fiber 经 cordis 服务等待的激活(注入的服务未就位即保持 PENDING,服务 provide 时级联激活)、update/refresh、拆除。治理代码按 vendor 政策与 host 侧逐字节相同。浏览器化是壳 vite 配置里的编译期映射:一个 `node:module` stub 别名加若干 `process.*` define,使 `ModuleLoader.fromInternal()` 返回 undefined——这正是留给壳来填的空槽。模块系统挂载为 `ctx.modules`。
@@ -9,14 +9,14 @@
en: 77713a6c0d15207e
zh: 2dc30d4c0182d8ba
/agent-note-compiler-independent-typert-type-model/decision:
en: ef283e9012a9484e
zh: a28d58fc8b21c51b
en: 9ecb064f733f9f1b
zh: 471aee71053174cd
/agent-note-compiler-independent-typert-type-model/verification-contract:
en: 7059790531ffef8a
zh: cef77a95dac9ba4c
en: c02d3f09e54f9a32
zh: c14c15ffb7316b07
/agent-note-compiler-independent-typert-type-model/alternatives-considered:
en: fa503dcfaa6f438f
zh: 26052212a124e133
/agent-note-compiler-independent-typert-type-model/consequences:
en: 2dc2e12298953ac8
zh: 54666b9d1f92dccd
en: e1022cf9523fb28e
zh: 01dfb764fb98de0d
@@ -24,7 +24,7 @@ PackageModel recognizes Cordis services, events, `@typert object` reference obje
Package artifact publication remains explicit opt-in through package exports. When invoked, `WorkspaceTypertGenerator` validates that each requested host face exposes the user-facing subpath `package/typert` from the root artifact `package/lib/typert.host.{js,d.ts}`, or that each requested client face exposes `package/client/typert` from `package/lib/typert.client.{js,d.ts}`; it never edits those exports. The later [Typert Remote design](2026-08-02-typert-remote-method-calls.md) adds a whole-workspace Host contract pass to root build, typecheck, lint, and documentation typecheck. For opted-in Host packages, that pass emits both local reflection and strict Host-for-Client `/remote` contracts before consumers resolve them. Generated local declarations keep `TYPERT` typed as `unknown`, so business packages do not depend on the registry.
At build time, `CordisCatalogProjector` consumes the analyzed `FaceModel` and `TypeGraph` once to generate `docs/cordis-catalog/events.md`, `docs/cordis-catalog/services.md`, and the static `SERVICE_API`, `EVENT_API`, and `TYPE_API` catalog committed for the `cordis-host-runner` inspect providers. Those providers read that static catalog and have no runtime dependency on `ctx.typert`. [`dsh-typert-loader`](../../../../packages/typert/loader/README.md) and the registry remain an independent runtime path: the loader follows Cordis Loader entry lifecycle events, imports an explicitly published `./typert` host artifact, and registers it through `ctx.typert`; neither component supplies the current `cordis_inspect` catalog.
At build time, `CordisCatalogProjector` consumes the analyzed `FaceModel` and `TypeGraph` once to generate `docs/cordis-catalog/events.md`, `docs/cordis-catalog/services.md`, and the static `SERVICE_API`, `EVENT_API`, and `TYPE_API` catalog committed for `tool-cordis`. `tool-cordis` reads that static catalog and has no runtime dependency on `ctx.typert`. [`dsh-typert-loader`](../../../../packages/typert/loader/README.md) and the registry remain an independent runtime path: the loader follows Cordis Loader entry lifecycle events, imports an explicitly published `./typert` host artifact, and registers it through `ctx.typert`; neither component supplies the current `cordis_inspect` catalog.
## Verification contract
@@ -34,7 +34,7 @@ For every property in `SyntaxZoo`, the TypeScript printer normalizes the source
Boundary cases pin explicit package imports within and across faces, cross-face named re-exports, exact export aliases, qualified `import()` links, and the External classification of global `@types` declarations; they reject TypeScript diagnostics originating in package-owned files, relative-path boundary crossings, references outside `package.json#exports`, and cross-face namespace re-exports without a model target. Interface declaration merging explicitly preserves every authored part; other merges that cannot be represented losslessly fail.
For each supported node kind and literal category, Zod emitter tests run both successful and failing parses; for each unsupported kind, they assert an explicit `TypertEmitError`. Emitter fixtures snapshot generated Zod JavaScript and `.d.ts` text, execute each schema factory, and typecheck the declarations. `dsh-typert-registry` tests pin atomic registration, first-use materialization, successful-result caching, retry after factory failure, queries, JSON Schema, and effect disposal; `dsh-typert-loader` tests also prove delayed mounting, unloading, and disposal while a dynamic import remains pending. A real `dsh-tools` vertical slice generates a contribution from the model, loads it through the runtime registry, and compares its service, event, and related-type records with the committed static `SERVICE_API`, `EVENT_API`, and `TYPE_API`. A full-workspace projector test regenerates the two Cordis catalog documents and the `cordis-host-runner` API catalog and requires all three texts to be byte-for-byte identical to the committed artifacts.
For each supported node kind and literal category, Zod emitter tests run both successful and failing parses; for each unsupported kind, they assert an explicit `TypertEmitError`. Emitter fixtures snapshot generated Zod JavaScript and `.d.ts` text, execute each schema factory, and typecheck the declarations. `dsh-typert-registry` tests pin atomic registration, first-use materialization, successful-result caching, retry after factory failure, queries, JSON Schema, and effect disposal; `dsh-typert-loader` tests also prove delayed mounting, unloading, and disposal while a dynamic import remains pending. A real `dsh-tools` vertical slice generates a contribution from the model, loads it through the runtime registry, and compares its service, event, and related-type records with the committed static `SERVICE_API`, `EVENT_API`, and `TYPE_API`. A full-workspace projector test regenerates the two Cordis catalog documents and the `tool-cordis` API catalog and requires all three texts to be byte-for-byte identical to the committed artifacts.
## Alternatives considered
@@ -50,6 +50,6 @@ For each supported node kind and literal category, Zod emitter tests run both su
New generation targets and static checks can reuse the same TypeGraph, and business categories can extend PackageModel without parsing the AST again. Preserving pre-evaluation types and independent faces makes the model more complex than a flattened schema; emitters must explicitly declare their supported scope and fail on missing capabilities.
Explicit package opt-in keeps artifact publication and exports under package ownership. Repository orchestration may still run the whole-workspace Host contract pass for every opted-in package; that pass remains owned by the later Remote Gateway Agent Note. The static Cordis catalogs remain reproducible from the canonical model without coupling the inspect providers to runtime registry state. `ctx.typert` reflects only artifacts mounted in the current runtime, and unloading does not control Zod instances that consumers retain after materializing them.
Explicit package opt-in keeps artifact publication and exports under package ownership. Repository orchestration may still run the whole-workspace Host contract pass for every opted-in package; that pass remains owned by the later Remote Gateway Agent Note. The static Cordis catalogs remain reproducible from the canonical model without coupling `tool-cordis` to runtime registry state. `ctx.typert` reflects only artifacts mounted in the current runtime, and unloading does not control Zod instances that consumers retain after materializing them.
Ordinary Host and Remote artifacts reuse this model to emit one static method spec per endpoint. Each parameter has normal `codec` and `strictCodec` variants derived from the same checker-resolved type model; neither analysis nor the model carries a per-method input policy. A pure factory returns a lazy info instance whose direct method index and descriptor list share objects; the existing Registry retains those descriptors, while `TYPERT_REMOTE.methods` supplies exact static types. The [unified Typert/Remote metadata note](../../proposed/architecture/2026-09-20-unified-typert-remote-metadata.md) records this delivery mechanism and the incomplete downstream adaptation. Declaration and face-isolation rules remain unchanged; separate Programs and processes do not share object identity.
@@ -24,7 +24,7 @@ PackageModel 识别 Cordis service、event、`@typert object` 引用对象和 `@
包产物发布仍通过 package exports 采用显式 opt-in。`WorkspaceTypertGenerator` 仅在被调用时校验所请求 face 的根目录产物协议:host face 必须通过面向用户的 subpath `package/typert` 暴露 `package/lib/typert.host.{js,d.ts}`,client face 必须通过 `package/client/typert` 暴露 `package/lib/typert.client.{js,d.ts}`;它不会修改这些 exports。后续的 [Typert Remote 设计](2026-08-02-typert-remote-method-calls.zh.md) 为根目录 build、typecheck、lint 与文档类型检查增加了全仓 Host 约定 pass。对于已 opt-in 的 Host 包,该 pass 会在消费方解析两者之前生成本地反射产物与严格的 Host-for-Client `/remote` 约定。生成的本地声明将 `TYPERT` 类型保持为 `unknown`,因此业务包不依赖注册表。
构建期的 `CordisCatalogProjector` 一次消费分析后的 `FaceModel` 与 `TypeGraph`,生成 `docs/cordis-catalog/events.md`、`docs/cordis-catalog/services.md`,以及为 `cordis-host-runner` 检查提供方提交的静态 `SERVICE_API`、`EVENT_API` 和 `TYPE_API` catalog。这些提供方读取该静态 catalog,运行时不依赖 `ctx.typert`。[`dsh-typert-loader`](../../../../packages/typert/loader/README.zh.md) 与注册表仍是独立的运行时路径:loader 监听 Cordis Loader 配置项生命周期事件,导入显式发布的 `./typert` host 产物,并通过 `ctx.typert` 注册;两者都不是当前 `cordis_inspect` catalog 的数据源。
构建期的 `CordisCatalogProjector` 一次消费分析后的 `FaceModel` 与 `TypeGraph`,生成 `docs/cordis-catalog/events.md`、`docs/cordis-catalog/services.md`,以及为 `tool-cordis` 提交的静态 `SERVICE_API`、`EVENT_API` 和 `TYPE_API` catalog。`tool-cordis` 读取该静态 catalog,运行时不依赖 `ctx.typert`。[`dsh-typert-loader`](../../../../packages/typert/loader/README.zh.md) 与注册表仍是独立的运行时路径:loader 监听 Cordis Loader 配置项生命周期事件,导入显式发布的 `./typert` host 产物,并通过 `ctx.typert` 注册;两者都不是当前 `cordis_inspect` catalog 的数据源。
## Verification contract
@@ -34,7 +34,7 @@ PackageModel 识别 Cordis service、event、`@typert object` 引用对象和 `@
边界用例固定同 face 与跨 face 的显式包导入、跨 face 命名 re-export、精确 export alias、qualified `import()` link 和全局 `@types` External 归属,并拒绝 package 自有 TypeScript 诊断、相对路径越界、`package.json#exports` 之外的引用,以及尚无模型 target 的跨 face namespace re-export。interface declaration merging 显式保留每个 authored part,无法无损表示的其他 merge 失败。
Zod emitter 对支持的节点和各类 literal 逐类执行成功与失败 parse,对不支持的节点逐类断言明确的 `TypertEmitError`。Emitter fixture 对生成的 Zod JavaScript 与 `.d.ts` 文本做快照,执行每个 schema factory,并对声明做类型检查。`dsh-typert-registry` 测试固定原子注册、首次使用物化、成功结果缓存、factory 失败后重试、查询、JSON Schema 和 effect 撤销,`dsh-typert-loader` 测试还证明延迟挂载、卸载及未完成 dynamic import 的释放行为。真实 `dsh-tools` 纵切从模型生成 contribution,经运行时注册表加载后,将其服务、事件与关联类型记录同已提交的静态 `SERVICE_API`、`EVENT_API` 和 `TYPE_API` 对照。全仓 projector 测试重新生成两份 Cordis catalog 文档与 `cordis-host-runner` API catalog,并要求三份文本同已提交产物逐字节一致。
Zod emitter 对支持的节点和各类 literal 逐类执行成功与失败 parse,对不支持的节点逐类断言明确的 `TypertEmitError`。Emitter fixture 对生成的 Zod JavaScript 与 `.d.ts` 文本做快照,执行每个 schema factory,并对声明做类型检查。`dsh-typert-registry` 测试固定原子注册、首次使用物化、成功结果缓存、factory 失败后重试、查询、JSON Schema 和 effect 撤销,`dsh-typert-loader` 测试还证明延迟挂载、卸载及未完成 dynamic import 的释放行为。真实 `dsh-tools` 纵切从模型生成 contribution,经运行时注册表加载后,将其服务、事件与关联类型记录同已提交的静态 `SERVICE_API`、`EVENT_API` 和 `TYPE_API` 对照。全仓 projector 测试重新生成两份 Cordis catalog 文档与 `tool-cordis` API catalog,并要求三份文本同已提交产物逐字节一致。
## Alternatives considered
@@ -50,6 +50,6 @@ Zod emitter 对支持的节点和各类 literal 逐类执行成功与失败 pars
新增生成目标或静态检查可复用同一 TypeGraph,业务类目也可在 PackageModel 上扩展,而无需再次解析 AST。保留计算前类型和独立 face 的代价是模型比打平后的 schema 更复杂,emitter 必须显式声明支持范围并对缺失能力失败。
包级显式 opt-in 使产物发布与 exports 由各包自行管理。仓库编排仍可为每个已 opt-in 的包运行全仓 Host 约定 pass;该 pass 仍由后续 Remote Gateway Agent Note 负责说明。静态 Cordis catalog 可从标准模型复现,同时不把检查提供方与运行时注册表状态耦合。`ctx.typert` 只反映当前运行时中已挂载的产物;对于消费方物化后仍持有的 Zod 实例,卸载流程无法控制。
包级显式 opt-in 使产物发布与 exports 由各包自行管理。仓库编排仍可为每个已 opt-in 的包运行全仓 Host 约定 pass;该 pass 仍由后续 Remote Gateway Agent Note 负责说明。静态 Cordis catalog 可从标准模型复现,同时不把 `tool-cordis` 与运行时注册表状态耦合。`ctx.typert` 只反映当前运行时中已挂载的产物;对于消费方物化后仍持有的 Zod 实例,卸载流程无法控制。
普通 Host 与 Remote 产物复用此模型,为每个端点生成一份静态方法 spec。每个参数都有从同一 checker 解析后类型模型派生的普通 `codec` 和 `strictCodec` 变体;分析过程与模型均不携带逐方法输入策略。纯 factory 返回惰性 info 实例,其直接方法索引与描述符列表共享对象;既有 Registry 保留这些描述符,而 `TYPERT_REMOTE.methods` 提供精确静态类型。[统一 Typert/Remote 元数据 note](../../proposed/architecture/2026-09-20-unified-typert-remote-metadata.zh.md)记录该交付机制及尚未完成的下游适配。声明与编译面隔离规则保持不变;独立 Program 和进程不共享对象身份。
@@ -12,11 +12,11 @@
en: a15c7c13f167e5ac
zh: a15c7c13f167e5ac
/agent-note-client-shell-layering-and-dynamic-package-boundaries/decision/layers-and-build-forms:
en: 4357a7d881fdcb99
zh: d90fd396f9dd6c2c
en: e0d6260cc782acb9
zh: 2ca2418d2b97bc03
/agent-note-client-shell-layering-and-dynamic-package-boundaries/decision/shared-module-requests:
en: d2531750bbe81189
zh: 130a16eca6e07c14
en: 96661da17622132a
zh: dab3424093130c2f
/agent-note-client-shell-layering-and-dynamic-package-boundaries/decision/parser-preloading-and-react-handoff:
en: 4b503618b271fc28
zh: e2148f44efa769d2
@@ -24,8 +24,8 @@
en: 47c332b836c2933b
zh: ed190dbb14b98911
/agent-note-client-shell-layering-and-dynamic-package-boundaries/alternatives-considered:
en: 265c8e910d525077
zh: 55ff5170dcc1c07c
en: 2257178f8f474757
zh: 7da85b5899b91520
/agent-note-client-shell-layering-and-dynamic-package-boundaries/consequences:
en: c3237ed7ae58fc48
zh: e9c6095705490622
en: c7653b12059aebd7
zh: a79b63f28d18f8c4
@@ -22,18 +22,17 @@ Shared UI libraries still expose synchronous TypeScript and React values to many
| --- | --- | --- | --- |
| Web compilation shell | `apps/web` | Owns `index.html`, Vite configuration, dist chunks, and static assets | Assembles final browser output from built package exports |
| Startup kernel | `packages/client/web` | Owns the plain-DOM boot page, module-system wiring, Cordis settlement, and renderer handoff | `clientShell` ESM entries; no `dsh.client` row |
| Shell-seeded modules | React, Cordis, and selected third-party libraries | Supply shared module identities | Bundled by Vite and seeded into the module table; not Loader entries |
| Static assembly library | `client-store` | Supplies a shared module identity and direct value APIs | Manifest `lib/index.js`, shared imports assembled by Vite, seeded into the module table; not a Loader entry |
| Static assembly libraries | Cordis, `ui-primitives`, `ui-slots` | Supply shared module identities and direct value APIs | Manifest `lib/index.js`, shared imports assembled by Vite; not Loader entries |
| Module bootstrap | `packages/client/modules` | Supplies the client module table and its Cordis wrapper | Dynamic package with one ordinary `lib/client.js`; the host delivers its factory early |
| Dynamic client packages | connection, `ui-renderer`, theme, feature plugins, `ui-slots`, `ui-primitives`, and `ui-dockkit` | Participate through Cordis services, slots, and effects; the `/client` value exports of the last three are a historical exception that will be reduced over time | Declare `dsh.client`, emit self-registering `lib/client.js`, and remain host-graph entries |
| Dynamic client packages | connection, `ui-renderer`, theme, and feature plugins | Participate through Cordis services, slots, and effects | Declare `dsh.client`, emit self-registering `lib/client.js`, and remain host-graph entries |
`packages/client/web` keeps Cordis as matching peer and development dependencies and uses modules and `client-store` as development compilation inputs. `apps/web` consumes built package exports rather than aliases into workspace source.
`packages/client/web` keeps Cordis as matching peer and development dependencies and uses modules and static UI packages as development compilation inputs. `apps/web` consumes built package exports rather than aliases into workspace source.
The `staticLinked` preset emits `lib/index.js` as ordinary ESM that keeps every bare import and dynamic import for Vite to resolve, deduplicate, and split, and adds one export, `__$dsh_client_module_manifest`, whose factory returns the library's own exports. A factory that runs the library body later would defer nothing useful: the third-party imports already evaluate when the module loads, and the shell registers these libraries at startup. CSS imports become deferred metadata resources. The [module metadata decision](2026-11-05-client-module-metadata.md) defines resource ownership; static libraries do not adopt dynamic plugins' private-dependency bundling policy. `client-store` uses the preset.
The `staticLinked` preset emits `lib/index.js` as ordinary ESM that keeps every bare import and dynamic import for Vite to resolve, deduplicate, and split, and adds one export, `__$dsh_client_module_manifest`, whose factory returns the library's own exports. A factory that runs the library body later would defer nothing useful: the third-party imports already evaluate when the module loads, and the shell registers these libraries at startup. CSS imports become deferred metadata resources. The [module metadata decision](2026-11-05-client-module-metadata.md) defines resource ownership; static libraries do not adopt dynamic plugins' private-dependency bundling policy.
### Shared module requests
Dynamic browser bundles implicitly externalize the common baseline ([shared module table](../../../../packages/client/web/README.md#the-shared-module-table)): React, Cordis, selected third-party libraries, and `client-store`, which the shell seeds, and `ui-slots`, `ui-primitives`, and `ui-dockkit`, whose `immediately` rows register before other plugins, while `PRELOADED_CLIENT_EXTERNALS` is reserved for a dynamic identity that must arrive before shell boot and is currently empty. A package uses `dsh.client.external` only for an exact non-baseline value request. Type-only imports are erased and create no request; non-baseline third-party implementation libraries remain private bundle contents. Shared third-party libraries use the shell's declared versions without per-plugin version negotiation; promotion into the baseline requires a measured reduction across the shell and shipped plugin bundles.
Dynamic browser bundles implicitly externalize the common baseline: `PLATFORM_MODULES` names shell-seeded React, Cordis, selected third-party libraries, and static UI identities, while `PRELOADED_CLIENT_EXTERNALS` is reserved for a dynamic identity that must arrive before shell boot and is currently empty. A package uses `dsh.client.external` only for an exact non-baseline value request. Type-only imports are erased and create no request; non-baseline third-party implementation libraries remain private bundle contents. Shared third-party libraries use the shell's declared versions without per-plugin version negotiation; promotion into the baseline requires a measured reduction across the shell and shipped plugin bundles.
A request has exactly two suppliers:
@@ -70,7 +69,7 @@ Ordinary installed libraries remain `dependencies`: a dynamic build may bundle a
## Alternatives considered
**Convert every client package into a dynamic plugin immediately.** `ui-primitives` and `ui-slots` still provide synchronous values without independent service or slot lifecycles; a manifest declaration alone would not remove those imports. `ui-slots`, `ui-primitives`, and `ui-dockkit` are dynamic plugin packages with `immediately: true` instead, and their value exports remain, a historical exception that will be reduced over time ([decision](2026-11-27-client-packages-as-immediately-dynamic-plugins.md)).
**Convert every client package into a dynamic plugin immediately.** `ui-primitives` and `ui-slots` still provide synchronous values without independent service or slot lifecycles; a manifest declaration alone would not remove those imports.
**Generate a separate `client-static.js` for modules.** The package remains a dynamic graph row and Cordis plugin; only its factory arrival is early. A second artifact would encode host policy in a filename and create two runtime products from one source.
@@ -88,4 +87,4 @@ The startup protocol depends on the modules package id, and modules must remain
The shell consumes built `lib/` products, so source and browser artifacts can drift until the relevant build or watcher runs. Typechecking source alone does not prove the served application uses the same code.
`client-store` is the statically linked Client library, and the shell seeds it; a store service would be a separate package, not a conversion of this one. `ui-slots`, `ui-primitives`, and `ui-dockkit` are dynamic plugin packages with `immediately: true` ([decision](2026-11-27-client-packages-as-immediately-dynamic-plugins.md)).
The two static UI libraries remain deliberate exceptions. Converting either one to a dynamic package requires moving all value consumers to services or slots and removing its identity from the static seed in the same change.
@@ -22,18 +22,17 @@ Client npm 依赖区段描述安装和开发关系,但不能可靠描述 bundl
| --- | --- | --- | --- |
| Web 编译壳 | `apps/web` | 拥有 `index.html`、Vite 配置、dist chunk 和静态资源 | 从已构建 package export 组装最终浏览器产物 |
| 启动内核 | `packages/client/web` | 拥有纯 DOM 启动页、模块系统接线、Cordis settle 和 renderer handoff | `clientShell` ESM 入口;无 `dsh.client` row |
| 外壳预置模块 | React、Cordis 及选定的第三方库 | 提供共享模块身份 | 由 Vite 打包并预置进模块表;不是 Loader entry |
| 静态装配库 | `client-store` | 提供共享模块身份和直接实体 API | Manifest `lib/index.js`,共享 import 由 Vite 组装,并预置进模块表;不是 Loader entry |
| 静态装配库 | Cordis、`ui-primitives`、`ui-slots` | 提供共享模块身份和直接实体 API | Manifest `lib/index.js`,共享 import 由 Vite 组装;不是 Loader entry |
| 模块自举包 | `packages/client/modules` | 提供 client 模块表及其 Cordis wrapper | 带一个普通 `lib/client.js` 的动态包;host 提前送达其 factory |
| 动态 client 包 | connection、`ui-renderer`、主题、功能插件,以及 `ui-slots`、`ui-primitives`、`ui-dockkit` | 通过 Cordis service、slot 和 effect 参与应用;后三个包的 `/client` 实体导出是会逐步缩减的历史例外 | 声明 `dsh.client`,产出自注册 `lib/client.js`,并保留 host graph entry |
| 动态 client 包 | connection、`ui-renderer`、主题和功能插件 | 通过 Cordis service、slot 和 effect 参与应用 | 声明 `dsh.client`,产出自注册 `lib/client.js`,并保留 host graph entry |
`packages/client/web` 把 Cordis 保持为 matching peer 与开发依赖,并把 modules 和 `client-store` 作为开发期编译输入。`apps/web` 消费已构建 package export,不通过 alias 读取 workspace 源码。
`packages/client/web` 把 Cordis 保持为 matching peer 与开发依赖,并把 modules 和静态 UI 包作为开发期编译输入。`apps/web` 消费已构建 package export,不通过 alias 读取 workspace 源码。
`staticLinked` 预设把 `lib/index.js` 输出为普通 ESM,保留所有裸 import 与动态 import 交给 Vite 解析、去重和拆分,并增加一个导出 `__$dsh_client_module_manifest`,其 factory 返回库自身的导出。让 factory 推迟执行库本体并没有实际收益:第三方 import 在模块加载时已经求值,外壳也在启动时登记这些库。CSS import 成为延迟求值的元信息资源。[模块元信息决定](2026-11-05-client-module-metadata.zh.md)定义资源所有权;静态库不采用动态插件的私有依赖打包策略。`client-store` 使用该预设。
`staticLinked` 预设把 `lib/index.js` 输出为普通 ESM,保留所有裸 import 与动态 import 交给 Vite 解析、去重和拆分,并增加一个导出 `__$dsh_client_module_manifest`,其 factory 返回库自身的导出。让 factory 推迟执行库本体并没有实际收益:第三方 import 在模块加载时已经求值,外壳也在启动时登记这些库。CSS import 成为延迟求值的元信息资源。[模块元信息决定](2026-11-05-client-module-metadata.zh.md)定义资源所有权;静态库不采用动态插件的私有依赖打包策略。
### 共享模块请求
动态浏览器 bundle 会隐式 external 统一基座([共享模块表](../../../../packages/client/web/README.zh.md#the-shared-module-table)):外壳播种的 React、Cordis、选定的第三方库和 `client-store`,以及 `immediately` row 先于其他插件登记的 `ui-slots`、`ui-primitives`、`ui-dockkit`;`PRELOADED_CLIENT_EXTERNALS` 则为必须先于 shell 启动到达的动态身份预留,当前为空。包只在精确请求基座外实体时使用 `dsh.client.external`。纯类型 import 会被擦除,不产生请求;基座外的第三方实现库保留为 bundle 私有内容。共享第三方库使用外壳声明的版本,不为单个插件协商版本;只有测量确认外壳与随包插件 bundle 的总体积减少,才将库纳入基座。
动态浏览器 bundle 会隐式 external 统一基座:`PLATFORM_MODULES` 命名由外壳播种的 React、Cordis、选定的第三方库和静态 UI 身份,`PRELOADED_CLIENT_EXTERNALS` 则为必须先于 shell 启动到达的动态身份预留,当前为空。包只在精确请求基座外实体时使用 `dsh.client.external`。纯类型 import 会被擦除,不产生请求;基座外的第三方实现库保留为 bundle 私有内容。共享第三方库使用外壳声明的版本,不为单个插件协商版本;只有测量确认外壳与随包插件 bundle 的总体积减少,才将库纳入基座。
请求只有两种提供方:
@@ -70,7 +69,7 @@ Theme 的 Host 贡献会前置到 index 收集顺序。head 中的 CSS 选择初
## Alternatives considered
**立即把所有 client 包改为动态插件。** `ui-primitives` 与 `ui-slots` 仍提供同步实体,且没有独立 service 或 slot 生命周期;只加 manifest 声明不会移除这些 import。`ui-slots`、`ui-primitives`、`ui-dockkit` 改为带 `immediately: true` 的动态插件包,它们的实体导出仍然保留,是会逐步缩减的历史例外([决定](2026-11-27-client-packages-as-immediately-dynamic-plugins.zh.md))。
**立即把所有 client 包改为动态插件。** `ui-primitives` 与 `ui-slots` 仍提供同步实体,且没有独立 service 或 slot 生命周期;只加 manifest 声明不会移除这些 import。
**为 modules 生成单独的 `client-static.js`。** 该包仍是动态图 row 和 Cordis 插件,只有 factory 提前到达。第二份产物会把宿主策略编码进文件名,并让同一源码产生两个运行期产品。
@@ -88,4 +87,4 @@ Theme 的 Host 贡献会前置到 index 收集顺序。head 中的 CSS 选择初
外壳消费已构建 `lib/` 产品,因此在相关 build 或 watcher 运行前,源码与浏览器产物可能漂移。仅源码 typecheck 通过不能证明实际服务的应用使用同一份代码。
`client-store` 是静态链接的 Client 库,由外壳播种;store service 将是一个独立的包,而不是对这个包的转换。`ui-slots`、`ui-primitives` 和 `ui-dockkit` 是带 `immediately: true` 的动态插件包([决定](2026-11-27-client-packages-as-immediately-dynamic-plugins.zh.md))。
两个静态 UI 库仍是明确例外。把其中任一项转换为动态包时,必须在同一变更中把全部实体消费者迁移到 service 或 slot,并从静态 seed 删除对应身份。
@@ -9,8 +9,8 @@
en: 5a39322836f06cd9
zh: 7a7ab48fe38a5788
/agent-note-package-and-update-the-electron-desktop-application/decision:
en: 39ba384f2df52828
zh: 06b9c61964a99537
en: b4d04297a7abae71
zh: 9b770c81c2267869
/agent-note-package-and-update-the-electron-desktop-application/ownership:
en: 50e16f318c5d0e1a
zh: 84b2ba8f1a6932b0
@@ -18,17 +18,17 @@
en: 4990a8ba137e28f0
zh: b12f68d30a5d18fa
/agent-note-package-and-update-the-electron-desktop-application/installation-and-resolution:
en: 22cae5f50a2cc3ed
zh: e99e7e61351e983e
en: 29def175ab33b7d6
zh: 87e55ec28c20c7c1
/agent-note-package-and-update-the-electron-desktop-application/updates-and-recovery:
en: 028b8146e5fe16f2
zh: 8835acb61eee8916
en: 61a02870beb953ec
zh: 205ecce330959e9a
/agent-note-package-and-update-the-electron-desktop-application/security-and-release-policy:
en: 5faaa53b58121311
zh: e1c3fc8d21a27d1a
/agent-note-package-and-update-the-electron-desktop-application/implementation:
en: 9d435fecbb539d57
zh: 35e24ba36e3dfca9
en: 041a6d35ed61b149
zh: 617c6b90a6f4fa4d
/agent-note-package-and-update-the-electron-desktop-application/alternatives-considered:
en: 10b1b0a8afe38def
zh: 0a4df988f72b8d11
@@ -24,7 +24,7 @@ Electron owns the reserved profile at `.dsh/profiles/desktop`. The [bundled-runt
One Desktop release number identifies the Electron artifact and its exact `@deepseek-ai/dsh` and `@deepseek-ai/dsh-desktop-host` dependencies. A release cannot select a different core version at build or runtime. Updating dsh therefore requires a new Electron release even when shell code is unchanged.
The Desktop Host exposes the shared Web plugin manager for its reserved profile and supplies bundled pnpm through launcher facts. The CLI reserves every case variant of the `desktop` name and rejects boot, config-dump, and plugin-management requests for it. Electron acquires its process-lifetime single-instance lock, scoped to its `userData` directory, before profile recovery or Host startup; later launches with the same `userData` focus or recreate the primary window without touching profile state. Applications with different `userData`, such as the installed application and `dev:desktop`, can run together on one profile.
The Desktop Host exposes the shared Web plugin manager for its reserved profile and supplies bundled pnpm through launcher facts. The CLI reserves every case variant of the `desktop` name and rejects boot, config-dump, and plugin-management requests for it. Electron acquires its process-lifetime single-instance lock before profile recovery or Host startup; later launches focus or recreate the primary window without touching profile state.
## Ownership
@@ -63,7 +63,7 @@ Update confirmations use the shell static origin because they must remain availa
The shared Web plugin manager owns profile package operations. Electron retains startup preparation and native recovery; the [Web wrapper decision](2026-09-10-desktop-web-wrapper.md) owns this separation.
The process-lifetime Electron lock is the authoritative owner among Desktop processes that share one `userData` directory. Profile preparation and native recovery use an exclusive lock recording the Electron PID; a live owner blocks a competing operation, while a stale PID can be recovered. Web package operations use the shared plugin manager’s locking.
The process-lifetime Electron lock is the authoritative Desktop owner. Profile preparation and native recovery use an exclusive lock recording the Electron PID; a live owner blocks a competing operation, while a stale PID can be recovered. Web package operations use the shared plugin manager’s locking.
Core materialization, first launch, plugin installation, and shared-module resolution follow the [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md). The actual Host composes enabled desktop plugins contributing `dsh.client` code when it starts.
@@ -73,7 +73,7 @@ Electron update uses one `electron-updater` release stream and signed `electron-
The [immediate-window reference](../../../../apps/desktop/README.md) owns the local loading page, direct Host startup, and recovery in the main window. Profile reconciliation follows the [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md).
`DSH_DESKTOP_AUTO_UPDATE_ENV` selects the test deployment by default or the production deployment for both the target-specific generic-provider URL and COS destination. Release automation supplies the test HTTPS origin through `DOWNLOAD_TEST_ORIGIN` and each deployment's bucket through `DOWNLOAD_TEST_COS_BUCKET` or `DOWNLOAD_PROD_COS_BUCKET`; keeping mutable test routing and COS storage identities out of source lets deployment infrastructure change without a code release, while the public production origin remains fixed. Packaging resolves only the public updater URL, disables electron-builder publishing, removes every COS credential field from its subprocess environment, and writes a completion record only after electron-builder and every signing or notarization hook succeeds. Target upload additionally requires the selected bucket, then requires the completion record, root dsh version, Desktop version, channel-selected metadata, artifact names, sizes, and SHA-512 values to agree before it reads the selected credentials or sends data. It uploads immutable versioned updater payloads and any separate blockmaps before replacing the channel metadata emitted by electron-builder, and it never deletes historical objects. The selected channel determines the metadata name: `stable.yml` or `nightly.yml`, with `-mac` before the extension for macOS; version suffixes do not select the channel. NSIS embeds its blockmap in the signed executable; the macOS ZIP carries a separate blockmap. Both let electron-updater download changed blocks when supported, while application replacement and the local pnpm package operation remain separate operations; [channel convergence and decoupled publishing](2026-11-25-desktop-channel-convergence-and-decoupled-publishing.md) owns default `stable` locking, `settings.json` version `"1"`, feed source headers, and multi-channel CI delivery from one retained package.
`DSH_DESKTOP_AUTO_UPDATE_ENV` selects the test deployment by default or the production deployment for both the target-specific generic-provider URL and COS destination. Release automation supplies the test HTTPS origin through `DOWNLOAD_TEST_ORIGIN` and each deployment's bucket through `DOWNLOAD_TEST_COS_BUCKET` or `DOWNLOAD_PROD_COS_BUCKET`; keeping mutable test routing and COS storage identities out of source lets deployment infrastructure change without a code release, while the public production origin remains fixed. Packaging resolves only the public updater URL, disables electron-builder publishing, removes every COS credential field from its subprocess environment, and writes a completion record only after electron-builder and every signing or notarization hook succeeds. Target upload additionally requires the selected bucket, then requires the completion record, root dsh version, Desktop version, channel-selected metadata, artifact names, sizes, and SHA-512 values to agree before it reads the selected credentials or sends data. It uploads immutable versioned updater payloads and any separate blockmaps before replacing the channel metadata emitted by electron-builder, and it never deletes historical objects. The selected channel determines the metadata name: `stable.yml` or `nightly.yml`, with `-mac` before the extension for macOS; version suffixes do not select the channel. NSIS embeds its blockmap in the signed executable; the macOS ZIP carries a separate blockmap. Both let electron-updater download changed blocks when supported, while application replacement and the local pnpm package operation remain separate operations.
Test releases require `DOWNLOAD_TEST_RELEASE_ID` from the platform dotenv file. Their feeds and binaries share `dsh-desk/<release-id>/`; production retains its fixed directories. The ID is part of the packaged update URL, so upload rejects a different ID. Internal distribution can supply a new installer after rotation; installed clients retain their existing feed. Random directories reduce guessing but provide no authorization for link holders. The [release configuration](../../../../apps/desktop/publishing/README.md#upload-updates) defines generation and reuse.
@@ -106,7 +106,7 @@ Architecture-specific builds report actual component-level compressed and instal
| Package state | Electron RunAsNode executes immutable core resources; bundled pnpm modifies only the external plugin graph in the Desktop profile. |
| Qualification | macOS packaging requires the configured company identity and notary credentials, verifies every native runtime file before inventory generation, verifies the completed application signature, and requires notarization plus Gatekeeper acceptance for both the application and DMG. Windows packaging requires the configured public certificate, SafeNet private-key container, Token Password, and SignTool, and verifies every produced signature. Update hosting, previous-version installed-artifact tests, and platform GUI recordings remain release-environment gates. |
`dev:desktop` builds the current workspace, projects the built CLI and private Desktop Host packages plus their dependency links into a disposable project, uses the normal Harness home, opens the Main, Renderer, and Host debuggers, and starts unpackaged Electron without preparing release resources. The disposable project supplies the workspace links; the `$DSH_HOME/profiles/desktop` plugin profile, its plugin management and recovery are shared with the installed application, so a workspace build can install plugins or write data formats that the installed version rejects. Fixed macOS arm64, macOS x64, and Windows x64 package commands pass one target through runtime preparation, dsh preparation, and electron-builder; each also has an unpacked-directory variant for release-path verification before installer generation.
`dev:desktop` builds the current workspace, projects the built CLI and private Desktop Host packages plus their dependency links into a disposable project, uses an isolated Harness home, opens the Main, Renderer, and Host debuggers, and starts unpackaged Electron without preparing release resources. The development runtime supplies workspace links to a separate plugin profile; plugin management and recovery use the same flow as packaged applications. Fixed macOS arm64, macOS x64, and Windows x64 package commands pass one target through runtime preparation, dsh preparation, and electron-builder; each also has an unpacked-directory variant for release-path verification before installer generation.
## Alternatives considered
@@ -24,7 +24,7 @@ Electron 拥有 `.dsh/profiles/desktop` 保留 profile。[内置运行时决策]
一个 Desktop 发布号同时标识 Electron 产物及其精确的 `@deepseek-ai/dsh` 与 `@deepseek-ai/dsh-desktop-host` 依赖。发布不能在构建或运行时选择不同的核心版本。因此,即使壳代码没有变化,更新 dsh 也必须产生新的 Electron 发布。
Desktop Host 为保留 profile 提供共享 Web 插件管理器,并通过启动器信息提供内置 pnpm。CLI 保留 `desktop` 名称的所有大小写变体,并拒绝针对它的启动、配置 dump 和插件管理请求。Electron 在 profile 恢复或 Host 启动前获取按其 `userData` 目录区分的进程生命周期单实例锁;使用相同 `userData` 的后续启动只会聚焦或重建主窗口,不会接触 profile 状态。`userData` 不同的应用(例如已安装应用与 `dev:desktop`)可以同时运行在同一个 profile 上。
Desktop Host 为保留 profile 提供共享 Web 插件管理器,并通过启动器信息提供内置 pnpm。CLI 保留 `desktop` 名称的所有大小写变体,并拒绝针对它的启动、配置 dump 和插件管理请求。Electron 在 profile 恢复或 Host 启动前获取进程生命周期单实例锁;后续启动只会聚焦或重建主窗口,不会接触 profile 状态。
## 归属
@@ -63,7 +63,7 @@ Desktop Host 为保留 profile 提供共享 Web 插件管理器,并通过启
共享 Web 插件管理器负责 profile 包操作。Electron 保留启动准备和原生恢复;[Web 薄壳决策](2026-09-10-desktop-web-wrapper.zh.md)负责这一职责划分。
在共享同一 `userData` 目录的 Desktop 进程之间,Electron 进程生命周期锁是权威所有者。profile 准备和原生恢复使用记录 Electron PID 的排他锁;存活的所有者阻止竞争操作,失效 PID 可被回收。Web 包操作使用共享插件管理器的锁。
Electron 进程生命周期锁是 Desktop 的权威所有者。profile 准备和原生恢复使用记录 Electron PID 的排他锁;存活的所有者阻止竞争操作,失效 PID 可被回收。Web 包操作使用共享插件管理器的锁。
核心物化、首次启动、插件安装和共享模块解析遵循[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)。实际 Host 启动时会组合已启用且提供 `dsh.client` 代码的桌面插件。
@@ -73,7 +73,7 @@ Electron 更新只使用一个 `electron-updater` 发布流和签名 `electron-b
[立即显示窗口参考](../../../../apps/desktop/README.zh.md)负责本地加载页、直接启动 Host 和主窗口恢复。profile 协调遵循[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)。
`DSH_DESKTOP_AUTO_UPDATE_ENV` 默认为测试部署,也可以选择生产部署,并同时决定目标专用的 generic-provider URL 与 COS 目标。发布自动化通过 `DOWNLOAD_TEST_ORIGIN` 提供测试 HTTPS origin,并通过 `DOWNLOAD_TEST_COS_BUCKET` 或 `DOWNLOAD_PROD_COS_BUCKET` 提供各部署的 bucket;可变的测试路由与 COS 存储身份不写入源码,部署基础设施变更时无需发布新代码,而公开的生产 origin 仍固定。打包只解析公开更新 URL、禁止 electron-builder 发布、从子进程环境中删除每个 COS 凭据字段,并且只有在 electron-builder 以及每个签名或公证 hook 成功后才写入完成记录。目标上传还必须提供所选 bucket,随后会先要求完成记录、根 dsh 版本、Desktop 版本、根据所选渠道确定的元数据、产物名称、大小与 SHA-512 全部一致,再读取所选凭据或发送数据。它先上传不可变且带版本的更新载荷与所有独立 blockmap,最后替换 electron-builder 生成的频道元数据,并且不会删除历史对象。所选渠道决定元数据名称:`stable.yml` 或 `nightly.yml`,macOS 在扩展名前加 `-mac`;版本后缀不决定渠道。NSIS 把 blockmap 嵌入已签名的可执行文件,macOS ZIP 则使用独立 blockmap;两者都让 electron-updater 在平台支持时只下载变化的数据块,而应用替换与本地 pnpm 包操作仍是两个独立操作;默认 `stable` 锁定、`settings.json` 版本 `"1"`、清单来源请求头以及单包多渠道 CI 投递由[渠道收敛与解耦发布决策](2026-11-25-desktop-channel-convergence-and-decoupled-publishing.zh.md)负责。
`DSH_DESKTOP_AUTO_UPDATE_ENV` 默认为测试部署,也可以选择生产部署,并同时决定目标专用的 generic-provider URL 与 COS 目标。发布自动化通过 `DOWNLOAD_TEST_ORIGIN` 提供测试 HTTPS origin,并通过 `DOWNLOAD_TEST_COS_BUCKET` 或 `DOWNLOAD_PROD_COS_BUCKET` 提供各部署的 bucket;可变的测试路由与 COS 存储身份不写入源码,部署基础设施变更时无需发布新代码,而公开的生产 origin 仍固定。打包只解析公开更新 URL、禁止 electron-builder 发布、从子进程环境中删除每个 COS 凭据字段,并且只有在 electron-builder 以及每个签名或公证 hook 成功后才写入完成记录。目标上传还必须提供所选 bucket,随后会先要求完成记录、根 dsh 版本、Desktop 版本、根据所选渠道确定的元数据、产物名称、大小与 SHA-512 全部一致,再读取所选凭据或发送数据。它先上传不可变且带版本的更新载荷与所有独立 blockmap,最后替换 electron-builder 生成的频道元数据,并且不会删除历史对象。所选渠道决定元数据名称:`stable.yml` 或 `nightly.yml`,macOS 在扩展名前加 `-mac`;版本后缀不决定渠道。NSIS 把 blockmap 嵌入已签名的可执行文件,macOS ZIP 则使用独立 blockmap;两者都让 electron-updater 在平台支持时只下载变化的数据块,而应用替换与本地 pnpm 包操作仍是两个独立操作。
测试发布必须从平台 dotenv 文件提供 `DOWNLOAD_TEST_RELEASE_ID`。清单和安装包共用 `dsh-desk/<release-id>/`,生产环境保留固定目录。ID 是打包更新 URL 的一部分,因此上传会拒绝不同的 ID。轮换后可通过内部分发提供新安装包,已安装客户端保留原清单地址。随机目录降低被猜中的概率,但不对持有链接者进行鉴权。[发布配置](../../../../apps/desktop/publishing/README.zh.md#upload-updates)定义生成与复用方式。
@@ -106,7 +106,7 @@ Windows 应用替换遵循[目录安装参考](../../../../apps/desktop/packagin
| 包状态 | Electron RunAsNode 执行不可变核心资源;内置 pnpm 只修改 Desktop profile 中的外部插件依赖图。 |
| 资格验证 | macOS 打包要求已配置的公司身份与公证凭据可用,在生成清单前验证每个原生运行时文件,验证完整应用签名,并要求应用和 DMG 都完成公证且通过 Gatekeeper。Windows 打包要求已配置的公开证书、SafeNet 私钥容器、Token Password 与 SignTool,并验证生成的每个签名。更新托管、跨上一版本的已安装产物测试和各平台 GUI 录制仍是发布环境门槛。 |
`dev:desktop` 会构建当前 workspace,把已构建 CLI 包、私有 Desktop Host 包及其依赖链接投影为一次性项目,使用正常的 Harness home,打开 Main、Renderer 和 Host 调试器,并在不准备发布资源的情况下启动未打包 Electron。一次性项目提供工作区链接;`$DSH_HOME/profiles/desktop` 插件 profile 及其插件管理和恢复与已安装应用共享,因此工作区构建可能安装插件或写入已安装版本拒绝的数据格式。固定的 macOS arm64、macOS x64 与 Windows x64 打包命令会把同一目标传给运行时准备、dsh 准备和 electron-builder;每条命令还提供未封装安装器的变体,用于在生成安装器前验证发布路径。
`dev:desktop` 会构建当前 workspace,把已构建 CLI 包、私有 Desktop Host 包及其依赖链接投影为一次性项目,使用隔离的 Harness home,打开 Main、Renderer 和 Host 调试器,并在不准备发布资源的情况下启动未打包 Electron。开发运行时为独立的插件 profile 提供工作区链接;插件管理和恢复使用与打包应用相同的流程。固定的 macOS arm64、macOS x64 与 Windows x64 打包命令会把同一目标传给运行时准备、dsh 准备和 electron-builder;每条命令还提供未封装安装器的变体,用于在生成安装器前验证发布路径。
## 考虑过的替代方案
@@ -6,26 +6,26 @@
en: 4f48d3f949d8e3eb
zh: 4060f4e66c36439e
/agent-note-workspace-file-service/problem:
en: c73bcfaa20a793ca
zh: 4c8a29e8d9a59e9a
en: 55d969715a48c9b3
zh: 755dab7523cd01c2
/agent-note-workspace-file-service/decision:
en: 99ae4bb7b6af4d98
zh: 2f71c2bcf42d423c
en: 17137a4e49e56470
zh: ed08cf3d2d7348c8
/agent-note-workspace-file-service/decision/package-topology:
en: d7c976eea9f0ba46
zh: d56fe8dbdca72fda
en: 5a8d81c95c031663
zh: 5bdeebe3b5e759c9
/agent-note-workspace-file-service/decision/the-workspacefiles-file-operations:
en: ec6c2626c837dfb4
zh: 3d5dcd982e6ec64f
en: 434a2f6b3fab4756
zh: ea83124d00c6a79c
/agent-note-workspace-file-service/decision/paths-on-the-wire:
en: 7b5a96adc08177bc
zh: ae4692e5e62e7de0
/agent-note-workspace-file-service/decision/file-checks-and-workspace-containment:
en: e0e1bd03d063d306
zh: bbfe08605b3e51f9
en: 1b588f346590a0fd
zh: 1cdac02b967b157f
/agent-note-workspace-file-service/decision/failures:
en: 300dfdb0a6be6884
zh: 79d0ab01cdb0eb85
en: 0e419dd7bdcf38ba
zh: 6cb588a77593913c
/agent-note-workspace-file-service/decision/configuration:
en: 796ee295af0895bd
zh: 4dfa113ed19f5f9a
@@ -39,8 +39,8 @@
en: ef015f605f7b00ab
zh: eee9c79faebf3dff
/agent-note-workspace-file-service/alternatives-considered:
en: d2b8b9fbd0c5f0cd
zh: b5064351042027b7
en: c750d88e0e746a99
zh: 9e904ad4172fda49
/agent-note-workspace-file-service/consequences:
en: 246bb7aed62f6c9b
zh: debf6d4129ee477b
@@ -8,15 +8,15 @@ English | [中文](2026-09-05-workspace-files-service.zh.md)
The Web client needs to look at files inside a session's workspace from a browser that may not be on the Host machine: a file the agent produced, the path a `read` tool row names, later a file tree and previews of files that are neither small nor text. The one endpoint that read a workspace file over the wire lived on the Session Controller as `workspace-file.ts`, beside session lifecycle it had nothing to do with. It returned a whole file under one total byte cap, so a large log could not be looked at even in part and a binary could not be looked at at all; it had no `stat`, no listing, and no change signal, so a preview could not learn that the agent had rewritten the file without re-reading it; and its result named the file by a Host `url`, a spelling nothing on the Client used as an address.
Two constraints frame the service. File reads through `ctx.fs` use the Session's composed filesystem backend, whose read authority may extend outside the workspace, while directory-tree and change-feed consumers are workspace-rooted. The service preserves the backend's read decisions for regular files while enforcing file-kind and bounded-buffer checks; `list` and `changes` apply a workspace check to directories. And `dsh-fs` exposed one raw-byte read, `readBytes(target, signal, maxBytes)`, which refuses any file longer than its cap: correct for an image the model ingests whole, useless for one window of a large file.
Two constraints frame the service. File reads through `ctx.fs` use the Session's composed filesystem backend, whose read authority may extend outside the workspace, while directory-tree and change-feed consumers are workspace-rooted. The service preserves the backend's read decisions for regular files while enforcing file-kind and bounded-buffer checks; `list` and `changes` retain workspace containment. And `dsh-fs` exposed one raw-byte read, `readBytes(target, signal, maxBytes)`, which refuses any file longer than its cap: correct for an image the model ingests whole, useless for one window of a large file.
## Decision
`packages/api/workspace-files` (`@deepseek-ai/dsh-api-workspace-files`) owns the Host `ctx.workspaceFiles` service, the `workspaceFiles` Remote namespace, and the Client `file` provider that turns `stat` and `changes` into live metadata for the [resource model](2026-09-05-client-resource-model.md); [dual-face packaging](../../../../packages/api/workspace-files/README.md) governs their package organization. File methods resolve relative paths from the workspace root but inherit the Session filesystem backend's read authority; `list` and `changes` accept a directory that resolves inside the workspace root or whose path descends from it. The [workspace file read authority](2026-09-09-workspace-file-read-authority.md) owns this split and its security consequences, and [directory links outside the workspace root](2026-11-20-workspace-directory-links-outside-root.md) owns the directory rule. Results name files by their absolute path in the filesystem's execution world, and content is bounded by page, byte window, or complete-file cap. The byte window rides on a new `dsh-fs` seam, `FileSystem.readByteRange`, implemented by every provider. The Session Controller carries no workspace-file code.
`packages/api/workspace-files` (`@deepseek-ai/dsh-api-workspace-files`) owns the Host `ctx.workspaceFiles` service, the `workspaceFiles` Remote namespace, and the Client `file` provider that turns `stat` and `changes` into live metadata for the [resource model](2026-09-05-client-resource-model.md); [dual-face packaging](../../../../packages/api/workspace-files/README.md) governs their package organization. File methods resolve relative paths from the workspace root but inherit the Session filesystem backend's read authority; `list` and `changes` remain workspace-scoped. The [workspace file read authority](2026-09-09-workspace-file-read-authority.md) owns this split and its security consequences. Results name files by their absolute path in the filesystem's execution world, and content is bounded by page, byte window, or complete-file cap. The byte window rides on a new `dsh-fs` seam, `FileSystem.readByteRange`, implemented by every provider. The Session Controller carries no workspace-file code.
### Package topology
[dual-face packaging](../../../../packages/api/workspace-files/README.md) supersedes this note's choice of separate Host and Client packages; the file service, paging, and change-feed decisions here remain in force. The [workspace file read authority](2026-09-09-workspace-file-read-authority.md) supersedes the original workspace-containment choice for file methods, and [directory links outside the workspace root](2026-11-20-workspace-directory-links-outside-root.md) supersedes judging a `list` or `changes` directory by its resolved target alone. Host and Client compile in separate leaf configurations, share wire types, and the Client does not import the Host runtime entry.
[dual-face packaging](../../../../packages/api/workspace-files/README.md) supersedes this note's choice of separate Host and Client packages; the file service, paging, and change-feed decisions here remain in force. The [workspace file read authority](2026-09-09-workspace-file-read-authority.md) supersedes the original workspace-containment choice for file methods. Host and Client compile in separate leaf configurations, share wire types, and the Client does not import the Host runtime entry.
| Face | Package | Files | Depends on |
|---|---|---|---|
@@ -41,7 +41,7 @@ Every Host method takes `WorkspaceFileScope` first. The `workspaceFileScope` Gat
- **`read`** returns one window of lines, `WorkspaceFileText = WorkspaceFileStat & { offset, text, lines, eof }`; `lines` counts the page's lines, so a page holding one empty line (`text: ''`, `lines: 1`) and a page past the end (`lines: 0`) read differently. `range.offset` is the 1-based first line and defaults to 1; `range.limit` is the largest number of lines and defaults to `maxLines`, which it may not exceed. Lines end at `\n` and a final `\n` terminates the last line rather than opening an empty one; `text` joins the page's lines with `\n` and carries no terminator; `eof` is true when the page includes the last line, and an offset past the end returns an empty page with `eof` true. The pager walks `streamText`, counts the lines before the window without keeping them, admits each in-window segment against `maxBytes` before buffering it, and returns at the first character past the window, so a file of any size costs one page of memory. The `version` and `bytes` on a page are the stat's, taken before the stream.
- **`readBytes`** returns native bytes with file metadata, offset, and EOF. The required options object selects a complete read under `maxFileBytes` when `range` is absent, or a bounded window under `maxBytes` when present. `range: {}` uses offset zero and the configured window cap; windows can read files above the complete-file cap. The [binary transfer decision](2026-09-17-workspace-file-binary-transfer.md) owns the Remote response encoding.
- **`baseFile`** selects target resolution independently of `range`: the target `path` must be relative and resolves from the base file's directory. The Host applies regular-file checks to both files and preserves backend read authority. [Document Preview](2026-09-08-document-preview-operations.md) owns content loading and address semantics.
- **`list`** returns `WorkspaceDirectoryListing { path, entries, truncated }`: the listed directory as a workspace path relative to the root (empty for the root), its direct children in the backend's stable name order as `{ name, type, size? }`, and whether `maxEntries` cut the list. `type` is `file`, `directory`, or `other`; a symlink child reports the type of what it points to and a dangling one is `other`. A child the listing reports as a directory opens through its resolved target, including a Windows junction, and the listing then names that target when it is inside the root and its child names below the root when it is outside; [directory link listing](../../../../packages/api/workspace-files/README.md) owns the rule. Dotfiles are listed; nothing is filtered.
- **`list`** returns `WorkspaceDirectoryListing { path, entries, truncated }`: the listed directory as a workspace path relative to the root (empty for the root), its direct children in the backend's stable name order as `{ name, type, size? }`, and whether `maxEntries` cut the list. `type` is `file`, `directory`, or `other`; a symlink child reports the type of what it points to and a dangling one is `other`. A child the listing reports as a directory opens through its resolved target, including a Windows junction, and the listing then names that target; [directory link listing](../../../../packages/api/workspace-files/README.md) owns the rule. Dotfiles are listed; nothing is filtered.
- **`changes`** yields `WorkspaceFileWatchFrame`: `{ kind: 'ready' }` after the observation queue is registered and the workspace root resolves, followed by `{ kind: 'change', change }`. The `WorkspaceFileChange` payload is `{ absolutePath, version }` for a present file or `{ absolutePath, absent: true }` for one observed gone. Its source is `fs/observed` inside the workspace root, never an OS watcher. Observations after the first pull are queued, including during root resolution; cancellation or plugin disposal ends the generation.
### Paths on the wire
@@ -52,14 +52,14 @@ Two path vocabularies leave the service, and each method uses exactly one. `read
### File checks and workspace containment
`read`, `readBytes`, and `stat` share regular-file checks and then rely on the filesystem backend's read authority. `list` shares path inspection but also applies the workspace check, while `changes` applies it to a watched directory. The service applies the following checks:
`read`, `readBytes`, and `stat` share regular-file checks and then rely on the filesystem backend's read authority. `list` shares path inspection but also checks workspace containment, while `changes` filters observations to the workspace root. The service applies the following checks:
1. **The path itself.** `lstat` inspects the path before anything follows it: a missing path is `not-found`, and a symlink — wherever it points, including back inside the workspace — is `not-regular-file` (kind `symlink`) for the file methods. `list` instead follows a final link and judges the resolved target: the target must stat as a directory, and a link to a file or a link whose target is gone is `not-directory` (kind `symlink`). An empty path is a `gateway/bad-request`.
2. **The workspace check for `list`.** The directory resolves to a target and passes when `ctx.fs.contains(root, target)` holds, where `root` is the `WorkspaceFileScope.workspaceRoot` resolved from the selected Session header, or when the path the backend resolved, in its unresolved spelling, descends from that root by child names without a `..` segment. An absolute directory outside the root, or a `..` traversal that resolves outside it, is `outside-workspace`. `changes` applies the same check to a watched directory.
2. **Workspace containment for `list`.** The directory resolves to a target and `ctx.fs.contains(root, target)` decides, where `root` is the `WorkspaceFileScope.workspaceRoot` resolved from the selected Session header. A `..` traversal or an absolute directory outside the root is `outside-workspace`. `changes` applies the same backend containment predicate to observed targets.
3. **The caps.** A page or window above `maxBytes`, or a `read` asking for more than `maxLines`, is refused, never shortened, because a silently cut page reads as the whole page; a listing above `maxEntries` is cut and says so. Complete and related-file reads are refused above `maxFileBytes`.
4. **Text.** For `read` only: content that is not UTF-8 up to the end of the page, a NUL byte in the backend's 8 KiB opening sample, or a NUL byte anywhere in the page is `not-text`; bytes past the page are not inspected.
After path inspection the file methods `stat` the resolved target once more, because the file may have gone or changed kind before the read: a vanished file is `not-found` and a replaced one `not-regular-file` with the new kind. For `list`, an outside entry whose type already disqualifies it reports its kind before its position; a final link resolves and passes the workspace check before its target kind is read.
After path inspection the file methods `stat` the resolved target once more, because the file may have gone or changed kind before the read: a vanished file is `not-found` and a replaced one `not-regular-file` with the new kind. For `list`, an outside entry whose type already disqualifies it reports its kind before its position; a final link resolves and passes containment before its target kind is read.
### Failures
@@ -68,7 +68,7 @@ Each failure is one `RemoteError` code with typed details, declared beside the t
| Code | When | Details |
|---|---|---|
| `workspace-file/not-found` | no entry at the path, or the file vanished after the gates | `{ path }` |
| `workspace-file/outside-workspace` | a `list` or watched directory neither resolves inside the workspace root nor has a path that descends from it | `{ path }` |
| `workspace-file/outside-workspace` | a `list` target is not inside the workspace root | `{ path }` |
| `workspace-file/too-large` | a page's text or byte window exceeds `maxBytes`, or a complete read exceeds `maxFileBytes` | `{ path, limit }` |
| `workspace-file/not-text` | invalid UTF-8 up to the page's end, or a NUL byte in the sample or the page (`read` only) | `{ path }` |
| `workspace-file/not-regular-file` | `read`, `readBytes`, or `stat` on something that is not a regular file | `{ path, kind: 'directory' \| 'symlink' \| 'other' }` |
@@ -125,7 +125,7 @@ The [resource model](2026-09-05-client-resource-model.md) owns `ctx.resources`,
**A default `readByteRange` in the `FileSystem` base class.** A non-abstract default over `readBytes` would have spared the test doubles a method but could only be implemented by reading the whole file up to the window's end, the very behaviour rejected above, or by passing an unbounded cap. Abstract, with every provider and double implementing it.
**String-prefix containment for workspace operations.** Comparing resolved path strings against the root is simpler than `fs.contains`, but `resolve` realpaths, so a symlink that leaves the root resolves to a path outside it while a prefix test on the unresolved spelling passes; and a prefix test on the resolved spelling still needs the backend's notion of "same file". The filesystem decides containment for `list` and `changes`; a path whose unresolved backend spelling descends from the root passes in addition, under [directory links outside the workspace root](2026-11-20-workspace-directory-links-outside-root.md).
**String-prefix containment for workspace operations.** Comparing resolved path strings against the root is simpler than `fs.contains`, but `resolve` realpaths, so a symlink that leaves the root resolves to a path outside it while a prefix test on the unresolved spelling passes; and a prefix test on the resolved spelling still needs the backend's notion of "same file". The filesystem decides containment for `list` and `changes`.
## Consequences
@@ -8,15 +8,15 @@ Status: implemented
Web 客户端需要从一个未必在 Host 机器上的浏览器查看会话工作区里的文件:agent 产出的文件、`read` 工具行点名的路径,之后还有文件树,以及既不小也不是文本的文件预览。唯一一个经线路读取工作区文件的端点以 `workspace-file.ts` 住在 Session Controller 上,与它毫无关系的会话生命周期为邻。它在一个总字节上限之下返回整个文件,因此大日志连一部分都看不了、二进制根本看不了;它没有 `stat`、没有列举、没有变更信号,预览不重读就无法得知 agent 已改写文件;其结果还以 Host 的 `url` 命名文件,而 Client 上没有任何东西把这种拼法当地址用。
两个约束框定了这项服务。经 `ctx.fs` 的文件读取使用 Session 组合后的文件系统后端,其读取权限可能延伸到工作区外,而目录树与变更流消费方以工作区为根。服务为普通文件保留后端的读取决策,同时执行文件类型与有界缓冲检查;`list` 与 `changes` 对目录执行工作区检查。另外 `dsh-fs` 只暴露一种原始字节读取 `readBytes(target, signal, maxBytes)`,它拒绝任何比上限更长的文件:对模型整体摄入的图片是正确的,对大文件的一个窗口则毫无用处。
两个约束框定了这项服务。经 `ctx.fs` 的文件读取使用 Session 组合后的文件系统后端,其读取权限可能延伸到工作区外,而目录树与变更流消费方以工作区为根。服务为普通文件保留后端的读取决策,同时执行文件类型与有界缓冲检查;`list` 与 `changes` 保留工作区包含限制。另外 `dsh-fs` 只暴露一种原始字节读取 `readBytes(target, signal, maxBytes)`,它拒绝任何比上限更长的文件:对模型整体摄入的图片是正确的,对大文件的一个窗口则毫无用处。
## Decision
`packages/api/workspace-files`(`@deepseek-ai/dsh-api-workspace-files`)同时拥有 Host 服务 `ctx.workspaceFiles`、`workspaceFiles` Remote 命名空间,以及将 `stat` 与 `changes` 转成[资源模型](2026-09-05-client-resource-model.zh.md)实时元数据的 Client `file` 提供者;包组织方式由[双面包组织](../../../../packages/api/workspace-files/README.zh.md)规定。文件方法从工作区根解析相对路径,但继承 Session 文件系统后端的读取权限;`list` 与 `changes` 接受解析到工作区根内、或路径由工作区根逐级向下写出的目录。[工作区文件读取权限](2026-09-09-workspace-file-read-authority.zh.md)拥有这一分层及其安全后果,[工作区根外的目录链接](2026-11-20-workspace-directory-links-outside-root.zh.md)拥有目录规则。结果以文件在文件系统执行环境中的绝对路径命名文件,内容则受页、字节窗口或整文件上限约束。字节窗口依托 `dsh-fs` 新增的 seam `FileSystem.readByteRange`,由每个提供者实现。Session Controller 不再携带任何工作区文件代码。
`packages/api/workspace-files`(`@deepseek-ai/dsh-api-workspace-files`)同时拥有 Host 服务 `ctx.workspaceFiles`、`workspaceFiles` Remote 命名空间,以及将 `stat` 与 `changes` 转成[资源模型](2026-09-05-client-resource-model.zh.md)实时元数据的 Client `file` 提供者;包组织方式由[双面包组织](../../../../packages/api/workspace-files/README.zh.md)规定。文件方法从工作区根解析相对路径,但继承 Session 文件系统后端的读取权限;`list` 与 `changes` 仍限于工作区。[工作区文件读取权限](2026-09-09-workspace-file-read-authority.zh.md)拥有这一分层及其安全后果。结果以文件在文件系统执行环境中的绝对路径命名文件,内容则受页、字节窗口或整文件上限约束。字节窗口依托 `dsh-fs` 新增的 seam `FileSystem.readByteRange`,由每个提供者实现。Session Controller 不再携带任何工作区文件代码。
### 包拓扑
[双面包组织](../../../../packages/api/workspace-files/README.zh.md)取代本记录中把 Host 与 Client 分成两个包的组织选择;这里的文件服务、分页和变更流约定保持不变。[工作区文件读取权限](2026-09-09-workspace-file-read-authority.zh.md)取代文件方法原有的工作区包含选择,[工作区根外的目录链接](2026-11-20-workspace-directory-links-outside-root.zh.md)取代只按解析后的目标判定 `list` 或 `changes` 目录的做法。Host 与 Client 分别编译在两个叶配置中,共享线路类型,Client 不导入 Host 运行时入口。
[双面包组织](../../../../packages/api/workspace-files/README.zh.md)取代本记录中把 Host 与 Client 分成两个包的组织选择;这里的文件服务、分页和变更流约定保持不变。[工作区文件读取权限](2026-09-09-workspace-file-read-authority.zh.md)取代文件方法原有的工作区包含选择。Host 与 Client 分别编译在两个叶配置中,共享线路类型,Client 不导入 Host 运行时入口。
| 面 | 包 | 文件 | 依赖 |
|---|---|---|---|
@@ -41,7 +41,7 @@ Web 客户端需要从一个未必在 Host 机器上的浏览器查看会话工
- **`read`** 返回一个行窗口 `WorkspaceFileText = WorkspaceFileStat & { offset, text, lines, eof }`;`lines` 计页内行数,使只含一个空行的页(`text: ''`、`lines: 1`)与越过文件末尾的页(`lines: 0`)可区分。`range.offset` 是 1 起算的首行,缺省 1;`range.limit` 是最多行数,缺省 `maxLines` 且不得超过。行以 `\n` 结束,末尾的 `\n` 终止最后一行而不是开启一空行;`text` 以 `\n` 连接本页各行且不带终止符;页含最后一行时 `eof` 为 true,越过末尾的 offset 返回 `eof` 为 true 的空页。切页器沿 `streamText` 前进,数过窗口前的行而不保留,把每个窗内片段先按 `maxBytes` 核准再缓冲,并在越过窗口的第一个字符处返回,因此任意大小的文件只花一页内存。页上的 `version` 与 `bytes` 来自流之前的那次 stat。
- **`readBytes`** 返回原生字节、文件元数据、偏移量和 EOF。必填选项对象未传 `range` 时,在 `maxFileBytes` 上限内完整读取;传入时,在 `maxBytes` 上限内读取有界窗口。`range: {}` 使用零偏移和配置的窗口上限;窗口可读取超过完整文件上限的文件。[二进制传输决议](2026-09-17-workspace-file-binary-transfer.zh.md)负责 Remote 响应编码。
- **`baseFile`** 独立于 `range` 选择目标解析方式:目标 `path` 必须为相对路径,从基准文件所在目录解析。Host 对两个文件执行普通文件检查,并保留后端读取权限。[Document Preview](2026-09-08-document-preview-operations.zh.md)负责内容加载与地址语义。
- **`list`** 返回 `WorkspaceDirectoryListing { path, entries, truncated }`:被列目录相对根的工作区路径(根为空串)、其直接子项按后端的稳定名序以 `{ name, type, size? }` 给出,以及 `maxEntries` 是否截断了列表。`type` 为 `file`、`directory` 或 `other`;符号链接子项报告其指向目标的类型,悬空者为 `other`。列表报告为目录的子项经其解析目标打开,Windows 目录联接亦然,此时列表在该目标位于根内时以它命名,位于根外时以其在根下的子项名称命名;[目录链接列举](../../../../packages/api/workspace-files/README.zh.md)拥有该规则。dotfile 照常列出,不做任何过滤。
- **`list`** 返回 `WorkspaceDirectoryListing { path, entries, truncated }`:被列目录相对根的工作区路径(根为空串)、其直接子项按后端的稳定名序以 `{ name, type, size? }` 给出,以及 `maxEntries` 是否截断了列表。`type` 为 `file`、`directory` 或 `other`;符号链接子项报告其指向目标的类型,悬空者为 `other`。列表报告为目录的子项经其解析目标打开,Windows 目录联接亦然,此时列表以该目标命名;[目录链接列举](../../../../packages/api/workspace-files/README.zh.md)拥有该规则。dotfile 照常列出,不做任何过滤。
- **`changes`** 产出 `WorkspaceFileWatchFrame`:在观察队列注册且工作区根解析完成后先发 `{ kind: 'ready' }`,随后为 `{ kind: 'change', change }`。载荷 `WorkspaceFileChange` 对存在的文件为 `{ absolutePath, version }`,对消失的文件为 `{ absolutePath, absent: true }`。来源是工作区根内的 `fs/observed`,不监视操作系统。首次拉取后的观察都会排队,包括根解析期间的观察;取消或插件释放会结束该代流。
### 线路上的路径
@@ -52,14 +52,14 @@ Web 客户端需要从一个未必在 Host 机器上的浏览器查看会话工
### 文件检查与工作区包含
`read`、`readBytes` 与 `stat` 共享普通文件检查,之后依赖文件系统后端的读取权限。`list` 共享路径检查,但还会执行工作区检查;`changes` 则对被监听的目录执行该检查。服务执行以下检查:
`read`、`readBytes` 与 `stat` 共享普通文件检查,之后依赖文件系统后端的读取权限。`list` 共享路径检查,但还会检查工作区包含关系;`changes` 则把观察过滤到工作区根内。服务执行以下检查:
1. **路径本身。** `lstat` 在跟随任何东西之前检查路径:缺失路径为 `not-found`;符号链接——不论指向哪里,包括指回工作区内——对文件方法为 `not-regular-file`(kind 为 `symlink`)。`list` 改为跟随末端链接并判定解析后的目标:目标经 stat 必须为目录,指向文件的链接或目标已消失的链接为 `not-directory`(kind 为 `symlink`)。空路径是 `gateway/bad-request`。
2. **`list` 的工作区检查。** 目录解析为目标,在 `ctx.fs.contains(root, target)` 成立时通过,其中 `root` 是从所选 Session header 解析出的 `WorkspaceFileScope.workspaceRoot`;后端所解析路径的未解析写法由该根逐级经子项名称向下写出且不含 `..` 段时也通过。根外绝对目录,或解析到根外的 `..` 路径,为 `outside-workspace`。`changes` 对被监听的目录执行同一检查。
2. **`list` 的工作区包含。** 目录解析为目标,由 `ctx.fs.contains(root, target)` 判定,其中 `root` 是从所选 Session header 解析出的 `WorkspaceFileScope.workspaceRoot`。`..` 爬出或根外绝对目录为 `outside-workspace`。`changes` 对观察到的目标使用相同的后端包含判定。
3. **上限。** 超过 `maxBytes` 的页或窗口,或 `read` 索要超过 `maxLines` 的行数,一律拒绝、绝不截短,因为悄悄截短的页读起来就像整页;超过 `maxEntries` 的列表被截断并如实报告。全文及关联文件读取超过 `maxFileBytes` 时被拒绝。
4. **文本。** 仅限 `read`:到页末为止不是 UTF-8 的内容、后端 8 KiB 开头样本里的 NUL 字节,或页内任何位置的 NUL 字节,都是 `not-text`;页之后的字节不检查。
路径检查之后,文件方法再对解析出的目标 `stat` 一次,因为文件可能在读取前已消失或换了种类:消失者为 `not-found`,被替换者为带新种类的 `not-regular-file`。对 `list` 而言,根外条目若类型本身已不合格,会先报告其种类而不是位置;末端链接先解析并通过工作区检查,再读取其目标种类。
路径检查之后,文件方法再对解析出的目标 `stat` 一次,因为文件可能在读取前已消失或换了种类:消失者为 `not-found`,被替换者为带新种类的 `not-regular-file`。对 `list` 而言,根外条目若类型本身已不合格,会先报告其种类而不是位置;末端链接先解析并通过包含检查,再读取其目标种类。
### 失败
@@ -68,7 +68,7 @@ Web 客户端需要从一个未必在 Host 机器上的浏览器查看会话工
| 代码 | 何时 | Details |
|---|---|---|
| `workspace-file/not-found` | 路径处无条目,或文件在过关后消失 | `{ path }` |
| `workspace-file/outside-workspace` | `list` 或被监听的目录既不解析到工作区根内,其路径也不是由工作区根向下写出 | `{ path }` |
| `workspace-file/outside-workspace` | `list` 的目标不在工作区根内 | `{ path }` |
| `workspace-file/too-large` | 一页文本或字节窗口超过 `maxBytes`,或全文读取超过 `maxFileBytes` | `{ path, limit }` |
| `workspace-file/not-text` | 到页末为止的非法 UTF-8,或样本或页内的 NUL 字节(仅 `read`) | `{ path }` |
| `workspace-file/not-regular-file` | 对非普通文件执行 `read`、`readBytes` 或 `stat` | `{ path, kind: 'directory' \| 'symlink' \| 'other' }` |
@@ -125,7 +125,7 @@ Client 导出向 `ctx.resources` 注册一个 `ResourceProvider<'file'>`,存
**在 `FileSystem` 基类里给 `readByteRange` 一个默认实现。** 基于 `readBytes` 的非抽象默认能免去测试替身一个方法,但只能靠把文件从头读到窗口末端来实现——正是上文否决的行为——或者传一个无界上限。改为抽象方法,由每个提供者与替身实现。
**工作区操作使用字符串前缀包含判定。** 把解析后的路径字符串与根比较比 `fs.contains` 简单,但 `resolve` 会取 realpath,离开根的符号链接解析到根外路径,而对未解析拼法的前缀测试会放行;对已解析拼法的前缀测试也仍需后端对"同一文件"的定义。`list` 与 `changes` 由文件系统判定包含关系;按[工作区根外的目录链接](2026-11-20-workspace-directory-links-outside-root.zh.md),后端未解析写法由根向下写出的路径也可通过。
**工作区操作使用字符串前缀包含判定。** 把解析后的路径字符串与根比较比 `fs.contains` 简单,但 `resolve` 会取 realpath,离开根的符号链接解析到根外路径,而对未解析拼法的前缀测试会放行;对已解析拼法的前缀测试也仍需后端对"同一文件"的定义。`list` 与 `changes` 由文件系统判定包含关系。
## Consequences
@@ -9,8 +9,8 @@
en: a35075e6babe3f7a
zh: 3a64ac57761e1009
/agent-note-document-preview-and-file-addresses/decision:
en: efed703b02c2a460
zh: 22e5a451991b96fe
en: 75b40970e401f2e3
zh: 970b2cc044ea17f4
/agent-note-document-preview-and-file-addresses/alternatives-considered:
en: 8e9616e954df488c
zh: 10801341ec53bbe8
@@ -12,7 +12,7 @@ File viewers need different loading policies and may offer several implementatio
Document Preview separates resource observation from content reads. The [resource model](2026-09-05-client-resource-model.md) shares observations by address alone: `source(address)`, `pin(address, signal)`, and provider `open(address, { signal })` carry no consuming Session. Providers return `AsyncIterable<RemoteResult<ResourceProtocolMap[P]>>`; `useResource` exposes only `{ status, value, failure }`. Holds start and stop observation, not the underlying file or Session. Content reads use ordinary injected Preview callbacks.
[Workspace Files](../../../../packages/api/workspace-files/README.md) retains Host line reads, byte windows, bounded complete reads, and bounded reads relative to another file's directory. Its Client `file` provider observes only `stat` and `changes`, with `ResourceProtocolMap.file` directly naming `WorkspaceFileStat`. The Host resolves every path through the Session filesystem; file reads inherit that backend's read authority, while directory listing and directory watching apply the workspace check that the Workspace Files README describes.
[Workspace Files](../../../../packages/api/workspace-files/README.md) retains Host line reads, byte windows, bounded complete reads, and bounded reads relative to another file's directory. Its Client `file` provider observes only `stat` and `changes`, with `ResourceProtocolMap.file` directly naming `WorkspaceFileStat`. The Host resolves every path through the Session filesystem; file reads inherit that backend's read authority, while directory listing and change observation stay workspace-scoped.
Readable files use `dsh-resource://file/session/<sessionId>/<path>`. The path may be workspace-relative or absolute; an encoded absolute path retains its leading slash. `fileAddressFor` always emits this Session-address form. The provider and Preview RPC take the Session only from that address, never from the current selection, first holder, or owning tab. A Session-less `absolute` URI cannot be read; the provider reports `workspace-file/unknown-workspace`. Session authorization is a file-protocol rule, not an additional Resource identity.
@@ -12,7 +12,7 @@ Status: implemented
Document Preview 将资源观察与内容读取分开。[资源模型](2026-09-05-client-resource-model.zh.md)只按地址共享观察:`source(address)`、`pin(address, signal)` 和提供方的 `open(address, { signal })` 均不携带消费 Session。提供方返回 `AsyncIterable<RemoteResult<ResourceProtocolMap[P]>>`;`useResource` 只暴露 `{ status, value, failure }`。持有只控制观察的启停,不控制底层文件或 Session 的生灭。内容通过普通注入的 Preview 回调读取。
[Workspace Files](../../../../packages/api/workspace-files/README.zh.md) 保留 Host 的行读取、字节窗口、有上限的全文读取和相对另一文件目录的有界读取。Client `file` 提供方只观察 `stat` 与 `changes`,`ResourceProtocolMap.file` 直接为 `WorkspaceFileStat`。Host 通过 Session 文件系统解析每条路径;文件读取继承该后端的读取权限,目录列举与目录监听执行 Workspace Files README 所述的工作区检查。
[Workspace Files](../../../../packages/api/workspace-files/README.zh.md) 保留 Host 的行读取、字节窗口、有上限的全文读取和相对另一文件目录的有界读取。Client `file` 提供方只观察 `stat` 与 `changes`,`ResourceProtocolMap.file` 直接为 `WorkspaceFileStat`。Host 通过 Session 文件系统解析每条路径;文件读取继承该后端的读取权限,目录列举与变更观察仍限定于工作区。
可读取的文件使用 `dsh-resource://file/session/<sessionId>/<path>`。路径可以相对工作区,也可以是绝对路径;编码后的绝对路径保留前导斜杠。`fileAddressFor` 始终生成这种 Session 地址。提供方与 Preview RPC 只从该地址取 Session,不取当前选择、首个持有者或 tab 所属 Session。不带 Session 的 `absolute` URI 无法读取;提供方报告 `workspace-file/unknown-workspace`。Session 授权是文件协议规则,不是额外的 Resource 身份。
@@ -9,11 +9,11 @@
en: ee5703dcce5d81c5
zh: 6c1aec04723d211b
/agent-note-workspace-file-read-authority/decision:
en: bb8b53dcfc26d18f
zh: 201249812e65c6fe
en: b4b88d397452d083
zh: 14069d83e001082d
/agent-note-workspace-file-read-authority/alternatives-considered:
en: 4786886538bf3e09
zh: 53d0da3e95b19173
en: 329e575be02d7392
zh: a78f428b36d40f59
/agent-note-workspace-file-read-authority/consequences:
en: 5596ccd54a474e24
zh: d31721c8d39b7fdc
@@ -12,7 +12,7 @@ Workspace Files serves both file content and workspace navigation. Applying work
`read`, `readBytes`, and `stat` inherit the addressed Session filesystem backend's read authority. The workspace root is the base for relative input paths, not a read boundary; absolute paths and relative paths that leave the workspace are readable when the backend allows them. The service still requires regular files, refuses symlinks, and applies its text and byte caps.
`list` and `changes` remain rooted at the workspace because they expose workspace navigation and observation rather than a named file read. Both accept a directory that resolves inside the root or whose path descends from it, and reject any other; [directory links outside the workspace root](2026-11-20-workspace-directory-links-outside-root.md) owns that rule.
`list` and `changes` remain workspace-scoped because they expose workspace navigation and observation rather than a named file read. `list` rejects a directory outside the root, and `changes` filters observations through the backend's workspace-containment predicate.
`readBytes` with `baseFile` resolves a relative path from the base file's directory. A `..` path may therefore read JavaScript or CSS outside the workspace when the Session backend permits it. With [Developer tools](../../../../packages/client/ui-sidebar-documentpreview/README.md) enabled, Document Preview packages bounded, statically declared local scripts and stylesheets into an HTML Blob iframe with `sandbox="allow-scripts"`; the opaque origin blocks parent access, but the browser retains normal network access. This exposure is an intentional security trade-off for rendering static generated HTML.
@@ -20,7 +20,7 @@ The [Workspace Files service](2026-09-05-workspace-files-service.md) owns paging
## Alternatives considered
**Contain every operation within the workspace.** This gives previews a narrower policy than the Session filesystem backend, blocks explicitly addressed readable files, and prevents HTML beside external assets from rendering. A workspace check remains where the operation itself represents the workspace.
**Contain every operation within the workspace.** This gives previews a narrower policy than the Session filesystem backend, blocks explicitly addressed readable files, and prevents HTML beside external assets from rendering. Workspace containment remains where the operation itself represents the workspace.
**Permit outside reads but block all iframe networking.** A stricter CSP would reduce exfiltration risk, but it would also reject external assets and network behavior intentionally retained for the static-HTML preview. The opaque sandbox protects the parent application; it does not promise network isolation.
@@ -12,7 +12,7 @@ Workspace Files 同时提供文件内容与工作区导航。对所有操作应
`read`、`readBytes` 与 `stat` 继承被寻址 Session 的文件系统后端读取权限。工作区根是输入相对路径的基准,而不是读取边界;只要后端允许,就可以读取绝对路径和离开工作区的相对路径。服务仍要求普通文件、拒绝符号链接,并应用文本和字节上限。
`list` 与 `changes` 仍以工作区为根,因为它们暴露工作区导航和观察,而不是读取一个具名文件。两者接受解析到根内、或路径由根逐级向下写出的目录,并拒绝其他目录;[工作区根外的目录链接](2026-11-20-workspace-directory-links-outside-root.zh.md)拥有该规则。
`list` 与 `changes` 仍限于工作区,因为它们暴露工作区导航和观察,而不是读取一个具名文件。`list` 拒绝根外目录,`changes` 通过后端的工作区包含判定过滤观察。
带 `baseFile` 的 `readBytes` 从基准文件所在目录解析相对路径。因此,只要 Session 后端允许,`..` 路径就可以读取工作区外的 JavaScript 或 CSS。开启[开发者工具](../../../../packages/client/ui-sidebar-documentpreview/README.zh.md)时,Document Preview 把有界、静态声明的本地脚本与样式表打包进带 `sandbox="allow-scripts"` 的 HTML Blob iframe;不透明源阻止访问父应用,但浏览器保留正常网络访问。这种暴露是为渲染静态生成 HTML 而有意接受的安全取舍。
@@ -20,7 +20,7 @@ Workspace Files 同时提供文件内容与工作区导航。对所有操作应
## Alternatives considered
**把所有操作限制在工作区内。** 这会让预览采用比 Session 文件系统后端更窄的策略,阻止读取明确寻址的可读文件,并使位于外部资源旁的 HTML 无法渲染。操作本身代表工作区时,仍保留工作区检查。
**把所有操作限制在工作区内。** 这会让预览采用比 Session 文件系统后端更窄的策略,阻止读取明确寻址的可读文件,并使位于外部资源旁的 HTML 无法渲染。操作本身代表工作区时,仍保留工作区包含限制。
**允许根外读取,但阻断 iframe 的全部网络。** 更严格的 CSP 可以降低数据外传风险,但也会拒绝静态 HTML 预览有意保留的外部资源与网络行为。不透明 sandbox 保护父应用,但不承诺网络隔离。
@@ -12,11 +12,11 @@
en: d3c8181e29c1ff3b
zh: a6f15b85e58907e5
/agent-note-bounded-shared-office-conversion/alternatives-considered:
en: 3f998467f8c6aec3
zh: b49ec2c1874ef2f5
en: 73888970b0fc7f6b
zh: 9bcccf774116f849
/agent-note-bounded-shared-office-conversion/consequences:
en: c2800ff56c8f89d1
zh: 3b3710072b59c443
/agent-note-bounded-shared-office-conversion/related:
en: 6c410bafda0ccaee
zh: 85c95c04e1e74057
en: 2e7b1a0f01c1f617
zh: ed2abc0181ea4abe
@@ -28,7 +28,7 @@ Foreground preview and explicit QA requests precede background work. Disabling b
**Build a second prewarm or QA converter.** Independent queues duplicate resource ownership and cannot prioritize shared foreground work.
**Separate service-definition and provider packages.** The service has one implementation; its LibreOffice Kit converter and the [Poppler PDF renderer](2026-11-23-poppler-pdf-renderer.md) are backends inside that provider and share its queue, cache, and admission, so they evolve together with the service. One `office-kit` package supplies the mountable service without duplicated package, dependency, and release configuration. Native and WASM engine selection remains inside the kit; a second independent implementation of the service can justify extracting an interface from actual consumer needs.
**Separate service-definition and provider packages for the sole LibreOffice implementation.** They evolve together and have no independent alternative implementation. One `office-kit` package supplies the mountable service without duplicated package, dependency, and release configuration. Native and WASM engine selection remains inside the kit; a second independent implementation can justify extracting an interface from actual consumer needs.
## Consequences
@@ -40,4 +40,4 @@ Controlled source and engine completions verify pre-read admission, content join
## Related
The [background scheduling proposal](../../proposed/simplification/2026-09-17-defer-office-background-scheduling.md) questions the need for speculative priority without a production caller; this note remains the authority for the implemented behavior. The [Poppler PDF renderer note](2026-11-23-poppler-pdf-renderer.md) records how image rendering selects a backend inside this queue.
The [background scheduling proposal](../../proposed/simplification/2026-09-17-defer-office-background-scheduling.md) questions the need for speculative priority without a production caller; this note remains the authority for the implemented behavior.
@@ -28,7 +28,7 @@ Office 预览和显式文档检查可能请求相同转换。仅缓存已完成
**另建预热或 QA 转换器。** 独立队列重复拥有资源,无法优先调度共享前台工作。
**拆分服务定义和提供方包。** 该服务只有一种实现;其 LibreOffice Kit 转换器和 [Poppler PDF 渲染后端](2026-11-23-poppler-pdf-renderer.zh.md)都是该提供方内部的后端,共用其队列、缓存和准入,因此与服务一同演化。单个 `office-kit` 包直接提供可挂载服务,避免重复维护包、依赖和发布配置。原生与 WASM 引擎选择仍由 kit 负责;若出现独立的第二种服务实现,再根据实际消费者提取接口。
**为唯一的 LibreOffice 实现拆分服务定义和提供方包。** 两者共同演化,没有独立的替代实现。单个 `office-kit` 包直接提供可挂载服务,避免重复维护包、依赖和发布配置。原生与 WASM 引擎选择仍由 kit 负责;若出现独立的第二种实现,再根据实际消费者提取接口。
## 后果
@@ -40,4 +40,4 @@ Office 预览通过 Workspace Files 检查源文件授权与版本,再使用 `
## 相关记录
[后台调度提案](../../proposed/simplification/2026-09-17-defer-office-background-scheduling.zh.md) 质疑没有生产调用方时保留推测性优先级的必要性;本记录仍定义已实现的行为。[Poppler PDF 渲染后端记录](2026-11-23-poppler-pdf-renderer.zh.md)说明图片渲染如何在此队列内选择后端。
[后台调度提案](../../proposed/simplification/2026-09-17-defer-office-background-scheduling.zh.md) 质疑没有生产调用方时保留推测性优先级的必要性;本记录仍定义已实现的行为。
@@ -29,12 +29,9 @@
/agent-note-resolve-profile-modules-along-the-ancestor-chain-with-an-interception-layer/decision/part-1-resolution-rules/5-hook-coverage:
en: 644f6f9a6ff8d6c8
zh: 7a81f928551e9041
/agent-note-resolve-profile-modules-along-the-ancestor-chain-with-an-interception-layer/decision/part-1-resolution-rules/6-rows-the-config-tree-requests:
en: c474b69fb9b029d5
zh: 033c7686f14bc587
/agent-note-resolve-profile-modules-along-the-ancestor-chain-with-an-interception-layer/decision/part-1-resolution-rules/7-package-directories-and-module-files:
en: ba52bd3dd63c641c
zh: ef7337e07e300eca
/agent-note-resolve-profile-modules-along-the-ancestor-chain-with-an-interception-layer/decision/part-1-resolution-rules/6-package-directories-and-module-files:
en: c85f82cb1c60360e
zh: c535f1c0ec58345e
/agent-note-resolve-profile-modules-along-the-ancestor-chain-with-an-interception-layer/decision/part-2-walkthroughs:
en: 906e0d58e3c2aff3
zh: ccc3a709034865b9
@@ -51,8 +48,8 @@
en: 35f27b53d995d59f
zh: 58a47c7bfced79a0
/agent-note-resolve-profile-modules-along-the-ancestor-chain-with-an-interception-layer/decision/part-3-developer-integration-guide/1-normal-installation:
en: a4e8f46669f79105
zh: a7590429589c12fb
en: d0bed60317e6e3a8
zh: 5714160678adc049
/agent-note-resolve-profile-modules-along-the-ancestor-chain-with-an-interception-layer/decision/part-3-developer-integration-guide/2-development-mode-the-plugin-repository-is-outside-the-profile-tree:
en: 22259a568693c641
zh: d81d15671398d033
@@ -75,11 +75,7 @@ The hook participates only when the importer is under `$DSH_HOME/profiles/**` or
The ESM and CommonJS adapters call the same routing function, and the main thread and Harness-owned Workers install the same runtime resolution. The implementation lives in `packages/boot/app-boot/src/profile-resolution/resolver.ts`; runtime resolution construction lives in `packages/boot/app-boot/src/profile.ts`.
#### 6. Rows the config tree requests
The root config tree requests its rows from the profile directory URL, and bundles insert most of those rows, including the rows of their agent presets. For each plugin package name that a bundle inserts as a row and declares as its own dependency, the runtime resolution records the first such bundle. A bare request for that name whose importer is the active profile directory resolves again as an import of that bundle does, before ① and ②. Every other importer, including a file in the profile and a package in its `node_modules`, follows the chain above. [Bundle plugin rows](2026-11-23-bundle-plugin-rows-load-bundle-selected-packages.md) owns the binding rules.
#### 7. Package directories and module files
#### 6. Package directories and module files
`packageDir('pkg', parentURL)` and `packageDir('pkg/sub', parentURL)` locate the package directory without loading code or validating the subpath. Ordinary entry and file requests still ask Node to apply `exports`, `main`, conditions, and file existence. A package-directory query can therefore succeed while importing a missing or unexported file fails. `import.meta.resolve` can return a URL for an exported file that does not exist; importing that URL still fails, as in native Node.
@@ -133,7 +129,7 @@ The profile links `<profile>/node_modules/my-plugin` to the plugin's real direct
`dsh plugin --profile <name> add <package | git spec | file:../local-checkout>` forwards its argument to pnpm, which installs inside the profile directory with a hoisted layout. The profile's `pnpm-workspace.yaml` sets `autoInstallPeers: false`, so dsh packages a plugin declares as peers are not installed into the profile; the interception layer supplies the copy from the running installation, and the plugin and dsh share one module instance.
The plugin's own third-party dependencies are hoisted to `$DSH_HOME/profiles/<name>/node_modules` and found at ② on the ancestor chain. When a name collides with the installation closure, the nearest wins and the plugin uses the version it declared; a row that a bundle inserts and declares still resolves from that bundle (Part 1 §6). The `file:` form copies the local checkout into the profile; resolution afterwards is identical to a registry installation.
The plugin's own third-party dependencies are hoisted to `$DSH_HOME/profiles/<name>/node_modules` and found at ② on the ancestor chain. When a name collides with the installation closure, the nearest wins and the plugin uses the version it declared. The `file:` form copies the local checkout into the profile; resolution afterwards is identical to a registry installation.
#### 2. Development mode: the plugin repository is outside the profile tree
@@ -75,11 +75,7 @@ hook 只在 importer 位于 `$DSH_HOME/profiles/**` 或某个 linked root 之下
ESM 与 CommonJS 两个适配器调用同一个路由函数,主线程与 Harness 自有 Worker 都安装同一份 runtime resolution。实现位于 `packages/boot/app-boot/src/profile-resolution/resolver.ts`,runtime resolution 的构造位于 `packages/boot/app-boot/src/profile.ts`。
#### 6. 配置树请求的行
根配置树从 profile 目录的 URL 请求它的行,其中大多数由 bundle 插入,包括 bundle 的 agent preset 里的行。对 bundle 作为行插入、并声明为自身依赖的每个插件包名,runtime resolution 记录第一个这样的 bundle。importer 是当前 profile 目录的裸包名请求,对这样的包名先于 ① 和 ② 按该 bundle 自己 import 的方式重新解析。其他 importer,包括 profile 里的文件和它的 `node_modules` 里的包,按上面的主线查找。绑定规则见 [bundle 插件行](2026-11-23-bundle-plugin-rows-load-bundle-selected-packages.zh.md)。
#### 7. 包目录与模块文件
#### 6. 包目录与模块文件
`packageDir('pkg', parentURL)` 与 `packageDir('pkg/sub', parentURL)` 定位包目录,不加载代码,也不校验子路径。普通入口与文件请求仍由 Node 应用 `exports`、`main`、conditions 和文件存在性规则。因此,包目录查询可以成功,同时导入缺失或未导出的文件会失败。`import.meta.resolve` 可以为不存在的已导出文件返回 URL,但导入该 URL 仍然失败,这与原生 Node 一致。
@@ -133,7 +129,7 @@ ESM 与 CommonJS 两个适配器调用同一个路由函数,主线程与 Harne
`dsh plugin --profile <name> add <包名 | git spec | file:../本地检出>` 把参数转发给 pnpm,在 profile 目录内以 hoisted 布局安装。profile 的 `pnpm-workspace.yaml` 设置 `autoInstallPeers: false`,插件声明为 peer 的 dsh 包不会被装进 profile,由拦截层提供当前运行安装的那一份,插件与 dsh 共用同一个模块实例。
插件自己的第三方依赖被 hoist 到 `$DSH_HOME/profiles/<name>/node_modules`,按主线 ② 找到。与 installation 闭包同名时最近者优先,插件使用自己声明的版本;bundle 插入并声明的行仍然从该 bundle 解析(第一部分第 6 节)。`file:` 形式把本地检出复制进 profile,随后的解析与注册表安装完全相同。
插件自己的第三方依赖被 hoist 到 `$DSH_HOME/profiles/<name>/node_modules`,按主线 ② 找到。与 installation 闭包同名时最近者优先,插件使用自己声明的版本。`file:` 形式把本地检出复制进 profile,随后的解析与注册表安装完全相同。
#### 2. 开发模式:插件仓库在 profile 树外
@@ -18,5 +18,5 @@
en: aceed1aa98ed9bec
zh: b9d99a25a8b25417
/agent-note-preset-scoped-schedule-tools/testing:
en: 8d3855ea5259878e
zh: 39ca6c8adccb02cb
en: 05080859ac790524
zh: 4b220c10da961608
@@ -31,4 +31,4 @@ English | [中文](2026-09-24-preset-scoped-schedule-tools.zh.md)
## Testing
`packages/schedule/tool-schedule/tests/tool-schedule.spec.ts` pins the four definitions and their error mapping, including `refuses every call from a registered delegated child whose scope mounts the tools`, and `packages/subagent/subagent/tests/schedule-tools.spec.ts` runs a delegated child through the native root registry and pins that refusal without a stored task. `apps/cli/tests/web-agent-presets.e2e.ts` asserts the `minimal` preset's tool list, and `snapshots/web/minimal-preset/tool-schemas.expected.json` records its tool table without reminder schemas. `packages/schedule/schedule/tests/subagent-ownership.spec.ts` pins the delegation-depth refusal, and `scripts/optional-bundles.spec.ts` asserts that both delegation rows in the three presets omit `toolFilter`. The Web preset e2e also checks equal parent/child tool schemas and refusal from all four reminder executors for fresh and seeded children. `snapshots/web/subagent-fork-schedule` records all four refusals in a seeded fork through the shipped Web composition and shares the standard preset's prompt and schema pins.
`packages/schedule/tool-schedule/tests/tool-schedule.spec.ts` pins the four definitions and their error mapping, including `refuses every call from a registered delegated child whose scope mounts the tools`, and `packages/subagent/subagent/tests/schedule-tools.spec.ts` runs a delegated child through the tool executor and pins that refusal without a stored task. `apps/cli/tests/web-agent-presets.e2e.ts` asserts the `minimal` preset's tool list, and `snapshots/web/minimal-preset/tool-schemas.expected.json` records its tool table without reminder schemas. `packages/schedule/schedule/tests/subagent-ownership.spec.ts` pins the delegation-depth refusal, and `scripts/optional-bundles.spec.ts` asserts that both delegation rows in the three presets omit `toolFilter`. The Web preset e2e also checks equal parent/child tool schemas and refusal from all four reminder executors for fresh and seeded children. `snapshots/web/subagent-fork-schedule` records all four refusals in a seeded fork through the shipped Web composition and shares the standard preset's prompt and schema pins.
@@ -31,4 +31,4 @@ Status: implemented
## Testing
`packages/schedule/tool-schedule/tests/tool-schedule.spec.ts` 固定这四个定义及其错误映射,包括 `refuses every call from a registered delegated child whose scope mounts the tools`;`packages/subagent/subagent/tests/schedule-tools.spec.ts` 通过原生根注册表运行一个被委派的子 agent,并在没有已存任务时固定该拒绝。`apps/cli/tests/web-agent-presets.e2e.ts` 断言 `minimal` preset 的工具列表,`snapshots/web/minimal-preset/tool-schemas.expected.json` 记录其不含提醒工具 schema 的工具表。`packages/schedule/schedule/tests/subagent-ownership.spec.ts` 固定委派深度拒绝,`scripts/optional-bundles.spec.ts` 断言三个 preset 的两行委派行都不含 `toolFilter`。Web preset e2e 还检查父子工具 schema 相等,且四个提醒执行器对新建和带种子的子级均拒绝执行。`snapshots/web/subagent-fork-schedule` 通过出货 Web 组合记录带种子 fork 中的四次拒绝,并共享 standard preset 的提示和 schema 预期。
`packages/schedule/tool-schedule/tests/tool-schedule.spec.ts` 固定这四个定义及其错误映射,包括 `refuses every call from a registered delegated child whose scope mounts the tools`;`packages/subagent/subagent/tests/schedule-tools.spec.ts` 通过工具执行器运行一个被委派的子 agent,并在没有已存任务时固定该拒绝。`apps/cli/tests/web-agent-presets.e2e.ts` 断言 `minimal` preset 的工具列表,`snapshots/web/minimal-preset/tool-schemas.expected.json` 记录其不含提醒工具 schema 的工具表。`packages/schedule/schedule/tests/subagent-ownership.spec.ts` 固定委派深度拒绝,`scripts/optional-bundles.spec.ts` 断言三个 preset 的两行委派行都不含 `toolFilter`。Web preset e2e 还检查父子工具 schema 相等,且四个提醒执行器对新建和带种子的子级均拒绝执行。`snapshots/web/subagent-fork-schedule` 通过出货 Web 组合记录带种子 fork 中的四次拒绝,并共享 standard preset 的提示和 schema 预期。
@@ -9,11 +9,11 @@
en: 32ba2b2b42e8deb5
zh: 6a6532561f81b8e2
/agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/decision:
en: f43ebe5ff75efda7
zh: b9485905c8489e53
en: 9bf594047ad5c864
zh: 366263d56f8a4fbf
/agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/alternatives-considered:
en: 08d82dad90ca1425
zh: a84ef590cc32209c
en: 6da221f6b821ea44
zh: b15774011abed7ed
/agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/consequences:
en: 7df559db44019a1e
zh: 82580a6ea36834e3
en: c90a122c1f33bb83
zh: 0175ca0f599d086b
@@ -10,17 +10,17 @@ English | [中文](2026-09-27-web-search-offered-by-provider-readiness.zh.md)
## Decision
Each role of the web capability seam owns one part of the readiness check that decides whether an Agent sees each Web tool:
Each role of the web capability seam owns one part of a per-step check:
- **Service Definition.** `WebSearchProvider` and `WebFetchProvider` have an optional `ready(llmProvider)` that answers whether an operation made for a model request on that chat route has a credential to send. It checks configuration only and makes no network calls. `ctx.web.searchReady(llmProvider?)` and `ctx.web.fetchReady(llmProvider?)` resolve the provider with the same rules as `search()` and `fetch()` and return its answer. A provider without `ready()` counts as ready, and a selection failure answers true because the operation reports that failure as a structured `WebError`.
- **Service Provider.** Each DeepSeek provider checks its credentials in the order its operation resolves them. `dsh-web-search-deepseek` checks, in a conversation on the account route, whether `ctx.deepseekAuth` has the account sign-in configured for its Messages endpoint, and then its literal `apiKey` or its `apiKeyEnv` reference. The Search and Fetch API providers of `dsh-web-deepseek-api` resolve the same plan as the operation ([credential resolution](2026-10-29-web-provider-selection.md)): a capability with its own YAML fields checks only the key under its `*ApiKeyEnv`; otherwise, on the account route with the account model route mounted, the account sign-in configured for the endpoint under that route's origin counts, and then the key of the `deepseek-official` route, or `DEEPSEEK_API_KEY` without that route. A key counts when `ctx.credentials.describe()` reports its reference configured (without that service, when the launching environment carries it); `ctx.deepseekAuth` performs these checks, a key's through the reference helpers of `dsh-credentials`. A failed account-token or credential-store read answers false, because the operation fails on that read instead of trying the next credential. The providers name no tool or prompt section.
- **Consumer.** `dsh-tool-web` registers `web_search` and `web_fetch` in an [`AgentToolRegistry`](../../../../packages/core/tools/README.md#per-agent-tools), asks `ctx.web.searchReady()` and `ctx.web.fetchReady()` about the route `agent.model.current()` names, and adds or removes each tool for that Agent. It checks when the Agent is created, which waits for the check; when the Agent's Session records a model selection, a request on another route, or a preset change; when a stored credential or the account sign-in changes; when the registered Web providers change; and for Agents that exist when it loads. The `tool:web_search` and `tool:web_fetch` prompt sections are registered with the tools and render for an Agent only while tool-web has added the tool for it. A step captures its tools once, so the declared tools, PTC program bindings, and dispatch read the same tools.
- **Consumer.** `dsh-tool-web` registers `web_search` and `web_fetch` with [step activation conditions](../../../../packages/core/tools/README.md#conditional-tools) that ask `ctx.web.searchReady()` and `ctx.web.fetchReady()` about the route of the step's model selection. The agent loop resolves conditions before it assembles the step, so the declared tools, the `tool:web_search` and `tool:web_fetch` prompt sections, PTC program bindings, and dispatch all read the same admitted set.
The route decides only whether the account token is checked before the API key, which happens on the `deepseek-account` route; an API key counts on every route, so a conversation on another provider's model is offered the DeepSeek web tools whenever a DeepSeek key is configured. A Search or Fetch API capability with its own YAML fields ignores the route and is ready exactly when its own key is configured.
Only presence decides: no API key value is read and no endpoint is contacted, so a wrong key or an endpoint that does not serve the native `web_search_20250305` server tool keeps the tool offered. A step whose Agent lacks a web tool also refuses calls to it as `UNKNOWN_TOOL`, so a model that repeats an earlier call reaches no provider; an operation made outside a model step resolves its credential when it runs and fails with `WEB_PROVIDER_CREDENTIAL_MISSING` when there is none.
Only presence decides: no API key value is read and no endpoint is contacted, so a wrong key or an endpoint that does not serve the native `web_search_20250305` server tool keeps the tool admitted. A step that does not admit a web tool also refuses calls to it as `UNKNOWN_TOOL`, so a model that repeats an earlier call reaches no provider; an operation made outside a model step resolves its credential when it runs and fails with `WEB_PROVIDER_CREDENTIAL_MISSING` when there is none.
The request header records the assembled tools, so the agent loop announces each change through tool-registry updates. A route switch, a stored key, or a removed key changes the first request that starts after the check finishes; DeepSeek routes load a returning tool as a deferred addition, and routes without tool-update support receive the complete tool list.
The request header records the assembled tools, so the agent loop announces each change through tool-registry updates. A route switch, a stored key, or a removed key changes the next request; DeepSeek routes load a returning tool as a deferred addition, and routes without tool-update support receive the complete tool list.
## Alternatives considered
@@ -30,7 +30,7 @@ The request header records the assembled tools, so the agent loop announces each
**Read the route from the Session's latest `request/context` event instead of passing it.** That event records the previous request, so a new Session's first request and the first request after a model switch would be decided for the wrong route or for none.
**Register or unregister `web_search` for the whole preset in `dsh-tool-web`.** Registration is shared by every Session of an agent preset, while credentials depend on each request's route. Unregistering would also make `toolOrder` entries and subagent `toolFilter` restrictions that name `web_search` fail. The per-Agent registry keeps one shared registration whose unscoped view still lists the tool, so those names stay valid.
**Register or unregister `web_search` in `dsh-tool-web`.** Registration is shared by every Session of an agent preset, while credentials depend on each request's route. Unregistering would also make `toolOrder` entries and subagent `toolFilter` restrictions that name `web_search` fail.
**Remove `web_search` from the assembled request.** A `system-prompt/assemble` listener could drop the declaration and its section, but the tool would stay executable, so a model that repeats an earlier call would still run it, and PTC programs would still bind it. Prompt assembly also no longer carries tool declarations.
@@ -44,10 +44,8 @@ The request header records the assembled tools, so the agent loop announces each
**Probe the key or endpoint before offering the tool.** A network request per model request adds latency and cost; the user controls configuration, not its validity at that moment.
**Check before every step from an awaited step event.** Every step would read its exact route and current credentials, but the agent loop would keep a public per-step extension point for this one consumer, and the check would run for every Agent and step although its inputs change rarely; most of them change through an event, and the ones without one are listed under Consequences.
## Consequences
`dsh-web` gains public members: the optional `ready()` of both provider interfaces, `WebRuntime.searchReady()`, and `WebRuntime.fetchReady()`. Each readiness method is the smallest query its one consumer needs, which is how the [observation-surface decision](../../archived/simplification/2026-07-04-drop-unconsumed-web-observation-surface.md) lets a status query return; neither reports availability or selection failures. The HTTP fetch provider implements no `ready()`, so `web_fetch` stays offered whenever HTTP fetch is selected. A step whose Agent lacks a web tool leaves it out of PTC program bindings too. An endpoint that cannot serve the native server tool keeps the tool offered and fails each call. A step that starts while a check runs uses the previous answer, so the first step after a model switch can still offer or omit a tool for the previous route; Web provider settings edited without a change event, such as a literal key, a key reference name, or the selected provider, apply at the Agent's next check. The route of a blank Web Session that follows the default model also changes without an event when another Session saves a new default: the first step uses the answer checked for the old route, that step's `request/header` starts a check, and if the new route is not ready the tool is withdrawn while the model answers, so a declared `web_search` call fails as `UNKNOWN_TOOL`, or with `WEB_PROVIDER_CREDENTIAL_MISSING` when it starts before the check settles. Removing a tool on an unchanged route changes the declared tools and misses the prompt cache once; a model switch already invalidates it. Searches and fetches from other providers' conversations bill the configured DeepSeek key. A deployment whose official route chats through a gateway sends the gateway's key to that gateway's origin with `/v1/tools` for the Search and Fetch APIs, and to the configured Messages endpoint, the official one by default, for legacy Messages search, where each search fails unless that endpoint accepts the key. The Search and Fetch APIs read the DeepSeek model routes' Loader entries through the model provider directory.
`dsh-web` gains public members: the optional `ready()` of both provider interfaces, `WebRuntime.searchReady()`, and `WebRuntime.fetchReady()`. Each readiness method is the smallest query its one consumer needs, which is how the [observation-surface decision](../../archived/simplification/2026-07-04-drop-unconsumed-web-observation-surface.md) lets a status query return; neither reports availability or selection failures. The HTTP fetch provider implements no `ready()`, so `web_fetch` stays admitted whenever HTTP fetch is selected. A step that does not admit a web tool leaves it out of PTC program bindings too. An endpoint that cannot serve the native server tool keeps the tool admitted and fails each call. Removing a tool on an unchanged route changes the declared tools and misses the prompt cache once; a model switch already invalidates it. Searches and fetches from other providers' conversations bill the configured DeepSeek key. A deployment whose official route chats through a gateway sends the gateway's key to that gateway's origin with `/v1/tools` for the Search and Fetch APIs, and to the configured Messages endpoint, the official one by default, for legacy Messages search, where each search fails unless that endpoint accepts the key. The Search and Fetch APIs read the DeepSeek model routes' Loader entries through the model provider directory.
Unit tests pin each role: [web.spec.ts](../../../../packages/web/web/tests/web.spec.ts) covers which provider `searchReady()` and `fetchReady()` ask and their answer on selection failure, [deepseek.spec.ts](../../../../packages/web/web-search-deepseek/tests/deepseek.spec.ts) and [credential-resolution.spec.ts](../../../../packages/web/web-deepseek-api/tests/credential-resolution.spec.ts) cover each credential case of `ready()` on the account route and on other routes, including readiness that matches each operation, and [tool-web.spec.ts](../../../../packages/web/tool-web/tests/tool-web.spec.ts) prepares model steps that offer or withhold both tools through the real prompt, tool, and root registry services, including the `UNKNOWN_TOOL` refusal of a call in a step that withheld the tool. In real compositions, the shipped headless keyless smoke test and the `web-search-unconfigured` recorded-session snapshot, whose search key references are unset, pin the withheld search tool. Snapshot replays supply a placeholder DeepSeek key, so their tool lists do not depend on the runner's environment; with it, the `pi-ai-conversation-updates` conversation on a pi-ai route keeps `web_search`.
Unit tests pin each role: [web.spec.ts](../../../../packages/web/web/tests/web.spec.ts) covers which provider `searchReady()` and `fetchReady()` ask and their answer on selection failure, [deepseek.spec.ts](../../../../packages/web/web-search-deepseek/tests/deepseek.spec.ts) and [credential-resolution.spec.ts](../../../../packages/web/web-deepseek-api/tests/credential-resolution.spec.ts) cover each credential case of `ready()` on the account route and on other routes, including readiness that matches each operation, and [tool-web.spec.ts](../../../../packages/web/tool-web/tests/tool-web.spec.ts) resolves step admission of both tools through the real prompt, tool, and executor services, including the `UNKNOWN_TOOL` refusal of a call in a step that withheld the tool. In real compositions, the shipped headless keyless smoke test and the `web-search-unconfigured` recorded-session snapshot, whose search key references are unset, pin the withheld search tool. Snapshot replays supply a placeholder DeepSeek key, so their tool lists do not depend on the runner's environment; with it, the `pi-ai-conversation-updates` conversation on a pi-ai route keeps `web_search`.
@@ -10,17 +10,17 @@ Status: implemented
## Decision
web 能力 seam 的每个角色各负责就绪检查的一部分,该检查决定 Agent 能否看到每个 Web 工具:
web 能力 seam 的每个角色各负责逐步骤检查的一部分:
- **Service Definition。** `WebSearchProvider` 与 `WebFetchProvider` 有一个可选的 `ready(llmProvider)`,回答为该对话路由上的模型请求发起的操作是否有可发送的凭据。它只检查配置,不发起网络调用。`ctx.web.searchReady(llmProvider?)` 与 `ctx.web.fetchReady(llmProvider?)` 按与 `search()`、`fetch()` 相同的规则解析提供方并返回其回答。没有 `ready()` 的提供方视为就绪;选择失败时回答 true,因为对应操作会把该失败报告为结构化 `WebError`。
- **Service Provider。** 每个 DeepSeek 提供方都按其操作解析凭据的顺序检查凭据。`dsh-web-search-deepseek` 在账号路由上的会话里检查 `ctx.deepseekAuth` 是否已为其 Messages 端点配置账号登录凭据,然后检查其字面 `apiKey` 或 `apiKeyEnv` 引用。`dsh-web-deepseek-api` 的 Search 与 Fetch API 提供方解析与操作相同的方案([凭据解析](2026-10-29-web-provider-selection.zh.md)):在 YAML 中设置了单独字段的能力只检查其 `*ApiKeyEnv` 下的密钥;否则,在账号路由上且账号模型路由已挂载时,为该路由 origin 之下的端点配置的账号登录凭据算数,然后是 `deepseek-official` 路由的密钥,没有该路由时为 `DEEPSEEK_API_KEY`。`ctx.credentials.describe()` 报告其引用已配置时(没有该服务时,启动环境中存在该变量),密钥即算存在;这些存在性检查由 `ctx.deepseekAuth` 执行,其中密钥的检查经由 `dsh-credentials` 的引用函数。读取账号 token 或凭据存储失败时回答 false,因为操作会在该次读取上失败,而不会尝试下一种凭据。提供方不点名任何工具或提示词段落。
- **Consumer。** `dsh-tool-web` 在一个 [`AgentToolRegistry`](../../../../packages/core/tools/README.zh.md#per-agent-tools) 中注册 `web_search` 与 `web_fetch`,以 `agent.model.current()` 指明的路由询问 `ctx.web.searchReady()` 与 `ctx.web.fetchReady()`,再为该 Agent 添加或移除每个工具。它在以下时机检查:创建 Agent 时,创建过程会等待该检查完成;该 Agent 的会话记录模型选择、另一路由上的请求或预设变化时;已存储的凭据或账号登录状态变化时;已注册的 Web 提供方变化时。它加载时还会检查已存在的 Agent。`tool:web_search` 与 `tool:web_fetch` 提示词段落与工具一起注册,并且只有在 tool-web 已为某个 Agent 添加该工具时,才会为该 Agent 渲染。每个步骤只捕获一次工具,因此声明的工具、PTC 程序绑定与派发都读取同一组工具。
- **Consumer。** `dsh-tool-web` 注册 `web_search` 与 `web_fetch` 时各带一个[步骤激活条件](../../../../packages/core/tools/README.zh.md#conditional-tools),以该步骤模型选择的路由询问 `ctx.web.searchReady()` 与 `ctx.web.fetchReady()`。agent loop 在组装该步骤之前解析各条件,因此声明的工具、`tool:web_search` 与 `tool:web_fetch` 提示词段落、PTC 程序绑定与派发都读取同一个准入集合。
路由只决定是否先检查账号 token 再检查 API 密钥,这发生在 `deepseek-account` 路由上;API 密钥在每条路由上都算数,因此只要配置了 DeepSeek 密钥,使用其他提供方模型的对话也会获得 DeepSeek Web 工具。在 YAML 中设置了单独字段的 Search 或 Fetch API 能力不看路由,恰在其自身密钥已配置时就绪。
只看凭据是否存在:不读取 API 密钥的值,也不访问任何端点,因此密钥错误,或端点不提供原生 `web_search_20250305` 服务器工具时,仍会提供该工具。所属 Agent 没有某个 Web 工具的步骤也会以 `UNKNOWN_TOOL` 拒绝对它的调用,因此模型重复先前的调用也到达不了任何提供方;在模型步骤之外发起的操作在运行时解析凭据,没有凭据时以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败。
只看凭据是否存在:不读取 API 密钥的值,也不访问任何端点,因此错误的密钥,或不提供原生 `web_search_20250305` 服务器工具的端点,仍会让该工具保持准入。未准入某个 Web 工具的步骤也会以 `UNKNOWN_TOOL` 拒绝对它的调用,因此模型重复先前的调用也到达不了任何提供方;在模型步骤之外发起的操作在运行时解析凭据,没有凭据时以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败。
请求头记录组装后的工具,因此 agent loop(智能体循环)通过工具注册表更新宣告每次变化。路由切换、存储密钥或删除密钥都会改变检查完成后开始的第一个请求;DeepSeek 路由以延迟加载的新增方式载入重新提供的工具,不支持工具更新的路由则接收完整工具列表。
请求头记录组装后的工具,因此 agent loop(智能体循环)通过工具注册表更新宣告每次变化。路由切换、存储密钥或删除密钥都会改变下一个请求;DeepSeek 路由以延迟加载的新增方式载入重新提供的工具,不支持工具更新的路由则接收完整工具列表。
## Alternatives considered
@@ -30,7 +30,7 @@ web 能力 seam 的每个角色各负责就绪检查的一部分,该检查决
**从会话最近的 `request/context` 事件读取路由,而不是传入路由。** 该事件记录的是上一个请求,因此新会话的首个请求,以及模型切换后的首个请求,会按错误的路由判断,或根本没有路由可用。
**在 `dsh-tool-web` 中为整个 preset 注册或注销 `web_search`。** 注册由同一 agent preset 的所有会话共享,而凭据取决于每个请求的路由。注销还会使点名 `web_search` 的 `toolOrder` 条目和 subagent `toolFilter` 限制失败。按 Agent 提供工具的注册表保留一份共享注册,其不带作用域的视图仍列出该工具,因此这些名称保持有效。
**在 `dsh-tool-web` 中注册或注销 `web_search`。** 注册由同一 agent preset 的所有会话共享,而凭据取决于每个请求的路由。注销还会使点名 `web_search` 的 `toolOrder` 条目和 subagent `toolFilter` 限制失败。
**从组装好的请求中移除 `web_search`。** `system-prompt/assemble` 监听器可以删掉该声明及其段落,但工具仍可执行,因此模型重复先前的调用时仍会运行它,PTC 程序也仍能绑定它。提示词组装也已不再携带工具声明。
@@ -44,10 +44,8 @@ web 能力 seam 的每个角色各负责就绪检查的一部分,该检查决
**提供工具前探测密钥或端点。** 每个模型请求都发起一次网络请求会增加延迟与成本;用户控制的是配置本身,而不是它在那一刻是否有效。
**在每个步骤之前,通过一个需等待完成的步骤事件检查。** 这样每个步骤都能读取其确切路由与当前凭据,但 agent loop 要为这一个消费方保留一个公共的逐步骤扩展点,而且尽管检查的输入很少变化,检查仍会对每个 Agent 的每个步骤运行。这些输入大多通过事件变化,没有对应事件的输入列在「Consequences」一节中。
## Consequences
`dsh-web` 增加以下公共成员:两个提供方接口上可选的 `ready()`、`WebRuntime.searchReady()` 与 `WebRuntime.fetchReady()`。每个就绪方法都是其唯一消费方所需的最小查询,这正是[观测接口决策](../../archived/simplification/2026-07-04-drop-unconsumed-web-observation-surface.md)允许状态查询回归的方式;它们既不报告可用性,也不报告选择失败。HTTP 抓取提供方没有实现 `ready()`,因此只要选中 HTTP 抓取,就始终提供 `web_fetch`。所属 Agent 没有某个 Web 工具的步骤,其 PTC 程序绑定中也没有它。端点无法提供原生服务器工具时,仍会提供该工具,并使每次调用失败。在检查运行期间开始的步骤使用先前的回答,因此模型切换后的第一个步骤仍可能按先前的路由提供或省略某个工具;在没有变化事件的情况下编辑的 Web 提供方设置(例如字面密钥、密钥引用名称或选中的提供方)在该 Agent 的下一次检查时生效。跟随默认模型的空白 Web 会话,其路由也会在另一个会话保存新的默认模型时变化,且没有对应事件:第一个步骤使用针对旧路由检查得到的回答,该步骤的 `request/header` 会启动一次检查;如果新路由未就绪,该工具会在模型回答期间被撤下,因此已声明的 `web_search` 调用以 `UNKNOWN_TOOL` 失败;若该调用在检查结算之前开始,则以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败。在路由不变时移除工具会改变声明的工具,并使提示词缓存失效一次;模型切换本身已经使缓存失效。其他提供方对话中的搜索与抓取由配置的 DeepSeek 密钥计费。官方路由经网关对话的部署,对 Search 与 Fetch API 会把网关的密钥发往该网关 origin 加 `/v1/tools`,对旧版 Messages 搜索则发往配置的 Messages 端点(默认是官方端点),除非该端点接受这个密钥,否则每次搜索都会失败。Search 与 Fetch API 通过模型提供方目录读取 DeepSeek 模型路由的 Loader 条目。
`dsh-web` 增加以下公共成员:两个提供方接口上可选的 `ready()`、`WebRuntime.searchReady()` 与 `WebRuntime.fetchReady()`。每个就绪方法都是其唯一消费方所需的最小查询,这正是[观测接口决策](../../archived/simplification/2026-07-04-drop-unconsumed-web-observation-surface.md)允许状态查询回归的方式;它们既不报告可用性,也不报告选择失败。HTTP 抓取提供方没有实现 `ready()`,因此只要选中 HTTP 抓取,`web_fetch` 就始终准入。未准入某个 Web 工具的步骤,其 PTC 程序绑定中也没有它。无法提供原生服务器工具的端点仍会让工具保持准入,并使每次调用失败。在路由不变时移除工具会改变声明的工具,并使提示词缓存失效一次;模型切换本身已经使缓存失效。其他提供方对话中的搜索与抓取由配置的 DeepSeek 密钥计费。官方路由经网关对话的部署,对 Search 与 Fetch API 会把网关的密钥发往该网关 origin 加 `/v1/tools`,对旧版 Messages 搜索则发往配置的 Messages 端点(默认是官方端点),除非该端点接受这个密钥,否则每次搜索都会失败。Search 与 Fetch API 通过模型提供方目录读取 DeepSeek 模型路由的 Loader 条目。
单元测试分别固定每个角色:[web.spec.ts](../../../../packages/web/web/tests/web.spec.ts) 覆盖 `searchReady()` 与 `fetchReady()` 询问哪个提供方以及选择失败时的回答,[deepseek.spec.ts](../../../../packages/web/web-search-deepseek/tests/deepseek.spec.ts) 与 [credential-resolution.spec.ts](../../../../packages/web/web-deepseek-api/tests/credential-resolution.spec.ts) 覆盖 `ready()` 在账号路由与其他路由上的每种凭据情况,包括就绪判断与每次操作一致,[tool-web.spec.ts](../../../../packages/web/tool-web/tests/tool-web.spec.ts) 通过真实的提示词、工具与根注册表服务准备提供或撤下这两个工具的模型步骤,包括在撤下该工具的步骤中调用它时以 `UNKNOWN_TOOL` 拒绝。在真实组合中,发行版 headless 无密钥冒烟测试与 `web-search-unconfigured` 录制会话快照的搜索密钥引用都未设置,二者固定了搜索工具的撤下行为。快照回放提供占位 DeepSeek 密钥,因此其工具列表不依赖运行环境;借助该密钥,`pi-ai-conversation-updates` 中 pi-ai 路由上的对话保留 `web_search`。
单元测试分别固定每个角色:[web.spec.ts](../../../../packages/web/web/tests/web.spec.ts) 覆盖 `searchReady()` 与 `fetchReady()` 询问哪个提供方以及选择失败时的回答,[deepseek.spec.ts](../../../../packages/web/web-search-deepseek/tests/deepseek.spec.ts) 与 [credential-resolution.spec.ts](../../../../packages/web/web-deepseek-api/tests/credential-resolution.spec.ts) 覆盖 `ready()` 在账号路由与其他路由上的每种凭据情况,包括就绪判断与每次操作一致,[tool-web.spec.ts](../../../../packages/web/tool-web/tests/tool-web.spec.ts) 通过真实的提示词、工具与执行器服务解析两个工具的步骤准入,包括在撤下该工具的步骤中调用它时以 `UNKNOWN_TOOL` 拒绝。在真实组合中,发行版 headless 无密钥冒烟测试与 `web-search-unconfigured` 录制会话快照的搜索密钥引用都未设置,二者固定了搜索工具的撤下行为。快照回放提供占位 DeepSeek 密钥,因此其工具列表不依赖运行环境;借助该密钥,`pi-ai-conversation-updates` 中 pi-ai 路由上的对话保留 `web_search`。
@@ -9,8 +9,8 @@
en: 9f652292b62cd015
zh: 14a97b5a4884c008
/agent-note-desktop-shell-configuration-independent-of-the-host/decision:
en: eb14fe1f888552dd
zh: 5414e5a108bd9bdc
en: e58311d3d5ebb6b6
zh: b4c791fcfde7b986
/agent-note-desktop-shell-configuration-independent-of-the-host/alternatives-considered:
en: 349210f3cf5f168b
zh: 019acfc3c3d71b4b
@@ -10,7 +10,7 @@ Desktop updates and native recovery can run before the Host starts or while it i
## Decision
Electron main owns `userData/desktop/settings.json` independently of Host startup and Cordis evaluation. Document `"version": "1"`, the test authentication popup switch, and the update-channel preference and unlock flag use this file; [channel convergence and decoupled publishing](2026-11-25-desktop-channel-convergence-and-decoupled-publishing.md) owns `"version": "1"` migration and default `stable` locking, and the [Desktop reference](../../../../apps/desktop/README.md#local-desktop-settings) owns field validation and runtime behavior.
Electron main owns `userData/desktop/settings.json` independently of Host startup and Cordis evaluation. The test authentication popup switch uses this file; the [Desktop reference](../../../../apps/desktop/README.md#local-desktop-settings) owns its fields and behavior.
Ownership follows runtime dependencies: Electron-owned functions needing configuration before Host startup or while the Host is unavailable use shell configuration. Host plugin settings, including shared Web/Desktop preferences, continue to use Cordis. Displaying a setting in Desktop alone does not justify shell ownership. A unified settings interface can use separate storage owners.
@@ -10,7 +10,7 @@ Desktop 更新和原生恢复可以在 Host 启动前或不可用时运行。依
## Decision
Electron 主进程负责 `userData/desktop/settings.json`,不依赖 Host 启动或 Cordis 求值。文档 `"version": "1"`、测试鉴权弹窗开关以及更新渠道偏好与解锁标记均使用此文件;`"version": "1"` 迁移与默认 `stable` 锁定见[渠道收敛与解耦发布决策](2026-11-25-desktop-channel-convergence-and-decoupled-publishing.zh.md),字段校验与运行时行为见 [Desktop 参考文档](../../../../apps/desktop/README.zh.md#local-desktop-settings)。
Electron 主进程负责 `userData/desktop/settings.json`,不依赖 Host 启动或 Cordis 求值。测试鉴权弹窗开关使用此文件;[Desktop 参考文档](../../../../apps/desktop/README.zh.md#local-desktop-settings)统一说明字段和行为。
配置归属按运行依赖划分:由 Electron 负责且需要在 Host 启动前或不可用时读取配置的功能,使用壳层配置。Host 插件设置,包括 Web/Desktop 共用偏好,继续使用 Cordis。仅仅展示在 Desktop 中,不构成归属壳层的理由。统一设置界面可以使用不同的存储归属。
@@ -1,22 +0,0 @@
# Bilingual-pair consistency record for 2026-10-12-im-automation-sessions.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-12-im-automation-sessions.md
/agent-note-im-integration-through-automation-sessions:
en: d6b30e7c14677e2f
zh: dd645fc940cd7735
/agent-note-im-integration-through-automation-sessions/problem:
en: 673f364e0086216d
zh: 365842270520db39
/agent-note-im-integration-through-automation-sessions/decision:
en: 6b4bea610a34a4a7
zh: ed9a350b57ad80a8
/agent-note-im-integration-through-automation-sessions/durability-and-ownership:
en: 68418aadd270de7f
zh: 69a3ec843097a1d9
/agent-note-im-integration-through-automation-sessions/alternatives-considered:
en: 450cc826c8260583
zh: 288ca53b6955a6b4
/agent-note-im-integration-through-automation-sessions/consequences:
en: bcf16d490d681bf1
zh: b0bf15e9652e2516
@@ -1,39 +0,0 @@
# Agent Note: IM integration through automation sessions
Status: implemented
English | [中文](2026-10-12-im-automation-sessions.zh.md)
## Problem
IM combines delayed input, multiple participants, quoted messages, and platform redelivery. A task can consume several messages without publishing an answer to each one. Treating every message as a GUI prompt and every assistant response as a platform reply couples input scheduling to publication.
## Decision
IM hosts persistent sessions through the existing agent factory, inbox, presets, and persistence APIs, and lets a plugin decide which session an admitted message reaches. The agent loop and core Session categories are unchanged. The [IM service](../../../../packages/experimental/im/README.md) admits external context and provides [explicit tools](../../../../packages/experimental/im/src/tools.ts) for reading and publishing; the [IM bundle](../../../../packages/experimental/im-bundle/README.md) mounts the service and the adapters as Host rows of an existing profile.
Source admission, write grants, delivery mode, model route, working directory, and preset are explicit deployment choices: a `sources` rule decides which chats may reach the host and how their messages are stored, and `defaultDispatch` composes the single session every unhandled addressed message reaches. Every chat shares that session's history, so a deployment that needs per-chat history or background workers mounts its own plugin on the `im/message` waterfall.
The transport layer uses the vendored Satori packages (`plugin-im-core`, `satori-element`, `plugin-im-adapter-lark`, and `plugin-im-adapter-qq`). The [vendor manifest](../../../../vendor/im/README.md) documents exact upstream pins and local modifications. Generated Feishu declarations stay outside Git and are regenerated from hash-checked pinned sources during installation.
## Durability and ownership
One service instance holds the live `Agent` for each hosted session. The `im_sessions` storage domain records each hosted session with its owner, composition, and bindings, and rejects a session id that already exists outside the IM store. `im_messages` records each external event digest and message before platform ACK. A deterministic inbox message ID (`deliveryMessageId`) and a Session log check reconcile admission across restarts so redeliveries and crash recoveries do not duplicate inbox messages.
Outbound sends with an `operationId` record a `pending` receipt in `im_receipts` before network dispatch and update it with the result afterwards. Replaying the same `operationId` returns the recorded receipt without resending. A platform error code indicating nothing was published is recorded as `failed`; a lost response, timeout, or crash after dispatch is recorded as `uncertain` and is never automatically resent.
The `im` message source is attribution metadata only ([compatibility record](../../../../docs/persistence-changes/2026-10-28-im-message-source.md)). Permission decisions remain in the live IM service, and existing sandbox and approval policies continue to apply.
## Alternatives considered
**Another GUI client through Host controllers.** Suitable for transcript mirroring and typed interaction controls, but it introduces conversation policy and output coupling that automation does not need. IM uses the agent factory directly while retaining the existing loop.
**ACP between IM and the harness.** ACP supports persistent programmatic sessions and suits process separation. Independent IM publication still requires a channel or tool route; in-process Cordis composition avoids an additional process without changing automation semantics.
**Operator-configured fixed sessions per chat.** Naming each session and its sources by hand requires a configuration change and restart for every new chat. One session composed from `sources` and `defaultDispatch` keeps access control in source rules without per-chat configuration.
**Automatic retries for uncertain sends.** A lost response cannot establish whether the platform created the message. Keeping `uncertain` for inspection avoids automatic duplicates while allowing an intentional new tool call to send again.
## Consequences
One host process owns each IM store and session set; multi-host coordination requires a separate design. Hosted sessions stay resident in memory after first use (except `ephemeral` sessions, which dispose their agent after the first turn). Finite receipt retention (`retentionMs`) bounds event deduplication, while pending messages and pending receipts do not expire automatically. Scanning Session logs for inbox message IDs increases recovery cost for long session histories.
@@ -1,39 +0,0 @@
# Agent Note: 通过自动化会话接入 IM
Status: implemented
[English](2026-10-12-im-automation-sessions.md) | 中文
## Problem
IM 同时包含延迟输入、多个参与者、消息引用和平台重投。一项任务可以消费多条消息,而不逐条发布答复。将每条消息作为 GUI 提示词、每条 assistant 回复作为平台答复,会把输入调度与发布耦合。
## Decision
IM 通过现有 agent 工厂、收件箱、预设和持久化 API 托管持久化会话,并由插件决定被接纳的消息进入哪个会话。agent-loop 与核心 Session 类别保持不变。[IM 服务](../../../../packages/experimental/im/README.zh.md) 接纳外部上下文并提供用于读取和发布的[显式工具](../../../../packages/experimental/im/src/tools.ts);[IM 组合包](../../../../packages/experimental/im-bundle/README.zh.md) 把服务与各适配器作为 Host 条目插入已有的 profile。
来源接纳、写权限、投递模式、模型路由、工作目录和预设均由部署显式配置:`sources` 规则决定哪些聊天可以进入宿主以及其消息如何入库,`defaultDispatch` 组合出所有未被处理且提及机器人的消息都会进入的那个会话。所有聊天共享该会话的历史,因此需要按聊天隔离历史或后台 worker 的部署,改为在 `im/message` 事件链上挂载自己的插件。
传输层使用内置的 Satori 包(`plugin-im-core`、`satori-element`、`plugin-im-adapter-lark` 与 `plugin-im-adapter-qq`)。[vendor 清单](../../../../vendor/im/README.md) 记录准确的上游版本与本地修改。生成的飞书类型声明不提交到 Git,在安装阶段从经过哈希校验的固定源码生成。
## Durability and ownership
每个托管会话由单个服务实例持有对应的活动 `Agent`。`im_sessions` 存储域记录每个托管会话的归属方、组合配置与聊天绑定,并拒绝已在 IM 存储之外存在的会话 id。`im_messages` 在向平台返回 ACK 前记录外部事件摘要与消息记录。确定性的收件箱消息 ID(`deliveryMessageId`)与 Session 日志核对保证了跨重启恢复时不会向收件箱重复写入消息。
带 `operationId` 的发送操作在发出网络请求前先向 `im_receipts` 写入 `pending` 状态,并在收到结果后更新回执。使用相同 `operationId` 重放会直接返回已记录的回执而不会重复发送。平台明确返回未发布的错误码时记录为 `failed`;响应丢失、超时或发出后崩溃则记录为 `uncertain`,绝不自动重发。
`im` 消息来源仅作为归属元数据使用(见[兼容性记录](../../../../docs/persistence-changes/2026-10-28-im-message-source.zh.md))。权限校验由运行中的 IM 服务负责,现有沙箱与审批策略继续生效。
## Alternatives considered
**通过 Host 控制器增加 GUI 客户端。** 这种方式适合文本记录镜像与类型化交互控件,但会引入自动化不需要的对话策略和输出耦合。IM 直接使用 agent 工厂,并保留现有循环。
**在 IM 与 harness 之间使用 ACP。** ACP 支持持久化程序会话,适合进程隔离。独立 IM 发布仍然需要渠道或工具路径;进程内 Cordis 组合在保留自动化语义的同时避免增加进程。
**按聊天手工配置固定会话。** 手工命名每个会话及其来源意味着每新增一个聊天都要修改配置并重启。由 `sources` 与 `defaultDispatch` 组合出的单个会话即可把访问控制保留在来源规则中,无需逐个聊天配置。
**自动重试不确定的发送。** 响应丢失时无法判断平台是否已经创建了消息。保留 `uncertain` 状态供检查可避免自动重复发送,同时允许通过新的工具调用主动重发。
## Consequences
每组 IM 存储和会话由单个主机进程负责,多主机协调需要独立设计。托管会话在首次使用后常驻内存(标记为 `ephemeral` 的临时会话除外,它们在首轮结束后释放 agent)。有限的保留期(`retentionMs`)限定了事件去重窗口,待处理消息和未决回执不会自动过期。恢复投递时扫描 Session 日志核对收件箱消息 ID 会使恢复耗时随会话历史增长。
@@ -21,8 +21,8 @@
en: ca6a5c372bb3cad1
zh: 1cd5028269b58c65
/agent-note-one-fold-motion-for-collapsing-on-the-next-message/testing:
en: 49ef4fbe86699a2a
zh: b3fa6d77415f3892
en: 6928ea8cc28112e5
zh: e9d69605558ea102
/agent-note-one-fold-motion-for-collapsing-on-the-next-message/alternatives-considered:
en: d8e1ea66e293cd93
zh: 0aaa9e693f441673
@@ -73,7 +73,7 @@ Let `start` be the scrollTop when the batch begins, `above` the height of closin
## Testing
[fold-blank-matrix.e2e.ts](../../../../apps/web/tests/fold-blank-matrix.e2e.ts) covers 19 main-Session cases and 8 right-Sidebar child cases across reader position (bottom, middle of the body, top of the body, inside the steps, previous Turn), input source (composer, Turn failing before its message is recorded, another tab, queued delivery, steer, parent message, several Turns folding at once), body length, and Standard and "On completion" controls. The layout gap is the tallest band between the scrollport top and the composer that no visible row's box covers: at most 120 px once settled, and over that for at most one animation frame. The probe reads the layout after the animation callbacks for each rendering opportunity, before paint. Identical gaps on consecutive frames count separately. It counts boxes, so a closing row that has faded but not finished shrinking still covers the space it reserves in the layout, wherever its visual translate draws it; a row nested in a moving row covers only the part that row does not clip. Tail cases assert the floor landing; reader-content-still cases assert that the reader's anchor row moves at most 2 px on screen. Short-body cases assert only that no room remains after the reply arrives.
[fold-blank-matrix.e2e.ts](../../../../apps/web/tests/fold-blank-matrix.e2e.ts) covers 19 main-Session cases and 8 right-Sidebar child cases across reader position (bottom, middle of the body, top of the body, inside the steps, previous Turn), input source (composer, Turn failing before its message is recorded, another tab, queued delivery, steer, parent message, several Turns folding at once), body length, and Standard and "On completion" controls. The layout gap is the tallest band between the scrollport top and the composer that no visible row's box covers: at most 120 px once settled, and over that for at most one animation frame. The probe reads the layout after the animation callbacks for each rendering opportunity, before paint. Identical gaps on consecutive frames count separately. It counts boxes, so a closing row that has faded but not finished shrinking still covers its space. Tail cases assert the floor landing; reader-content-still cases assert that the reader's anchor row moves at most 2 px on screen. Short-body cases assert only that no room remains after the reply arrives.
## Alternatives considered
@@ -73,7 +73,7 @@ Status: implemented
## Testing
[fold-blank-matrix.e2e.ts](../../../../apps/web/tests/fold-blank-matrix.e2e.ts) 覆盖主会话 19 例与右侧栏子会话 8 例,维度包括读者位置(底部、正文中段、正文开头、步骤中间、上一轮)、输入来源(输入框、回合在写入消息前失败、另一个标签页、排队投递、steer、父消息、一次折叠多轮)、正文长短,以及 Standard 与「完成时收起」对照。布局空洞指视口顶部到输入框之间没有任何可见行的盒子覆盖的最大连续高度:落定后不超过 120 px,动画中至多 1 帧超过。探针在每次渲染机会的动画回调全部结束、绘制之前读取布局;相邻两帧的空洞即使相同,也分别计数。它按盒子计算:已经淡出但尚未收完的收起行仍覆盖它在布局中占据的空间,不论视觉位移把它画在哪里;嵌套在移动行里的行只覆盖移动行没有裁掉的部分。「到底部」的用例断言落到底部;「内容不动」的用例断言读者锚定行的屏幕位置变化不超过 2 px。正文很短的用例只断言回复到达后不再留空。
[fold-blank-matrix.e2e.ts](../../../../apps/web/tests/fold-blank-matrix.e2e.ts) 覆盖主会话 19 例与右侧栏子会话 8 例,维度包括读者位置(底部、正文中段、正文开头、步骤中间、上一轮)、输入来源(输入框、回合在写入消息前失败、另一个标签页、排队投递、steer、父消息、一次折叠多轮)、正文长短,以及 Standard 与「完成时收起」对照。布局空洞指视口顶部到输入框之间没有任何可见行的盒子覆盖的最大连续高度:落定后不超过 120 px,动画中至多 1 帧超过。探针在每次渲染机会的动画回调全部结束、绘制之前读取布局;相邻两帧的空洞即使相同,也分别计数。它按盒子计算,已经淡出但尚未收完的收起行仍算作覆盖。「到底部」的用例断言落到底部;「内容不动」的用例断言读者锚定行的屏幕位置变化不超过 2 px。正文很短的用例只断言回复到达后不再留空。
## Alternatives considered
@@ -12,8 +12,8 @@
en: a15c7c13f167e5ac
zh: 63bcc2ef60c2f344
/agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/decision/boot-the-same-profile-as-the-served-web-deployment:
en: efd95b62fb8949f9
zh: 135719b3ab2e38ae
en: 9b957e37f290abaf
zh: 06a4599c8fe449ad
/agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/decision/node-internal-module-interfaces-in-the-worker:
en: 37d8e809eaa21d25
zh: 8c7c31bd6f45c823
@@ -21,8 +21,8 @@
en: 608b24ca97ab5bca
zh: 94bb28377c856b2e
/agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/decision/separate-archives-for-lazily-loaded-chunks:
en: bb3f7f2737dddec6
zh: c514e53f6a4837ff
en: 428699f74f19e998
zh: 2e8fcdbc9616f70b
/agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/decision/watching-and-client-plugin-delivery:
en: 814c344e891f7f91
zh: a024d5e30607968b
@@ -30,8 +30,8 @@
en: 99ee505e82fa9c7c
zh: 448bc0e160424cbf
/agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/consequences:
en: e369a4b3dc5ecdb3
zh: 2da4047f4a5486b8
en: ed424571c81bcb91
zh: 9b79bf03741c1c21
/agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/testing:
en: 532918df1acd147d
zh: e476c090d183d0a4
@@ -27,7 +27,6 @@ The served launch path (apps/cli, app-boot) carries no Preview-specific code; th
- The image carries a manifest-only `node_modules/@deepseek-ai/dsh/package.json` (a verbatim copy of `apps/cli/package.json`) as the installation anchor, and the image manifest names it in `installation`.
- The image carries no composed configuration and no `config/cordis.yml`; the image manifest records the `profile` the Worker boots.
- The image carries a home patch, `home/cordis.patch.yml`: for each row the runtime's `PLATFORM_ENTRY_CONFIG` names (`session-persistence-jsonl`), the config the template's bundle layers compose with the required fields over it (`compression: none`). A patch replaces a row's whole config, so the composed fields stay; the bundle files read at pack time are the ones in the image.
- The image seeds the profile patch, `home/profiles/<profile>/cordis.patch.yml`, with the Preview's keyless model defaults: it inserts the [`llm-mock`](../../../../packages/experimental/llm-mock/README.md) row, sets `agent-default-model` to the `mock` route, and sets `credentialOnboarding: false` on `ui-settings-models`. App-boot keeps an existing profile patch when it initializes the profile, and ConfigEditor writes that layer, so users can still select and save another model and add a provider key in Models settings. A profile recovery that moves the patch aside also drops these defaults.
- **Worker**
- The image's app-boot `loadProfile` initializes `home/profiles/<profile>` from the template, the Worker writes an empty root `cordis.yml`, and `readProfilePatches` composes the layers.
- profileContext is filled the way `runProfile` fills it: name, dir, patchPath, installAnchor, startedBundles, cwd, home, and an empty overlay list, so the Worker calls `readProfilePatches` once, as the launcher does without `--patch`.
@@ -52,7 +51,7 @@ The Worker's structural stubs throw errors carrying `ERR_FEATURE_UNAVAILABLE_ON_
### Separate archives for lazily loaded chunks
- **Classification**: the client build preset emits asynchronous package-local chunk requests only as `require.async("./client.<name>.js")`, optionally with a `{ deps: [...] }` prefetch hint that names every other chunk the request needs ([chunk dependencies](2026-11-26-package-local-chunk-dependencies.md)). The packer's `lazyChunksOf` scans every page asset in the swept image (each package's `lib/client.js` and `lib/client.*.js`) for these literals, hint entries included, so a chunk that another chunk requests is found without following requests from the `./client` entry. A target that a package's `./client` export names under any condition (such as `client.browser.js`) loads eagerly and stays in the base image; every other target leaves it. A request for a chunk the package does not publish fails the pack.
- **Classification**: the client build preset emits package-local chunk requests only as `require.async("./client.<name>.js")`, and `verify-client-packages` forbids synchronous chunk requires. The packer's `lazyChunksOf` scans every page asset in the swept image (each package's `lib/client.js` and `lib/client.*.js`) for these literals, so a chunk that another chunk requests is found without following requests from the `./client` entry. A target that a package's `./client` export names under any condition (such as `client.browser.js`) loads eagerly and stays in the base image; every other target leaves it. A request for a chunk the package does not publish fails the pack.
- **Archives**: each chunk gets one deterministic tar.gz named `lazy/<sha256>.tar.gz` after the SHA-256 of the compressed archive. The base manifest's `lazy` list records each archive as `{ archive, files: [{ path, size }] }`, with no file mode. There is no size threshold.
- **Registration**: the Worker registers each listed file with `MemoryVfs.deferArchive`, which creates its parent directories and gives it the VFS default file mode; an image that lists lazy archives must be fetched from a URL, against which the archive names resolve. `exists`, `stat`, and `readdir` answer synchronously from the registration.
- **Fetch**: the asynchronous faces of the Worker's `node:fs` and `node:fs/promises` that read a registered file wait for its archive: `fs.promises.readFile`, `fs.promises.open` (so every FileHandle opens after arrival), `fs.promises.cp`, and `fs.createReadStream`. The first of them fetches the archive, inflates it, checks that it carries exactly the registered paths at the registered sizes, and materializes the files; concurrent readers share one fetch. The digest in the archive name is not verified. A failed fetch fails only the reads waiting on it; the files stay registered and the next asynchronous read fetches again.
@@ -82,7 +81,7 @@ The Worker's structural stubs throw errors carrying `ERR_FEATURE_UNAVAILABLE_ON_
## Consequences
The Preview boots the composition the served Web deployment boots. With no bundle enabled, the Worker composition differs from the served Web composition only by the jsonl platform override and the seeded profile patch's keyless model defaults, and enabling any bundle skips no patch. The Plugins page lists every `OPTIONAL_BUNDLES` entry with its title and icon and no metadata error. Switching each of the 11 optional bundles on and then off returns `applied` both times; after enabling, every enabled row it changes is active, and after disabling, the plugin list returns to its prior rows. Enabling session-titles disables `@deepseek-ai/dsh-session-title-first-prompt-llm` (row `session-title-llm`) and enables `@deepseek-ai/dsh-session-title-all-prompts-llm`, as in the served Web deployment; enabling inspector-profile runs Session Inspector and starts the NodeJS Inspector degraded. Degradation requires `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`, so a served `dsh web` runs the full Inspector.
The Preview boots the composition the served Web deployment boots. With no bundle enabled, the Worker composition differs from the served Web composition only by the jsonl platform override, and enabling any bundle skips no patch. The Plugins page lists every `OPTIONAL_BUNDLES` entry with its title and icon and no metadata error. Switching each of the 11 optional bundles on and then off returns `applied` both times; after enabling, every enabled row it changes is active, and after disabling, the plugin list returns to its prior rows. Enabling session-titles disables `@deepseek-ai/dsh-session-title-first-prompt-llm` (row `session-title-llm`) and enables `@deepseek-ai/dsh-session-title-all-prompts-llm`, as in the served Web deployment; enabling inspector-profile runs Session Inspector and starts the NodeJS Inspector degraded. Degradation requires `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`, so a served `dsh web` runs the full Inspector.
Size (MiB, measured): the base image is 9.20 (12.79 with pack-time composition and eager chunks, −28%) including 11 optional bundles, plus 5 lazy tar archives totaling 4.45 (pdf 2.88, excel 1.39, terminal 0.13, frontmatter 0.05, Inspector bottom panel 0.00). The base image contains no lazily loaded chunk, and the page fetches an archive only when it requests the chunk.
@@ -27,7 +27,6 @@ Status: implemented
- 镜像里放一份只含清单的 `node_modules/@deepseek-ai/dsh/package.json`(原样复制 `apps/cli/package.json`),作为安装锚点,镜像 manifest 在 `installation` 里记录它。
- 镜像不带组合好的配置,也没有 `config/cordis.yml`;镜像 manifest 记录 Worker 要启动的 `profile`。
- 镜像带一份 home patch `home/cordis.patch.yml`:对运行时 `PLATFORM_ENTRY_CONFIG` 列出的每一行(`session-persistence-jsonl`),写入模板各 bundle 层合成出的配置,并在其上设置所需字段(`compression: none`)。补丁会整体替换一行的配置,所以保留合成出的字段;打包时读取的 bundle 文件就是镜像里的那些。
- 镜像预置 profile patch `home/profiles/<profile>/cordis.patch.yml`,写入 Preview 无需密钥的模型默认值:插入 [`llm-mock`](../../../../packages/experimental/llm-mock/README.zh.md) 行,把 `agent-default-model` 设为 `mock` 路由,并在 `ui-settings-models` 上设置 `credentialOnboarding: false`。App-boot 初始化 profile 时保留已有的 profile patch,ConfigEditor 写入该层,因此用户仍可在模型设置中选择并保存其他模型、添加提供方密钥。Profile 恢复流程把该 patch 移走时,这些默认值也会一并丢失。
- **Worker**
- 用镜像里 app-boot 的 `loadProfile` 从模板初始化 `home/profiles/<profile>`,写空的根 `cordis.yml`,用 `readProfilePatches` 组合。
- profileContext 按 `runProfile` 填写:name、dir、patchPath、installAnchor、startedBundles、cwd、home,overlay 列表为空,因此 Worker 与不带 `--patch` 的启动器一样只调用一次 `readProfilePatches`。
@@ -52,7 +51,7 @@ Worker 的结构化 stub 抛出带 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 的错
### 懒加载 chunk 独立归档
- **分类**:client 构建预设只以 `require.async("./client.<name>.js")` 的形式产出异步的包内 chunk 请求,可选带上 `{ deps: [...] }` 预取提示,列出该请求需要的其他所有 chunk([分片依赖](2026-11-26-package-local-chunk-dependencies.zh.md))。packer 的 `lazyChunksOf` 扫描清扫后镜像里的每个页面资源(各包的 `lib/client.js` 和 `lib/client.*.js`)中的这些字面量,包括提示中的项,因此 chunk 引用的 chunk 不必从 `./client` 入口沿请求追踪也能找到。在任一条件下被某个包的 `./client` 导出指向的目标(如 `client.browser.js`)会被立即加载,留在基础镜像;其余目标移出基础镜像。请求包未发布的 chunk 会让打包失败。
- **分类**:client 构建预设只以 `require.async("./client.<name>.js")` 的形式产出包内 chunk 请求,`verify-client-packages` 禁止同步 require chunk。packer 的 `lazyChunksOf` 扫描清扫后镜像里的每个页面资源(各包的 `lib/client.js` 和 `lib/client.*.js`)中的这些字面量,因此 chunk 引用的 chunk 不必从 `./client` 入口沿请求追踪也能找到。在任一条件下被某个包的 `./client` 导出指向的目标(如 `client.browser.js`)会被立即加载,留在基础镜像;其余目标移出基础镜像。请求包未发布的 chunk 会让打包失败。
- **归档**:每个 chunk 一个确定性 tar.gz,按压缩后归档的 SHA-256 命名为 `lazy/<sha256>.tar.gz`。基础 manifest 的 `lazy` 列表把每个 archive 记录为 `{ archive, files: [{ path, size }] }`,不记录文件 mode。不设大小阈值。
- **登记**:Worker 用 `MemoryVfs.deferArchive` 登记列出的每个文件,同时创建其父目录,并赋予 VFS 默认文件 mode;列出懒加载 archive 的镜像必须从 URL 拉取,archive 名相对这个 URL 解析。`exists`、`stat`、`readdir` 依据登记同步作答。
- **拉取**:Worker 的 `node:fs` 和 `node:fs/promises` 中读取已登记文件的异步接口会等待其 archive:`fs.promises.readFile`、`fs.promises.open`(因此每个 FileHandle 都在到达后才打开)、`fs.promises.cp` 和 `fs.createReadStream`。其中第一个调用拉取 archive、解压,校验其中恰好是登记的路径和登记的大小,再物化文件;并发读取方共用一次拉取。archive 名里的摘要不做校验。拉取失败只让等待它的读取失败;文件保持登记,下一次异步读取再次拉取。
@@ -82,7 +81,7 @@ Worker 的结构化 stub 抛出带 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 的错
## 后果
Preview 启动的组合与正式 Web 相同。不开 bundle 时,Worker 组合与正式 Web 只差 jsonl 的平台覆盖和预置 profile patch 中无需密钥的模型默认值;开任一 bundle 都没有被跳过的补丁。插件页列出全部 `OPTIONAL_BUNDLES`,每个都显示标题和图标,没有元信息错误。11 个 optional bundle 逐个开启再关闭,两次都返回 `applied`;开启后它改动的每个启用行都是 active,关闭后插件列表恢复原样。启用 session-titles 会禁用 `@deepseek-ai/dsh-session-title-first-prompt-llm`(行 `session-title-llm`)并启用 `@deepseek-ai/dsh-session-title-all-prompts-llm`,与正式 Web 一致;启用 inspector-profile 后 Session Inspector 运行,NodeJS Inspector 降级启动。降级以 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 为前提,所以正常 `dsh web` 运行完整的 Inspector。
Preview 启动的组合与正式 Web 相同。不开 bundle 时,Worker 组合与正式 Web 只差 jsonl 的平台覆盖;开任一 bundle 都没有被跳过的补丁。插件页列出全部 `OPTIONAL_BUNDLES`,每个都显示标题和图标,没有元信息错误。11 个 optional bundle 逐个开启再关闭,两次都返回 `applied`;开启后它改动的每个启用行都是 active,关闭后插件列表恢复原样。启用 session-titles 会禁用 `@deepseek-ai/dsh-session-title-first-prompt-llm`(行 `session-title-llm`)并启用 `@deepseek-ai/dsh-session-title-all-prompts-llm`,与正式 Web 一致;启用 inspector-profile 后 Session Inspector 运行,NodeJS Inspector 降级启动。降级以 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 为前提,所以正常 `dsh web` 运行完整的 Inspector。
体积(MiB,实测):基础镜像 9.20(打包期组合且 chunk 随启动下载时为 12.79,−28%),含 11 个 optional bundle;另有 5 个 lazy tar 共 4.45(pdf 2.88、excel 1.39、terminal 0.13、frontmatter 0.05、inspector 底部面板 0.00)。基础镜像不含懒加载 chunk,页面请求 chunk 时才拉取对应 archive。
@@ -1,37 +0,0 @@
# Bilingual-pair consistency record for 2026-10-15-desktop-shared-texture-api.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-15-desktop-shared-texture-api.md
/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package:
en: de5e9439711001ae
zh: e5ac22aa5d51043d
/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/problem:
en: 4adf47d0d97b0e23
zh: 12dedda00f579336
/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/decision:
en: beeb92d43bbf3389
zh: 39e77f9c22210ea3
/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/decision/desktop-shared-textures:
en: 9cf55a65959c002c
zh: b29f1fc65936632e
/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/decision/trust-model:
en: d056763e283a5d30
zh: fd7f1bba0ce5eba6
/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/decision/the-frame-forwarding-package:
en: 59b3109d10f52831
zh: f04c9bd2a730b30a
/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/decision/frame-path:
en: 7ba66e63258cc160
zh: 87373d062c2dde60
/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/alternatives-considered:
en: dfa341b1fe449288
zh: 475e6ab42702ba36
/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/verification:
en: a98f84f310538d8b
zh: bd345d71474eb862
/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/consequences:
en: b823f7ee32d12180
zh: f7338b942f03e81c
/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/consequences/native-producer-sdk:
en: 9eabfbc1a83598d4
zh: d43c9db0b40942c8
@@ -1,105 +0,0 @@
# Agent Note: Generic Desktop shared-texture API with a shared frame-forwarding package
Status: implemented
English | [中文](2026-10-15-desktop-shared-texture-api.zh.md)
## Problem
The native Office preview needs textures rendered by a LibreOffice process to reach the Electron renderer without copying pixels, which requires an Electron main-process import and a renderer-side `sharedTexture` consumer. The first design of the Office Preview and Editing bundle let a bundle declare `dsh.bundle.desktop` with `main`, `preload`, and `verify` exports: Desktop imported the bundle's module into the main process, registered its preload for every frame of the default session, and verified the bundle's native payload with the bundle's own verifier. That selection could only be made at application startup, so enabling or disabling the bundle required a Desktop restart, and the startup selection had to be pinned through `loadProfileDirectory`, `ProfileRuntimeResolution`, `DSH_DESKTOP_STARTUP_BUNDLES`, the plugin manager (`restart-required`, `desktop-only`), the package manifest types, and the Web plugin list. Any installed package carrying the declaration could run code in the main process and in a session-wide preload, and Electron's `setSharedTextureReceiver` is a document singleton, so two such bundles would have overwritten each other.
The correction that followed made frame forwarding a fixed Desktop capability: the Electron main process ran the native receiver (first loaded from the LibreOffice Kit's receiver SDK in the dsh runtime, then built from Kit sources copied into `apps/desktop`), validated producer metadata, and answered `frame-forwarding` control messages that carried viewports, generations, and credits. `apps/desktop` therefore carried protocol that only the Office preview used, its preload exposed frame forwarding rather than textures, a receiver inside Electron Main could not use libuv and needed Electron-compatible builds, and every protocol change required a Desktop release before a Kit release could use it. Copying the Kit's C++ into Desktop added a second claimed origin for one protocol; loading it from the Kit tied every Desktop receiver change to a Kit release. Frame forwarding is also not Office's: other Host plugins will render in native processes of their own, so the receiver, its transport, and its Host service cannot belong to the Office package either, and the Kit is one producer among several.
Electron fixes what Desktop must own. `sharedTexture.importSharedTexture` runs only in the main process and accepts only a handle local to that process: an `IOSurfaceRef` on macOS, an NT `HANDLE` on Windows. `sharedTexture.subtle` exports an imported texture for a renderer to import, and each reference's release callback runs after the GPU work that used it completes. The managed `sendSharedTexture` waits at most 1000 ms for the renderer's acknowledgement; when Main then releases its reference, a renderer that was busy for longer imports a destroyed texture and shows an empty frame. Electron has no API that receives a GPU handle from a process outside Chromium, and Node cannot receive Mach messages or duplicate Win32 handles. On macOS, bringing a foreign IOSurface into Main needs native code in Main; on both platforms, carrying a Host-local handle toward Main needs native code in the Host.
Whatever Desktop adds for that consumer is reachable by other code in the same process: a Host service by every Host plugin, a preload object by every script of the document. Two consumers of one texture interface would steal each other's frames, and a consumer that registers while frame forwarding is idle would take the interface over. The Office slideshow also entered window fullscreen through `dshDesktop.window.setFullscreen`, a Desktop-private API that Office read by duck typing and that Main restored by bookkeeping of its own; every plugin that needs fullscreen, for example a game, would have needed the same window control.
## Decision
Desktop owns an internal shared-texture API whose only consumer is frame forwarding, including the hop and ingress addons that open a native channel between the Host and Electron Main and carry Host-local handles across it; no plugin runs code in the Electron main process or a session-wide preload. The [`frame-forwarding`](../../../../packages/experimental/frame-forwarding/README.md) package owns frame forwarding for every Host plugin: the `frameForwarding` Host service, and the renderer-side views.
### Desktop: shared textures
Plugins see frame forwarding only. The shared-texture service definitions live in [`@deepseek-ai/dsh-shared-texture`](../../../../packages/shared-texture/shared-texture/README.md) with separate Host and Client compiler faces. Its root entry (`.`) defines the abstract Host `SharedTexture` Cordis service (`ctx.sharedTexture`), whose `claim()` grants `capabilities`, `nativeSink`, and `adapterLuid` to one holder until `release()` or the disposal of the scope that claimed; its `./types` entry defines the Cordis-free `SharedTextureClientExport`, `SharedTextureHostExport`, and `SharedTextureLease` shared by Desktop preload and the Client plugin; and its `./client` entry is the Client plugin that provides that bridge as the Client `ctx.sharedTexture`, typed `SharedTextureClientExport`. web-app mounts the package; its Host entry does nothing. Because Host and Client faces compile with separate `tsconfig.{host,client}.json` programs, the Host `Context` declaration never enters a Client program. Desktop Main takes the types of the `shared-texture` control messages (`capabilities` and `adapter-luid`) exchanged over the Host child-process channel from the Desktop Host's own `types` export ([`apps/desktop-host/src/types.ts`](../../../../apps/desktop-host/src/types.ts)), a private protocol between the two rather than a plugin API, and the hop addon's interfaces stay beside the service that loads it; each side validates every message it receives at runtime ([Main's channel](../../../../apps/desktop/src/shared-texture/channel.ts), [`apps/desktop-host/src/shared-texture.ts`](../../../../apps/desktop-host/src/shared-texture.ts)). The two apps share no package dependency; Main compiles against that export through a TypeScript project reference. Electron Main wires everything through one [entry](../../../../apps/desktop/src/shared-texture/main.ts) that attaches the [shared-texture channel](../../../../apps/desktop/src/shared-texture/channel.ts) to each Host process and supplies the window and Host cleanups; the channel validates every control request before Main's presenter sees it, and the Host-process lifecycle carries no shared-texture routing.
- The Desktop Host's [`sharedTexture` service](../../../../apps/desktop-host/src/shared-texture.ts) takes Host-local handles and loads the hop addon ([`native/shared-texture/hop.cc`](../../../../apps/desktop/native/shared-texture/hop.cc), Node-API 8 only) that Main names in its capabilities on first use. On macOS and Windows the hop opens one native two-way connection to Main's ingress — a pair of Mach ports on macOS, and a duplex message named pipe on Windows where Main duplicates each frame's Host-local NT handle into its own process — and every frame's submission, delivery reply, and settlement travel on that connection while the Host IPC channel carries only `capabilities` and `adapter-luid`. Each connection admits at most 128 unsettled requests; losing the connection settles its unsettled requests as `invalidated`, and the next frame opens a new connection. `nativeSink(timeoutMs)` returns an opaque `napi_external` pointing to `dsh_shared_texture_sink_v2` ([`native/shared-texture/shared-texture-sink.h`](../../../../apps/desktop/native/shared-texture/shared-texture-sink.h)) for same-process native addons; a consumer built for another ABI version refuses it. A frame carries its handle, size, pixel format, metadata, and a delivery deadline that applies in the Host only, and no request identifier. The sink is bound to that connection: `present` returns `DSH_SHARED_TEXTURE_PRESENT_OK` when the request left the Host, `DSH_SHARED_TEXTURE_PRESENT_REJECTED` when it refused only that frame and the sink stays usable, and `DSH_SHARED_TEXTURE_PRESENT_DISCONNECTED` once the connection was closed or lost, for every later frame too, so the consumer obtains a new sink. Ending a claim that took `nativeSink` closes that connection and settles its unsettled frames as `invalidated`. `adapterLuid(timeoutMs)` returns `null` outside Windows without asking Main and never opens the native connection; on Windows Main exports one texture from Chromium's compositor, reads its adapter's LUID through the ingress addon, and releases the texture at once. Main keeps the answer until Chromium's GPU process exits or the Host stops, shares one reading among concurrent queries, and keeps no failed reading. The answer is `<HighPart>:<LowPart>` in lowercase hexadecimal, the text frame forwarding's receiver uses for adapters, or `null` when Chromium exports no Direct3D 11 compositor texture, DXGI cannot read its adapter, or a cleanup cancelled the reading.
- Main's ingress ([`native/shared-texture/ingress.cc`](../../../../apps/desktop/native/shared-texture/ingress.cc)) queues at most 32 frames waiting for Main's JavaScript thread and refuses any frame beyond them with no reference kept, so the Host can reuse that texture at once. For each admitted frame, Main's [presenter](../../../../apps/desktop/src/shared-texture/presenter.ts) imports the handle and sends the subtle transfer with the Host's metadata unchanged to the product main frame over Desktop's IPC. Main keeps its import until the document reports its own reference, then replies `delivered` on the native channel; a busy renderer delays that reply — keeping the Host's slot past a delivery timeout until settlement — instead of losing the texture. Main settles every admitted presentation once on the native channel: it replies `released` after its own release callback and the document's release, which the document sends from its release callback, have both arrived, and `invalidated` when the document, renderer, GPU process, or GPU release synchronization failed or went away first; a failure reply with no reference kept means Main retained nothing. Main validates the pixel dimensions Electron bounds and parses `metadata` JSON without interpreting its fields.
- Main's `capabilities` reports its process identity to the Desktop Host, which passes only support and a reason to its consumer; on macOS and Windows it also reports the hop addon path and opens one native ingress (Node-API 8 only) for the requesting Host. On macOS ([`native/shared-texture/ingress-darwin.cc`](../../../../apps/desktop/native/shared-texture/ingress-darwin.cc)) the ingress is a Mach receive port: it accepts a message only when its audit trailer names the Host process Main spawned, resolves the carried port with `IOSurfaceLookupFromMachPort`, delivers the Main-local `IOSurfaceRef`, and replies to the Host's reply port, dropping messages from other processes and oversized messages while the Host's messages keep arriving. On Windows ([`native/shared-texture/ingress-win32.cc`](../../../../apps/desktop/native/shared-texture/ingress-win32.cc)) the ingress is a single-instance duplex message named pipe: it checks `GetNamedPipeClientProcessId` against that Host process before reading, disconnects any other client, holds a `PROCESS_DUP_HANDLE | SYNCHRONIZE` handle to the connected Host, and duplicates each frame's NT `HANDLE` from the Host into Main; the same addon reads, through DXGI, the adapter LUID of a Main-local shared texture for `adapter-luid`. The ingress lives as long as that Host process: window-level cleanup keeps it, so the Host queries capabilities once per connection and presents every later frame over the native channel without another IPC round trip. An explicit capability query always reaches Main, which reports `gpu-compositing-disabled` while Chromium composites in software, for example after repeated GPU process crashes. A message from the Host with another protocol version or malformed contents stops the ingress with an error, ending the connection, and the next capability query reopens it.
The application preload exposes `dshDesktop.textures` to the product main frame only: it imports each transfer, reports the result to Main at once, delivers `{ frame, metadata, release }` to the single document consumer, and releases textures that arrive without one. The shared-texture Client plugin provides `globalThis.dshDesktop?.textures` as the Client `ctx.sharedTexture`, so other Client plugins never read `globalThis.dshDesktop`. Desktop offers the document no window control: a plugin that shows a view fullscreen uses the document's Fullscreen API through frame forwarding, Electron makes the window fullscreen for the document's fullscreen element, and the existing state relay keeps window chrome in step. Main cancels a pending adapter reading, refuses frames arriving during cleanup, settles the textures sent to the document as `invalidated`, and starts a new document generation when the renderer or GPU process exits, a cross-document navigation commits, or the window closes; a GPU process exit also forgets the compositor adapter, and the ingress closes only when the Host process stops or fails. Main never reports an unobserved reference as released. Cancelled, intercepted, and same-document navigations keep the document's textures, and the document generation fails a capability query that spans a reset during ingress replacement.
### Trust model
Main trusts only the Host process it spawned. The macOS ingress drops every message whose audited sender PID differs from the Host's and keeps receiving the Host's; the Windows ingress checks `GetNamedPipeClientProcessId` before reading, disconnects any other client, and duplicates handles only from that Host process. Producers never communicate with Main, and only Desktop's hop touches the Host-to-Main channel.
Security review has two process boundaries. The Host-to-Main boundary is Desktop's: any code in the Host process can send to Main without the `sharedTexture` service, so Main's request validation and the ingress PID check are audited as part of Desktop and do not change with frame forwarding. The producer-to-Host boundary is frame forwarding's, recorded in its [security semantics](../../../../packages/experimental/frame-forwarding/README.md#security-semantics). The plugin API is `frameForwarding` alone; reserving `sharedTexture` for the exclusive frame-forwarding consumer makes it unsupported for general plugins rather than unreachable, so it is not a security boundary. Both shared-texture surfaces admit one consumer at a time, and frame forwarding takes both while it is loaded: its Host plugin holds the Host `sharedTexture` claim from load to unload, and its Client consumes Client `ctx.sharedTexture` from start to disposal, also while no channel is open. Another consumer therefore fails at once instead of taking either interface over when frame forwarding is idle. A claim ends with the scope that took it, so a holder unloaded without releasing cannot keep it.
### The frame-forwarding package
`@deepseek-ai/dsh-frame-forwarding` owns frame forwarding for any Host plugin whose producer speaks its wire protocol.
- The frame-forwarding workspace keeps the [receiver source](../../../../packages/experimental/frame-forwarding/native/receiver.cc) alongside the plugin that uses its protocol. Desktop builds it directly from the workspace for each macOS and Windows target and ships the binary and build record. The plugin’s npm package excludes the receiver sources and binary. Main resolves the addon's absolute path for the running Desktop and passes it to the Host as `--frame-receiver-path`. The Host publishes this path through its internal `desktopFrameReceiver` service. On first use the plugin checks the build record against its own protocol and handshake requirements, then loads the addon in the Host process. The listener and producer handshake for each channel run in the Host process.
- The Host [forwarder](../../../../packages/experimental/frame-forwarding/src/host/forwarder.ts) owns channels and their producer connections ([frame-forwarding channels](2026-10-18-frame-forwarding-channels.md)), the frame and byte budgets, and viewport acknowledgement and replay. When opening a channel, it asks `sharedTexture.capabilities()`, obtains `sharedTexture.nativeSink()`, and on Windows reads Chromium's adapter from `sharedTexture.adapterLuid()` before creating the receiver; every channel asks, because Desktop reads the adapter again after Chromium's GPU process restarts. It attaches the sink to the channel's receiver with `attachSink`, with a presentation deadline of at most 30000 ms, and updates the receiver's deliverable state via `setDeliverable` as connections, viewports, and visibility change. In the receiver addon, the C++ Desktop bridge validates producer metadata on the thread that produced the frame, filters frames against that deliverable state, and submits matching frames through `dsh_shared_texture_sink_v2` with `rx`, `connectionId`, `requestId`, `frameId`, `generation`, `revision`, `width`, and `height` as metadata, so steady-state frames never cross the Host's JavaScript event loop. On `on_settled`, the bridge returns the frame's credit directly when released; on `invalidated`, it stops the receiver before releasing the delivery and notifies the forwarder to close the channel as `lost`. Refused submissions and failed deliveries report `presentation-error` to the renderer; a submission refused with any result other than `DSH_SHARED_TEXTURE_PRESENT_REJECTED` detaches that sink, while a rejected frame leaves it attached; without an attached sink, frames arrive in JavaScript as `frame` events, where the forwarder returns the credit at once, requests a fresh `nativeSink`, and reattaches it to open channels.
- The Host plugin is a Typert Remote service: consumers use `capabilities`, `channel`, `isOpen`, and `close`; the renderer applies viewports through the `viewport` Remote and follows channel states from the `events` stream. The Client plugin provides the renderer-side `frameForwarding` service only when Client `ctx.sharedTexture` is available; `connect(rx)` returns a receive channel that consumes `ctx.sharedTexture`, routes textures by the `rx` in their metadata, lends each frame to a consumer callback, and releases it when the callback settles. Receive channels also hold the document's fullscreen element, one at a time, and report coverage to the others ([frame-forwarding channels](2026-10-18-frame-forwarding-channels.md)). A channel closes with the Cordis scope that opened it.
- Every consumer bundle inserts frame forwarding as the same row, `frame-forwarding`, without a config. The Loader keeps one row per id, so consumers enabled together share one instance and its one claim, and disabling one consumer leaves the instance and the other consumers' channels running; deployments tune its limits with a patch targeting that id.
### Frame path
```
LibreOffice (Kit producer holding the channel's TX credential)
│ Packet protocol: hello / allocate / frame (+ handle) / release / message
▼
Host process — frame-forwarding receiver addon + C++ Desktop bridge (attachSink, setDeliverable)
│ credits, budget, handoff, metadata check, deliverable filter → dsh_shared_texture_sink_v2.present
▼
Host process — Desktop shared-texture hop addon (≤ 128 unsettled; Host IPC: capabilities / adapter-luid only)
│ macOS: Mach port pair (IOSurface port + reply port) ⇄ Main ingress
│ Windows: duplex message named pipe (Host NT HANDLE; Main DuplicateHandle from Host) ⇄ Main ingress
▼
Electron Main — shared-texture ingress addon (delivery queue ≤ 32) + presenter → renderer frame
│ document import result → delivered reply, Main drops its import; both GPU releases → released
▼
Native channel reply (released or invalidated) → hop reader → bridge on_settled returns credit (invalidated stops receiver first → channel lost)
```
## Alternatives considered
**Keep the bundle-declared main, preload, and verify exports.** This hands every installed bundle main-process and session-wide preload execution for one consumer, duplicates a singleton Electron API across bundles, and forces startup-only activation with its restart plumbing through app-boot, plugin manager, manifest types, and the Web plugin list. Rejected in review.
**Keep frame forwarding in Electron Main as a fixed Desktop capability.** This was the intermediate decision. It leaves protocol only one plugin uses and a receiver bound to the Electron main process in `apps/desktop`, couples protocol changes to Desktop releases, and makes the preload API a frame-forwarding API. Its own rejected variants remain rejected for the same reasons: loading the receiver SDK from the Kit installed in the dsh runtime ties every receiver change to a Kit release; libuv completion signalling (`uv_async_t`) lies outside Node-API's ABI guarantee and would force Electron-exact builds.
**Give the Office package its own receiver addon with the hop inside it.** Frame forwarding serves every Host plugin that renders natively, not Office alone, and the hop is Desktop's shared-texture mechanism, not frame forwarding's. An Office-owned addon would have to be copied by the next consumer and would make a feature package the owner of Mach and Win32 handle transfer.
**Electron's managed `sendSharedTexture` and `setSharedTextureReceiver`.** Its fixed 1000 ms acknowledgement deadline fails a view whenever the renderer's main thread is busy longer, and keeping Main's import past the deadline still returned the producer's texture before the renderer's GPU work completed. Rejected after real-device stall tests.
**Load the plugin's addon into Electron Main through an extension slot.** Plugin native code would run in the main process. Loading it in the Host keeps Main's native code fixed to Desktop's ingress addon.
**Publish the receiver as prebuilt npm platform packages now.** Desktop packaging already runs on each target operating system with a C++ toolchain; platform packages would add four packages, a release workflow, and Windows prebuild CI before the package has a second consumer. Deferred, not rejected.
**No native code in Desktop, with pixels copied through the Host.** Each frame would copy tens of megabytes and lose the shared-texture path that motivates native preview. It remains a possible fallback for small viewports, not the design.
**Let the producer send surfaces directly to Main's ingress.** This saves one Mach message per frame but requires Main to authenticate a process it did not spawn and requires the consumer to obtain Main's endpoint before starting the producer. The trust model excludes it; measured hop cost is the condition for revisiting.
**Global IOSurface identifiers (`IOSurfaceLookup`).** Deprecated by Apple and readable by every process of the user.
**Place the receiver in `apps/desktop-host`.** The Desktop Host would then carry one protocol's native build and service; Desktop Host provides shared textures and the preinstalled receiver’s location. The plugin owns the protocol checks and Node-API bindings.
**Keep `dshDesktop.window.setFullscreen`.** It is a Desktop window control per plugin need, read by duck typing, with Main-side restore bookkeeping. Element fullscreen is document-scoped, ends on Escape without plugin code, and tells frame forwarding which channel covers the others.
**Give each consumer bundle its own frame-forwarding row.** Two instances would compete for the one `sharedTexture` claim and the one renderer texture subscription; the second would report native rendering unavailable while the first serves only its own consumer.
**Insert frame forwarding from the Desktop profile itself.** Every Desktop session would load the receiver and hold Desktop's interfaces even with no consumer enabled, and a profile without Desktop-specific rows could not stay shared with Web.
**Making the Office Host plugin itself hide the bundle in Web.** The plugin needs no profile check: without `frameForwarding` support it reports unavailable, the Client registers no UI, and the existing PDF and spreadsheet preview remains.
## Verification
Desktop specs cover the [presenter](../../../../apps/desktop/tests/shared-texture-presenter.spec.ts) (one ingress per Host and replacement for another Host, software-compositing detection, the hop addon path and ingress endpoint, the 128-frame limit, Electron import failure without keeping a reference, renderer import results including a busy renderer, a failed import, and a missing GPU sync token, delivery-before-settlement reply ordering, `reset` invalidating frames sent to the document while keeping the ingress, `dispose` closing the ingress after abandoning sent frames, ingress failure and reopening, adapter LUID readings kept for their GPU process, shared by concurrent queries, not kept when they fail or a GPU process exit overtakes them, and null outside Windows, and the Main entry answering through its channel), the [preload bridge](../../../../apps/desktop/tests/preload-shared-texture.spec.ts) including import reports and the release report after its consumer and the GPU, [sent-texture settlement](../../../../apps/desktop/tests/shared-texture-transfer.spec.ts), the [shared-texture channel](../../../../apps/desktop/tests/shared-texture-channel.spec.ts) accepting only capability and bounded adapter requests and routing control with the Host identity, [generic Host-process channels](../../../../apps/desktop/tests/host-process.spec.ts), [declared native package builds](../../../../apps/desktop/tests/native-package-builds.spec.ts), and the [shared-texture addon verifier](../../../../apps/desktop/tests/shared-texture-runtime.spec.ts). The [Desktop native e2e](../../../../apps/desktop/tests/shared-texture-native.e2e.ts) exchanges real textures between separate Main and Host processes over the built hop and ingress addons from native `dsh_shared_texture_sink_v2` threads, covers every reply kind, refuses presentations that cannot leave the Host without sending them, reports sink ABI version 2 so a consumer built for another version refuses it, rejects frames beyond the 32-frame delivery queue at once while Main's JavaScript thread is blocked and resumes afterwards, ignores another process at the endpoint while continuing to serve the registered Host, ends the connection when a send finds Main gone or Main cannot deliver its replies, stops the ingress on another protocol version or malformed requests, enforces hop delivery deadlines while keeping the slot until Main settles, reconnects and settles once on close or Main exit, and reads the adapter LUID of a shared Direct3D 11 texture as the text Host addons derive while reading none from other handles. The [built-preload e2e](../../../../apps/desktop/tests/preload.e2e.ts) asserts `dshDesktop.textures` exposes only `onFrame` and `dshDesktop` exposes no window control. [Desktop Host specs](../../../../apps/desktop-host/tests/shared-texture.spec.ts) cover the single claim, its end with the claiming scope, including a claim taken inside an effect of that scope as frame forwarding takes it, a release before the scope's disposal that leaves the next holder's claim intact, hop connection reuse and reconnection after disconnect with unsettled frames invalidated, `nativeSink` closing its connection when the claim that took it ends while claims that never took it settle normally, `adapterLuid` returning Main's reading or null without opening the native connection, refusing a reading that is not a LUID, reporting Desktop's reason, and timing out while ignoring the late reply, unrelated channel traffic, and pending work rejected on disposal. Frame-forwarding specs cover the [forwarder](../../../../packages/experimental/frame-forwarding/tests/forwarder.host.spec.ts) (every Windows channel reading the adapter LUID from Desktop, every channel asking Desktop for its current `nativeSink` with concurrent requests shared, the sink deadline capped at 30000 ms, refresh when unattached frames reach JavaScript, deliverable-state updates pushed before each viewport is sent, presentation error and invalidation handling, producer connections and handoff, viewport replay, and teardown), the [Host service](../../../../packages/experimental/frame-forwarding/tests/service.host.spec.ts) with its claim, channel ownership by the opening scope, and Remote, the [receiver loader](../../../../packages/experimental/frame-forwarding/tests/native.host.spec.ts) and its build-record check, the [Client mount](../../../../packages/experimental/frame-forwarding/tests/mount.client.spec.ts), the [wire adapter](../../../../packages/experimental/frame-forwarding/tests/wire.client.spec.ts) with its lifelong texture subscription and fullscreen holder, and [receive channels](../../../../packages/experimental/frame-forwarding/tests/rx.client.spec.ts). The [Desktop bridge native e2e](../../../../packages/experimental/frame-forwarding/tests/desktop-bridge-native.e2e.ts) drives a real producer through the built receiver's C++ sink bridge, covering metadata projection, credit return on release and outside the delivLine truncated
## Consequences
Preinstalling the receiver lets users install or enable the plugin without a C++ toolchain. Native fixes and receiver protocol updates ship with Desktop. Each plugin version checks the preinstalled receiver and reports it as unavailable if incompatible. Steady-state frames bypass the Host's JavaScript event loop; between Host and Main each frame costs Mach messages on macOS or named-pipe messages and one `DuplicateHandle` by Main on Windows, never a pixel copy. Texture lifetime spans three processes: Main owns and closes the Windows handles it duplicated from the Host once Electron's GPU work finishes or Host teardown runs, and a Main exit ends the Host and the producer with it. On Windows, Main opens the Host it spawned with `PROCESS_DUP_HANDLE | SYNCHRONIZE` while the Host never opens Main; a failed open disconnects the pipe and a denied `DuplicateHandle` replies with a delivery error rather than presenting nothing silently.
### Native producer SDK
The native producer interface is still evolving with the Office integration. DSH defers publishing a third-party producer SDK because external plugins could come to depend on C calls that still change with the engine. Reconsider publication once the producer interface has settled. LibreOffice Kit connects through its own engine.
@@ -1,105 +0,0 @@
# Agent Note: 通用 Desktop 共享纹理 API 与共享的帧转发包
Status: implemented
[English](2026-10-15-desktop-shared-texture-api.md) | 中文
## Problem
原生 Office 预览需要把 LibreOffice 进程渲染的纹理不经像素拷贝地送达 Electron renderer,这要求一个 Electron 主进程侧的导入和一个 renderer 侧的 `sharedTexture` 消费者。“Office 预览编辑”bundle 的第一版设计允许 bundle 通过 `dsh.bundle.desktop` 声明 `main`、`preload` 和 `verify` 导出:Desktop 把 bundle 的模块导入主进程,为默认 session 的每一个 frame 注册其 preload,并用 bundle 自带的校验器校验其原生载荷。这种选择只能在应用启动时做出,因此启用或关闭该 bundle 必须重启 Desktop,而启动时的选择又必须穿透 `loadProfileDirectory`、`ProfileRuntimeResolution`、`DSH_DESKTOP_STARTUP_BUNDLES`、插件管理器(`restart-required`、`desktop-only`)、包清单类型和 Web 插件列表加以钉死。任何带有该声明的已安装包都能在主进程和 session 级 preload 中运行代码;而 Electron 的 `setSharedTextureReceiver` 是 document 级单例,两个这样的 bundle 会互相覆盖。
随后的修正把帧转发变成 Desktop 的固定能力:Electron 主进程运行原生接收器(先是从 dsh runtime 内的 LibreOffice Kit 接收端 SDK 加载,后来用拷贝进 `apps/desktop` 的 Kit 源码构建),校验 producer 元数据,并应答携带 viewport、generation 和信用的 `frame-forwarding` 控制消息。于是 `apps/desktop` 带着只有 Office 预览使用的协议,其 preload 暴露的是帧转发而不是纹理,位于 Electron Main 内的接收器不能使用 libuv 且需要与 Electron 兼容的构建,而每次协议变更都要先发 Desktop 版本,Kit 版本才能使用。把 Kit 的 C++ 拷进 Desktop 让同一个协议多出第二个自称的来源;从 Kit 加载则把 Desktop 接收器的每次变更绑死在 Kit 发版上。帧转发也不属于 Office:其他 Host 插件将来也会在各自的原生进程中渲染,因此接收器、传输和 Host 服务也不能归 Office 包所有,Kit 只是多个 producer 中的一个。
Electron 决定了 Desktop 必须持有什么。`sharedTexture.importSharedTexture` 只在主进程运行,且只接受该进程本地的句柄:macOS 上是 `IOSurfaceRef`,Windows 上是 NT `HANDLE`。`sharedTexture.subtle` 导出已导入的纹理供 renderer 导入,每个引用的释放回调在使用它的 GPU 工作完成后运行。托管的 `sendSharedTexture` 最多等待 renderer 确认 1000 ms;此后 Main 释放自己的引用,忙碌更久的 renderer 会导入一个已销毁的纹理并显示空帧。Electron 没有任何 API 能从 Chromium 之外的进程接收 GPU 句柄,Node 也不能接收 Mach 消息或复制 Win32 句柄。在 macOS 上,把外部 IOSurface 带进 Main 需要 Main 里的原生代码;在两个平台上,把 Host 本地句柄送往 Main 都需要 Host 里的原生代码。
Desktop 为这个消费者新增的任何东西,同一进程中的其他代码也能触达:Host 服务能被每个 Host 插件调用,preload 对象能被文档中的每段脚本调用。同一纹理接口的两个消费者会互相抢走对方的帧,在帧转发空闲时注册的消费者会接管该接口。Office 放映还通过 `dshDesktop.window.setFullscreen` 进入窗口全屏,这是 Desktop 的私有 API,Office 以鸭子类型读取它,Main 则靠自己的记录来恢复窗口状态;每个需要全屏的插件(例如游戏)都得要同样的窗口控制。
## Decision
Desktop 持有一个内部共享纹理 API,其唯一消费者是帧转发,包括在 Host 与 Electron Main 之间建立原生通道并跨通道传递 Host 本地句柄的跳转与 ingress addon;没有任何插件在 Electron 主进程或 session 级 preload 中运行代码。[`frame-forwarding`](../../../../packages/experimental/frame-forwarding/README.zh.md) 包为所有 Host 插件持有帧转发:`frameForwarding` Host 服务和 renderer 侧视图。
### Desktop:共享纹理
插件只看到帧转发。共享纹理服务定义位于 [`@deepseek-ai/dsh-shared-texture`](../../../../packages/shared-texture/shared-texture/README.zh.md),采用独立的 Host 与 Client 编译面。其根入口(`.`)定义抽象 Host Cordis 服务 `SharedTexture`(`ctx.sharedTexture`),其 `claim()` 把 `capabilities`、`nativeSink` 和 `adapterLuid` 交给唯一的持有者,直到 `release()` 或发起认领的作用域被销毁;`./types` 入口定义不含 Cordis 依赖的 `SharedTextureClientExport`、`SharedTextureHostExport` 与 `SharedTextureLease`,供 Desktop preload 与 Client 插件共用;`./client` 入口是 Client 插件,把该桥接提供为 Client 侧的 `ctx.sharedTexture`,类型为 `SharedTextureClientExport`。web-app 挂载本包,其 Host 入口不做任何事。由于 Host 与 Client 编译面使用各自独立的 `tsconfig.{host,client}.json` 程序,Host 的 `Context` 声明不会进入 Client 程序。Desktop Main 从 Desktop Host 自己的 `types` 导出([`apps/desktop-host/src/types.ts`](../../../../apps/desktop-host/src/types.ts))导入两者经 Host 子进程通道交换的 `shared-texture` 控制消息(`capabilities` 和 `adapter-luid`)的类型;这是两者之间的私有协议,不是插件 API,hop addon 的接口留在加载它的服务旁边。两侧各自在运行时校验收到的每条消息([Main 的通道](../../../../apps/desktop/src/shared-texture/channel.ts)、[Host 的服务](../../../../apps/desktop-host/src/shared-texture.ts))。两个应用之间没有包依赖:Main 通过 TypeScript 项目引用编译这组导出。Electron Main 通过一个[入口](../../../../apps/desktop/src/shared-texture/main.ts)接入全部内容:它把 [shared-texture 通道](../../../../apps/desktop/src/shared-texture/channel.ts)挂到每个 Host 进程上,并提供窗口级和 Host 级清理;通道在 Main 的 presenter 看到请求之前校验每个控制请求,Host 进程生命周期不携带任何 shared-texture 路由。
- Desktop Host 的 [`sharedTexture` 服务](../../../../apps/desktop-host/src/shared-texture.ts)接收 Host 本地句柄,并在首次使用时加载 Main 在其能力中给出的跳转 addon([`native/shared-texture/hop.cc`](../../../../apps/desktop/native/shared-texture/hop.cc),仅依赖 Node-API 8)。macOS 和 Windows 上都由跳转向 Main 的 ingress 打开一条原生双向连接——macOS 上是一对 Mach 端口,Windows 上是双工消息命名管道并由 Main 把每帧的 Host 本地 NT 句柄复制进自己的进程——每帧的提交、送达回执和结算都走这条连接,Host 的 IPC 通道只承载 `capabilities` 和 `adapter-luid`。每条连接最多接纳 128 个未结算请求;连接丢失时所有未结算请求按 `invalidated` 结算,下一帧打开新连接。`nativeSink(timeoutMs)` 返回一个指向 `dsh_shared_texture_sink_v2`([`native/shared-texture/shared-texture-sink.h`](../../../../apps/desktop/native/shared-texture/shared-texture-sink.h))的不透明 `napi_external` 供同进程原生 addon 使用;按其他 ABI 版本构建的消费者会拒绝它。每帧携带句柄、尺寸、像素格式、元数据和只在 Host 本地生效的送达期限,不带请求标识。sink 归属当前连接:请求已离开 Host 时 `present` 返回 `DSH_SHARED_TEXTURE_PRESENT_OK`,只拒绝这一帧且 sink 仍可用时返回 `DSH_SHARED_TEXTURE_PRESENT_REJECTED`,连接已关闭或丢失时返回 `DSH_SHARED_TEXTURE_PRESENT_DISCONNECTED`,之后每一帧也都如此,消费者随即取得新的 sink。取过 `nativeSink` 的认领结束时会关闭该连接并把未结算帧按 `invalidated` 结算。`adapterLuid(timeoutMs)` 在 Windows 以外直接返回 `null` 而不询问 Main,且从不打开原生连接;Windows 上 Main 从 Chromium 合成器导出一张纹理,经 ingress addon 读出其 adapter 的 LUID,并立即释放该纹理。Main 保留这个答案直到 Chromium 的 GPU 进程退出或 Host 停止,并发查询共用一次读取,失败的读取不保留。答案是小写十六进制的 `<HighPart>:<LowPart>`,与帧转发接收器表示 adapter 的文本一致;Chromium 没有导出 Direct3D 11 合成器纹理、DXGI 读不出其 adapter 或读取被清理取消时为 `null`。
- Main 的 ingress([`native/shared-texture/ingress.cc`](../../../../apps/desktop/native/shared-texture/ingress.cc))最多排队 32 帧等待 Main 的 JavaScript 线程,超出的帧当场按未保留引用拒绝,Host 可立即复用该纹理。对每一帧获准进入的帧,Main 的 [presenter](../../../../apps/desktop/src/shared-texture/presenter.ts) 导入句柄,经 Desktop 的 IPC 把 subtle 传输连同 Host 原样的 metadata 送到产品主 frame。Main 一直持有自己的导入,直到文档报告它已持有自己的引用,再在原生通道上回复 `delivered`;忙碌的 renderer 只会推迟该回复——即使送达超时也继续保留 Host 的槽位直至结算——而不会丢失纹理。Main 在原生通道上对每次获准的呈现只结算一次:自己的释放回调和文档的释放(文档在其释放回调中发出)都到达后回复 `released`;文档、renderer、GPU 进程或 GPU 释放同步先行消失或失败时回复 `invalidated`;不保留引用的失败回复表示 Main 未保留任何引用。Main 校验 Electron 限定的像素尺寸,解析 `metadata` 的 JSON 而不解释其中的字段。
- Main 的 `capabilities` 向 Desktop Host 报告其进程身份,Desktop Host 只把是否支持及原因交给其消费者;macOS 和 Windows 上还报告跳转 addon 路径,并为发出请求的 Host 打开一个仅依赖 Node-API 8 的原生 ingress。macOS 上([`native/shared-texture/ingress-darwin.cc`](../../../../apps/desktop/native/shared-texture/ingress-darwin.cc))ingress 是 Mach 接收端口:仅当消息的 audit trailer 指向 Main 所启动的 Host 进程时才接受,用 `IOSurfaceLookupFromMachPort` 解析携带的端口,交付 Main 本地的 `IOSurfaceRef` 并向 Host 的回复端口应答,同时丢弃其他进程的消息和超长消息而继续接收 Host 的消息。Windows 上([`native/shared-texture/ingress-win32.cc`](../../../../apps/desktop/native/shared-texture/ingress-win32.cc))ingress 是单实例双工消息命名管道:读取前先核对 `GetNamedPipeClientProcessId` 为该 Host 进程并断开任何其他客户端,连接期间持有该 Host 的 `PROCESS_DUP_HANDLE | SYNCHRONIZE` 句柄,把每帧的 NT `HANDLE` 从 Host 复制进 Main;同一 addon 还为 `adapter-luid` 经 DXGI 读取 Main 本地共享纹理的 adapter LUID。ingress 与该 Host 进程同寿命:窗口级清理保留它,因此 Host 每条连接只查询一次能力,之后每一帧都直接经原生通道呈现,无需额外的 IPC 往返。显式的能力查询总会到达 Main;Chromium 改用软件合成时(例如 GPU 进程多次崩溃后),Main 报告 `gpu-compositing-disabled`。Host 发来的协议版本不符或内容畸形的消息会以错误停止 ingress 并结束连接,下一次能力查询会重新打开它。
应用 preload 仅向产品主 frame 暴露 `dshDesktop.textures`:它导入每个传输,立即向 Main 报告结果,把 `{ frame, metadata, release }` 交付给唯一的文档消费者,没有消费者时立即释放到达的纹理。共享纹理 Client 插件把 `globalThis.dshDesktop?.textures` 提供为 Client 侧的 `ctx.sharedTexture`,因此其他 Client 插件从不读取 `globalThis.dshDesktop`。Desktop 不向文档提供窗口控制:要全屏显示视图的插件经帧转发使用文档的 Fullscreen API,Electron 为文档的全屏元素让窗口全屏,现有的状态同步让窗口外观随之调整。当 renderer 或 GPU 进程退出、跨文档导航提交或窗口关闭时,Main 取消待完成的 adapter 读取、拒绝清理期间到达的帧、把已发往文档的纹理结算为 `invalidated`,并开始新的文档代次;GPU 进程退出还会让 Main 忘掉合成器 adapter,只有在 Host 进程停止或失败时才关闭 ingress。Main 从不把未观察到的引用报告为已释放。被取消、被拦截和同文档导航保留文档的纹理,文档代次让跨越 ingress 替换期间发生的 reset 的能力查询失败。
### 信任模型
Main 只信任自己启动的 Host 进程。macOS ingress 丢弃经 audit 的发送方 PID 与 Host 不同的每条消息,并继续接收 Host 的消息;Windows ingress 在读取前核对 `GetNamedPipeClientProcessId`,断开任何其他客户端,并只从该 Host 进程复制句柄。producer 永远不与 Main 通信,Host 中只有 Desktop 的跳转接触 Host 到 Main 的通道。
安全审查面对两条进程边界。Host 到 Main 的边界属于 Desktop:Host 进程中的任何代码都能绕过 `sharedTexture` 服务直接向 Main 发送消息,因此 Main 的请求校验和 ingress 的 PID 检查作为 Desktop 的一部分审计,不随帧转发变化。producer 到 Host 的边界属于帧转发,记录在其[安全语义](../../../../packages/experimental/frame-forwarding/README.zh.md#security-semantics)中。插件 API 只有 `frameForwarding`;将 `sharedTexture` 保留给独占的帧转发消费者,只让它对普通插件不受支持,而不是不可达,因此它不是安全边界。两侧共享纹理接口同一时间都只接纳一个消费者,帧转发在加载期间占用二者:其 Host 插件从加载到卸载持有 Host 的 `sharedTexture` 认领,其 Client 从启动到销毁消费 Client 的 `ctx.sharedTexture`(没有打开的通道时也是如此)。因此其他消费者会立即失败,而不会在帧转发空闲时接管任一接口。认领随发起它的作用域结束,因此未释放就被卸载的持有者无法继续占用它。
### 帧转发包
`@deepseek-ai/dsh-frame-forwarding` 为任何 producer 使用其线上协议的 Host 插件持有帧转发。
- frame-forwarding 工作区将[接收器源码](../../../../packages/experimental/frame-forwarding/native/receiver.cc)与使用其协议的插件放在一起。Desktop 打包时直接从工作区为 macOS 和 Windows 的目标架构编译接收器,并预装二进制文件和构建清单。插件 npm 包不含接收器源码和二进制文件。Desktop 主进程根据当前安装位置或开发目录确定接收器的绝对路径,通过启动参数 `--frame-receiver-path` 传给 Host。Host 通过内部服务 `desktopFrameReceiver` 提供这个路径。插件首次使用时按自身要求校验构建清单中的协议版本和握手能力,再在 Host 进程中加载模块。每个通道的监听和与 producer 的握手都在 Host 进程中完成。
- Host 的 [forwarder](../../../../packages/experimental/frame-forwarding/src/host/forwarder.ts) 持有通道及其 producer 连接([帧转发通道](2026-10-18-frame-forwarding-channels.zh.md))、帧数与字节预算,以及 viewport 确认与重放。打开通道时,它询问 `sharedTexture.capabilities()`,取得 `sharedTexture.nativeSink()`,Windows 上还在创建接收器前通过 `sharedTexture.adapterLuid()` 读取 Chromium 的 adapter;每个通道都会询问,因为 Chromium 的 GPU 进程重启后 Desktop 会重新读取 adapter。它以 `attachSink` 把 sink 挂到该通道的接收器上,呈现期限最多 30000 ms,随后随连接、viewport 和可见性变化通过 `setDeliverable` 更新可交付状态。接收器 addon 内的 C++ Desktop 桥在产生帧的线程上校验 producer 元数据、按该可交付状态过滤帧,并以 `rx`、`connectionId`、`requestId`、`frameId`、`generation`、`revision`、`width` 和 `height` 作为元数据经 `dsh_shared_texture_sink_v2` 提交匹配的帧,稳态帧不经过 Host 的 JavaScript 事件循环。`on_settled` 回调在正常释放时直接归还帧信用;`invalidated` 时先停止接收器再释放交付,并通知 forwarder 以 `lost` 关闭通道。被拒绝的提交和失败的送达向 renderer 报告 `presentation-error`;以 `DSH_SHARED_TEXTURE_PRESENT_REJECTED` 之外的结果被拒的提交会解挂该 sink,被拒绝的单帧则保留 sink;未挂载 sink 时帧以 `frame` 事件到达 JavaScript,forwarder 立即归还信用,重新获取 `nativeSink` 并挂回各打开的通道。
- Host 插件是一个 Typert Remote 服务:消费者使用 `capabilities`、`channel`、`isOpen` 和 `close`;renderer 通过 `viewport` Remote 应用 viewport,并从 `events` 流跟随通道状态。Client 插件仅在 Client `ctx.sharedTexture` 可用时提供 renderer 侧的 `frameForwarding` 服务;`connect(rx)` 返回一个接收通道,它消费 `ctx.sharedTexture`,按元数据中的 `rx` 路由纹理,把每一帧借给消费者回调,并在回调结束后释放该帧。接收通道还持有文档的全屏元素(同一时间只有一个),并向其他通道报告遮挡([帧转发通道](2026-10-18-frame-forwarding-channels.zh.md))。通道随打开它的 Cordis 作用域一起关闭。
- 每个消费者 bundle 都以同一行 `frame-forwarding` 插入帧转发,且不带 config。Loader 对每个 id 只保留一行,因此同时启用的消费者共享同一个实例及其唯一的认领,关闭其中一个消费者时,该实例和其他消费者的通道继续运行;部署方用针对该 id 的 patch 调整其上限。
### 帧路径
```
LibreOffice (Kit producer holding the channel's TX credential)
│ Packet protocol: hello / allocate / frame (+ handle) / release / message
▼
Host process — frame-forwarding receiver addon + C++ Desktop bridge (attachSink, setDeliverable)
│ credits, budget, handoff, metadata check, deliverable filter → dsh_shared_texture_sink_v2.present
▼
Host process — Desktop shared-texture hop addon (≤ 128 unsettled; Host IPC: capabilities / adapter-luid only)
│ macOS: Mach port pair (IOSurface port + reply port) ⇄ Main ingress
│ Windows: duplex message named pipe (Host NT HANDLE; Main DuplicateHandle from Host) ⇄ Main ingress
▼
Electron Main — shared-texture ingress addon (delivery queue ≤ 32) + presenter → renderer frame
│ document import result → delivered reply, Main drops its import; both GPU releases → released
▼
Native channel reply (released or invalidated) → hop reader → bridge on_settled returns credit (invalidated stops receiver first → channel lost)
```
## Alternatives considered
**保留 bundle 声明的 main、preload 和 verify 导出。** 这为一个消费者把主进程和 session 级 preload 的执行权交给每个已安装的 bundle,在多个 bundle 间重复一个单例 Electron API,并强制只能在启动时激活,连带穿透 app-boot、插件管理器、清单类型和 Web 插件列表的重启管线。评审中否决。
**把帧转发作为 Desktop 的固定能力留在 Electron Main。** 这是中间阶段的决定。它把只有一个插件使用的协议和绑定在 Electron 主进程的接收器留在 `apps/desktop`,把协议变更与 Desktop 发版耦合,并让 preload API 成为帧转发 API。它自身否决过的变体出于同样理由仍被否决:从 dsh runtime 内安装的 Kit 加载接收端 SDK 把每次接收器变更绑在 Kit 发版上;libuv 完成信号(`uv_async_t`)在 Node-API 的 ABI 保证之外,会迫使按 Electron 精确头文件构建。
**让 Office 包自带一个内含跳转的接收器 addon。** 帧转发服务于每个原生渲染的 Host 插件,而不只是 Office;跳转是 Desktop 共享纹理的机制,不是帧转发的。Office 自有的 addon 会被下一个消费者再拷一份,并让一个功能包成为 Mach 和 Win32 句柄传递的所有者。
**Electron 托管的 `sendSharedTexture` 和 `setSharedTextureReceiver`。** 它固定的 1000 ms 确认期限会在 renderer 主线程忙碌更久时让视图失败;即使在期限后继续持有 Main 的导入,也仍会在 renderer 的 GPU 工作完成前把 producer 的纹理归还。经真机卡顿测试后否决。
**通过扩展槽把插件的 addon 加载进 Electron Main。** 插件原生代码会在主进程中运行。在 Host 中加载它,让 Main 的原生代码固定为 Desktop 的 ingress addon。
**现在就把接收器作为预构建的 npm 平台包发布。** Desktop 打包已经在每个目标操作系统上带 C++ 工具链运行;在该包有第二个消费者之前,平台包会增加四个包、一条发布流程和 Windows 预构建 CI。推迟,而非否决。
**Desktop 不含原生代码,像素经 Host 拷贝。** 每帧要拷贝几十 MB,并失去原生预览赖以成立的共享纹理路径。它仍可作为小视口的兜底,不是本设计。
**让 producer 直接把 surface 发到 Main 的 ingress。** 这每帧省一条 Mach 消息,但要求 Main 鉴别一个不是它启动的进程,并要求消费者在启动 producer 之前拿到 Main 的端点。信任模型排除了它;重新考虑的条件是实测的跳转开销。
**全局 IOSurface 标识符(`IOSurfaceLookup`)。** 已被 Apple 弃用,且用户的任何进程都可读取。
**把接收器放在 `apps/desktop-host`。** Desktop Host 将因此背上一个协议的原生构建和服务;Desktop Host 提供共享纹理和预装接收器的位置,协议校验和 Node-API 绑定由插件维护。
**保留 `dshDesktop.window.setFullscreen`。** 它是按插件需求增设的 Desktop 窗口控制,以鸭子类型读取,并需要 Main 一侧的恢复记录。元素全屏以文档为范围,按 Escape 即可结束而无需插件代码,并让帧转发知道是哪个通道遮挡了其他通道。
**让每个消费者 bundle 各自插入一行帧转发。** 两个实例会争夺唯一的 `sharedTexture` 认领和唯一的 renderer 纹理订阅;第二个实例会报告原生渲染不可用,而第一个只服务自己的消费者。
**由 Desktop profile 自身插入帧转发。** 即使没有启用任何消费者,每个 Desktop 会话也会加载接收器并占用 Desktop 的接口,而不带 Desktop 专属行的 profile 也无法继续与 Web 共用。
**让 Office Host 插件自己在 Web 中隐藏 bundle。** 插件不需要 profile 检查:`frameForwarding` 不受支持时它报告不可用,Client 不注册 UI,现有的 PDF 和表格预览保持不变。
## Verification
Desktop 规格测试覆盖 [presenter](../../../../apps/desktop/tests/shared-texture-presenter.spec.ts)(每个 Host 一个 ingress 并在换 Host 时替换、软件合成检测、跳转 addon 路径与 ingress 端点、128 帧上限、不保留引用的 Electron 导入失败、renderer 导入结果(包括忙碌的 renderer、失败的导入和缺失的 GPU 同步 token)、先送达回复再结算回复的顺序、`reset` 在保留 ingress 的同时把已发往文档的帧结算为 `invalidated`、`dispose` 先放弃已发送的帧再关闭 ingress、ingress 失败与重开、adapter LUID 读取按 GPU 进程保留、并发查询共用、失败或被 GPU 进程退出抢先时不保留、Windows 以外返回 null,以及经通道应答的 Main 入口)、[preload 桥接](../../../../apps/desktop/tests/preload-shared-texture.spec.ts)(含导入结果报告,以及消费者和 GPU 用完之后的释放报告)、[已发送纹理的结算](../../../../apps/desktop/tests/shared-texture-transfer.spec.ts)、[shared-texture 通道](../../../../apps/desktop/tests/shared-texture-channel.spec.ts)只接受能力查询与有界 adapter 请求并携带 Host 身份路由控制、[通用 Host 进程通道](../../../../apps/desktop/tests/host-process.spec.ts)、[声明式原生包构建](../../../../apps/desktop/tests/native-package-builds.spec.ts),以及 [shared-texture addon 校验器](../../../../apps/desktop/tests/shared-texture-runtime.spec.ts)。[Desktop 原生 e2e](../../../../apps/desktop/tests/shared-texture-native.e2e.ts) 在独立的 Main 与 Host 进程间经已构建的跳转与 ingress addon 从原生 `dsh_shared_texture_sink_v2` 线程交换真实纹理,覆盖每种回复类型、无法离开 Host 的呈现不发送即被拒、报告 sink ABI 版本 2 使按其他版本构建的消费者拒绝它、Main 的 JavaScript 线程阻塞时超出 32 帧投递队列的帧当场被拒并在恢复后继续处理、忽略端点上的其他进程并继续服务已注册的 Host、发送时发现 Main 已退出或 Main 无法投递其回复时结束连接、协议版本不符或请求畸形时停止 ingress、执行跳转送达期限的同时保留槽位直至 Main 结算、关闭或 Main 退出后的重连与单次结算,以及把共享 Direct3D 11 纹理的 adapter LUID 读成 Host addon 推导出的文本、其他句柄读不出 adapter。[构建产物 preload 的 e2e](../../../../apps/desktop/tests/preload.e2e.ts) 断言 `dshDesktop.textures` 只暴露 `onFrame`,且 `dshDesktop` 不暴露窗口控制。[Desktop Host 规格测试](../../../../apps/desktop-host/tests/shared-texture.spec.ts)覆盖唯一的认领、认领随发起它的作用域结束(包括像帧转发那样在该作用域的 effect 中发起的认领)、作用域销毁前的释放不影响下一个持有者的认领、跳转连接复用以及断连时把未结算帧置为 `invalidated` 并重连、取过 `nativeSink` 的认领结束时关闭该连接而未取过的认领正常结算、`adapterLuid` 不打开原生连接即返回 Main 的读取结果或 null、拒绝不是 LUID 的读取结果、报告 Desktop 给出的原因、超时并忽略迟到的回复、无关的通道流量,以及销毁时拒绝待完成的工作。帧转发规格测试覆盖 [forwarder](../../../../packages/experimental/frame-forwarding/tests/forwarder.host.spec.ts)(每个 Windows 通道都向 Desktop 读取 adapter LUID、每个通道都向 Desktop 取当前的 `nativeSink` 且并发请求合并、sink 期限上限 30000 ms、未挂载帧到达 JavaScript 时的刷新、在发出每个 viewport 之前更新可交付状态、呈现错误与失效处理、producer 连接与交接、viewport 重放、拆除)、[Host 服务](../../../../packages/experimental/frame-forwarding/tests/service.host.spec.ts)及其认领、由打开方作用域持有的通道和 Remote、[接收器加载器](../../../../packages/experimental/frame-forwarding/tests/native.host.spec.ts)及其构建记录检查、[Client 挂载](../../../../packages/experimental/frame-forwarding/tests/mount.client.spec.ts)、[wire 适配](../../../../packages/experimental/frame-forwarding/tests/wire.client.spec.ts)(含常驻的纹理订阅与全屏持有者)和[接收通道](../../../../packages/experimental/frame-forwarding/tests/rx.client.spec.ts)。[Desktop 桥原生 e2e](../../../../packages/experimental/frame-forwarding/tests/desktop-bridge-native.e2e.ts) 驱动真实 producer 穿过已构建接收器的 C++ sink 桥,覆盖元数据投射、正常释放和处于可交付状态之外时的信用归还、送达错误、被置为失效的帧先发出通知、再停止接收器及其连接后才释放、单帧被拒时保留 sink 而连接断开时解挂 sink 让后续帧到达 JavaScript、`present` 内同步触发的回调、拒绝其他 magic 或版本 1、3 的 sink 的 ABI 检查、接收器关闭并被垃圾回收后到达的结算,以及在 Desktop 的 addon 已构建时经 DesktoLine truncated
## Consequences
插件可以在运行时安装或启用。由 Desktop 预装接收器,可以在没有 C++ 工具链的机器上启用 Office 预览;接收器的协议和原生修复随 Desktop 发版。各版本插件自行校验预装接收器,不兼容时报告不可用。稳态帧绕过 Host 的 JavaScript 事件循环;在 Host 与 Main 之间,每帧在 macOS 上开销为 Mach 消息,在 Windows 上开销为命名管道消息加 Main 执行的一次 `DuplicateHandle`,没有像素拷贝。纹理生命周期跨越三个进程:Main 自己持有并在 Electron 的 GPU 工作完成或 Host 拆除时关闭它从 Host 复制来的 Windows 句柄,Main 退出会连带结束 Host 和 producer。Windows 上由 Main 以 `PROCESS_DUP_HANDLE | SYNCHRONIZE` 打开自己启动的 Host,Host 从不打开 Main;打开失败会断开管道,`DuplicateHandle` 被拒绝会返回送达错误,而不是静默地什么都不呈现。
### Native producer SDK
原生 producer 接口仍在随 Office 集成调整。DSH 暂不向第三方发布 producer SDK:现在公开 C 头文件和静态库会让外部插件依赖仍可能变化的调用方式。待接口定型后再决定是否开放。LibreOffice Kit 通过自己的引擎接入。
@@ -1,46 +0,0 @@
# Bilingual-pair consistency record for 2026-10-18-frame-forwarding-channels.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-18-frame-forwarding-channels.md
/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget:
en: 6ffcd2e12496f609
zh: 3aac5b5b6fcaf426
/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/problem:
en: 41f0d6fa7045c3a2
zh: 15ee3e573127d43c
/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision:
en: a15c7c13f167e5ac
zh: a15c7c13f167e5ac
/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision/channels-and-credentials:
en: ccf914afe119ab1e
zh: 12fbff4a5e879ca4
/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision/connections-and-handoff:
en: 4fdd0bed5e2a8bf9
zh: 361d50bee163c4d9
/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision/producers-name-only-their-own-handles:
en: 1c00e9088f93e12f
zh: 060e06ef9ebc164b
/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision/compatibility:
en: 0f0266faf90bd2b2
zh: 565841a9155bbfed
/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision/host-and-renderer:
en: 135ab5329118eadb
zh: dd5f84ac1358764b
/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision/hidden-and-covered-views-return-their-surfaces:
en: 216abcac1e6cd25d
zh: d19600a531086ccb
/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision/the-window-budget-follows-physical-memory:
en: 070fdad928fd862d
zh: 85f39b3adccc19c5
/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision/fullscreen-belongs-to-frame-forwarding:
en: 01ca9d01aacc84d6
zh: 82b7c5cdeedb33e1
/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/alternatives-considered:
en: 43089e5b5935fe17
zh: 9534aa449fbdd343
/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/verification:
en: f9130f0bda61a5d7
zh: c1bf0f49f6c51908
/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/consequences:
en: d73bd477975a1249
zh: db4e9d5732c05513
@@ -1,101 +0,0 @@
# Agent Note: Frame-forwarding channels with transferable credentials, producer-local handles, covered views, and a memory-sized budget
Status: implemented
English | [中文](2026-10-18-frame-forwarding-channels.zh.md)
## Problem
A frame-forwarding view authorized one producer process. The Host plugin started the producer, passed it a private endpoint, and called `bind(viewId, pid)`; the receiver accepted only that PID, could not be rebound, and failed the view when the producer disconnected. Replacing a producer therefore meant a new receiver, a new view identifier, and a new renderer consumer: the Office preview's CPU restart rebuilt the whole path, a crashed engine took its view with it, and the parent had to know the child's PID before the child connected. A PID is also a poor authorization identity: the operating system reuses it, it names a process rather than a holder of authority, and a successor process of the same feature cannot inherit it.
Once any process holding a channel's credential may connect a producer, what such a producer can do to the Host matters. On Windows a producer duplicated each frame's NT handle into the receiver's process and sent the resulting value, and the receiver treated whatever value arrived as a handle of its own. A packet with a forged value therefore made the Host open that handle as a texture or, on an error path, close it, whichever Host object it named. The same scheme also required the producer to hold `PROCESS_DUP_HANDLE` on the Host, which an engine running in a sandbox below the Host's integrity level cannot obtain.
All channels of the window share one byte budget, granted first come, first served. A producer whose view was hidden stopped rendering but kept its idle pooled surfaces and its pending requests, so a visible view could wait behind a hidden one for budget nobody was using. While one view occupied the screen in a slideshow, the views it covered kept rendering frames nobody could see, and nothing told frame forwarding which channel covered the others.
The budget was also a fixed 256 MiB, at most 1 GiB, whatever the machine. A channel streaming 4K frames holds up to three 3840×2160 surfaces of 31.64 MiB each, so two such channels filled it, and on the Windows relay path, which also reserves three target textures and two staging textures per channel, a 4096-pixel-wide slideshow frame exceeded the share one allocation may take.
## Decision
### Channels and credentials
A receiver is a logical channel with two halves. The Host plugin calls `frameForwarding.channel()` and receives `{ tx, rx }`: `tx` is an opaque, serializable credential that any process holding a copy may present, and `rx` is the receive identity the renderer passes to `frameForwarding.connect(rx)`. `close(rx)` closes the channel permanently and withdraws the credential, and a channel also closes when the Cordis scope that read the service is disposed. `bind`, `bindProducer`, and the receiver's permanent expected PID no longer exist; the OS-reported peer process is checked per physical connection only for packet origin and handle duplication. The credential never reaches a renderer, a log, or a diagnostic.
### Connections and handoff
A channel serves one connection at a time and moves Idle → Active(N) → Draining(N) → Idle → Active(N+1); Closed and Failed are reachable from every state. Connection IDs increase and are never reused; ready carries N, and every later packet is checked against it. While N is connected, other candidates are refused as `channel-busy`, and N is never preempted, even when it stops responding. After N disconnects by goodbye, error, or process exit, N keeps its frames, allocations, budget, relay state, and submitted GPU work until each is released. During that drain one authenticated successor waits for ready within its own deadline and cancellation, and others are refused. Frames and allocations are keyed by connection, delivery IDs stay unique within the channel, credit returns only to the frame's own connection, and a late release of N returns nothing to N+1. GPU work whose completion is unknown keeps its resources and reports `drain-blocked`; no timeout ends a drain. On macOS each connection has its own Mach ports, delivered in ready; on Windows each connection uses its own pipe instance; a failed handshake closes only its candidate. A producer's `close()` completes once its own sender is closed, and the successor's ready completes the handoff.
### Producers name only their own handles
The hello capability `producer-local-handles` declares that every handle a producer names belongs to it. On Windows a frame carries a handle value in the producer's process. When a pipe client connects, the receiver opens that process with `PROCESS_DUP_HANDLE | SYNCHRONIZE` from `GetNamedPipeClientProcessId`, and it duplicates each frame's value from there. A value that names no handle of a live producer ends that connection as "sent a handle it does not own" without touching any Host handle; a producer that already exited took its handles with it, and its connection ends as lost. A hello that carries a handle is dropped, and the producer side never interprets a received value. macOS keeps Mach port transfer, where the kernel names the right in the receiver.
### Compatibility
Channels change no wire protocol version, constant, packet layout, or endpoint prefix; they add hello capability bits that both sides check. The current wire protocol, version 2, sends each packet as a fixed header followed by only the bytes of its text and requires the same capabilities. The hello declares `transferable-tx` and `producer-local-handles`. Ready carries the connection ID in its token field and, in `ready.stride`, unused before, echoes the capabilities the receiver accepted. A receiver refuses a producer without `transferable-tx` as `transferable-tx-required`, one without `producer-local-handles` as `producer-local-handles-required`, and a producer of another version as `protocol-mismatch`, naming both versions. A producer refuses a ready without a connection ID or without the `producer-local-handles` echo, so neither side of a mixed build sends or reads a handle value under the other rule. Build records (the Kit's `sdk.json`, `receipt.json`, and prebuild manifests, and DSH's `frame-forwarding.json`) list `capabilities: ["transferable-tx", "producer-local-handles"]`, and their loaders and verifiers reject artifacts without both, so a matching version number alone never passes a compatibility check. Desktop [preinstalls the receiver](2026-10-15-desktop-shared-texture-api.md). The Kit 0.2.3 engine is a protocol 1 producer, which the protocol 2 receiver refuses as `protocol-mismatch`.
### Host and renderer
The Host keeps the renderer's latest viewport per channel, sends it to each new connection, and presents frames only from the current connection, up to the latest viewport's version. The gate opens before the viewport is sent, because the receiver judges a frame in native code, possibly before the Host's JavaScript handles the acknowledgement that preceded it. A viewport request belongs to the connection that received it and reports `producer-changed` when that connection ends; a timeout fails the request and keeps the channel. Each event-stream subscription starts with a snapshot of every channel's state, then carries states with increasing sequence numbers and producer errors. Frame metadata carries `connectionId` beside `generation`, which remains the viewport version. A `FrameRx` streams the latest frame across producer switches. Frames whose connection state has yet to arrive wait within the channel's frame limit, and the renderer releases frames from earlier connections. Native producers can still use `dsh_frame_forwarding_submit` for ordered delivery or `dsh_frame_forwarding_submit_latest` for replaceable frames. `ready()` resolves once a producer acknowledged the latest viewport.
On `invalidated`, which [Desktop's settlement](2026-10-15-desktop-shared-texture-api.md) reports when the document, renderer, or GPU process went away first, the bridge queues the notice, then stops the receiver and the frame's connection before releasing the delivery, so its producer never writes that texture again; the forwarder closes the channel as `lost` when it handles the notice. A producer disconnect, by contrast, drains and hands over.
### Hidden and covered views return their surfaces
A consumer sends its next viewport version with `visible: false` whenever its view is hidden or covered. The producer SDK's `dsh_frame_forwarding_trim` deallocates every surface that is neither acquired nor submitted: available surfaces, the queued latest frame, granted allocations not yet created, and pending requests; on Windows it then flushes the producer's D3D11 context, because D3D11 destroys a released texture only at the next flush. The Kit engine trims after acknowledging an invisible viewport, so its allocations return to the shared budget, and its next visible frame requests them again.
### The window budget follows physical memory
`maxBytes: auto`, the default, resolves to half of physical memory and at least 256 MiB when the first channel opens; no budget exceeds physical memory, and a larger byte count is reduced to it with a Host warning. Sizing waits for the first channel because a Host that never loads the receiver, such as the browser worker deployment, cannot read physical memory. The budget is a ceiling, not a reservation: each channel still holds at most `maxFrames` surfaces, so a larger budget lets more channels hold surfaces at once without enlarging any of them. A producer whose allocation does not fit waits until other channels return surfaces; its channel stays open, and its consumer keeps what it shows and draws a placeholder where content has not arrived.
### Fullscreen belongs to frame forwarding
A receive channel shows its consumer's element fullscreen through the document's Fullscreen API with `FrameRx.requestFullscreen(element)`, which the consumer calls before its click handler awaits anything. One channel holds fullscreen at a time. Every other channel learns `{ active: true, holder: false }` and treats its view as covered; the holder learns `active: false` when the fullscreen ends, including on Escape; closing the holding channel or disposing the Client leaves its fullscreen. Desktop exposes no window control of its own ([shared-texture API](2026-10-15-desktop-shared-texture-api.md)).
Each document view runs its Host operations in arrival order, and different views run concurrently, so a view that waits for frame surfaces delays only its own later operations. A frame that misses `frameTimeoutMs`, or the Kit engine's own report that no frame surface became free, does not fail the view: tiles and page previews request their frame again once the late request settles, a slideshow keeps its stream, and the view keeps its retained tiles, page previews, or last slideshow frame, draws a checkerboard where nothing has arrived, and says that it waits for graphics memory until a frame draws.
## Alternatives considered
**Rebind the receiver to a successor's PID.** This keeps the PID as authority, still requires the parent to learn the child's PID before it connects, and needs a new bind call for crash takeover.
**Preempt a connected producer after a timeout.** A stalled producer may still own GPU work on the channel's textures, so preemption would hand those textures to a successor while they are in use. Only the operating system's disconnect or the producer's own close starts a drain.
**Connect the successor at once and keep the old connection's frames separately.** Two producers would share one channel's budget and frame limit, and the renderer would interleave their frames. Draining first keeps one producer's resources and credit in flight at a time.
**Open a new channel per producer, as before.** Every producer switch would replace the renderer's consumer and lose its viewport and stream subscription.
**Mark channels with a new wire protocol version.** Channels change no packet layout; capability bits that both sides check refuse mixed builds as well, and the frame-forwarding README promises that within a version the wire changes only by such capabilities.
**Return invalidated textures through a drain.** Desktop cannot observe their remaining references, so a successor could write a texture a stale document still reads; a closed channel is the only state in which releasing them is safe.
**Validate the received value before use.** The receiver could check that a value names a shared D3D11 texture. That checks the object's type, not its owner: a forged value naming another channel's texture or any other shared object of the Host passes, and error paths still release the value.
**Keep producer-side duplication and verify it in the receiver.** The receiver cannot tell a value the producer duplicated in from a value it guessed without the producer's handle table, and the producer would still need `PROCESS_DUP_HANDLE` on the Host, which a sandboxed engine lacks.
**A new wire message that pauses covered producers.** Viewport visibility already tells a producer to stop rendering, carries a version the Host orders, and reaches each new connection through the viewport replay, so a separate pause message would duplicate it.
**Per-channel byte caps or a channel count limit.** Trimming covered views and closing channels with the scope that opened them handle the observed contention; on the Windows relay path the budget formula would make a low cap block a 4K slideshow. Deferred until a measurement shows the need.
**Fullscreen the document element and keep the slideshow overlay on `document.body`.** The application chrome would then share the fullscreen screen, including the Windows menu and caption controls that need their own fullscreen handling, and frame forwarding could not name the covering view.
**Keyboard Lock.** Letting a holder keep Escape suits games, not slideshows, and is deferred until a consumer needs it.
**Keep a fixed default budget.** 256 MiB held two 4K streams on the shared-texture paths and refused a 4096-pixel-wide frame on the relay path, however much memory the machine had.
**A quarter of physical memory**, the ceiling Chromium sets for a renderer's tile memory. Half lets more views render at once, which suits using whatever the machine has, and still stays below the working set Metal recommends, about two thirds to four fifths of unified memory.
**95% or 100% of physical memory.** The operating systems' graphics limits are lower: WDDM lets graphics use `min(80%, max(RAM − 16 GB, 50%))` of system memory, and Metal's recommended working set is the fraction above. The same memory also holds the engines, Chromium, and other applications. Frame forwarding would never refuse first: exhaustion would surface wherever the operating system fails an allocation, for example in Chromium's GPU process, whose exit closes every channel, and nothing would bound the frame memory producers make the Host and the GPU process hold.
**Fail a view whose frame misses its deadline.** A missing allocation is usually temporary: hiding, covering, or closing another view frees it, while a failed view waits for the user to retry.
**Run every Office operation in one Host queue.** A view waiting for frame surfaces would hold every other document's operations for the engine's whole wait, and opening one document would stall the others.
**Tell a budget wait from a stalled engine.** The receiver does not report a pending grant to the Host, and distinguishing that state would require a new producer-to-Host diagnostic; an engine that stops answering still ends at `operationTimeoutMs`.
**Size the budget from the operating system's GPU budget** (DXGI `QueryVideoMemoryInfo`, Metal `recommendedMaxWorkingSetSize`). It would follow dedicated video memory, which physical memory does not show, but requires platform-specific native queries in the receiver.
## Verification
The Kit's transport tests and DSH's [receiver native e2e](../../../../packages/experimental/frame-forwarding/tests/receiver-native.e2e.ts) connect a separate producer process with a copied credential and cover busy refusal, a waiting successor, deadline expiry, crash takeover, IDs reused across connections with late releases, mixed-build refusals in both directions including a producer built without `producer-local-handles` and a ready without the echo, budget return after repeated handoffs, and a trimmed producer's allocation passing to another channel sharing its budget. On Windows the Kit's tests close the connection of a producer that sends a receiver handle's value while that sentinel handle stays valid, and show the trimmed textures' video memory freed through the shared-texture and relay paths; the serialized native suite passes on macOS arm64, two Windows x64 hardware hosts, and Windows ARM64. The [Kit frames e2e](../../../../packages/experimental/frame-forwarding/tests/kit-frames-native.e2e.ts) hands a real Office engine's channel to a replacement and, after a crash, to a successor, renders two engines on two channels at once, and trims an invisible engine's surfaces. Unit specs cover the Host's viewport replay and connection-bound requests, the renderer's snapshot and sequence handling and early-frame ordering, the [wire adapter](../../../../packages/experimental/frame-forwarding/tests/wire.client.spec.ts) and [receive channel](../../../../packages/experimental/frame-forwarding/tests/rx.client.spec.ts) with the single fullscreen holder, coverage events, exits during a pending entry or after Escape, and exits on close and disposal. The [service specs](../../../../packages/experimental/frame-forwarding/tests/service.host.spec.ts) cover `auto` at half of physical memory, its 256 MiB floor, and the refused load of a budget above physical memory.
## Consequences
Producer replacement and crash takeover keep the channel, the renderer's consumer, and the viewport, and need no PID: a parent hands over a string. In exchange, every protocol 1 receiver, producer, engine, and build record must be upgraded together, and older builds are refused explicitly: Kit 0.2.2 and earlier producers and receivers cannot interoperate with these sources in either direction, so the Kit, its engines, and Desktop, which compiles the receiver when it packages, upgrade together. A stalled producer that stays connected blocks its channel until it exits or the channel closes, and a successor waits for Desktop and its consumers to release the previous producer's frames. A GPU-process exit closes the channels that had frames on screen, and its consumer must open a new channel instead of continuing on the old one. A producer must keep a sent handle open until the receiver reads the frame, and a producer that exits right after submitting loses that frame with its connection. An engine sandboxed below the Host's integrity level keeps working, since only the Host opens the other process; conversely a producer elevated above the Host, which the Host cannot open, cannot connect, and the receiver closes it during the handshake without a Host diagnostic. A view that becomes visible again waits for an allocation grant before its first frame, and trimming returns frame surfaces only, not an engine's own renderer caches. Escape always leaves fullscreen, and coverage is per document: a fullscreen element of the document covers every receive channel except the holder's. On Windows machines with 32 GB or less, half of physical memory equals the system memory WDDM lets graphics use, so the operating system's limit can be reached there before the budget; a discrete GPU keeps frames in its dedicated memory, which the budget does not see, and WDDM pages rather than fails when that memory runs out.
@@ -1,101 +0,0 @@
# Agent Note: 带可转交凭据、生产者自有句柄、被遮挡视图和按内存定额预算的帧转发通道
Status: implemented
[English](2026-10-18-frame-forwarding-channels.md) | 中文
## Problem
帧转发视图只授权一个生产者进程。Host 插件启动生产者,向其传递私有端点,再调用 `bind(viewId, pid)`;接收端只接受该 PID,不能重新绑定,生产者断开时视图随之失败。因此替换生产者意味着新的接收端、新的视图标识和新的渲染端消费者:Office 预览的 CPU 重启要重建整条路径,引擎崩溃会带走其视图,父进程还必须在子进程连接前得知其 PID。PID 也不适合作为授权身份:操作系统会复用 PID,它指代进程而非权限持有者,同一功能的后继进程也无法继承它。
一旦任何持有通道凭据的进程都能连接生产者,这样的生产者能对 Host 做什么就变得重要。在 Windows 上,生产者把每帧的 NT 句柄复制进接收端进程并发送复制后的值,接收端则把收到的任何值都当作自身的句柄。因此,带有伪造值的包会让 Host 把该句柄当作纹理打开,或在出错路径上关闭它,无论它指向 Host 中的哪个对象。这一方案还要求生产者持有 Host 的 `PROCESS_DUP_HANDLE` 权限,而在低于 Host 完整性级别的沙箱中运行的引擎拿不到该权限。
窗口内所有通道共享一个按先来先得授予的字节预算。视图被隐藏的生产者虽停止渲染,却仍保留其空闲池中的 surface 和尚在申请中的分配,于是可见视图可能排在隐藏视图之后,等待一份无人使用的预算。放映时一个视图占满屏幕,被它遮挡的视图仍在渲染无人可见的帧,帧转发也无从知道是哪个通道遮挡了其他通道。
预算还固定为 256 MiB,最多 1 GiB,与机器无关。传输 4K 帧的通道最多持有三个 3840×2160、每个 31.64 MiB 的 surface,两个这样的通道就能占满预算;在 Windows 中继路径上,每个通道还要预留三个目标纹理和两个暂存纹理,一个 4096 像素宽的放映帧超出了单次分配可占的份额。
## Decision
### 通道与凭据
接收端是一个由两半组成的逻辑通道。Host 插件调用 `frameForwarding.channel()` 得到 `{ tx, rx }`:`tx` 是不透明、可序列化的凭据,任何持有副本的进程都可出示;`rx` 是接收身份,渲染端将其传给 `frameForwarding.connect(rx)`。`close(rx)` 永久关闭通道并撤回凭据;读取该服务的 Cordis 作用域销毁时,通道也随之关闭。`bind`、`bindProducer` 和接收端永久的预期 PID 已不存在;操作系统报告的对端进程仅按物理连接用于检查数据包来源和句柄复制。凭据从不进入渲染端、日志或诊断信息。
### 连接与交接
通道同一时间只服务一个连接,状态依次为 Idle → Active(N) → Draining(N) → Idle → Active(N+1);任何状态都可进入 Closed 或 Failed。连接 ID 递增且永不复用;ready 携带 N,之后每个数据包都按其校验。N 在线时,其他候选连接以 `channel-busy` 被拒绝,N 即使停止响应也不会被抢占。N 因 goodbye、错误或进程退出而断开后,其帧、分配、预算、中继状态和已提交的 GPU 工作一直保留到各自释放。排空期间,一个通过认证的后继在自身截止时间和取消条件内等待 ready,其余候选被拒绝。帧和分配按连接区分,交付 ID 在通道内保持唯一,信用只返还给帧所属的连接,N 迟到的释放不会给 N+1 返还任何东西。完成情况未知的 GPU 工作保留其资源并报告 `drain-blocked`;不存在结束排空的超时。macOS 上每个连接拥有自己的 Mach 端口,随 ready 交付;Windows 上每个连接使用独立的管道实例;握手失败只关闭该候选连接。生产者的 `close()` 在本地发送端关闭后完成,后继的 ready 标志交接完成。
### 生产者只指名自己的句柄
握手能力 `producer-local-handles` 声明生产者指名的每个句柄都归它所有。在 Windows 上,帧携带的是生产者进程中的句柄值。管道客户端连接时,接收端根据 `GetNamedPipeClientProcessId` 以 `PROCESS_DUP_HANDLE | SYNCHRONIZE` 打开该进程,并从那里复制每一帧的值。若值不对应仍在运行的生产者的任何句柄,该连接以“sent a handle it does not own”结束,且不触碰任何 Host 句柄;已退出的生产者带走了自己的句柄,其连接以丢失结束。携带句柄的 hello 会被丢弃,生产者一侧从不解读收到的值。macOS 保留 Mach 端口传递,由内核在接收端中为端口权限命名。
### 兼容性
通道不改变通信协议的版本、常量、数据包布局或端点前缀,只增加双方都检查的 hello 能力位。当前的通信协议为版本 2,每个数据包由固定的包头加上仅含其文本字节的部分组成,并要求同样的能力。hello 声明 `transferable-tx` 和 `producer-local-handles`。ready 在 token 字段中携带连接 ID,并在此前未使用的 `ready.stride` 中回显接收端接受的能力。接收端以 `transferable-tx-required` 拒绝不带 `transferable-tx` 的生产者,以 `producer-local-handles-required` 拒绝不带 `producer-local-handles` 的生产者,并以写明双方版本的 `protocol-mismatch` 拒绝其他版本的生产者。生产者拒绝不含连接 ID 或未回显 `producer-local-handles` 的 ready,因此混合构建的任一方都不会按另一套规则发送或读取句柄值。构建记录(Kit 的 `sdk.json`、`receipt.json` 和预构建清单,以及 DSH 的 `frame-forwarding.json`)列出 `capabilities: ["transferable-tx", "producer-local-handles"]`,其加载器和校验器拒绝缺少其中任一能力的产物,因此仅版本号相同永远无法通过兼容性检查。Desktop [预装接收器](2026-10-15-desktop-shared-texture-api.zh.md)。Kit 0.2.3 引擎是协议 1 的生产者,协议 2 的接收器以 `protocol-mismatch` 拒绝它。
### Host 与渲染端
Host 按通道保存渲染端最新的视口,发送给每个新连接,并且只呈现当前连接 generation 不超过最新视口版本的帧。门控在视口发出之前就已打开,因为接收器在原生代码里判定帧,可能早于 Host 的 JavaScript 处理排在该帧之前的确认。视口请求属于接收它的连接,该连接结束时报告 `producer-changed`;超时只让该请求失败,通道保留。每个事件流订阅先收到所有通道状态的快照,随后收到带递增序号的状态和生产者错误。帧元数据在 `generation`(仍为视口版本)旁携带 `connectionId`。`FrameRx` 在生产者切换后继续交付最新帧。连接状态尚未到达的帧在通道帧上限内等待,渲染端释放更早连接的帧。原生生产者仍可通过 `dsh_frame_forwarding_submit` 按序提交帧,或通过 `dsh_frame_forwarding_submit_latest` 提交可替换的帧。`ready()` 在生产者确认最新视口后完成。
[Desktop 的结算](2026-10-15-desktop-shared-texture-api.zh.md)在文档、渲染进程或 GPU 进程先行消失时报告 `invalidated`;收到它时,桥先把通知排入队列,再停止接收器和该帧所属的连接,然后释放交付,因此其生产者不会再写入该纹理;forwarder 处理该通知后以 `lost` 关闭通道。相比之下,生产者断开则排空后交接。
### 隐藏和被遮挡的视图归还 surface
视图被隐藏或遮挡时,消费者以下一个视口版本发送 `visible: false`。生产者 SDK 的 `dsh_frame_forwarding_trim` 释放所有既未被获取也未被提交的 surface:可用的 surface、排队中的最新帧、已获批但尚未创建的分配,以及尚在申请中的分配;在 Windows 上它随后刷新生产者的 D3D11 上下文,因为 D3D11 只在下一次刷新时销毁已释放的纹理。Kit 引擎在确认不可见视口后执行收缩,使其分配回到共享预算,下一个可见帧再重新申请。
### 窗口预算随物理内存确定
默认值 `maxBytes: auto` 在第一个通道打开时解析为物理内存的一半,且不低于 256 MiB;任何预算都不超过物理内存,更大的字节数降为物理内存并在 Host 日志中警告。预算等到第一个通道才确定,因为从不加载接收器的 Host(例如浏览器 worker 部署)读不到物理内存。预算是上限而非预留:每个通道仍最多持有 `maxFrames` 个 surface,因此更大的预算让更多通道能同时持有 surface,而不会让任何一个通道变大。分配放不进预算的 producer 会等待其他通道归还 surface;其通道保持打开,它的消费方保留已显示的内容,并在内容尚未到达处绘制占位。
### 全屏归帧转发所有
接收通道通过文档的 Fullscreen API,以 `FrameRx.requestFullscreen(element)` 全屏显示其消费者的元素;消费者须在点击处理函数 await 任何东西之前调用它。同一时间只有一个通道持有全屏。其他每个通道收到 `{ active: true, holder: false }`,并将其视图视为被遮挡;全屏结束时(包括按 Escape),持有者收到 `active: false`;关闭持有全屏的通道或销毁 Client 都会退出其全屏。Desktop 自身不暴露任何窗口控制([共享纹理 API](2026-10-15-desktop-shared-texture-api.zh.md))。
每个文档视图的 Host 操作按到达顺序执行,不同视图并发执行,因此等待帧 surface 的视图只会推迟它自己后续的操作。错过 `frameTimeoutMs` 的帧,或 Kit 引擎自身报告没有空闲的帧 surface,都不会让视图失败:图块和分页预览在迟到的请求结束后重新请求其帧,放映保留其流;视图保留已保存的图块、分页预览或放映的最后一帧,在尚无内容处绘制棋盘格,并提示正在等待图形内存,直到有帧绘制出来。
## Alternatives considered
**把接收端重新绑定到后继的 PID。** 这仍以 PID 作为权限,父进程仍须在子进程连接前得知其 PID,崩溃接管也需要新的绑定调用。
**超时后抢占在线的生产者。** 停滞的生产者可能仍持有作用于通道纹理的 GPU 工作,抢占会在纹理仍被使用时把它们交给后继。只有操作系统的断开或生产者自身的关闭才开始排空。
**立即连接后继,并单独保留旧连接的帧。** 两个生产者会共用一个通道的预算和帧上限,渲染端会交错收到双方的帧。先排空保证同一时间只有一个生产者的资源和信用在途。
**像以前一样为每个生产者打开新通道。** 每次切换生产者都会替换渲染端的消费者,并丢失其视口和流式订阅。
**为通道启用新的通信协议版本。** 通道不改变数据包布局;双方都检查的能力位同样能拒绝混合构建,帧转发 README 也承诺同一版本内的线上协议只通过这类能力演进。
**通过排空归还已失效的纹理。** Desktop 无法观察这些纹理剩余的引用,后继可能写入过期文档仍在读取的纹理;只有通道关闭后释放它们才安全。
**使用前校验收到的值。** 接收端可以检查该值是否指向共享的 D3D11 纹理。但这只检查对象的类型而非归属:指向另一通道纹理或 Host 中其他共享对象的伪造值仍能通过,出错路径也仍会释放该值。
**保留生产者一侧的复制,由接收端验证。** 没有生产者的句柄表,接收端无法区分生产者复制进来的值与猜测的值;生产者也仍需持有 Host 的 `PROCESS_DUP_HANDLE` 权限,而沙箱中的引擎没有该权限。
**新增一条暂停被遮挡生产者的线上消息。** 视口的可见性已经告诉生产者停止渲染,携带由 Host 排序的版本,并通过视口重放到达每个新连接,因此单独的暂停消息与之重复。
**每通道字节上限或通道数上限。** 收缩被遮挡的视图、通道随打开它的作用域一起关闭,已能处理观察到的争用;在 Windows 中继路径上,预算公式会让较低的上限卡住 4K 放映。等测量证明需要时再做。
**让文档根元素全屏,并把放映浮层保留在 `document.body`。** 这样应用界面会一起占用全屏屏幕,其中包括需要另行处理全屏的 Windows 菜单和标题栏按钮,帧转发也无法指明是哪个视图在遮挡。
**Keyboard Lock。** 让持有者保留 Escape 适合游戏而不适合放映,等有消费者需要时再做。
**保留固定的默认预算。** 无论机器有多少内存,256 MiB 在共享纹理路径上只能容纳两路 4K 流,在中继路径上会拒绝 4096 像素宽的帧。
**物理内存的四分之一**,即 Chromium 为渲染进程 tile 内存设的上限。一半能让更多视图同时渲染,契合尽量使用机器已有资源的目标,并且仍低于 Metal 建议的工作集,约为统一内存的三分之二到五分之四。
**物理内存的 95% 或 100%。** 操作系统的图形上限更低:WDDM 允许图形使用 `min(80%, max(RAM − 16 GB, 50%))` 的系统内存,Metal 建议的工作集即上述比例。同一份内存还要容纳引擎、Chromium 和其他应用。帧转发将永远不会先拒绝:耗尽会出现在操作系统让分配失败的地方,例如 Chromium 的 GPU 进程,其退出会关闭所有通道;producer 让 Host 和 GPU 进程持有的帧内存也将不受任何约束。
**帧错过期限时让视图失败。** 分配不足通常是暂时的:隐藏、遮挡或关闭另一个视图就能释放它,而失败的视图要等用户重试。
**让所有 Office 操作走同一个 Host 队列。** 等待帧 surface 的视图会在引擎整个等待期间挡住其他所有文档的操作,打开一个文档也会让其他文档停顿。
**区分预算等待与停滞的引擎。** 接收器不会向 Host 报告尚未批准的分配,区分这种状态需要新增一项从生产者到 Host 的诊断;停止响应的引擎仍会在 `operationTimeoutMs` 到期时结束。
**按操作系统的 GPU 预算确定预算**(DXGI `QueryVideoMemoryInfo`、Metal `recommendedMaxWorkingSetSize`)。它能跟随物理内存反映不出的独立显存,但需要接收器调用各平台的原生 API 查询 GPU 预算。
## Verification
Kit 的传输测试和 DSH 的[接收器原生 e2e](../../../../packages/experimental/frame-forwarding/tests/receiver-native.e2e.ts) 用复制的凭据连接独立的生产者进程,覆盖忙碌拒绝、等待中的后继、截止时间到期、崩溃接管、跨连接复用 ID 及迟到释放、双向的混合构建拒绝(包括不具备 `producer-local-handles` 的生产者和未回显能力的 ready)、多次交接后的预算归还,以及被收缩的生产者的分配交给共享其预算的另一个通道。在 Windows 上,Kit 的测试会在生产者发送接收端句柄的值时关闭其连接,而该哨兵句柄保持有效,并显示经共享纹理和中继两条路径收缩的纹理释放其显存;串行的原生测试套件在 macOS arm64、两台 Windows x64 硬件主机和 Windows ARM64 上通过。[Kit 帧 e2e](../../../../packages/experimental/frame-forwarding/tests/kit-frames-native.e2e.ts) 把真实 Office 引擎的通道交给替代引擎,并在崩溃后交给后继;它还在两个通道上同时渲染两个引擎,并收缩不可见引擎的 surface。单元测试覆盖 Host 的视口重放和绑定连接的请求、渲染端的快照与序号处理及提前到达帧的排序,以及 [wire 适配](../../../../packages/experimental/frame-forwarding/tests/wire.client.spec.ts)与[接收通道](../../../../packages/experimental/frame-forwarding/tests/rx.client.spec.ts)的唯一全屏持有者、遮挡事件、在进入全屏尚未完成或已按 Escape 后的退出,以及关闭和销毁时的退出。[服务规格测试](../../../../packages/experimental/frame-forwarding/tests/service.host.spec.ts)覆盖 `auto` 取物理内存的一半、其 256 MiB 下限,以及超过物理内存的预算被拒绝加载。
## Consequences
生产者替换和崩溃接管保留通道、渲染端消费者和视口,且无需 PID:父进程只需交出一个字符串。代价是:协议 1 的所有接收端、生产者、引擎和构建记录必须一起升级,旧构建会被明确拒绝:Kit 0.2.2 及更早的生产者和接收端在两个方向上都无法与这些源码互通,因此 Kit、其引擎以及在打包时编译接收器的 Desktop 必须一起升级。保持连接但停滞的生产者会阻塞其通道,直到它退出或通道关闭;后继要等待 Desktop 及其消费者释放前一个生产者的帧。GPU 进程退出会关闭画面上有帧的通道,消费者须打开新通道,而不能继续使用旧通道。生产者必须让已发送的句柄保持打开,直到接收端读取该帧;提交后立即退出的生产者会连同其连接一起丢失这一帧。在低于 Host 完整性级别的沙箱中运行的引擎依然可用,因为只有 Host 打开另一进程;反过来,权限高于 Host 的 producer 无法被 Host 打开,因而无法连接,接收器会在握手时关闭它,且 Host 不记录诊断。重新可见的视图要等到分配获批后才能出第一帧,收缩只归还帧 surface,不归还引擎自身的渲染缓存。Escape 总会退出全屏;遮挡以文档为范围:文档中的全屏元素会遮挡除持有者以外的所有接收通道。在 32 GB 及以下的 Windows 机器上,物理内存的一半等于 WDDM 允许图形使用的系统内存,因此那里可能先达到操作系统的上限而非预算;独立 GPU 把帧放在其独立显存中,预算看不到这部分内存,显存用尽时 WDDM 会换页而不是失败。
@@ -12,11 +12,11 @@
en: 8ffcd355ec5e8271
zh: 2932530bf783e3f7
/agent-note-client-plugin-package-assets-served-by-url/decision/references-and-file-names:
en: a97bfcd05c710f0f
zh: 3679312c92bf39ee
en: 704267953c123629
zh: 860997024ad7825e
/agent-note-client-plugin-package-assets-served-by-url/decision/build:
en: e1f52e41d5207cae
zh: a378ce36e9e4c17c
en: 485013b2b6778fa2
zh: 7e5cb238bb2b8585
/agent-note-client-plugin-package-assets-served-by-url/decision/host-route:
en: 151b7300f5b27a9f
zh: fae9adff942c2ce8
@@ -27,8 +27,8 @@
en: eedff52d04763c50
zh: 203bfcf81242b8fe
/agent-note-client-plugin-package-assets-served-by-url/decision/gates-and-migration:
en: c3a4201627d742bb
zh: 03fa25c637a2a803
en: 1e4d83d0de2d47c9
zh: dc2c2876c73d3b1c
/agent-note-client-plugin-package-assets-served-by-url/alternatives-considered:
en: 98960e10634ee536
zh: f0fdb0b0cdf9511c
@@ -26,11 +26,11 @@ plugins/@deepseek-ai/dsh-client-ui-chat/assets/running-whale%402x-06738fa29b2f.p
Each path segment is percent-encoded with `encodeURIComponent` and then `!`, `'`, `(`, `)`, and `*`, so the reference is also a valid unquoted CSS `url()`, and the package name is emitted verbatim. The URL is relative to the shell document, like every app-owned route, so it resolves under any mount and from injected `<style>` text. Components need no hook, injected value, or service: the URL is a module constant computed when the module first runs.
The supported extensions are `.svg`, `.png`, `.webp`, `.jpg`, `.jpeg`, `.woff2`, `.woff`, `.ttf`, and `.otf`. [`src/assets.ts`](../../../../packages/client/modules/src/assets.ts) in client-modules owns the media-type table, the export key and target, the revision, the emitted name, and the URL, and the preset, the route, and the gates read them from there. The shared Client type root [`scripts/types/client-assets`](../../../../scripts/types/client-assets/index.d.ts), registered in [`tsconfig.base.client.json`](../../../../tsconfig.base.client.json), declares each extension as a module with a string default export; a test keeps it equal to the table.
The supported extensions are `.svg`, `.png`, `.webp`, `.jpg`, and `.jpeg`. [`src/assets.ts`](../../../../packages/client/modules/src/assets.ts) in client-modules owns the media-type table, the export key and target, the revision, the emitted name, and the URL, and the preset, the route, and the gates read them from there. The shared Client type root [`scripts/types/client-assets`](../../../../scripts/types/client-assets/index.d.ts), registered in [`tsconfig.base.client.json`](../../../../tsconfig.base.client.json), declares each extension as a module with a string default export; a test keeps it equal to the table.
### Build
The `dsh-package-asset` plugin of the dynamic browser face resolves an import against its source location and fails the build when the file's real path is outside the package's `src/client/assets/` (which also rejects another package's or a dependency's image), when `exports["./assets/*"]` is not exactly `./lib/assets/*`, when the extension is unsupported, when a path segment is `node_modules` or contains `%`, `#`, `?`, `\`, or NUL, which the Host route cannot serve, or when the extension is not lowercase, as the import types are. It emits each file once per build and registers it as a watch input. The three CSS pipelines (CSS Modules, global, and `?inline`) rewrite relative `url()` values through a lightningcss visitor in stylesheets inside the package's own `src/`; `data:`, fragment, scheme, `/`-prefixed, and empty URLs stay unchanged, a relative file reference with a fragment or query fails the build. A stylesheet that a dependency package owns, the nearest named `package.json` above it other than the package's own, is rewritten as well: its referenced file must lie inside that dependency and is emitted under `lib/assets/vendor/<dependency name>/<path in the dependency>`, and each `@font-face` keeps only its first `url()` source. A stylesheet that neither the package's `src/` nor a dependency owns is not rewritten. lightningcss does not call its `Url` visitor inside `image-set()`, so an `Image` visitor rewrites those options with the same rule. The rewrite writes an identifier placeholder that lightningcss never escapes, so a file name with parentheses or quotes still becomes its resolver call. The Node Client face of a dual-face package rejects asset imports. The browser face is the only writer of `lib/assets/`: a one-shot build deletes files it did not emit, and a watch rebuild keeps them, because the Host still serves the previous bundle generation and pages running it request those names.
The `dsh-package-asset` plugin of the dynamic browser face resolves an import against its source location and fails the build when the file's real path is outside the package's `src/client/assets/` (which also rejects another package's or a dependency's image), when `exports["./assets/*"]` is not exactly `./lib/assets/*`, when the extension is unsupported, when a path segment is `node_modules` or contains `%`, `#`, `?`, `\`, or NUL, which the Host route cannot serve, or when the extension is not lowercase, as the import types are. It emits each file once per build and registers it as a watch input. The three CSS pipelines (CSS Modules, global, and `?inline`) rewrite relative `url()` values through a lightningcss visitor in stylesheets inside the package's own `src/`; `data:`, fragment, scheme, `/`-prefixed, and empty URLs stay unchanged, a relative file reference with a fragment or query fails the build, and dependency stylesheets are not rewritten. lightningcss does not call its `Url` visitor inside `image-set()`, so an `Image` visitor rewrites those options with the same rule. The rewrite writes an identifier placeholder that lightningcss never escapes, so a file name with parentheses or quotes still becomes its resolver call. The Node Client face of a dual-face package rejects asset imports. The browser face is the only writer of `lib/assets/`: a one-shot build deletes files it did not emit, and a watch rebuild keeps them, because the Host still serves the previous bundle generation and pages running it request those names.
### Host route
@@ -48,9 +48,9 @@ A rebuilt image produces a new file name in a rebuilt `client.js`, which reaches
### Gates and migration
[`check-workspace-constraints`](../../../../scripts/check-workspace-constraints.ts) requires `lib/assets` in `files` when the export is declared. [`verify-client-packages`](../../../../scripts/verify-client-packages.ts) requires the exact export target, allows the export only on dynamic Web Client packages, and keeps the export and the package's references (imports, and `url()` in the package and dependency stylesheets its Client sources import) consistent in both directions. [`verify-package-dependencies`](../../../../scripts/verify-package-dependencies.ts) treats `./assets/*` as a non-code export. ui-settings-account and ui-chat moved to package assets, and ui-chat's tsdown plugin is gone.
[`check-workspace-constraints`](../../../../scripts/check-workspace-constraints.ts) requires `lib/assets` in `files` when the export is declared. [`verify-client-packages`](../../../../scripts/verify-client-packages.ts) requires the exact export target, allows the export only on dynamic Web Client packages, and keeps the export and the package's references (imports, and `url()` in the stylesheets its Client sources import) consistent in both directions. [`verify-package-dependencies`](../../../../scripts/verify-package-dependencies.ts) treats `./assets/*` as a non-code export. ui-settings-account and ui-chat moved to package assets, and ui-chat's tsdown plugin is gone.
Files that third-party libraries load themselves (PDF.js fonts, cmaps, wasm, and workers), plugin metadata icons, detail-document images, and static-linked packages keep their own delivery.
Images that third-party libraries load themselves (PDF.js fonts, cmaps, wasm, and workers), plugin metadata icons, detail-document images, and static-linked packages keep their own delivery.
## Alternatives considered
@@ -26,11 +26,11 @@ plugins/@deepseek-ai/dsh-client-ui-chat/assets/running-whale%402x-06738fa29b2f.p
路径逐段先用 `encodeURIComponent` 编码,再编码 `!`、`'`、`(`、`)` 和 `*`,因此引用本身也是合法的无引号 CSS `url()`;包名原样输出。URL 和其他应用自有路由一样相对外壳文档,在任意挂载下、以及在注入的 `<style>` 文本中都能正确解析。组件不需要 hook、注入值或 service:URL 就是模块首次运行时算出的常量。
支持的扩展名是 `.svg`、`.png`、`.webp`、`.jpg`、`.jpeg`、`.woff2`、`.woff`、`.ttf` 和 `.otf`。client-modules 的 [`src/assets.ts`](../../../../packages/client/modules/src/assets.ts) 统一定义类型表、导出键与目标、revision、产出文件名和 URL,预设、路由和门禁都从这里读取。共享的 Client 类型根 [`scripts/types/client-assets`](../../../../scripts/types/client-assets/index.d.ts) 在 [`tsconfig.base.client.json`](../../../../tsconfig.base.client.json) 中登记,把每个扩展名声明为默认导出字符串的模块;有测试保证它与类型表一致。
支持的扩展名是 `.svg`、`.png`、`.webp`、`.jpg` 和 `.jpeg`。client-modules 的 [`src/assets.ts`](../../../../packages/client/modules/src/assets.ts) 统一定义类型表、导出键与目标、revision、产出文件名和 URL,预设、路由和门禁都从这里读取。共享的 Client 类型根 [`scripts/types/client-assets`](../../../../scripts/types/client-assets/index.d.ts) 在 [`tsconfig.base.client.json`](../../../../tsconfig.base.client.json) 中登记,把每个扩展名声明为默认导出字符串的模块;有测试保证它与类型表一致。
### 构建
动态浏览器 face 的 `dsh-package-asset` 插件按源码位置解析 import。以下情况构建失败:文件真实路径不在本包 `src/client/assets/` 内(他包或依赖里的图片也因此被拒绝);`exports["./assets/*"]` 不是恰好 `./lib/assets/*`;扩展名不受支持;路径段为 `node_modules` 或含 Host 路由无法提供的 `%`、`#`、`?`、`\` 或 NUL;扩展名不是小写(导入类型只声明小写扩展名)。每个文件每次构建只产出一次,并登记为监听输入。三条 CSS 管线(CSS Modules、全局样式、`?inline`)对本包 `src/` 内的样式表,经 lightningcss visitor 改写相对 `url()`;`data:`、片段、带协议、以 `/` 开头和空的 URL 保持不变,带片段或查询串的相对文件引用会让构建失败。属于某个依赖包的样式表——即样式表上方最近的、带 `name` 且不是本包的 `package.json`——同样改写:被引用的文件必须位于该依赖包内,并输出到 `lib/assets/vendor/<依赖包名>/<依赖包内路径>`,每个 `@font-face` 只保留第一个 `url()` 来源。既不属于本包 `src/`、也不属于任何依赖包的样式表不改写。lightningcss 不会在 `image-set()` 内部调用 `Url` visitor,因此由 `Image` visitor 按同样的规则改写这些选项。改写时先写入 lightningcss 从不转义的标识符占位,因此含括号或引号的文件名仍会变成对应的解析调用。双 face 包的 Node Client face 拒绝资源 import。浏览器 face 是 `lib/assets/` 的唯一写入方:一次性构建会删除本次没有产出的文件,watch 重建则保留它们,因为 Host 仍在提供上一代 bundle,运行它的页面会请求那些文件名。
动态浏览器 face 的 `dsh-package-asset` 插件按源码位置解析 import。以下情况构建失败:文件真实路径不在本包 `src/client/assets/` 内(他包或依赖里的图片也因此被拒绝);`exports["./assets/*"]` 不是恰好 `./lib/assets/*`;扩展名不受支持;路径段为 `node_modules` 或含 Host 路由无法提供的 `%`、`#`、`?`、`\` 或 NUL;扩展名不是小写(导入类型只声明小写扩展名)。每个文件每次构建只产出一次,并登记为监听输入。三条 CSS 管线(CSS Modules、全局样式、`?inline`)对本包 `src/` 内的样式表,经 lightningcss visitor 改写相对 `url()`;`data:`、片段、带协议、以 `/` 开头和空的 URL 保持不变,带片段或查询串的相对文件引用会让构建失败,依赖包的样式表不改写。lightningcss 不会在 `image-set()` 内部调用 `Url` visitor,因此由 `Image` visitor 按同样的规则改写这些选项。改写时先写入 lightningcss 从不转义的标识符占位,因此含括号或引号的文件名仍会变成对应的解析调用。双 face 包的 Node Client face 拒绝资源 import。浏览器 face 是 `lib/assets/` 的唯一写入方:一次性构建会删除本次没有产出的文件,watch 重建则保留它们,因为 Host 仍在提供上一代 bundle,运行它的页面会请求那些文件名。
### Host 路由
@@ -48,9 +48,9 @@ plugins/@deepseek-ai/dsh-client-ui-chat/assets/running-whale%402x-06738fa29b2f.p
### 门禁与迁移
[`check-workspace-constraints`](../../../../scripts/check-workspace-constraints.ts) 要求声明导出时 `files` 含 `lib/assets`。[`verify-client-packages`](../../../../scripts/verify-client-packages.ts) 要求导出目标精确匹配,只允许动态 Web Client 包声明该导出,并要求导出与包内引用(import,以及其 Client 源码所 import 的本包与依赖包样式表中的 `url()`)双向一致。[`verify-package-dependencies`](../../../../scripts/verify-package-dependencies.ts) 把 `./assets/*` 视为非代码导出。ui-settings-account 和 ui-chat 已迁移到包资源,ui-chat 的 tsdown 插件已删除。
[`check-workspace-constraints`](../../../../scripts/check-workspace-constraints.ts) 要求声明导出时 `files` 含 `lib/assets`。[`verify-client-packages`](../../../../scripts/verify-client-packages.ts) 要求导出目标精确匹配,只允许动态 Web Client 包声明该导出,并要求导出与包内引用(import,以及其 Client 源码所 import 的样式表中的 `url()`)双向一致。[`verify-package-dependencies`](../../../../scripts/verify-package-dependencies.ts) 把 `./assets/*` 视为非代码导出。ui-settings-account 和 ui-chat 已迁移到包资源,ui-chat 的 tsdown 插件已删除。
三方库自己加载的文件(PDF.js 的字体、cmap、wasm 和 worker)、插件元数据图标、详情文档图片,以及 static-linked 包,保留各自的交付方式。
三方库自己加载的资源(PDF.js 的字体、cmap、wasm 和 worker)、插件元数据图标、详情文档图片,以及 static-linked 包,保留各自的交付方式。
## Alternatives considered
@@ -9,8 +9,8 @@
en: f2c70036a57ddb41
zh: 9bbbf3dd09d486f5
/agent-note-durable-computer-use-consent-within-one-profile/decision:
en: fa65adc692d849b8
zh: 15d234ba7b791b45
en: 11622523090f5d88
zh: 1d0f8ad94645f069
/agent-note-durable-computer-use-consent-within-one-profile/alternatives-considered:
en: 2af74afa3ecaf3b9
zh: 96f7f43c5d1150df
@@ -10,7 +10,7 @@ Application grants stored as plugin configuration make each authorization change
## 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. [Permission attributes](2026-11-26-cua-permission-attributes.md) decide which stored records a selection matches.
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.
@@ -10,7 +10,7 @@ Status: implemented
## 决策
CUA 使用现有域存储服务,每个 profile 的真实目录对应独立存储域,按本机应用身份保存长期许可和会话决定。对话 ID 限定权限范围,不把本会话许可扩展为所有对话的许可。本机身份规则仍由[Bundle ID 授权](2026-10-25-cua-bundle-id-consent.zh.md)负责,本记录仅替代其中的存储和重启后有效期选择。[权限属性](2026-11-26-cua-permission-attributes.zh.md)决定选择匹配哪些已存储记录。
CUA 使用现有域存储服务,每个 profile 的真实目录对应独立存储域,按本机应用身份保存长期许可和会话决定。对话 ID 限定权限范围,不把本会话许可扩展为所有对话的许可。本机身份规则仍由[Bundle ID 授权](2026-10-25-cua-bundle-id-consent.zh.md)负责,本记录仅替代其中的存储和重启后有效期选择。
每个操作使用现有文件锁,在 profile 锁内打开并读取最新存储状态,关闭域后才释放锁。原生操作和撤销使用单独的目标应用锁;原生调用期间仍可读取存储或访问其他应用。撤销先取消本进程中受影响的工作,再等待其他进程已获准执行的操作结束后提交。因此,撤销完成后不会留下仍使用旧授权的操作。应用级撤销代次和各对话的决定版本,阻止旧句柄或迟到回答恢复被撤销的访问权限。
@@ -1,19 +0,0 @@
# Bilingual-pair consistency record for 2026-10-19-im-session-strategies.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-im-session-strategies.md
/agent-note-im-session-strategies:
en: c701e8fcc2c77418
zh: de6be36e59ef1ace
/agent-note-im-session-strategies/problem:
en: 5ce30763ab012b06
zh: 39c831cb8f64b079
/agent-note-im-session-strategies/decision:
en: 29005c64c8967565
zh: 7b07b4e21d65f2e8
/agent-note-im-session-strategies/alternatives-considered:
en: ebecd48e91907e6d
zh: 06231ece36e4ba33
/agent-note-im-session-strategies/consequences:
en: 8264424d4f0c15c9
zh: df733d9d987848ea
@@ -1,25 +0,0 @@
# Agent Note: IM session strategies
Status: implemented
English | [中文](2026-10-19-im-session-strategies.zh.md)
## Problem
IM deployments differ on how incoming chat messages map to agent sessions. A per-chat conversation deployment gives each chat its own persistent session and delegates long work to background tasks, whereas a multi-chat triage deployment wants one shared dispatcher session to read addressed messages across chats and reply or delegate work from there. Both models need the same message admission, durability, outbound receipts, and authorized `im_*` tools. Hard-coding a single routing model inside the IM host would force a fork of the host for any other routing model.
## Decision
The [IM service](../../../../packages/experimental/im/README.md) owns platform intake, durability, session hosting (`ctx.im.sessions`), outbound publication (`ctx.im.send`/`stream`), and the `im_*` tools, while session selection is handled by listeners on the `im/message` waterfall (and the optional built-in `defaultDispatch` fallback on `@deepseek-ai/dsh-experimental-im`).
The host's own fallback lives in [`dispatcher.ts`](../../../../packages/experimental/im/src/dispatcher.ts): with `defaultDispatch` configured, addressed messages no listener claimed reach a single shared session (`im:dispatcher`) that accumulates bindings for each chat it hears and receives a `<im-chat key="…" source="…" type="…" />` header before each message. Read and publication tools accept an optional `chat` parameter so a multi-chat session can target any chat in its bindings.
## Alternatives considered
**Hard-coding per-chat sessions in `@deepseek-ai/dsh-experimental-im`.** Baking `conversation:<chatKey>` routing into the host would prevent one-shot command plugins, custom routing plugins, or a shared dispatcher session from using the same intake and session store.
**Listing dynamically accumulated chats inside a static system prompt.** A dispatcher session's bound chats grow as new chats send messages; prefixing each delivered message with `<im-chat key="…" />` tells the model which chat sent the message without rewriting earlier turns.
## Consequences
Each session key in `im_sessions` is owned by the `owner` name that created it (`dispatcher` for the default fallback, or the name a plugin picks), and `ctx.im.sessions.ensure` rejects attempts by a different `owner` to claim an existing key. A shared dispatcher session serializes turns across all chats it serves.
@@ -1,25 +0,0 @@
# Agent Note: IM 会话策略
Status: implemented
[English](2026-10-19-im-session-strategies.md) | 中文
## Problem
不同的 IM 部署对入站聊天消息如何映射到 agent 会话有不同需求。按聊天隔离的部署为每个聊天维护一个独立的持久化会话,并将耗时工作委派给后台任务;而集中处理多个聊天的部署则希望由一个共享的分派会话统一接收各聊天的消息并负责回复或委派。两种模式都需要相同的消息准入、持久化存储、发送回执与 `im_*` 授权工具。如果将单一路由模型写死在 IM 宿主中,其他路由模式就必须复制整套宿主逻辑。
## Decision
[IM 服务](../../../../packages/experimental/im/README.zh.md) 负责平台接收、持久化存储、会话托管(`ctx.im.sessions`)、消息发送(`ctx.im.send`/`stream`)与 `im_*` 工具,而消息进入哪个会话则由 `im/message` 事件链上的监听器(以及 `@deepseek-ai/dsh-experimental-im` 上可选的 `defaultDispatch` 兜底)决定。
宿主自带的兜底处理器位于 [`dispatcher.ts`](../../../../packages/experimental/im/src/dispatcher.ts):配置了 `defaultDispatch` 后,没有被任何监听器认领且提及了机器人的消息会进入全局共享的 `im:dispatcher` 会话;该会话自动将见过的每个聊天加入绑定列表,并在每条消息前附上 `<im-chat key="…" source="…" type="…" />` 头部。所有读取与发送工具均支持可选的 `chat` 参数,以便绑定了多个聊天的会话指定目标聊天。
## Alternatives considered
**在 `@deepseek-ai/dsh-experimental-im` 中写死按聊天路由。** 将 `conversation:<chatKey>` 路由硬编码进宿主会导致单次命令插件、自定义路由插件或全局共享分派会话无法复用同一套接收与会话存储。
**仅靠静态系统提示词标识来源聊天。** 分派会话绑定的聊天随新消息到达而增加;在每条投递的消息前加上 `<im-chat key="…" />` 头部,可以直接告知模型当前消息所属的聊天,而无需重写之前的轮次记录。
## Consequences
`im_sessions` 中的每个会话键都记录创建它的 `owner` 名称(默认兜底为 `dispatcher`,其他插件可自取名称),当不同 `owner` 尝试使用已有键调用 `ctx.im.sessions.ensure` 时会被拒绝。共享的 `dispatcher` 会话在单个会话内串行处理多个聊天的轮次。
@@ -9,8 +9,8 @@
en: d2edaafdd83e5974
zh: 57ce9ad368c404c2
/agent-note-ordinary-forks-have-no-durable-creator-relationship/decision:
en: f5be3310dd9382f9
zh: 58414e478a4929dd
en: aae0053e9dc3be9f
zh: bd37095fd5c43c3d
/agent-note-ordinary-forks-have-no-durable-creator-relationship/compatibility:
en: 8393e8526f927134
zh: c957cbde9dc6712d
@@ -10,7 +10,7 @@ Using `parentSession` for both copied history and delegation makes an ordinary f
## 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, and `origin: side` marks an ordinary fork created as a side conversation, which records its source under the [side conversation source decision](2026-11-26-side-conversation-source.md); 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).
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.
@@ -10,7 +10,7 @@ Status: implemented
## 决策
普通 fork 保留完整的选定前缀、`isSeeded`、`inheritedEventCount` 及继承结束标记,但不记录来源 ID。子代理保留直接创建者,包括 backend 复制历史的情况。`origin: subagent` 提供粗粒度分类,`origin: side` 标记作为侧栏对话创建的普通 fork,后者按[侧栏对话来源决策](2026-11-26-side-conversation-source.zh.md)记录来源;有效的自身区间 descriptor 单独提供继续运行身份。历史父元数据保持可读且不变。运行时 Agent 归属仍遵循[显式身份决策](2026-08-31-explicit-agent-runtime-identity.zh.md)。
普通 fork 保留完整的选定前缀、`isSeeded`、`inheritedEventCount` 及继承结束标记,但不记录来源 ID。子代理保留直接创建者,包括 backend 复制历史的情况。`origin: subagent` 提供粗粒度分类;有效的自身区间 descriptor 单独提供继续运行身份。历史父元数据保持可读且不变。运行时 Agent 归属仍遵循[显式身份决策](2026-08-31-explicit-agent-runtime-identity.zh.md)。
V4 reader 仅在已验证的继承区间中允许其他 Session 的投递 ID。自身区间标记仍要求当前 ID,每个活动代际的 `throughSeq` 必须早于其标记。这些检查不需要持久来源关系。
@@ -9,11 +9,11 @@
en: bb387fc89c1c578c
zh: 947456baea45cc95
/agent-note-macos-consent-shared-by-bundle-identifier/decision:
en: 99766ed875d39b9b
zh: f887548b2f8f792a
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: 0c18386a48c36c2d
zh: bb3afb6cc1a13163
en: 1af6d29a57ff86e2
zh: 32517607b2fc935f
@@ -12,7 +12,7 @@ Users who install multiple versions of one application want one permission decis
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 executable path comes from the operating system: applications use the executable URL in their macOS application metadata, and processes without that metadata use the kernel process path. Applications such as Google Chrome can run from a temporary code-signing copy whose kernel path names the copy instead of the installed executable. 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 the bundle identifier and the running executable path are unavailable, consent fails with the path query cause. Process identity must still be verified, and any available running executable path must match the selected target. Missing catalog path metadata does not block consent when the running executable path is available. If the runtime bundle identifier is unavailable, a reported application bundle can supply it only when its main executable matches the running executable path; otherwise that 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.
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.
@@ -28,6 +28,6 @@ Apple’s [PPPC configuration](https://support.apple.com/guide/deployment/privac
## 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. Because application metadata supplies the running executable path, the selection check compares the executable that macOS registered for an application process, not the image the kernel runs: a process whose running image differs from that registration, such as an application still running after an in-place update, keeps the registered path and identity. 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.
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, application metadata that differs from the kernel process path, process restarts, symlink aliases, pending and running identity agreement, shared handle revocation and refusal to widen old grants.
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.
@@ -12,7 +12,7 @@ Status: implemented
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)中的可执行文件和签名身份选择,原记录仍负责执行检查与用户决定。运行中的可执行路径由操作系统提供:应用使用其 macOS 应用元数据中的可执行文件 URL,没有应用元数据的进程使用内核报告的进程路径。Google Chrome 等应用可能从临时代码签名副本运行,内核报告的路径指向该副本,而不是已安装的可执行文件。有效的运行时 Bundle ID 不依赖路径查询成功。无法取得路径时省略授权记录中的可选路径信息,不用缓存的应用目录路径代替。Bundle ID 和运行中的可执行路径均不可用时,授权失败并报告路径查询原因。进程身份仍须验证,可取得的运行中可执行路径仍须与所选目标一致。只要能取得运行中的可执行路径,应用目录信息中缺少路径不会阻止授权。运行时无法取得 Bundle ID 时,仅在其报告的应用 bundle 主可执行文件与运行中的可执行路径一致时读取该标识,否则按该路径识别授权。原生进程、可执行文件位置和窗口检查继续把每个句柄绑定到所选目标。启动检查从磁盘重新读取 Bundle ID 和可执行路径,但不计算可执行内容指纹。因此,在相同路径下替换内容且保留相同标识或路径身份时,许可仍会沿用,包括等待用户批准期间的替换。
本决策取代[应用授权](2026-09-26-cua-application-consent.zh.md)中的可执行文件和签名身份选择,原记录仍负责执行检查与用户决定。运行进程的可执行路径由操作系统提供。有效的运行时 Bundle ID 不依赖路径查询成功。无法取得路径时省略授权记录中的可选路径信息,不用缓存的应用目录路径代替。Bundle ID 和实际路径均不可用时,授权失败并报告路径查询原因。进程身份仍须验证,可取得的实际路径仍须与所选目标一致。只要能取得实际进程路径,应用目录信息中缺少路径不会阻止授权。运行时无法取得 Bundle ID 时,仅在其报告的应用 bundle 主可执行文件与进程路径一致时读取该标识,否则按可执行路径识别授权。原生进程、可执行文件位置和窗口检查继续把每个句柄绑定到所选目标。启动检查从磁盘重新读取 Bundle ID 和可执行路径,但不计算可执行内容指纹。因此,在相同路径下替换内容且保留相同标识或路径身份时,许可仍会沿用,包括等待用户批准期间的替换。
身份前缀将新授权与旧的路径和签名、进程实例、可执行内容摘要分开。旧授权仍可撤销,但不能授予新 Bundle ID 身份访问权限;许可覆盖其他安装副本前,需要用户重新决定。
@@ -28,6 +28,6 @@ Apple 的 [PPPC 配置](https://support.apple.com/guide/deployment/privacy-prefe
## 后果
其他程序声明相同 Bundle ID,或替换路径授权对应的可执行文件时,会继承许可,包括通过其他已授权模型工具创建或修改的程序。由于运行中的可执行路径取自应用元数据,选择检查比较的是 macOS 为应用进程登记的可执行文件,而不是内核实际运行的映像:进程实际运行的映像与登记不一致时,例如原地更新后仍在运行的应用,仍沿用登记的路径和身份。最坏后果是在应用已有数据和能力范围内,读取或控制用户未单独批准的程序。模型不能在 CUA 请求中提交授权身份,该身份由原生 helper 从实际选中的应用读取。不同 Bundle ID 仍需分别授权,即使用户将它们视为同一产品的不同版本。
其他程序声明相同 Bundle ID,或替换路径授权对应的可执行文件时,会继承许可,包括通过其他已授权模型工具创建或修改的程序。最坏后果是在应用已有数据和能力范围内,读取或控制用户未单独批准的程序。模型不能在 CUA 请求中提交授权身份,该身份由原生 helper 从实际选中的应用读取。不同 Bundle ID 仍需分别授权,即使用户将它们视为同一产品的不同版本。
撤销作用于同一标识的所有安装副本。测试覆盖未签名副本、不同标识、缺少标识时的持久路径许可、应用元数据与内核进程路径不一致、进程重启、符号链接、启动前后身份一致、多个句柄共同撤销,以及不扩大旧授权。
撤销作用于同一标识的所有安装副本。测试覆盖未签名副本、不同标识、缺少标识时的持久路径许可、进程重启、符号链接、启动前后身份一致、多个句柄共同撤销,以及不扩大旧授权。
@@ -1,34 +0,0 @@
# Bilingual-pair consistency record for 2026-10-25-im-architecture-v4.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-im-architecture-v4.md
/agent-note-im-architecture-in-v4:
en: 6d31353cd74e9432
zh: f3371b2adcfd5d94
/agent-note-im-architecture-in-v4/problem:
en: 024834c385990be7
zh: 7865b32d373f0484
/agent-note-im-architecture-in-v4/decision:
en: 7d8e9449618a1a9e
zh: 666b9aa64640af5c
/agent-note-im-architecture-in-v4/decision/the-host:
en: 23e9dbcc7062aefd
zh: 11e9e3a2cec281da
/agent-note-im-architecture-in-v4/decision/message-routing-and-the-default-dispatcher:
en: 05e188c631db10aa
zh: d034e4f4102fe74e
/agent-note-im-architecture-in-v4/decision/session-strategies:
en: 397eb04ae8dcffe8
zh: 5c8469820765a83b
/agent-note-im-architecture-in-v4/decision/output-renderers:
en: 7db1986c5b25cb14
zh: 623231c42979666a
/agent-note-im-architecture-in-v4/decision/platform-layer:
en: 1aec79ab90d94964
zh: b321c83decc7a8c5
/agent-note-im-architecture-in-v4/alternatives-considered:
en: 58392b3805a29cd4
zh: 9715f7c9c5b33e34
/agent-note-im-architecture-in-v4/consequences:
en: 8c14d0a1c8fc9368
zh: f7bae48c08fae040
@@ -1,53 +0,0 @@
# Agent Note: IM architecture in v4
Status: implemented
English | [中文](2026-10-25-im-architecture-v4.zh.md)
## Problem
An IM integration has to answer three independent questions: what the platform delivered and what a session is allowed to do with it, which session should receive an incoming message, and how a running turn should be displayed in the chat. Combining routing and output rendering inside the core IM service forces every deployment onto a single routing strategy and a single platform payload builder, and requires modifying the core whenever a new slash command, routing strategy, or output format is needed.
## Decision
`@deepseek-ai/dsh-experimental-im` is a platform-neutral host: it admits and stores platform messages, hosts agent sessions, enforces chat bindings and publication receipts, and tracks turn activity. Routing, slash commands, background tasks, and turn output rendering are separate plugins.
### The host
[`ImService`](../../../../packages/experimental/im/src/index.ts) provides `ctx.im` (`sessions`, `history`, `outputs`, `send`, `stream`, `format`, `bot`, `chat`, and `status()`) as defined in [`api.ts`](../../../../packages/experimental/im/src/api.ts). Intake ([`intake.ts`](../../../../packages/experimental/im/src/intake.ts)) resolves `satori/receive` only after both the message record and the event deduplication digest are persisted in `im_messages`, and the adapter acknowledges the platform event afterwards. Redelivering a `(bot, eventId)` the intake already recorded is the same delivery, so the record the first delivery stored stands and a payload that drifted from it is logged once; messages from chats not matched by any `sources` rule are neither stored nor emitted. The dispatch loop then runs the `im/message` waterfall for each admitted message—different chats in parallel, messages within the same chat sequentially in `seq` order—and records the outcome. Retention removes only expired settled records; pending messages and pending receipts remain until resolved.
Hosted sessions ([`sessions.ts`](../../../../packages/experimental/im/src/sessions.ts)) are keyed by an owner-defined string (`im:dispatcher` for the default dispatcher, or any key a plugin picks) with one active session per key, storing the composition, bindings, output renderer, and owner metadata on the record itself. `ensure` creates or updates the record, `deliver` persists a delivery intent (`steer`, `followup`, or `inject`) and deduplicates it against the session log before inserting into the agent inbox, `reset` disposes the agent and increments `generation` to issue a new `sessionId`, and `stop` cancels a running turn. Outbound sends go through [`send.ts`](../../../../packages/experimental/im/src/send.ts), where an optional `operationId` records a durable receipt (`confirmed`, `failed`, `uncertain`, or `partial`).
### Message routing and the default dispatcher
`im/message` is a waterfall declared in [`api.ts`](../../../../packages/experimental/im/src/api.ts). Listeners registered with `{ prepend: true }` run before routing strategies—[`session-commands`](../../../../packages/experimental/im-session-commands/src/index.ts) uses this position so `/stop`, `/clear`, `/new`, `/status`, `/help`, and passthrough commands run before any strategy turns the message into model input. Routing plugins register in normal order and call `next()` when a message does not match their rules. When `defaultDispatch` is configured on `@deepseek-ai/dsh-experimental-im`, the innermost fallback ([`dispatcher.ts`](../../../../packages/experimental/im/src/dispatcher.ts)) delivers any remaining addressed message to a single shared session (`key: 'im:dispatcher'`, `owner: 'dispatcher'`), accumulating chat bindings as messages arrive and prefixing each message with `<im-chat key="…" source="…" type="…" />`; without `defaultDispatch`, the fallback returns `ignored`. If a listener throws, the message remains `pending` for retry, so listeners must pass deterministic delivery ids and `operationId` values.
### Session strategies
Routing is a listener's decision: a plugin that wants one session per chat, one session per command, or one session per topic registers on `im/message` and hosts what it needs through `ctx.im.sessions`. The shipped bundle mounts `session-commands` and, when `defaultDispatch` is configured, the host's own dispatcher; no other listener claims a message.
### Output renderers
The host aggregates agent events for each turn of a hosted session into an `ImActivity` snapshot, emits `im/activity`, and drives the renderer named by `spec.output` through `ctx.im.outputs` ([`outputs.ts`](../../../../packages/experimental/im/src/outputs.ts)). `output: 'none'` is the default, so a hosted session publishes only when the agent calls `im_send`, `im_reply`, or `im_send_file`; the shipped bundle registers no renderer, and a plugin that wants streamed progress registers one instead of changing the host.
### Platform layer
Below `ctx.im` sit the vendored Satori packages: [`plugin-im-core`](../../../../vendor/im/core/src/index.ts) (protocol, per-mode element registry, transformation and fallback table, capability evaluation, degradation scoring, stream scheduler, and test conformance kit), [`satori-element`](../../../../vendor/im/element/src/index.ts) (element types and GFM markdown conversion), and the [`plugin-im-adapter-lark`](../../../../vendor/im/adapter-lark/src/bot.ts) and [`plugin-im-adapter-qq`](../../../../vendor/im/adapter-qq/src/bot.ts) adapters.
## Alternatives considered
**A single `ctx.imSessions` strategy service instead of the `im/message` waterfall.** Requiring the host to call a single strategy service prevents command plugins, custom command handlers, and routing strategies from composing in sequence, and forces platform adapters to wait on strategy injection before connecting. A waterfall allows pre-routing command listeners, routing plugins, and the default dispatcher fallback to compose in a deterministic order.
**Building platform card payloads inside the host.** Embedding one platform's card JSON and streaming schedule inside `dsh-im` couples every deployment to that platform and makes automatic turn streaming mandatory. Separating `im/activity` and `ctx.im.outputs` keeps platform-neutral rendering in a plugin that registers on that registry while allowing `output: 'none'` sessions to publish solely through explicit tool calls.
**Streaming assistant text into the chat by default.** Automatically publishing every assistant turn conflicts with agents that use explicit `im_send`/`im_reply` calls to decide what to say and in which chat. Defaulting `output` to `'none'` keeps session hosting independent of turn rendering.
**Splitting the `im_*` tools into a separate `tool-*` package.** Splitting them from the service that owns chat grants and publication receipts required duplicate internal contracts to pass session identity and permissions across packages. Registering the `im_*` tools in the host keeps each tool alongside the state it enforces.
## Consequences
A deployment mounts `@deepseek-ai/dsh-experimental-im` together with the routing plugins and output renderers it needs. If no routing plugin matches a message and `defaultDispatch` is not configured, the message is acknowledged, stored, and recorded as `ignored` in `ctx.im.status()`.
Waterfall listeners are responsible for idempotency: because a throwing listener leaves the message `pending` for retry, plugins must supply deterministic delivery ids and `operationId` values so retries do not duplicate inbox insertions or outbound messages.
Verification: `packages/experimental/im/tests/{intake,dispatcher,sessions,send,outputs,activity,tools,store}.spec.ts` cover the host modules; `packages/experimental/im-session-commands/tests/commands.spec.ts` covers the commands plugin. See [IM storage unit identity in v4](2026-10-25-im-storage-unit-identity.md) for the three storage domain names (`im_messages`, `im_sessions`, `im_receipts`).
@@ -1,53 +0,0 @@
# Agent Note: v4 中的 IM 架构
Status: implemented
[English](2026-10-25-im-architecture-v4.md) | 中文
## Problem
IM 集成需要解决三个相互独立的问题:平台投递了什么以及会话拥有哪些权限、入站消息应当路由给哪个会话、以及运行中的轮次应当如何在聊天中展示。如果将会话路由与输出渲染耦合在同一个核心服务中,每次部署都会被绑定到单一路由策略与单一平台的载荷构造逻辑,且新增斜杠命令、路由策略或输出样式都必须修改核心服务。
## Decision
`@deepseek-ai/dsh-experimental-im` 是平台无关的宿主服务:负责接纳并存储平台消息、托管 agent 会话、执行聊天权限校验与发送回执记录,并跟踪轮次活动。会话路由、斜杠命令、后台任务与轮次输出渲染均由独立插件实现。
### The host
[`ImService`](../../../../packages/experimental/im/src/index.ts) 按照 [`api.ts`](../../../../packages/experimental/im/src/api.ts) 中的定义提供 `ctx.im`(`sessions`、`history`、`outputs`、`send`、`stream`、`format`、`bot`、`chat` 与 `status()`)。接收模块([`intake.ts`](../../../../packages/experimental/im/src/intake.ts))在消息记录与事件去重摘要均持久化写入 `im_messages` 后才完成 `satori/receive`,随后适配器才向平台返回 ACK。已被接收层记录的 `(bot, eventId)` 再次投递就是同一次投递:首次投递写入的记录为准,载荷与它不同时只记录一次告警;不匹配任何 `sources` 规则的聊天既不入库也不发出事件。派发循环随后对每条被接纳消息触发 `im/message` 事件链——不同聊天并行派发,同一聊天内按 `seq` 顺序串行派发——并记录处理结果。过期清理仅删除已完成的旧记录;处于待处理状态的消息与回执会一直保留,直到处理完成。
托管会话([`sessions.ts`](../../../../packages/experimental/im/src/sessions.ts))以插件定义的键寻址(默认分派器使用 `im:dispatcher`,其它插件可使用任意键),每个键对应一个活动会话,组合配置、聊天绑定、输出渲染器与自定义元数据直接保存在会话记录中。`ensure` 创建或更新会话记录,`deliver` 在写入 agent 收件箱前先持久化投递意图(`steer`、`followup` 或 `inject`)并通过核对会话日志去重,`reset` 释放当前 agent 并递增 `generation` 以生成新的 `sessionId`,`stop` 取消正在运行的轮次。出站发送统一经过 [`send.ts`](../../../../packages/experimental/im/src/send.ts),传入可选的 `operationId` 时会将发送结果记录为持久化回执(`confirmed`、`failed`、`uncertain` 或 `partial`)。
### Message routing and the default dispatcher
`im/message` 是在 [`api.ts`](../../../../packages/experimental/im/src/api.ts) 中声明的事件链。使用 `{ prepend: true }` 注册的监听器先于路由策略运行——[`session-commands`](../../../../packages/experimental/im-session-commands/src/index.ts) 位于该位置,使 `/stop`、`/clear`、`/new`、`/status`、`/help` 与透传命令在任何策略将文本转为模型输入前直接执行。路由插件按普通顺序注册,遇到不属于自己的消息时调用 `next()` 向后传递。当在 `@deepseek-ai/dsh-experimental-im` 上配置了 `defaultDispatch` 时,最内层的兜底处理器([`dispatcher.ts`](../../../../packages/experimental/im/src/dispatcher.ts))会将未被认领且提及了机器人的消息投递给一个全局共享会话(`key: 'im:dispatcher'`,`owner: 'dispatcher'`),随消息到达自动累积聊天绑定,并在每条消息前添加 `<im-chat key="…" source="…" type="…" />` 头部;未配置 `defaultDispatch` 时则返回 `ignored`。如果监听器抛出异常,消息会保持 `pending` 等待重试,因此监听器必须使用确定性的投递 id 和 `operationId`。
### Session strategies
路由由监听器决定:希望按聊天、按命令或按话题划分会话的插件自行注册到 `im/message`,并通过 `ctx.im.sessions` 托管所需会话。随附的组合包只挂载 `session-commands`,并在配置了 `defaultDispatch` 时挂载宿主自带的默认分派器;其余消息没有监听器认领。
### Output renderers
宿主将托管会话每轮的 agent 事件汇总为 `ImActivity` 快照,发出 `im/activity` 事件,并通过 `ctx.im.outputs`([`outputs.ts`](../../../../packages/experimental/im/src/outputs.ts))驱动会话 `spec.output` 指定的输出渲染器。`output: 'none'` 是默认值,托管会话仅在 agent 调用 `im_send`、`im_reply` 或 `im_send_file` 时发布内容;随附的组合包不注册任何渲染器,需要流式进度的插件自行注册,无需改动宿主。
### Platform layer
`ctx.im` 之下是内置的 Satori 包:[`plugin-im-core`](../../../../vendor/im/core/src/index.ts)(协议、按模式的元素注册表、转换与回退表、能力评估、降级计分、流式调度器与一致性测试套件)、[`satori-element`](../../../../vendor/im/element/src/index.ts)(元素类型与 GFM Markdown 转换),以及 [`plugin-im-adapter-lark`](../../../../vendor/im/adapter-lark/src/bot.ts) 和 [`plugin-im-adapter-qq`](../../../../vendor/im/adapter-qq/src/bot.ts) 平台适配器。
## Alternatives considered
**使用单一 `ctx.imSessions` 策略服务替代 `im/message` 事件链。** 由宿主调用单一策略服务会使斜杠命令插件、自定义命令插件与路由策略无法按顺序组合,并迫使平台适配器在连接前等待策略服务注入。事件链允许前置命令监听器、路由插件与默认分派会话按确定顺序协同工作。
**在宿主内部构造平台卡片载荷。** 将单一平台的卡片 JSON 构造与流式更新节奏写进 `dsh-im`,会把所有部署绑定到该平台,并使自动流式输出成为强制行为。拆分出 `im/activity` 与 `ctx.im.outputs` 后,平台无关的渲染逻辑留在注册到该注册表的插件中,同时允许 `output: 'none'` 的会话仅通过显式工具调用发言。
**默认将助手文本流式发布到聊天。** 自动把每一轮文本发到聊天中,会与通过显式调用 `im_send`/`im_reply` 决定发言内容和目标聊天的 agent 产生冲突。将 `output` 默认设为 `'none'` 可保持会话托管与轮次渲染正交。
**将 `im_*` 工具拆分到独立的 `tool-*` 包中。** 把它们从管理聊天授权与发送回执的服务包中拆出,需要维护额外的跨包内部接口来传递会话身份与权限。将 `im_*` 工具注册在宿主中,使工具与其依赖的状态管理保持在同一包内。
## Consequences
部署按需挂载 `@deepseek-ai/dsh-experimental-im`、路由插件与输出渲染器。若没有任何路由插件认领消息且未配置 `defaultDispatch`,被接纳的消息仍会完成 ACK、入库并在 `ctx.im.status()` 中记录为 `ignored`。
事件链监听器需自行保证幂等性:监听器抛错会让消息保持 `pending` 并在后续重试,因此插件必须提供确定性的投递 id 和 `operationId`,避免重试时重复写入收件箱或重复发送消息。
验证:`packages/experimental/im/tests/{intake,dispatcher,sessions,send,outputs,activity,tools,store}.spec.ts` 覆盖宿主各模块;`packages/experimental/im-session-commands/tests/commands.spec.ts` 覆盖命令插件。三个持久化存储域(`im_messages`、`im_sessions`、`im_receipts`)的命名规则见 [v4 中的 IM 存储 unit 身份](2026-10-25-im-storage-unit-identity.zh.md)。
@@ -1,19 +0,0 @@
# Bilingual-pair consistency record for 2026-10-25-im-storage-unit-identity.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-im-storage-unit-identity.md
/agent-note-im-storage-unit-identity-in-v4:
en: dfe7222b2c39ed68
zh: 437376ab9dd5fa6d
/agent-note-im-storage-unit-identity-in-v4/problem:
en: e797e295bb466f4c
zh: 6710f2fb5a6ce0f4
/agent-note-im-storage-unit-identity-in-v4/decision:
en: bb21e01ff613b3fb
zh: 8a6c7a132541ff85
/agent-note-im-storage-unit-identity-in-v4/alternatives-considered:
en: 87c050a966f70cc5
zh: 80f678f0390db637
/agent-note-im-storage-unit-identity-in-v4/consequences:
en: 491e0391ce6ee905
zh: 943510bea0b14e07
@@ -1,41 +0,0 @@
# Agent Note: IM storage unit identity in v4
Status: implemented
English | [中文](2026-10-25-im-storage-unit-identity.zh.md)
## Problem
Booting v4 over an existing home fails before the service starts (`StorageError: unit 'im': stored version 1 != expected 2`) when a v4 message store reuses the v3 `im` unit name at version 2 with a different table layout (`events`/`messages`/`chats` instead of v3's `sessions`/`tasks`/`intake`/`output`). A unit name is its identity on the storage medium and a single-document unit is read at its exact version only, so reusing a v3 unit name with an incompatible layout or record schema fails on every boot over a v3 home.
The storage domain layer has no in-place migration or reset hook: [`DomainSpec`](../../../../packages/storage/storage-domain/src/spec.ts) declares a name, a version, a layout, and record schemas, and [`KvFacet`](../../../../packages/storage/storage/src/backend.ts) provides `open`/`loadAll`/`putRecord`/`deleteRecord`/`setGlobal`/`close` without a transform or destroy primitive ([`packages/storage/storage-domain/README.md`](../../../../packages/storage/storage-domain/README.md)). Moreover, v3 intake receipts and hosted sessions are not reusable by the v4 IM packages, whose admission, session, receipt, and task records have different schemas.
## Decision
Each IM storage domain uses its own v4 unit name, leaving pre-v4 unit names unused:
| Domain | Unit (v4) | Owner |
|---|---|---|
| Message store: events, messages, chats | `im_messages` | `packages/experimental/im/src/state.ts` |
| Hosted sessions and pending deliveries | `im_sessions` | `packages/experimental/im/src/sessions.ts` |
| Publication receipts | `im_receipts` | `packages/experimental/im/src/send.ts` |
Because each v4 domain has a new unit name, each starts at version 1. Existing pre-v4 `im`, `im_conversation`, and `im_dispatch` units remain untouched on the storage medium: nothing in v4 reads, migrates, or deletes them, and the first v4 boot opens empty v4 stores cleanly without manual intervention. A deployment that ran the removed task plugin keeps its `im_tasks` records the same way: no v4 domain opens that unit.
## Alternatives considered
**Declare a v1-to-v2 migration that discards the v3 state.** `DomainSpec` and the storage backend contract have no migration, reset, or destroy hook; adding one would require new storage-layer primitives ([the `recovery: 'reset'` proposal](../../proposed/architecture/2026-07-28-storage-root-and-derived-medium-recovery.md)), and reaching around the storage backend from the IM package would break backend abstraction.
**Keep the `im` name and bump the version to 2.** A single-document unit is checked for an exact version match, so version 2 over a stored version 1 unit fails with `version-mismatch` on every boot.
**Keep the old unit names and loosen schemas to accept v3 records.** v3 and v4 records represent different data models; accepting v3 records under v4 schemas would misinterpret obsolete routing and intake state instead of starting clean.
**Delete the v3 units at boot.** The storage backend provides no unit-deletion primitive, and deleting user storage files automatically during service startup is outside the IM package's scope.
## Consequences
An upgraded `$DSH_HOME` retains any pre-v4 `im.json`, `im_conversation.json`, and `im_dispatch.json` files unused alongside the v4 unit files. The v4 IM service starts with fresh message, session, and receipt stores.
Any future compatible schema change within one of these three domains increments that unit's version and declares `compatibleVersions` only when existing records remain valid under the new schema.
Verification: `packages/experimental/im/tests/store.spec.ts` boots the message store over a medium seeded with a v3-shaped `im` unit at version 1, verifies that v4 writes land in `im_messages` while the v3 unit stays untouched, and verifies that opening `im` at version 2 rejects with `version-mismatch`.
@@ -1,41 +0,0 @@
# Agent Note: v4 中的 IM 存储 unit 身份
Status: implemented
[English](2026-10-25-im-storage-unit-identity.md) | 中文
## Problem
如果 v4 消息存储沿用 v3 的 `im` unit 名称并将版本设为 2(表结构改为 `events`/`messages`/`chats`,而非 v3 的 `sessions`/`tasks`/`intake`/`output`),在已有 v3 home 目录上启动 v4 会在服务启动前失败:`StorageError: unit 'im': stored version 1 != expected 2`。unit 名称是其在存储介质上的身份标识,且单文档 unit 仅按精确版本号读取,因此在已有 v3 目录上复用旧 unit 名称且表结构或记录 schema 不兼容时,每次启动都会报错。
存储域层不提供就地迁移或重置机制:[`DomainSpec`](../../../../packages/storage/storage-domain/src/spec.ts) 仅包含名称、版本、布局与记录 schema,[`KvFacet`](../../../../packages/storage/storage/src/backend.ts) 仅提供 `open`/`loadAll`/`putRecord`/`deleteRecord`/`setGlobal`/`close`,不包含转换或销毁原语(见 [`packages/storage/storage-domain/README.zh.md`](../../../../packages/storage/storage-domain/README.zh.md))。此外,v3 的接收回执与会话记录对 v4 IM 各包并不可复用,v4 的消息、会话、回执与任务记录本身具有不同的数据结构。
## Decision
每个 IM 存储域使用独立的 v4 unit 名称,不再复用 v4 之前的名称:
| 存储域 | unit 名称(v4) | 所属模块 |
|---|---|---|
| 消息存储:事件、消息、聊天 | `im_messages` | `packages/experimental/im/src/state.ts` |
| 托管会话与待处理投递 | `im_sessions` | `packages/experimental/im/src/sessions.ts` |
| 发送回执 | `im_receipts` | `packages/experimental/im/src/send.ts` |
由于每个 v4 存储域均使用全新名称,各自从版本 1 开始。介质上已有的 v3 `im`、`im_conversation` 与 `im_dispatch` unit 保持原样:v4 不读取、不迁移也不删除它们,首次启动 v4 时会自动创建并使用全新的存储单元,无需人工清理步骤。运行过已移除的任务插件的部署,其 `im_tasks` 记录同样保持原样:没有任何 v4 存储域会打开该 unit。
## Alternatives considered
**声明 v1 到 v2 的迁移以丢弃 v3 状态。** `DomainSpec` 与存储后端契约均无迁移、重置或销毁钩子;引入该机制需要先在存储层增加原语(见 [`recovery: 'reset'` 提案](../../proposed/architecture/2026-07-28-storage-root-and-derived-medium-recovery.zh.md)),而在 IM 包内绕过存储后端直接操作文件会破坏存储抽象。
**保留 `im` 名称并将版本升至 2。** 单文档 unit 要求版本号精确匹配,在版本 1 的介质上以版本 2 打开每次都会因 `version-mismatch` 失败。
**保留旧名称并放宽 schema 以兼容 v3 记录。** v3 与 v4 记录代表不同的数据模型;放宽 schema 会导致 v4 将已废弃的旧路由和接收状态误读为当前记录。
**启动时自动删除 v3 unit。** 存储后端没有删除 unit 的原语,且在启动阶段自动删除用户存储文件不属于 IM 包的职责范围。
## Consequences
升级后的 `$DSH_HOME` 目录会将旧版 `im.json`、`im_conversation.json` 与 `im_dispatch.json` 原样保留在 v4 存储单元旁且不再读取。v4 IM 服务以空的消息、会话与回执存储启动。
今后若在这三个存储域内部进行兼容的 schema 变更,只需递增对应 unit 的版本号,并在旧记录符合新 schema 时声明 `compatibleVersions`。
验证:`packages/experimental/im/tests/store.spec.ts` 在预置了 v3 `im` unit(版本 1)的存储介质上启动消息存储,验证 v4 写入落在 `im_messages` 中且 v3 介质保持不变,同时验证以版本 2 打开 `im` 会因 `version-mismatch` 被拒绝。
@@ -9,8 +9,8 @@
en: 129d30508926bbc5
zh: 15feff44556fc9b7
/agent-note-office-skills-in-every-deployment-with-one-office-kit-package/decision:
en: e8f7468f6d6a9379
zh: 69a5dc67ad2195b8
en: 7d70a22025ab858e
zh: cc37cb9932e78787
/agent-note-office-skills-in-every-deployment-with-one-office-kit-package/alternatives-considered:
en: 167c52da0171028f
zh: 9c87c2370d0719df
@@ -18,9 +18,9 @@ The bundled Python environment ([`tool-workspace-dependencies`](../../../../pack
[`@deepseek-ai/dsh-office-kit`](../../../../packages/document/office-kit/README.md) owns Kit location and the shared conversion service. Kit location is an internal implementation of the provider and is not exported: the provider passes its own `import.meta.resolve` lookup, and native engine paths use ASAR-unpacked mapping. Location reads no environment variables. The [on-demand Office tools](2026-10-31-native-office-tool.md) run Kit operations inside the Host, so no deployment publishes Kit CLI paths or Office executable variables.
An absent Kit degrades instead of failing a load. The conversion service registers and rejects conversions with code `unavailable`, retaining only a successful Kit import and reporting each distinct failure once; the `document_render`, `document_convert`, and `document_recalculate` tools stay registered and return that message when called.
An absent Kit degrades instead of failing a load. The conversion service registers and rejects conversions with code `unavailable`, retaining only a successful Kit import and reporting each distinct failure once; the `office_render`, `office_convert`, and `office_recalculate` tools stay registered and return that message when called.
`office-to-pdf` became `office-kit` so that later Kit consumers, such as native rendering (PR #5374) and the `tool-document` package, take Kit from one package. LibreOffice Kit dependencies declare one exact version in every manifest, so the converter and packaged engine come from the same Kit release.
`office-to-pdf` became `office-kit` so that later Kit consumers, such as native rendering (PR #5374) and the `tool-office` package, take Kit from one package. LibreOffice Kit dependencies declare one exact version in every manifest, so the converter and packaged engine come from the same Kit release.
## Alternatives considered
@@ -18,9 +18,9 @@ Status: implemented
[`@deepseek-ai/dsh-office-kit`](../../../../packages/document/office-kit/README.zh.md) 负责 Kit 定位和共享转换服务。Kit 定位是提供方的内部实现,不对外导出:提供方传入自己的 `import.meta.resolve` 查找函数,原生引擎路径使用 ASAR 解包映射。定位不读取环境变量。[按需激活的 Office 工具](2026-10-31-native-office-tool.zh.md)在 Host 内执行 Kit 操作,因此任何部署都不发布 Kit CLI 路径或 Office 可执行文件变量。
Kit 缺失时降级,而不是加载失败。转换服务照常注册,以代码 `unavailable` 拒绝转换,只保留成功的 Kit 导入,并对每种不同的失败只报告一次;`document_render`、`document_convert` 和 `document_recalculate` 工具保持注册并在调用时返回该消息。
Kit 缺失时降级,而不是加载失败。转换服务照常注册,以代码 `unavailable` 拒绝转换,只保留成功的 Kit 导入,并对每种不同的失败只报告一次;`office_render`、`office_convert` 和 `office_recalculate` 工具保持注册并在调用时返回该消息。
`office-to-pdf` 改为 `office-kit`,使后续的 Kit 消费方(例如原生渲染(PR #5374)和 `tool-document` 包)从同一个包获取 Kit。LibreOffice Kit 依赖在每个清单中声明同一个精确版本,因此转换器和打包的引擎来自同一个 Kit 发行版。
`office-to-pdf` 改为 `office-kit`,使后续的 Kit 消费方(例如原生渲染(PR #5374)和 `tool-office` 包)从同一个包获取 Kit。LibreOffice Kit 依赖在每个清单中声明同一个精确版本,因此转换器和打包的引擎来自同一个 Kit 发行版。
## 考虑过的替代方案
@@ -1,19 +0,0 @@
# Bilingual-pair consistency record for 2026-10-27-im-dispatch-out-of-v1.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-27-im-dispatch-out-of-v1.md
/agent-note-rule-driven-im-dispatch-leaves-the-v1-package-set:
en: adafb8ddbbb8f339
zh: 10a63fd931bc5b1a
/agent-note-rule-driven-im-dispatch-leaves-the-v1-package-set/problem:
en: 3b7d39cd4924ad76
zh: 04ed58ef19fc57c2
/agent-note-rule-driven-im-dispatch-leaves-the-v1-package-set/decision:
en: d869683b9760a7fc
zh: 9a8cef79272a9dfe
/agent-note-rule-driven-im-dispatch-leaves-the-v1-package-set/alternatives-considered:
en: 288528e7edab6442
zh: 47f80c327a39cfe5
/agent-note-rule-driven-im-dispatch-leaves-the-v1-package-set/consequences:
en: d39bd4db7d30bd86
zh: d60b0564fa4596b3
@@ -1,27 +0,0 @@
# Agent Note: Rule-driven IM dispatch leaves the v1 package set
Status: implemented
English | [中文](2026-10-27-im-dispatch-out-of-v1.zh.md)
## Problem
`dsh-im-session-dispatch` carried most of the IM plane's complexity: a QuickJS sandbox compiled to WebAssembly for model-written route rules, its own `im_rules` storage unit, a `copy`/`cut` path that took messages away from the dispatcher, rule notices in both directions, and nine dispatcher plus five worker tools. Only one deployment used it. `dsh-im-session-tasks` was coupled to it and to platform threads: it posted a topic announcement, fell back to a `#task` message on platforms without threads, learned thread ids from the first reply, and listened on `im/message` to route topic replies, with a `topicDelivery: rules` mode that existed only for the dispatcher.
## Decision
The rule-driven dispatcher moved into the one deployment plugin that uses it, outside this repository, unchanged in its rule language and storage. In this repository:
- The [`@deepseek-ai/dsh-experimental-im` host](../../../../packages/experimental/im/src/dispatcher.ts) gained a minimal default: with `defaultDispatch` configured, an addressed message no listener handles reaches one session shared by every chat. It has no routing and no rules; without the configuration an unhandled message is ignored as before.
- Background work left with it: no task service ships, so a plugin that needs worker sessions hosts them through `ctx.im.sessions` and routes the messages it wants a worker to receive.
- A publication targets a chat in its session's bindings, so a session bound to several chats answers where it was asked.
## Alternatives considered
**Keep dispatch in v1 without QuickJS.** A predicate language the harness maintains would still need its own store, notices, and tools, and would still be used by one deployment.
**Routing topic replies in the task service.** Which messages reach a worker is routing policy, and routing belongs to the plugin that owns the sessions; a task service would otherwise keep a second, platform-specific router beside every strategy.
## Consequences
A deployment that ran `dsh-im-session-dispatch` mounts its own plugin and its own dispatch presets; its `im_rules` and `im_tasks` records stay on the medium untouched because neither unit name nor version changed, and no storage domain in this repository opens them.
@@ -1,27 +0,0 @@
# Agent Note: 规则驱动的 IM 分派移出 v1 包集合
Status: implemented
[English](2026-10-27-im-dispatch-out-of-v1.md) | 中文
## Problem
`dsh-im-session-dispatch` 承载了 IM 平面的大部分复杂度:为模型编写的路由规则编译到 WebAssembly 的 QuickJS 沙箱、自己的 `im_rules` 存储 unit、把消息从分派者手中拿走的 `copy`/`cut` 路径、双向的规则通知,以及九个分派者工具与五个 worker 工具。只有一个部署使用它。`dsh-im-session-tasks` 与它以及平台线程耦合:它发布话题公告,在没有线程的平台上退化为 `#task` 消息,从第一条回复学习线程 id,并监听 `im/message` 路由话题回复,其中 `topicDelivery: rules` 模式只为分派者存在。
## Decision
规则驱动的分派者移入唯一使用它的部署插件,位于本仓库之外,规则语言与存储保持不变。在本仓库中:
- [`@deepseek-ai/dsh-experimental-im` 宿主](../../../../packages/experimental/im/src/dispatcher.ts) 增加了一个最小默认行为:配置 `defaultDispatch` 后,没有监听器处理的、找机器人的消息进入所有聊天共用的一个会话。它没有路由也没有规则;不配置时未处理的消息照旧被忽略。
- 后台工作随任务服务一同离开本仓库:没有任何任务服务随附,需要 worker 会话的插件通过 `ctx.im.sessions` 自行托管,并自行把希望 worker 收到的消息路由过去。
- 发布面向会话绑定中的某个聊天,因此绑定了多个聊天的会话会在被提问的地方作答。
## Alternatives considered
**在 v1 中保留不含 QuickJS 的分派。** 由 harness 维护的谓词语言仍需要自己的存储、通知和工具,而且仍然只有一个部署使用。
**由任务服务路由话题回复。** 哪些消息到达 worker 属于路由策略,路由属于拥有这些会话的插件;否则任务服务会在每个策略旁边再保留一个特定于平台的路由器。
## Consequences
运行过 `dsh-im-session-dispatch` 的部署改为挂载自己的插件与自己的分派预设;由于 unit 名与版本都未变化,其 `im_rules` 与 `im_tasks` 记录原样留在介质上,本仓库没有任何存储域会打开它们。
@@ -1,19 +0,0 @@
# Bilingual-pair consistency record for 2026-10-28-im-fallback-alternatives-replace-capabilities.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-28-im-fallback-alternatives-replace-capabilities.md
/agent-note-fallback-alternatives-replaced-the-im-capability-layer:
en: 3d9781a91b72777f
zh: b8dd45d77aad30b1
/agent-note-fallback-alternatives-replaced-the-im-capability-layer/problem:
en: 0396e84086598eab
zh: d851b99cba361545
/agent-note-fallback-alternatives-replaced-the-im-capability-layer/decision:
en: d514f78ebca1f125
zh: a0b8994e4468b39a
/agent-note-fallback-alternatives-replaced-the-im-capability-layer/alternatives-considered:
en: 01dc0b64d0c2f957
zh: 278f7b33e13f4636
/agent-note-fallback-alternatives-replaced-the-im-capability-layer/consequences:
en: 2a67d6ce76d7852c
zh: d512af265f406271
@@ -1,37 +0,0 @@
# Agent Note: `<fallback>` alternatives replaced the IM capability layer
Status: implemented
English | [中文](2026-10-28-im-fallback-alternatives-replace-capabilities.zh.md)
## Problem
The vendored IM runtime answered "can this platform do X in this chat" before doing it. `plugin-im-core` owned a capability layer — `ChatFacts`, a per-bot `FactCache`, `LearnedFact`, `Support`, the `element.*` / `message.*` / `limit.*` key vocabulary, `evaluateCapabilities` and `mergeCapabilities` — that every adapter fed from three sides: a mode's declared operations, the adapter hooks, and a per-chat probe. The Lark adapter added a `getChat` probe plus five learned facts, and the QQ adapter published passive-reply windows through the same channel.
Every consumer then had to branch on the answer. `@deepseek-ai/dsh-experimental-im` exposed `caps` on the message event, on the service and on each turn's output IO; the summary and trace renderers asked five or six keys before deciding what to publish; a stop button existed only where `element.button.action` and `interaction.button` both answered `native`. The layer was also wrong in both directions: `unknown` had to mean "attempt it" for operations and "do not render it" for elements, so a probe that could not read a chat silently downgraded work, and a probe that answered `unknown` made the pipeline learn the same thing again from the failure. Nothing about a chat is knowable before the platform answers.
## Decision
The capability layer is deleted, not deprecated, and content itself carries the alternatives.
`@deepseek-ai/satori-element` gains the `<fallback>` element: each direct child is one ranked candidate, and a JSX fragment counts as one candidate, so `<fallback><title>…</title><h3>…</h3><text>…</text></fallback>` names three spellings of one message. `normalize` rewrites each candidate into an internal `<case>` normalized as content of the element the `<fallback>` stands in, which lets a fallback of phrasing content join the surrounding inline run. `RenderEngine` renders the first candidate whose whole subtree its registry renders natively — tag registered, variants declared, structural children standing — and otherwise the last candidate with the usual lowering; a nested fallback counts as native when one of its own candidates is. The choice lands in `RenderReport.fallbacks` and `degradationScore` charges a later candidate, so a mode that renders the author's first choice wins the per-publication mode resolution. Nothing in the engine consults per-chat state.
Removed with it: `capabilities.ts`, `Bot.supports` / `support` / `capabilities`, `Adapter.facts`, `Mode.operations`, `HandlerOptions.available`, `PlatformError.facts`, `RenderContext.caps` / `supports`, the Lark `facts.ts` chat probe and its learned facts, and the QQ passive-window facts. `LimitKey` moved to `mode.ts` and gained `limit.delete.window`; what a mode can do is now a registry fact (does it register the tag and declare the variant), an adapter-hook fact (`editPayload`, `deletePart`, `streamDriver`) or a declared limit. `Bot.edit` and `Bot.delete` decide from those, and a refusal is the classified `PlatformError` the platform answered — never a prediction.
`MessageStream.abort()` now reports whether a recall removed the published message, which is the one question a renderer cannot answer from its own content.
The IM consumers stop querying capabilities. `ImOutputIO`, `ImMessageEvent` and `ImApi` lost `caps`; the summary renderer resolves its plan from the strategy of the stream it opened (`patch` / `edit` publish provisional content, `final` / `append` do not) and writes its stop control as a `<fallback>` of an action button and a `reply /stop` line; the trace renderer writes each reasoning and tool item as a `<fallback>` of a collapsible panel and a one-line summary, and leaves the element budget to the mode that has one.
## Alternatives considered
**Keep the layer and add `<fallback>` beside it.** Two mechanisms would answer the same question and disagree: a renderer could ask whether a mode supports `<details>` while the mode's own registry is the only thing that decides it.
**Keep a small synchronous capability description for the consumers.** The renderers only need three answers (which stream strategy was opened, whether a recall succeeded, whether a button is actionable), and each of those is already reported by the event, the call, or the content itself. A description of "what this platform can do" would reintroduce the guessing that made the layer wrong.
**Probe the chat lazily and cache the answers per chat.** TTLs move the guess, they do not remove it: a mute, a whitelist refusal or an edit policy can change between two sends, and a stale `false` then blocks a working call.
## Consequences
A refusal costs one round trip and surfaces as an error, where the layer used to pre-empt it. Content that must degrade gracefully now says so in its own tree, which puts the decision in the renderer that knows what it is rendering rather than in a key table. Modes own their element budgets in `assemble` and `check`; the trace renderer no longer pre-folds panels. Adapters no longer cache anything about a chat, so a bot needs no probe, no TTL and no invalidation, and the QQ passive bookkeeping answers only the one question the stream driver asks (`remaining()`).
The corpus gained a `fallback` case, and conformance's text-conservation check ignores a `<fallback>`: which candidate renders is a property of the mode, so no single text is conserved. What was given up is any way to answer "can this chat do X" without trying, which the QQ and Lark `230075` paths previously used to choose a buffered stream up front; they now rely on the classified `limit` error to recall and resend.
@@ -1,37 +0,0 @@
# Agent Note:`<fallback>` 备选内容取代了 IM 能力层
Status: implemented
[English](2026-10-28-im-fallback-alternatives-replace-capabilities.md) | 中文
## Problem
内置的 IM 运行时在做事之前先回答「这个平台在这个聊天里能不能做 X」。`plugin-im-core` 拥有一整层能力评估——`ChatFacts`、按 bot 的 `FactCache`、`LearnedFact`、`Support`、`element.*` / `message.*` / `limit.*` 键词汇、`evaluateCapabilities` 与 `mergeCapabilities`——每个适配器都从三个方向喂它:模式声明的操作表、适配器钩子,以及按聊天探测的结果。飞书适配器额外加了 `getChat` 探测和五条学习到的事实,QQ 适配器则把被动回复窗口也从同一条通道发布出去。
于是每个消费方都得对答案分支。`@deepseek-ai/dsh-experimental-im` 在消息事件、服务和每一轮输出的 IO 上都暴露 `caps`;summary 与 trace 渲染器发布前要问五六个键;只有 `element.button.action` 与 `interaction.button` 同时答 `native` 的地方才有停止按钮。这层评估在两个方向上都错:`unknown` 对操作必须表示「照做」,对元素却必须表示「不要渲染」,于是一个读不到聊天的探测会悄悄降级工作,而一个答 `unknown` 的探测又让管线从失败里再学一遍同样的事。平台回答之前,关于聊天的一切本来就无从得知。
## Decision
能力层被删除而不是弃用,改由内容本身携带备选。
`@deepseek-ai/satori-element` 新增 `<fallback>` 元素:每个直接子元素是一个有排序的候选,JSX fragment 整体算一个候选,所以 `<fallback><title>…</title><h3>…</h3><text>…</text></fallback>` 是一条消息的三种写法。`normalize` 把每个候选改写成内部的 `<case>`,按 `<fallback>` 所在元素的内容模型归一化,因此行内内容的 fallback 可以并入周围的行内流。`RenderEngine` 渲染整棵子树都能被其注册表原生渲染的第一个候选(标签已注册、变体已声明、结构子节点成立),否则按常规降级渲染最后一个候选;嵌套 fallback 只要自身某个候选可原生渲染就算可原生渲染。选择结果写入 `RenderReport.fallbacks`,`degradationScore` 会为更靠后的候选计费,因此能渲染作者首选的那个模式会赢得每次发布时的模式解析。引擎中没有任何一处查询按聊天的状态。
随之移除的有:`capabilities.ts`、`Bot.supports` / `support` / `capabilities`、`Adapter.facts`、`Mode.operations`、`HandlerOptions.available`、`PlatformError.facts`、`RenderContext.caps` / `supports`、飞书的 `facts.ts` 聊天探测及其学习到的事实,以及 QQ 的被动窗口事实。`LimitKey` 移到 `mode.ts` 并新增 `limit.delete.window`;一个模式能做什么,如今是注册表事实(是否注册该标签、是否声明该变体)、适配器钩子事实(`editPayload`、`deletePart`、`streamDriver`)或声明的上限。`Bot.edit` 与 `Bot.delete` 据此判断,拒绝就是平台给出的、被分类过的 `PlatformError`,而不是预测。
`MessageStream.abort()` 现在会回报撤回是否真的删掉了已发布的消息——这是渲染器无法从自己的内容里得出的唯一问题。
IM 的消费方不再查询能力。`ImOutputIO`、`ImMessageEvent` 与 `ImApi` 去掉了 `caps`;summary 渲染器根据自己打开的流的策略(`patch` / `edit` 会发布临时内容,`final` / `append` 不会)算出渲染计划,并把停止控件写成一个由操作按钮与「回复 /stop 停止」一行组成的 `<fallback>`;trace 渲染器把每段思考与每次工具调用写成一个由可折叠面板与单行摘要组成的 `<fallback>`,把元素预算留给真正有预算的模式。
## Alternatives considered
**保留这层能力评估,另加 `<fallback>`。** 两套机制会回答同一个问题并互相矛盾:渲染器可以问某个模式是否支持 `<details>`,而真正决定这一点的只有该模式自己的注册表。
**为消费方保留一份精简的同步能力描述。** 渲染器只需要三个答案(打开的是哪种流策略、撤回是否成功、按钮是否可点),每一个都已经由事件、调用本身或内容本身给出。「这个平台能做什么」的描述会重新引入让这层评估出错的猜测。
**按聊天惰性探测并缓存答案。** TTL 只是把猜测挪了位置,并没有消除它:禁言、白名单拒绝或编辑策略都可能在两次发送之间变化,而过期的 `false` 会挡住一次本来能成功的调用。
## Consequences
一次拒绝要付一个往返并作为错误浮出水面,而以前这层评估会提前拦下它。需要优雅降级的内容现在在自己的内容树里说明,于是决定权落在清楚自己在渲染什么的渲染器上,而不是一张键表里。各模式在 `assemble` 与 `check` 中自己负责元素预算;trace 渲染器不再预先折叠面板。适配器不再缓存任何关于聊天的东西,因此 bot 不需要探测、TTL 和失效处理,QQ 的被动记账只回答流驱动问的那一个问题(`remaining()`)。
语料新增了 `fallback` 用例,而 conformance 的文本保全检查会跳过 `<fallback>`:渲染哪个候选是模式的属性,因此没有哪段文本是被普遍保全的。被放弃的是「不试就知道这个聊天能不能做 X」——QQ 与飞书 `230075` 的路径以前靠它提前选择缓冲式流,现在依靠被分类为 `limit` 的错误撤回并重发。
@@ -9,11 +9,11 @@
en: 5b23962ecc835664
zh: c96ea8720ebc9419
/agent-note-on-demand-office-tools-for-rendering-conversion-and-recalculation/decision:
en: ae28f6574f8eb7b1
zh: 847b5dbb73fb79a9
en: 64a4a913bc6b5a38
zh: ad3eb83aa7f32016
/agent-note-on-demand-office-tools-for-rendering-conversion-and-recalculation/alternatives-considered:
en: bf3febecef30340c
zh: f925d1d6bd976a7b
en: f36e8534958e5a46
zh: 96a3876a26a9d9ac
/agent-note-on-demand-office-tools-for-rendering-conversion-and-recalculation/consequences:
en: 4d7153613045e027
zh: db66a7f25ccfe2e0
en: 8ea5f5c493dfae3d
zh: 29d7160bd3f98512
@@ -10,13 +10,13 @@ Office operation skills ran the LibreOffice Kit CLI through ordinary shell comma
## Decision
The [`tool-document` package](../../../../packages/document/tool-document/README.md) exposes `document_render`, `document_convert`, and `document_recalculate` as three on-demand Host tools. Each tool states its parameter rules in its own JSON Schema: `document_render` accepts document paths, page or slide `pages`, worksheet `sheet` and `range` selection, `dpi`, and an optional `renderer` ([Poppler PDF renderer](2026-11-23-poppler-pdf-renderer.md)); `document_convert` accepts all nine output formats (`pdf`, `docx`, `odt`, and `txt` for Word; `pdf`, `xlsx`, `ods`, and `csv` for Excel; `pdf`, `pptx`, and `odp` for PowerPoint) plus `sheet` for CSV output (required when the workbook has several sheets); and `document_recalculate` accepts `xlsx` and `ods`. Together the three declarations total ~1,988 characters, paid only in Sessions that load an Office skill. They call the [Office kit](../../../../packages/document/office-kit/README.md) service, which loads Kit in the Host process through its `src/locate.ts` resolver and runs every operation through the queue, concurrency limits, byte reservations, and cache that Office previews use. Tool requests use `foreground` priority, the class of an open preview, so background prewarming cannot starve them. The SDK composition mounts `tool-document` beside `office-kit`, and the Web bundle's standard and PTC agent presets mount it while its minimal preset keeps its fixed roster; when Kit is missing the tools still register and every call returns the service's `unavailable` message. Each tool reads the service at each call instead of injecting it, so a composition that omits or disables `office-kit` still creates Sessions with the tools and each call fails as `unavailable`; a service loaded later serves the next call. Standard and PTC modes reach the same registrations; nested PTC calls re-enter the ordinary execution pipeline.
The [`tool-office` package](../../../../packages/document/tool-office/README.md) exposes `office_render`, `office_convert`, and `office_recalculate` as three on-demand Host tools. Each tool states its parameter rules in its own JSON Schema: `office_render` accepts document paths, page or slide `pages`, worksheet `sheet` and `range` selection, and `dpi`; `office_convert` accepts all nine output formats (`pdf`, `docx`, `odt`, and `txt` for Word; `pdf`, `xlsx`, `ods`, and `csv` for Excel; `pdf`, `pptx`, and `odp` for PowerPoint) plus `sheet` for CSV output (required when the workbook has several sheets); and `office_recalculate` accepts `xlsx` and `ods`. Together the three declarations total ~1,813 characters, paid only in Sessions that load an Office skill. They call the [Office kit](../../../../packages/document/office-kit/README.md) service, which loads Kit in the Host process through its `src/locate.ts` resolver and runs every operation through the queue, concurrency limits, byte reservations, and cache that Office previews use. Tool requests use `foreground` priority, the class of an open preview, so background prewarming cannot starve them. The SDK composition mounts `tool-office` beside `office-kit`, and the Web bundle's standard and PTC agent presets mount it while its minimal preset keeps its fixed roster; when Kit is missing the tools still register and every call returns the service's `unavailable` message. Each tool reads the service at each call instead of injecting it, so a composition that omits or disables `office-kit` still creates Sessions with the tools and each call fails as `unavailable`; a service loaded later serves the next call. Standard and PTC modes reach the same registrations; nested PTC calls re-enter the ordinary execution pipeline.
`document_render` returns PNG images in the tool result; the Web Client's Office row shows only the result's text blocks and does not display the images. The tool commits the images through the attachment store before the result is logged, so the model-visible images are reconstructable from the Session log, resume and fork restore them, and image offload applies to them. The complete result is bounded by image count, per-image pixels and dimensions, and total PNG bytes, each the lower of the tool configuration and the attachment store's limits; an over-limit selection fails instead of being truncated. A route without image input is refused before rendering.
`office_render` returns PNG images in the tool result; the Web Client's Office row shows only the result's text blocks and does not display the images. The tool commits the images through the attachment store before the result is logged, so the model-visible images are reconstructable from the Session log, resume and fork restore them, and image offload applies to them. The complete result is bounded by image count, per-image pixels and dimensions, and total PNG bytes, each the lower of the tool configuration and the attachment store's limits; an over-limit selection fails instead of being truncated. A route without image input is refused before rendering.
`document_convert` and `document_recalculate` do not write into the workspace. The filesystem service intentionally provides only binary reads, and binary files in the workspace come only from the shell, whose sandbox and approvals already govern writes. The Office kit saves each output in an owner-only directory under its configurable `outputDirectory` (`$DSH_HOME/office-kit/outputs` by default), grouped by the root Session of the caller's subagent tree, and deletes it after `outputRetentionMs`, when `maxOutputStoreBytes` needs room for newer outputs, when that root Session is disposed, or when the provider unloads. A subagent's output therefore outlives the subagent, so the delegating agent can still copy it. Each tool returns the absolute temporary path, format, size, and the page count the converter reports, with the instruction to copy the file with the shell now, because it may be deleted after a retention period or to free space, and is deleted when the conversation ends. A filesystem backend that cannot read Host paths, such as an SSH workspace, refuses these two tools before converting, because a remote shell cannot read the Host output store. Shell sandboxes allow reads of the Harness home on macOS Seatbelt, Linux bubblewrap, and Linux Landlock, so a confined shell can copy the file into the workspace.
`office_convert` and `office_recalculate` do not write into the workspace. The filesystem service intentionally provides only binary reads, and binary files in the workspace come only from the shell, whose sandbox and approvals already govern writes. The Office kit saves each output in an owner-only directory under its configurable `outputDirectory` (`$DSH_HOME/office-kit/outputs` by default), grouped by the root Session of the caller's subagent tree, and deletes it after `outputRetentionMs`, when `maxOutputStoreBytes` needs room for newer outputs, when that root Session is disposed, or when the provider unloads. A subagent's output therefore outlives the subagent, so the delegating agent can still copy it. Each tool returns the absolute temporary path, format, size, and the page count the converter reports, with the instruction to copy the file with the shell now, because it may be deleted after a retention period or to free space, and is deleted when the conversation ends. A filesystem backend that cannot read Host paths, such as an SSH workspace, refuses these two tools before converting, because a remote shell cannot read the Host output store. Shell sandboxes allow reads of the Harness home on macOS Seatbelt, Linux bubblewrap, and Linux Landlock, so a confined shell can copy the file into the workspace.
Instead of staying resident in every request, the three tools register in one `AgentToolRegistry` that `ctx.tools` includes; an `Agent` sees them only after `tool-document` adds all three for that `Agent` with `set()`. `tool-document` adds them on a non-error `skill` tool result (`tools/result` with `!result.isError`, including a nested `skill` call inside `run_code`) or a direct user skill invocation (`session/event` where `event.type === 'user/message'` and `event.data.source.kind === 'skill-invocation'`) whose skill name is in `activationSkills` (`office` by default). It also adds them on `agent/created`, and for each `Agent` that exists when the plugin loads, if `agent.session.requestHeader()?.tools` already lists `document_render`, `document_convert`, or `document_recalculate`, or one of their earlier names `office_render`, `office_convert`, and `office_recalculate` that Sessions recorded before the rename. The registry keeps the tool names added for each `Agent` in memory and drops them with the `Agent`. The declarations appear on the step after the skill loads and stay active for the rest of the Session; calling an `document_*` tool before activation fails as `UNKNOWN_TOOL`. When mid-session activation adds the tools, the agent loop records a `developer/message` (`source: { kind: 'tool-registry' }`) with `tool-addition` items: models that declare `toolUpdate` (`in-history` or `addition-only`) keep their existing request prefix, whereas models without `toolUpdate` start a new request series once. Because standard-mode request headers are already persisted in the Session log, checking `requestHeader()` preserves activation across resume, fork, and compaction without a Session projection. In PTC mode, the recorded request header declares only `run_code`, so a resumed or forked PTC Session (or a process crash between loading a skill and recording the next native request header) does not retain `document_*` bindings until an Office skill loads again; the [`office` skill](../../../../packages/skill/skill-office/README.md) instructs the model to load `office` again when `document_render`, `document_convert`, or `document_recalculate` is not in the tool list. No skill wraps a single operation, and a standalone render, recalculation, or conversion loads only `office`. The skills carry no executable paths, so `skill-office` has no Node, CLI, or Kit location configuration, `office-kit`'s `src/locate.ts` resolves no CLI, Desktop and the bundles publish no Office executable variables, and the Python sidecar's standalone Node remains only for the Python `deepseek_harness.office` module.
The three tools share one `when(agent)` predicate instead of staying resident in every request. An `Agent` activates them when `marked.has(agent)` is true or when `agent.session.requestHeader()?.tools` already lists `office_render`, `office_convert`, or `office_recalculate`; `agent/disposed` clears the `WeakSet<Agent>` mark. `tool-office` marks the `Agent` on a non-error `skill` tool result (`tools/result` with `!result.isError`, including a nested `skill` call inside `run_code`) or a direct user skill invocation (`session/event` where `event.type === 'user/message'` and `event.data.source.kind === 'skill-invocation'`) whose skill name is in `activationSkills` (`office` by default). The declarations appear on the step after the skill loads and stay active for the rest of the Session; calling an `office_*` tool before activation fails as `UNKNOWN_TOOL`. When mid-session activation adds the tools, the agent loop records a `developer/message` (`source: { kind: 'tool-registry' }`) with `tool-addition` items: models that declare `toolUpdate` (`in-history` or `addition-only`) keep their existing request prefix, whereas models without `toolUpdate` start a new request series once. Because standard-mode request headers are already persisted in the Session log, checking `requestHeader()` preserves activation across resume, fork, and compaction without a Session projection. In PTC mode, the recorded request header declares only `run_code`, so a resumed or forked PTC Session (or a process crash between loading a skill and recording the next native request header) does not retain `office_*` bindings until an Office skill loads again; the [`office` skill](../../../../packages/skill/skill-office/README.md) instructs the model to load `office` again when `office_render`, `office_convert`, or `office_recalculate` is not in the tool list. No skill wraps a single operation, and a standalone render, recalculation, or conversion loads only `office`. The skills carry no executable paths, so `skill-office` has no Node, CLI, or Kit location configuration, `office-kit`'s `src/locate.ts` resolves no CLI, Desktop and the bundles publish no Office executable variables, and the Python sidecar's standalone Node remains only for the Python `deepseek_harness.office` module.
This decision partially supersedes [progressive Office skills](2026-09-27-progressive-office-skills.md): its operation skills, ordinary-shell execution, and rejection of a dedicated renderer tool are replaced here, and its four-skill catalog is replaced by the `office` skill with concise inline guidance under the [single Office skill](2026-11-06-single-office-skill.md) decision.
@@ -28,7 +28,7 @@ This decision partially supersedes [progressive Office skills](2026-09-27-progre
**Add a Session projection for loaded Office skills.** Folding `tools/result` and `user/message` records in a dedicated projection would reconstruct skill activation across PTC resume and fork, but requires a new projection service, fold rules, and cross-package dependencies for state that standard-mode request headers already record and that PTC mode recovers by reloading `office`.
**Track activation only in `Agent` memory.** Checking only `WeakSet<Agent>` (as `action-cards` does) drops the `document_*` declarations on the first step after a standard-mode resume or fork because the new `Agent` instance starts unmarked; consulting `agent.session.requestHeader()?.tools` preserves the declarations from the persisted header.
**Track activation only in `Agent` memory.** Checking only `WeakSet<Agent>` (as `action-cards` does) drops the `office_*` declarations on the first step after a standard-mode resume or fork because the new `Agent` instance starts unmarked; consulting `agent.session.requestHeader()?.tools` preserves the declarations from the persisted header.
**Keep one skill per operation.** Separate render, recalculation, and PDF export skills add a `skill` call before each standalone operation and repeat what the tool schema and results already state.
@@ -40,8 +40,8 @@ This decision partially supersedes [progressive Office skills](2026-09-27-progre
## Consequences
Visual inspection takes one `document_render` call after loading an Office skill and needs no cleanup, and its images follow the Session's attachment, offload, and replay rules. Sessions that do not load an Office skill pay zero Office tool-declaration tokens; Sessions that load one activate ~1,988 characters of operation-specific schemas, keeping the existing request prefix on models with `toolUpdate` and starting one new request series on models without it. Standard-mode resume, fork, and compaction retain the tools through the recorded request header, while PTC resume or fork and crashes before the next recorded header recover by loading `office` again. Office operations behave the same in standard and PTC modes and across deployments once activated, and the deployment-specific Node, CLI, and containment code is gone.
Visual inspection takes one `office_render` call after loading an Office skill and needs no cleanup, and its images follow the Session's attachment, offload, and replay rules. Sessions that do not load an Office skill pay zero Office tool-declaration tokens; Sessions that load one activate ~1,813 characters of operation-specific schemas, keeping the existing request prefix on models with `toolUpdate` and starting one new request series on models without it. Standard-mode resume, fork, and compaction retain the tools through the recorded request header, while PTC resume or fork and crashes before the next recorded header recover by loading `office` again. Office operations behave the same in standard and PTC modes and across deployments once activated, and the deployment-specific Node, CLI, and containment code is gone.
Converted files need a shell copy; compositions without a shell tool can render but cannot deliver converted files, and remote workspaces cannot convert at all. Temporary outputs disappear after retention or root Session disposal, so a resumed Session must convert again. Saving page images as files is not offered.
Verification covers the three tools' schemas, results, argument rules, limits, failures, cancellation, PTC dispatch, and disposal in `tool-document.spec.ts`, and skill-driven activation, custom `activationSkills`, failed skill calls, direct `/office` invocation, `requestHeader()` persistence across resume and fork, and PTC reactivation in `activation.spec.ts`; the output store's retention, eviction, release, and sweeping in Office kit tests; Loader compositions that return the `unavailable` message with Kit absent and with the `office-kit` row absent, then reach the service once the row loads; packaged Desktop smoke checks that render, convert, and recalculate real DOCX, XLSX, and PPTX files through the service; and recorded headless sessions that omit `document_*` before an Office skill loads and declare `document_render`, `document_convert`, and `document_recalculate` on the step after loading one, including a render that `document_render` refuses for a route without image input.
Verification covers the three tools' schemas, results, argument rules, limits, failures, cancellation, PTC dispatch, and disposal in `tool-office.spec.ts`, and skill-driven activation, custom `activationSkills`, failed skill calls, direct `/office` invocation, `requestHeader()` persistence across resume and fork, and PTC reactivation in `activation.spec.ts`; the output store's retention, eviction, release, and sweeping in Office kit tests; Loader compositions that return the `unavailable` message with Kit absent and with the `office-kit` row absent, then reach the service once the row loads; packaged Desktop smoke checks that render, convert, and recalculate real DOCX, XLSX, and PPTX files through the service; and recorded headless sessions that omit `office_*` before an Office skill loads and declare `office_render`, `office_convert`, and `office_recalculate` on the step after loading one, including a render that `office_render` refuses for a route without image input.
@@ -10,13 +10,13 @@ Status: implemented
## 决策
[`tool-document` 包](../../../../packages/document/tool-document/README.zh.md)提供三个按需激活的 Host 工具:`document_render`、`document_convert` 和 `document_recalculate`。每个工具在各自的 JSON Schema 中直接声明参数规则:`document_render` 接受文档路径、页码或幻灯片 `pages`、工作表 `sheet` 与 `range` 选择、`dpi` 以及可选的 `renderer`([Poppler PDF 渲染后端](2026-11-23-poppler-pdf-renderer.zh.md));`document_convert` 保留全部九种输出格式(Word 支持 `pdf`、`docx`、`odt`、`txt`,Excel 支持 `pdf`、`xlsx`、`ods`、`csv`,PowerPoint 支持 `pdf`、`pptx`、`odp`)以及仅用于 CSV 输出的 `sheet`(工作簿含多个工作表时必填);`document_recalculate` 接受 `xlsx` 和 `ods`。三个工具声明共约 1,988 个字符,仅在加载了 Office 技能的 Session 中付出。它们调用 [Office 套件](../../../../packages/document/office-kit/README.zh.md)服务;该服务通过 `src/locate.ts` 在 Host 进程中加载 Kit,并让每个操作经过 Office 预览所用的队列、并发上限、字节预留和缓存。工具请求使用 `foreground` 优先级,即打开的预览所属的类别,因此后台预热不会饿死它们。SDK 组合在 `office-kit` 旁挂载 `tool-document`,Web bundle 的标准和 PTC Agent 预设挂载它,minimal 预设保持其固定工具列表;Kit 缺失时三个工具仍然注册,每次调用都返回服务的 `unavailable` 消息。每个工具在每次调用时读取该服务而不是注入它,因此省略或禁用 `office-kit` 的组合仍能带着这些工具创建 Session,每次调用以 `unavailable` 失败;之后加载的服务会处理下一次调用。标准模式与 PTC 模式使用同一组注册;PTC 嵌套调用重新进入普通执行管线。
[`tool-office` 包](../../../../packages/document/tool-office/README.zh.md)提供三个按需激活的 Host 工具:`office_render`、`office_convert` 和 `office_recalculate`。每个工具在各自的 JSON Schema 中直接声明参数规则:`office_render` 接受文档路径、页码或幻灯片 `pages`、工作表 `sheet` 与 `range` 选择以及 `dpi`;`office_convert` 保留全部九种输出格式(Word 支持 `pdf`、`docx`、`odt`、`txt`,Excel 支持 `pdf`、`xlsx`、`ods`、`csv`,PowerPoint 支持 `pdf`、`pptx`、`odp`)以及仅用于 CSV 输出的 `sheet`(工作簿含多个工作表时必填);`office_recalculate` 接受 `xlsx` 和 `ods`。三个工具声明共约 1,813 个字符,仅在加载了 Office 技能的 Session 中付出。它们调用 [Office 套件](../../../../packages/document/office-kit/README.zh.md)服务;该服务通过 `src/locate.ts` 在 Host 进程中加载 Kit,并让每个操作经过 Office 预览所用的队列、并发上限、字节预留和缓存。工具请求使用 `foreground` 优先级,即打开的预览所属的类别,因此后台预热不会饿死它们。SDK 组合在 `office-kit` 旁挂载 `tool-office`,Web bundle 的标准和 PTC Agent 预设挂载它,minimal 预设保持其固定工具列表;Kit 缺失时三个工具仍然注册,每次调用都返回服务的 `unavailable` 消息。每个工具在每次调用时读取该服务而不是注入它,因此省略或禁用 `office-kit` 的组合仍能带着这些工具创建 Session,每次调用以 `unavailable` 失败;之后加载的服务会处理下一次调用。标准模式与 PTC 模式使用同一组注册;PTC 嵌套调用重新进入普通执行管线。
`document_render` 在工具结果中返回 PNG 图片;Web Client 的 Office 行只显示结果的文本块,不显示这些图片。工具在结果写入日志之前通过附件存储提交图片,因此模型可见的图片可以从 Session 日志还原,恢复和分叉会还原它们,图片卸载也适用于它们。完整结果受图片数量、单图像素与尺寸以及 PNG 总字节数约束,每项取工具配置与附件存储上限中的较小值;超出上限的选择直接失败,不会被截断。不支持图片输入的路由在渲染前即被拒绝。
`office_render` 在工具结果中返回 PNG 图片;Web Client 的 Office 行只显示结果的文本块,不显示这些图片。工具在结果写入日志之前通过附件存储提交图片,因此模型可见的图片可以从 Session 日志还原,恢复和分叉会还原它们,图片卸载也适用于它们。完整结果受图片数量、单图像素与尺寸以及 PNG 总字节数约束,每项取工具配置与附件存储上限中的较小值;超出上限的选择直接失败,不会被截断。不支持图片输入的路由在渲染前即被拒绝。
`document_convert` 和 `document_recalculate` 不写入工作区。文件系统服务有意只提供二进制读取,工作区中的二进制文件只由 shell 产生,而 shell 的沙箱和审批已经管理写入。Office 套件把每个输出保存在可配置的 `outputDirectory`(默认 `$DSH_HOME/office-kit/outputs`)下仅属主可访问的目录中,按调用方 subagent 树的根 Session 分组;输出在 `outputRetentionMs` 到期、`maxOutputStoreBytes` 需要为较新的输出腾出空间、该根 Session 卸载或提供方卸载时删除。因此 subagent 的输出在 subagent 结束后仍然保留,委派它的 agent 仍可复制。工具返回临时文件的绝对路径、格式、大小和转换器报告的页数,并指示立即用 shell 复制该文件,因为文件可能在保留期到期或需要腾出空间时被删除,且对话结束后会被删除。无法读取 Host 路径的文件系统后端(例如 SSH 工作区)会在转换前拒绝这两个工具,因为远程 shell 读不到 Host 的输出存储。macOS Seatbelt、Linux bubblewrap 和 Linux Landlock 的 shell 沙箱都允许读取 Harness 主目录,因此受限的 shell 可以把文件复制进工作区。
`office_convert` 和 `office_recalculate` 不写入工作区。文件系统服务有意只提供二进制读取,工作区中的二进制文件只由 shell 产生,而 shell 的沙箱和审批已经管理写入。Office 套件把每个输出保存在可配置的 `outputDirectory`(默认 `$DSH_HOME/office-kit/outputs`)下仅属主可访问的目录中,按调用方 subagent 树的根 Session 分组;输出在 `outputRetentionMs` 到期、`maxOutputStoreBytes` 需要为较新的输出腾出空间、该根 Session 卸载或提供方卸载时删除。因此 subagent 的输出在 subagent 结束后仍然保留,委派它的 agent 仍可复制。工具返回临时文件的绝对路径、格式、大小和转换器报告的页数,并指示立即用 shell 复制该文件,因为文件可能在保留期到期或需要腾出空间时被删除,且对话结束后会被删除。无法读取 Host 路径的文件系统后端(例如 SSH 工作区)会在转换前拒绝这两个工具,因为远程 shell 读不到 Host 的输出存储。macOS Seatbelt、Linux bubblewrap 和 Linux Landlock 的 shell 沙箱都允许读取 Harness 主目录,因此受限的 shell 可以把文件复制进工作区。
三个工具不在每次请求中常驻,而是注册在 `ctx.tools` 引入的同一个 `AgentToolRegistry` 中;只有 `tool-document` 通过 `set()` 为某个 `Agent` 一并添加这三个工具后,该 `Agent` 才能看到它们。当非错误的 `skill` 工具结果(`tools/result` 且 `!result.isError`,包括 `run_code` 内嵌套的 `skill` 调用)或直接的用户技能调用(`session/event` 中 `event.type === 'user/message'` 且 `event.data.source.kind === 'skill-invocation'`)加载了 `activationSkills`(默认为 `office`)中的技能时,`tool-document` 为该 `Agent` 添加这些工具。`tool-document` 还会在 `agent/created` 时,以及插件加载时对每个已存在的 `Agent`,检查 `agent.session.requestHeader()?.tools`:若其中已包含 `document_render`、`document_convert` 或 `document_recalculate`,或改名前记录的 Session 中的旧名 `office_render`、`office_convert`、`office_recalculate` 之一,就为该 `Agent` 添加这些工具。注册表在内存中保存为每个 `Agent` 添加的工具名,并随 `Agent` 一起丢弃。工具声明在加载技能后的下一步出现,并在该 Session 剩余时间内保持激活;激活前调用 `document_*` 工具会以 `UNKNOWN_TOOL` 失败。会话中途激活新增这些工具时,agent loop 会记录一条带 `tool-addition` 项的 `developer/message`(`source: { kind: 'tool-registry' }`):声明了 `toolUpdate`(`in-history` 或 `addition-only`)的模型保留现有请求前缀,未声明 `toolUpdate` 的模型则开启一次新的请求序列。由于标准模式的请求头本就持久化在 Session 日志中,检查 `requestHeader()` 即可在恢复、分叉和压缩后保留激活状态,无需新增 Session projection。PTC 模式下记录的请求头只声明 `run_code`,因此恢复或分叉的 PTC Session(或加载技能后、下一条原生请求头记录前发生进程崩溃)不会保留 `document_*` 绑定,直到再次加载 Office 技能;[`office` 技能](../../../../packages/skill/skill-office/README.zh.md)指示模型在 `document_render`、`document_convert` 或 `document_recalculate` 不在工具列表中时调用 `skill` 重新加载 `office`。没有技能只包装单个操作,单独的渲染、重算或转换只需加载 `office`。技能不再携带可执行文件路径,因此 `skill-office` 没有 Node、CLI 或 Kit 位置配置,`office-kit` 的 `src/locate.ts` 没有 CLI 解析器,Desktop 和各 bundle 不发布 Office 可执行文件变量,Python sidecar 的独立 Node 只保留给 Python `deepseek_harness.office` 模块使用。
三个工具共享同一个 `when(agent)` 谓词,而不是在每次请求中常驻。当 `marked.has(agent)` 为真,或 `agent.session.requestHeader()?.tools` 已包含 `office_render`、`office_convert` 或 `office_recalculate` 时,`Agent` 激活它们;`agent/disposed` 会清除 `WeakSet<Agent>` 标记。当非错误的 `skill` 工具结果(`tools/result` 且 `!result.isError`,包括 `run_code` 内嵌套的 `skill` 调用)或直接的用户技能调用(`session/event` 中 `event.type === 'user/message'` 且 `event.data.source.kind === 'skill-invocation'`)加载了 `activationSkills`(默认为 `office`)中的技能时,`tool-office` 标记该 `Agent`。工具声明在加载技能后的下一步出现,并在该 Session 剩余时间内保持激活;激活前调用 `office_*` 工具会以 `UNKNOWN_TOOL` 失败。会话中途激活新增这些工具时,agent loop 会记录一条带 `tool-addition` 项的 `developer/message`(`source: { kind: 'tool-registry' }`):声明了 `toolUpdate`(`in-history` 或 `addition-only`)的模型保留现有请求前缀,未声明 `toolUpdate` 的模型则开启一次新的请求序列。由于标准模式的请求头本就持久化在 Session 日志中,检查 `requestHeader()` 即可在恢复、分叉和压缩后保留激活状态,无需新增 Session projection。PTC 模式下记录的请求头只声明 `run_code`,因此恢复或分叉的 PTC Session(或加载技能后、下一条原生请求头记录前发生进程崩溃)不会保留 `office_*` 绑定,直到再次加载 Office 技能;[`office` 技能](../../../../packages/skill/skill-office/README.zh.md)指示模型在 `office_render`、`office_convert` 或 `office_recalculate` 不在工具列表中时调用 `skill` 重新加载 `office`。没有技能只包装单个操作,单独的渲染、重算或转换只需加载 `office`。技能不再携带可执行文件路径,因此 `skill-office` 没有 Node、CLI 或 Kit 位置配置,`office-kit` 的 `src/locate.ts` 没有 CLI 解析器,Desktop 和各 bundle 不发布 Office 可执行文件变量,Python sidecar 的独立 Node 只保留给 Python `deepseek_harness.office` 模块使用。
此决定部分取代[渐进式 Office 技能](2026-09-27-progressive-office-skills.zh.md):其操作技能、普通 shell 执行方式以及否决专用渲染工具的决定由本文取代;按照[单个 Office 技能](2026-11-06-single-office-skill.zh.md)决策,其四技能目录已由携带精简内联指导的 `office` 技能取代。
@@ -28,7 +28,7 @@ Status: implemented
**为已加载的 Office 技能新增 Session projection。** 在专用 projection 中折叠 `tools/result` 和 `user/message` 记录虽可在 PTC 恢复和分叉后还原技能激活状态,但需要新增 projection 服务、折叠规则和跨包依赖,而标准模式已由持久化的请求头记录该状态,PTC 模式只需重新加载 `office` 即可恢复。
**仅在 `Agent` 内存中记录激活状态。** 若像 `action-cards` 那样只检查 `WeakSet<Agent>`,标准模式恢复或分叉后的第一步会丢失 `document_*` 声明,因为新的 `Agent` 实例初始未标记;同时检查 `agent.session.requestHeader()?.tools` 可从已持久化的请求头保留声明。
**仅在 `Agent` 内存中记录激活状态。** 若像 `action-cards` 那样只检查 `WeakSet<Agent>`,标准模式恢复或分叉后的第一步会丢失 `office_*` 声明,因为新的 `Agent` 实例初始未标记;同时检查 `agent.session.requestHeader()?.tools` 可从已持久化的请求头保留声明。
**为每个操作保留一个技能。** 单独的渲染、重算和 PDF 导出技能会在每次单独操作前多一次 `skill` 调用,并重复工具 schema 与结果中已有的说明。
@@ -40,8 +40,8 @@ Status: implemented
## 影响
加载 Office 技能后,视觉检查只需一次 `document_render` 调用且无需清理,图片遵循 Session 的附件、卸载和回放规则。未加载 Office 技能的 Session 不消耗任何 Office 工具声明 token;加载了 Office 技能的 Session 激活约 1,988 个字符的专用 schema,支持 `toolUpdate` 的模型保留现有请求前缀,不支持 `toolUpdate` 的模型只开启一次新的请求序列。标准模式的恢复、分叉和压缩通过已记录的请求头保留工具声明,PTC 恢复或分叉以及在记录下一条请求头前崩溃的场景则通过再次加载 `office` 恢复。激活后,Office 操作在标准模式与 PTC 模式之间、在不同部署之间行为一致,各部署专用的 Node、CLI 和约束代码已经删除。
加载 Office 技能后,视觉检查只需一次 `office_render` 调用且无需清理,图片遵循 Session 的附件、卸载和回放规则。未加载 Office 技能的 Session 不消耗任何 Office 工具声明 token;加载了 Office 技能的 Session 激活约 1,813 个字符的专用 schema,支持 `toolUpdate` 的模型保留现有请求前缀,不支持 `toolUpdate` 的模型只开启一次新的请求序列。标准模式的恢复、分叉和压缩通过已记录的请求头保留工具声明,PTC 恢复或分叉以及在记录下一条请求头前崩溃的场景则通过再次加载 `office` 恢复。激活后,Office 操作在标准模式与 PTC 模式之间、在不同部署之间行为一致,各部署专用的 Node、CLI 和约束代码已经删除。
转换后的文件需要 shell 复制;没有 shell 工具的组合可以渲染,但无法交付转换后的文件,远程工作区则完全不能转换。临时输出在保留期满或根 Session 卸载后消失,恢复的 Session 需要重新转换。不提供把页面图片保存为文件。
验证包括:`tool-document.spec.ts` 覆盖三个工具的 schema、结果、参数规则、上限、失败、取消、PTC 分发和卸载,`activation.spec.ts` 覆盖技能触发激活、自定义 `activationSkills`、失败的技能调用、直接 `/office` 调用、跨恢复与分叉的 `requestHeader()` 持久化以及 PTC 重新激活;Office 套件测试覆盖输出存储的保留、淘汰、释放和清扫;Loader 组合测试在 Kit 缺失时以及 `office-kit` 条目缺失时返回 `unavailable` 消息,并在该条目加载后调用到服务;Desktop 打包 smoke 通过服务对真实 DOCX、XLSX 和 PPTX 文件执行渲染、转换和重算;录制的 headless Session 在加载 Office 技能前不声明 `document_*`,在加载后的下一步声明 `document_render`、`document_convert` 和 `document_recalculate`,其中包括一次因路由不接受图片输入而被 `document_render` 拒绝的渲染。
验证包括:`tool-office.spec.ts` 覆盖三个工具的 schema、结果、参数规则、上限、失败、取消、PTC 分发和卸载,`activation.spec.ts` 覆盖技能触发激活、自定义 `activationSkills`、失败的技能调用、直接 `/office` 调用、跨恢复与分叉的 `requestHeader()` 持久化以及 PTC 重新激活;Office 套件测试覆盖输出存储的保留、淘汰、释放和清扫;Loader 组合测试在 Kit 缺失时以及 `office-kit` 条目缺失时返回 `unavailable` 消息,并在该条目加载后调用到服务;Desktop 打包 smoke 通过服务对真实 DOCX、XLSX 和 PPTX 文件执行渲染、转换和重算;录制的 headless Session 在加载 Office 技能前不声明 `office_*`,在加载后的下一步声明 `office_render`、`office_convert` 和 `office_recalculate`,其中包括一次因路由不接受图片输入而被 `office_render` 拒绝的渲染。
@@ -1,19 +0,0 @@
# Bilingual-pair consistency record for 2026-11-02-im-file-media-admission.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-11-02-im-file-media-admission.md
/agent-note-im-media-admission-keeps-non-images-as-verbatim-files:
en: 717f477ade0b46d9
zh: a1be749bdfcef95e
/agent-note-im-media-admission-keeps-non-images-as-verbatim-files/problem:
en: 178f6a04fb7a0ed2
zh: fca0244178df74bf
/agent-note-im-media-admission-keeps-non-images-as-verbatim-files/decision:
en: ca514fc2df5ce15a
zh: d23baa204ab5d0cc
/agent-note-im-media-admission-keeps-non-images-as-verbatim-files/alternatives-considered:
en: ebe114e43895f8f2
zh: f28eeecf91bb46a7
/agent-note-im-media-admission-keeps-non-images-as-verbatim-files/consequences:
en: 098a547db5748ad8
zh: 037f50c170152071
@@ -1,29 +0,0 @@
# Agent Note: IM media admission keeps non-images as verbatim files
Status: implemented
English | [中文](2026-11-02-im-file-media-admission.zh.md)
## Problem
`@deepseek-ai/dsh-experimental-im` labelled every media element of a stored message with a stable id (`[图片 #12.1]`, `[文件 #12.2 report.pdf]`, `[语音 #12.3 语音.opus]`) but could admit only the image kind: `ImMediaStore.admit` answered `skipped: 'unsupported'` for `file`, `audio` and `video`, and the only read tool, `im_read_image`, refused them the same way. A person who sent a document, a voice message or a video into a chat therefore handed the model a label it could not open — the transport, the Lark decoder and the core resource fetcher already carried the bytes (`<file src="satori:…/resources/<file_key>?type=file">`), and nothing consumed them. The `media` field's own contract already said images and files are downloaded, so the implementation was behind its documented behavior.
## Decision
Admission is by payload, not by kind. `ImMediaStore` fetches and bounds a reference exactly as before, then stores an image as a normalized image block and every other kind as the exact bytes of a durable verbatim file through `ctx.attachments.saveFile`. `ImFormatter.format({ media: true })` appends each admitted file as a `file` content block beside the text, so request assembly projects it to the deterministic handle text naming the saved read-only path — the same representation a browser-attached file gets.
The model reaches a file that is no longer in the delivered window through the new `im_read_file` tool: it resolves the label to its element, admits it as a verbatim file, and stages the bytes at `<tools.fileDir>/<seq>.<index>-<name>` under the session's working directory through `ctx.fs.writeBytes`, returning that path with the display name, byte length and content digest. The seam gained `writeBytes` for this: staging through `writeText` would have decoded and normalized the bytes, and the attachment store's host path is not reachable from a remote execution filesystem. `im_read_image` keeps its image-only contract; guidance names both tools and the two label shapes.
## Alternatives considered
**Add the read tool without admitting files eagerly.** Every new message would then cost one download less, but the model would have to ask for a file the sender just handed it, which is exactly the request shape the image path already answers without a tool call.
**Read text-like files into the tool result.** Sniffing a media type to inline text adds a format allowlist and a second representation of the same bytes; a path lets the model's own file tools decide how much to read.
**Resolve the stored attachment's host path and hand it to the model.** That is what the request projection does for a delivered `file` block, and it works only where the execution filesystem maps the harness host path — a local backend does, a remote SSH environment does not, which is exactly the deployment that needed this. Staging through the seam works wherever the provider can write bytes, and the path it returns is one the model's own file tools can open.
## Consequences
An execution filesystem must be able to store the bytes: `fs-local` writes them through the same atomic staging file as its text writes, `fs-ssh` carries them as base64 to the helper under that helper's single-frame budget (8 MiB), and a provider that keeps the base rejection makes `im_read_file` fail instead of inventing a path. A delivered file still depends on host-path mapping for the handle text, so a remote worker learns the copy exists there and stages it on demand. Staging costs a second copy of the element (the durable attachment plus the workspace file), and one id always stages to the same relative path, so a re-read overwrites instead of accumulating. Downloading is still bounded by `media.maxItems` per message and `media.maxBytes` per element, and `media.download: false` keeps labels only.
The prompt section grew one sentence (two label shapes, two tools), and the tool catalog, subsystem page and both READMEs list `im_read_file`.
@@ -1,29 +0,0 @@
# Agent Note:IM 媒体准入把非图片保留为原样文件
Status: implemented
[English](2026-11-02-im-file-media-admission.md) | 中文
## Problem
`@deepseek-ai/dsh-experimental-im` 会给已存消息的每个媒体元素打上稳定 id 标签(`[图片 #12.1]`、`[文件 #12.2 report.pdf]`、`[语音 #12.3 语音.opus]`),但只能准入图片这一种:`ImMediaStore.admit` 对 `file`、`audio`、`video` 一律返回 `skipped: 'unsupported'`,唯一的读取工具 `im_read_image` 同样拒绝它们。于是在聊天里发出文档、语音或视频的人,交给模型的只是一个打不开的标签——传输层、飞书解码器和 core 的资源抓取其实都已经带上字节(`<file src="satori:…/resources/<file_key>?type=file">`),只是没有人去消费。`media` 字段自己的契约本来就写着图片与文件都会下载,实现落后于它写下的行为。
## Decision
准入按载荷决定,而不是按种类决定。`ImMediaStore` 依旧抓取并按上限裁剪一个引用,随后把图片存成归一化的图片块,把其余每种元素通过 `ctx.attachments.saveFile` 原样存成持久文件。`ImFormatter.format({ media: true })` 把每个准入的文件作为 `file` 内容块追加在文本之后,请求装配因此把它投影成指名已保存只读路径的确定性 handle 文本——和浏览器附件的文件拿到的是同一种表示。
模型通过新增的 `im_read_file` 工具取回已经不在投递窗口里的文件:它把标签解析到对应元素,按原样文件准入,并通过 `ctx.fs.writeBytes` 把字节暂存到会话工作目录下的 `<tools.fileDir>/<seq>.<index>-<name>`,返回该路径与显示名、字节数、内容摘要。为此给 seam 增加了 `writeBytes`:走 `writeText` 会把字节解码并归一化,而附件存储的宿主路径在远端执行文件系统里根本不存在。`im_read_image` 保持只处理图片的契约;系统提示词指引同时点明两个工具和两种标签。
## Alternatives considered
**只加读取工具,不做提前准入。** 每条新消息能省下一次下载,但模型得为自己刚收到的东西再发一次请求——而这恰恰是图片路径不需要工具调用就能回答的请求形态。
**把文本类文件读进工具结果。** 靠媒体类型嗅探来内联文本,会引入一份格式白名单和同一份字节的第二种表示;给出路径则让模型自己的文件工具决定读多少。
**解析已存附件的宿主路径直接交给模型。** 这正是请求装配为已投递 `file` 块做的事,但它只在执行文件系统能映射宿主路径时成立——本地后端可以,远端 SSH 环境不行,而那恰恰是最需要它的部署。走 seam 暂存则在任何能写字节的提供方上成立,返回的路径模型自己的文件工具就能打开。
## Consequences
执行文件系统必须能存下这些字节:`fs-local` 通过与文本写入相同的原子暂存文件落盘,`fs-ssh` 把字节以 base64 交给辅助进程并受其单帧预算(8 MiB)限制,保留基类拒绝的提供方会让 `im_read_file` 直接失败,而不是编造一个路径。已投递的文件仍要靠宿主路径映射才有 handle 文本,因此远端 worker 只知道副本存在、按需自行暂存。暂存会多一份副本(持久附件加工作区文件),同一个 id 总是落到同一相对路径,重读只会覆盖而不会堆积。下载仍受每条消息的 `media.maxItems` 与单个元素的 `media.maxBytes` 约束,`media.download: false` 依旧只保留标签。
系统提示词段落多出一句(两种标签、两个工具),工具目录、子系统页面与两份 README 都列出 `im_read_file`。
@@ -12,8 +12,8 @@
en: d23bc3c8c3b20ac9
zh: 874c7a4dda283e89
/agent-note-add-the-hoc-slot-kind-so-plugins-can-wrap-owner-content-in-layers/decision/implementation:
en: 14492f95b195917b
zh: e9ee4c438dccd225
en: 02ec3c2bfad692af
zh: 229a3ae12eac49a6
/agent-note-add-the-hoc-slot-kind-so-plugins-can-wrap-owner-content-in-layers/decision/first-consumer:
en: 1afdf4ceeef7a3b3
zh: be01cf39850db0ca
@@ -21,5 +21,5 @@
en: b4824619c502b422
zh: 610364f2dc8cb2b7
/agent-note-add-the-hoc-slot-kind-so-plugins-can-wrap-owner-content-in-layers/consequences:
en: 7576007507f393dc
zh: d964cc1419bb6917
en: 6d350e8f9df1d33a
zh: 5411b39fc4cc14ce
@@ -42,7 +42,7 @@ Add a fifth kind: `hoc`.
| Package | Realization |
|---|---|
| `ui-slots` | `SlotKind` includes `'hoc'`; `HocRenderOpts` (optional `children` and `entryKey`), `HocKeysOf`, `HocShare`; `RenderSlotFn` has a hoc-key overload taking optional `{ children, entryKey }`; `KindOptions` has a hoc branch with optional `key`; `SlotCore.register` / `entriesOfSlot` key hoc cells by `(key or wildcard, id)` |
| `ui-renderer` | `HocOutlet` takes its render function from `hocChainFor`, which caches one chain per host, spec object, slot name, and `entryKey` across outlet instances. Once per ledger version it reselects the key's layers with `hocLayersFor` (wildcard winners plus exact-key winners, an exact-key layer replacing the wildcard layer with its id, sorted by `order`) and calls `composeHocLayers` to nest them into one render function only when that ordered list changes by entry identity. Each layer is one Component that fixes its scope-specific Entry (`StrictSessionEntry` / `SessionMaybeEntry` / `RootEntry`), entry, slot inject, and crash reporting at composition, and receives only `owner` and the next inner layer when rendering. With no layer the outlet returns the owner content directly. `HocContentBoundary` wraps each layer's inner content and rethrows its errors as `HocContentError`, which layer boundaries pass through and `HocOutletBoundary` unwraps to the original error. The Entry chain passes `children` to the registered Component as JSX children; non-hoc entries receive `undefined`. `SlotErrorBoundary` takes a `crashed` replacement node, which a layer's boundary keeps rendering for the rest of its mount; layer crash reports pass `abdicate: false` |
| `ui-renderer` | `HocOutlet` takes its render function from `hocChainFor`, a cache per host, live declaration, and dispatch key that every outlet dispatching the same key shares. Once per ledger version it reselects the key's layers with `hocLayersFor` (wildcard winners plus exact-key winners, an exact-key layer replacing the wildcard layer with its id, sorted by `order`) and calls `composeHocLayers` to nest them into one render function only when that ordered list changes by entry identity. Each layer is one Component that fixes its scope-specific Entry (`StrictSessionEntry` / `SessionMaybeEntry` / `RootEntry`), entry, slot inject, and crash reporting at composition, and receives only `owner` and the next inner layer when rendering. With no layer the outlet returns the owner content directly. `HocContentBoundary` wraps each layer's inner content and rethrows its errors as `HocContentError`, which layer boundaries pass through and `HocOutletBoundary` unwraps to the original error. The Entry chain passes `children` to the registered Component as JSX children; non-hoc entries receive `undefined`. `SlotErrorBoundary` takes a `crashed` replacement node, which a layer's boundary keeps rendering for the rest of its mount; layer crash reports pass `abdicate: false` |
| `scripts/gen-client-catalog.ts` | Register options, a `children`-rendering example, and the `wraps-owner-content` replace risk for hoc slots |
### First consumer
@@ -66,9 +66,9 @@ Add a fifth kind: `hoc`.
- Adding or removing a layer remounts everything inside it, including the composer on the home.
- Every non-hoc registered Component receives `children: undefined`, which overrides any owner prop of that name.
- Each layer adds one Component and two error boundaries to the tree; each hoc slot with layers adds one outlet boundary.
- The renderer marks the slot and [where each layer renders `children`](../../../../docs/subsystems/slots.md#hoc-layers), not the layer's own markup. Plugins need no wrapper of their own, but structural selectors must account for those DOM elements.
- The outlet's `[data-slot]` element sits between the owner and its content, so owner selectors cannot assume the content is a direct child.
- React 18 recollects the component stack where an error is rethrown, so a content error reaching boundaries above a hoc slot with layers carries a component stack that starts at `HocOutletBoundary`.
- A layer that wraps its `children` in its own error boundary catches the internal `HocContentError` rather than the original content error.
- The frame contract holds only on the home: other phases leave the Conversation root out of the stacking order, so unportaled Conversation popovers still rise above AppFrame chrome that floats over the column, while on the home they stack only within the root.
- `HocOutlet` keeps its layer Components in a shared compile cache, not in outlet-instance state, so they do not depend on React retaining memoized values; these Components are the remount boundary of the content inside them. Different slot names use separate chains even when they share a spec object.
- `HocOutlet` keeps its layer Components in a compile cache shared per host, live declaration, and dispatch key, not in outlet-instance state, so they do not depend on React retaining memoized values; these Components are the remount boundary of the content inside them, and a redeclared slot starts with an empty cache.
- [The slot system standard](2026-07-22-slot-type-chain-implementation.md) remains authoritative for the other kinds; this note adds the fifth.
@@ -42,7 +42,7 @@ Status: implemented
| 包 | 实现 |
|---|---|
| `ui-slots` | `SlotKind` 包含 `'hoc'`;`HocRenderOpts`(可选 `children` 与 `entryKey`)、`HocKeysOf`、`HocShare`;`RenderSlotFn` 为 hoc key 提供接受可选 `{ children, entryKey }` 的重载;`KindOptions` 的 hoc 分支含可选 `key`;`SlotCore.register` / `entriesOfSlot` 按 `(key 或通配, id)` 划分 hoc cell |
| `ui-renderer` | `HocOutlet` 从 `hocChainFor` 取渲染函数,后者按 host、spec 对象、slot 名和 `entryKey` 缓存层链,同一组合的 outlet 实例共享一条层链。每个 ledger 版本它只用 `hocLayersFor` 重新选出一次该 key 的层(通配胜者加精确 key 胜者,精确 key 的层替换同 id 的通配层,按 `order` 排序),仅当这一有序列表按 entry 身份比较发生变化时才调用 `composeHocLayers` 把各层组合成一个嵌套渲染函数。每层是一个组件,在组合时固定按 scope 选定的 Entry(`StrictSessionEntry` / `SessionMaybeEntry` / `RootEntry`)、entry、slot inject 与崩溃上报,渲染时只接收 `owner` 与内一层。没有层时 outlet 直接返回宿主内容。`HocContentBoundary` 包住每层的内层内容,把其中的错误包装为 `HocContentError` 重新抛出;层的边界放行这种错误,`HocOutletBoundary` 再解开为原始错误。Entry 链以 JSX children 把 `children` 交给注册组件;非 hoc entry 收到 `undefined`。`SlotErrorBoundary` 接受 `crashed` 替换节点,层的边界在本次挂载内一直渲染该节点;层的崩溃上报传 `abdicate: false` |
| `ui-renderer` | `HocOutlet` 从 `hocChainFor` 取渲染函数,该缓存按 host、存活声明与分派 key 划分,分派同一 key 的所有 outlet 共享。每个 ledger 版本它只用 `hocLayersFor` 重新选出一次该 key 的层(通配胜者加精确 key 胜者,精确 key 的层替换同 id 的通配层,按 `order` 排序),仅当这一有序列表按 entry 身份比较发生变化时才调用 `composeHocLayers` 把各层组合成一个嵌套渲染函数。每层是一个组件,在组合时固定按 scope 选定的 Entry(`StrictSessionEntry` / `SessionMaybeEntry` / `RootEntry`)、entry、slot inject 与崩溃上报,渲染时只接收 `owner` 与内一层。没有层时 outlet 直接返回宿主内容。`HocContentBoundary` 包住每层的内层内容,把其中的错误包装为 `HocContentError` 重新抛出;层的边界放行这种错误,`HocOutletBoundary` 再解开为原始错误。Entry 链以 JSX children 把 `children` 交给注册组件;非 hoc entry 收到 `undefined`。`SlotErrorBoundary` 接受 `crashed` 替换节点,层的边界在本次挂载内一直渲染该节点;层的崩溃上报传 `abdicate: false` |
| `scripts/gen-client-catalog.ts` | hoc 插槽的注册选项、渲染 `children` 的示例,以及 `wraps-owner-content` 替换风险 |
### 首个使用者
@@ -66,9 +66,9 @@ Status: implemented
- 增减一层会让其内部所有内容重新挂载,包括首页的输入框。
- 所有非 hoc 的注册组件都会收到 `children: undefined`,会覆盖同名的 owner prop。
- 每层在组件树中多一个组件和两个 error boundary;有层的 hoc 插槽另多一个 outlet 边界。
- 渲染器标记的是 slot 和[各层渲染 `children` 的位置](../../../../docs/subsystems/slots.zh.md#hoc-layers),而不是层组件自己的元素。插件不必添加自己的包装元素,但结构选择器必须考虑这些 DOM 元素。
- outlet 的 `[data-slot]` 元素位于 owner 与内容之间,owner 侧选择器不能假定内容是直接子元素。
- React 18 会在错误被重新抛出的位置重新采集组件栈,因此有层的 hoc 插槽之上的边界收到的内容错误,组件栈从 `HocOutletBoundary` 开始。
- 层如果自己在 `children` 外包错误边界,捕获到的是内部的 `HocContentError`,而不是原始的内容错误。
- frame 契约只在首页阶段成立:其他阶段根元素不参与层叠隔离,未经 portal 的 Conversation 浮层仍能盖住悬浮在中栏上方的 AppFrame 元素;首页阶段它们只在根元素内部比较层级。
- `HocOutlet` 把层组件保存在共享的编译缓存中,而不是 outlet 实例状态里,因此不依赖 React 保留 memo 缓存;这些组件是其内部内容的重新挂载边界。不同名称的 slot 即使复用同一个 spec 对象,也不共享层链。
- `HocOutlet` 把层组件保存在按 host、存活声明与分派 key 共享的编译缓存中,而不是 outlet 实例状态里,因此不依赖 React 保留 memo 缓存;这些组件是其内部内容的重新挂载边界,重新声明的插槽从空缓存开始。
- 其他 kind 仍以 [slot 体系标准](2026-07-22-slot-type-chain-implementation.zh.md) 为准;本 Note 新增第五种。
@@ -9,8 +9,8 @@
en: 6938aa715106bb99
zh: ea1497b337712f33
/agent-note-session-workspace-root/decision:
en: 8b86ea995b0f8044
zh: edf88155c8499940
en: 0b07db6326c2ecd6
zh: 19ba9a1adf93af1f
/agent-note-session-workspace-root/alternatives-considered:
en: 8a4859a6f96ef49e
zh: fa7088d29ebe3dd6
@@ -18,7 +18,7 @@ Worktree creation enters the checkout through `set`. The model has one tool for
Every consumer reads that directory. The model's file, search, and process tools resolve relative paths from it, and everything the user sees or that describes the project is bounded by it: the sandbox `workspace-write` boundary, the workspace file service and desktop file drag, the change recorder, the Files tree, deliverables, open-in-app actions and Session rows, new sidebar terminals, `@` file candidates, the skill catalog, project-instruction discovery, and the LSP workspace.
The sandbox policy reads no Git layout: it bounds a Session by its directory and adds only the directories the deployment configured or a Host plugin registered for that Session through `registerWritableRoot`. A repository's Git directory lies outside a linked worktree, so after a move into a worktree a Git command that writes it, such as `git commit`, is denied under `workspace-write` until a grant covers that directory; the original project is not writable either. The [linked-worktree grant](2026-11-18-linked-worktree-git-directory-grant.md), a plugin the worktree service mounts, reads the Git layout and registers that directory for the Session. Host maintenance of a checkout the Session does not work in keeps the original boundary: removing a worktree on archive, restoring a removed one, and reading its branch in the source repository run under a policy the worktree service and the forge panel build themselves, the Session's mode and grants with the recorded source checkout as the root. The Session's own root may be the removed directory, and a process sandbox cannot bind a missing or vanishing root.
The sandbox policy reads no Git layout: it bounds a Session by its directory and adds only the directories the deployment configured or a Host plugin registered for that Session through `registerWritableRoot`. A repository's Git directory lies outside a linked worktree, so after a move into a worktree a Git command that writes it, such as `git commit`, is denied under `workspace-write` until a grant covers that directory; the original project is not writable either. Granting the Git directory of the checkout a Session works in belongs to a separate plugin that reads the Git layout and registers the directory, which this decision defers. Host maintenance of a checkout the Session does not work in keeps the original boundary: removing a worktree on archive, restoring a removed one, and reading its branch in the source repository run under a policy the worktree service and the forge panel build themselves, the Session's mode and grants with the recorded source checkout as the root. The Session's own root may be the removed directory, and a process sandbox cannot bind a missing or vanishing root.
## Alternatives considered
@@ -18,7 +18,7 @@ Status: implemented
每个消费方都读取这个目录。模型的文件、搜索与进程工具从它解析相对路径,用户看到的、以及描述项目的一切都以它为界:沙箱 `workspace-write` 边界、工作区文件服务与桌面文件拖拽、变更记录器、文件树、交付物、在应用中打开操作与 Session 行、新开的侧栏终端、`@` 文件候选、技能目录、项目指令发现和 LSP 工作区。
沙箱策略不读取任何 Git 布局:它以 Session 的目录为界,只加入部署配置的目录,以及 Host 插件通过 `registerWritableRoot` 为该 Session 注册的目录。仓库的 Git 目录位于链接工作树之外,因此移入工作树之后,写入它的 Git 命令(例如 `git commit`)在 `workspace-write` 下会被拒绝,直到有授权覆盖该目录;原始项目也不再可写。[链接工作树授权](2026-11-18-linked-worktree-git-directory-grant.zh.md)是 worktree 服务挂载的插件,它读取 Git 布局并为该 Session 注册该目录。Host 对 Session 并不在其中工作的检出目录做维护时保留原来的边界:归档时移除 worktree、恢复被删除的 worktree、在源仓库中读取其分支,都在 worktree 服务与 forge 面板自己构造的策略下运行,即沿用 Session 的模式与授权、以记录中的源检出目录为根。Session 自身的根可能正是被删除的目录,而进程沙箱无法绑定缺失或正在消失的根。
沙箱策略不读取任何 Git 布局:它以 Session 的目录为界,只加入部署配置的目录,以及 Host 插件通过 `registerWritableRoot` 为该 Session 注册的目录。仓库的 Git 目录位于链接工作树之外,因此移入工作树之后,写入它的 Git 命令(例如 `git commit`)在 `workspace-write` 下会被拒绝,直到有授权覆盖该目录;原始项目也不再可写。为 Session 所在检出目录授权其 Git 目录,属于一个读取 Git 布局并注册该目录的独立插件,本决策将其延后。Host 对 Session 并不在其中工作的检出目录做维护时保留原来的边界:归档时移除 worktree、恢复被删除的 worktree、在源仓库中读取其分支,都在 worktree 服务与 forge 面板自己构造的策略下运行,即沿用 Session 的模式与授权、以记录中的源检出目录为根。Session 自身的根可能正是被删除的目录,而进程沙箱无法绑定缺失或正在消失的根。
## Alternatives considered
@@ -1,40 +0,0 @@
# Bilingual-pair consistency record for 2026-11-04-environment.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-11-04-environment.md
/agent-note-execution-environment-tool-i-o-and-the-original-resident-daemon-decision:
en: 223bd669d9a0ab1d
zh: 3f16c86f50e9c700
/agent-note-execution-environment-tool-i-o-and-the-original-resident-daemon-decision/problem:
en: b8fc840646b8a2a6
zh: 513184d1e6c7f51b
/agent-note-execution-environment-tool-i-o-and-the-original-resident-daemon-decision/decision:
en: a78a0620497d6da2
zh: 9d272080b5696a88
/agent-note-execution-environment-tool-i-o-and-the-original-resident-daemon-decision/decision/registry-changes-carry-no-payload:
en: 32eb641a81d930db
zh: 3e47554eb0430723
/agent-note-execution-environment-tool-i-o-and-the-original-resident-daemon-decision/decision/a-definition-binds-everything-except-the-environment-and-the-arguments:
en: 2dc6db37ac287e8a
zh: 034d16fe4a1d7a60
/agent-note-execution-environment-tool-i-o-and-the-original-resident-daemon-decision/decision/each-run-occupies-a-worker-thread:
en: 566a0ba1e325eb39
zh: da0afd7a70b35f7b
/agent-note-execution-environment-tool-i-o-and-the-original-resident-daemon-decision/decision/transports-are-plugins:
en: 1cb952499260c764
zh: f116c28ad45311ff
/agent-note-execution-environment-tool-i-o-and-the-original-resident-daemon-decision/decision/trust-comes-from-the-transport-and-the-handshake-leaves-room-for-more:
en: 6389ffc937259ab5
zh: 94743bbe851d6887
/agent-note-execution-environment-tool-i-o-and-the-original-resident-daemon-decision/decision/values-cross-as-structured-clones-in-split-frames:
en: d5cea86d0b2e51d7
zh: 0307f7cc71a50220
/agent-note-execution-environment-tool-i-o-and-the-original-resident-daemon-decision/decision/shared-peer-code:
en: 54e22a1638a5ba4a
zh: 5cdc4c90ee73236c
/agent-note-execution-environment-tool-i-o-and-the-original-resident-daemon-decision/alternatives-considered:
en: b259b018bbb27f6a
zh: a65ed379787076d9
/agent-note-execution-environment-tool-i-o-and-the-original-resident-daemon-decision/consequences:
en: 68ce6b1a5f813f9a
zh: 1fd798c8241448c4
Loaded 100 of 6154 files, more files were not shown because too many files have changed in this diff. Show more