Merge remote-tracking branch 'origin/master' into feat/hmr-watch-patch-overlays
This commit is contained in:
commit
245f37b9ef
2160 files changed
+78497
-15214
No files matched your search
+2
-2
@@ -36,5 +36,5 @@
|
||||
en: 31ba63101fca5790
|
||||
zh: af4ceefab2033142
|
||||
/agent-note-prompt-variables-and-tool-guidance-ownership/consequences:
|
||||
en: 94c38eb61a2dcd4a
|
||||
zh: 8a047857b6d3a4a3
|
||||
en: c8df49ae0580af19
|
||||
zh: 0ecd9a95c44fa7cb
|
||||
+1
-1
@@ -68,4 +68,4 @@ Per-tool semantics and selection guidance live in tool descriptions. Prompt sect
|
||||
- `{{model}}` reflects `AgentOptions.model` at assembly time. A plugin that switches models in the `agent/request` waterfall makes the prompt's claim stale for that step, and one that SUPPLIES the model there (options.model unset — the loop's documented fallback) leaves the variable valueless at render, failing a `{{model}}` persona before the waterfall runs. Both have the same remedy, and it is the ownership rule itself: the plugin that owns the late-bound model fact states it early on the `system-prompt/assemble` waterfall (`assembly.variables['model'] = …`) — one owner, both statements; a loop test pins the supply path end-to-end. Accepted.
|
||||
- While a bound provider is absent (not yet activated, unloaded, mid-HMR-reload), the subagent tool does not exist and a model request in that window simply lacks it. That is the honest state — the alternative was a registered tool whose description or execution could not be trusted.
|
||||
- Strict interpolation rejects missing or valueless variables before a model request. The turn ends with `error` while the loop remains available for later turns; a persona referencing `{{model}}` requires its composing runtime to supply that value.
|
||||
- Inline escapes remain unsupported in interpolated text; literal sections need no escaping. PTC unit tests cover both modes and runtime languages, and the recorded `ptc-turn` scenario preserves tool-template examples in the model-visible prompt.
|
||||
- Inline escapes remain unsupported in interpolated text; literal sections need no escaping. Unit tests cover native presentation and literal TypeScript SDK sections, and the recorded `ptc-turn` scenario preserves tool-template examples in the model-visible prompt.
|
||||
+1
-1
@@ -68,4 +68,4 @@ Status: implemented
|
||||
- `{{model}}` 在组装时反映 `AgentOptions.model`。如果一个插件在 `agent/request` waterfall 中切换模型,提示词对该步骤的声明就会过时;如果一个插件在那里提供模型(options.model 未设置——循环文档中记载的回退路径),变量在渲染时无值,包含 `{{model}}` 的 persona 会在 waterfall 运行前失败。两者的补救方式相同,就是归属规则本身:拥有延迟绑定模型事实的插件在 `system-prompt/assemble` waterfall 上提前声明它(`assembly.variables['model'] = …`)——一个归属方,两处声明;一个循环测试端到端固定了 supply 路径。已接受。
|
||||
- 当一个已绑定的提供方不存在时(尚未激活、已卸载、HMR(热模块替换)重载中),subagent 工具不存在,该窗口内的模型请求中不会包含它。这是诚实的状态——替代方案是注册一个 description 或执行都不可信的工具。
|
||||
- 严格插值在模型请求之前拒绝缺失或无值的变量。该轮次以 `error` 结束,循环仍可服务后续轮次;引用 `{{model}}` 的 persona 要求组合它的运行时提供该值。
|
||||
- 插值文本仍不支持行内转义;字面文本段无需转义。PTC 单元测试覆盖两种模式和运行时语言,录制的 `ptc-turn` 场景在模型可见的提示词中保留工具模板示例。
|
||||
- 插值文本仍不支持行内转义;字面文本段无需转义。单元测试覆盖 native 呈现与字面 TypeScript SDK 段,录制的 `ptc-turn` 场景在模型可见的提示词中保留工具模板示例。
|
||||
+2
-2
@@ -15,8 +15,8 @@
|
||||
en: 0e1399cad4151f87
|
||||
zh: 960fa0ccbe0f8fea
|
||||
/agent-note-cooperative-tool-cancellation-at-the-registry-boundary/decision/cancellation-codes-record-whether-dispatch-occurred:
|
||||
en: 86c5566581c1d3d6
|
||||
zh: 3cb71fbb97bdb291
|
||||
en: 4d8436958c27f98e
|
||||
zh: cd4ed8238428a2c4
|
||||
/agent-note-cooperative-tool-cancellation-at-the-registry-boundary/decision/pre-aborted-entry-short-circuits-after-materialization:
|
||||
en: 53362db6a0c71698
|
||||
zh: 311de45ca26d3fdc
|
||||
|
||||
@@ -32,7 +32,7 @@ An around-dispatch wrapper may replace `exec.signal` for its delegated lifetime
|
||||
|
||||
`ABORTED_BEFORE_DISPATCH` carries `{ name: 'AbortError' }` and model text `Error: tool call aborted before dispatch`. It applies whenever cancellation prevents body invocation, including pre-aborted entry, cancellation during pre-policy or approval, an aborted wrapper signal, a wrapper success overtaken by caller cancellation before delegation, and agent-loop siblings skipped after turn cancellation.
|
||||
|
||||
`ABORTED` carries model text `Error: tool call aborted` and applies only after the body was invoked, including cancellation while an around wrapper or post-policy listener waits after body completion. A started body that throws the signal's reason or an `Error` named `AbortError` without `HarnessError` identity keeps that message and carries `{ name: 'AbortError', code: 'ABORTED' }`. A denial, wrapper failure, other tool failure, or post-policy failure remains more specific than generic cancellation. A timeout owned by timeout-policy remains `TOOL_TIMEOUT`, and contexts deferred before a successful outcome is replaced remain attached.
|
||||
`ABORTED` carries model text `Error: tool call aborted` and applies only after the body was invoked, including cancellation while an around wrapper or post-policy listener waits after body completion. A started body that throws the signal's reason or an `Error` named `AbortError` without `HarnessError` identity keeps that message and carries `{ name: 'AbortError', code: 'ABORTED' }`. A `tools/execute` wrapper that throws such a value after caller cancellation is classified the same way, with `ABORTED_BEFORE_DISPATCH` when the body never started. A denial, other wrapper failure, other tool failure, or post-policy failure remains more specific than generic cancellation. A timeout owned by timeout-policy remains `TOOL_TIMEOUT`, and contexts deferred before a successful outcome is replaced remain attached.
|
||||
|
||||
### Pre-aborted entry short-circuits after materialization
|
||||
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@ Status: implemented
|
||||
|
||||
`ABORTED_BEFORE_DISPATCH` 携带 `{ name: 'AbortError' }` 和模型可见文本 `Error: tool call aborted before dispatch`。凡取消阻止工具主体调用时都使用该结果,包括进入时已中止、前置策略或审批期间取消、包装层信号已中止、包装层在委托前返回的成功结果被调用方取消抢先,以及轮次取消后 agent loop(智能体循环)跳过的同批调用。
|
||||
|
||||
`ABORTED` 携带模型可见文本 `Error: tool call aborted`,并且只在工具主体已经调用后使用,包括工具主体完成后环绕包装层或后置策略监听器等待期间发生的取消。已开始的工具主体抛出 signal 的 reason,或不具备 `HarnessError` 身份、name 为 `AbortError` 的 `Error` 时,结果保留该 message,并携带 `{ name: 'AbortError', code: 'ABORTED' }`。拒绝、包装层失败、其他工具失败或后置策略失败比通用取消更具体。timeout-policy 自身拥有的超时仍为 `TOOL_TIMEOUT`,成功结果被取消替换前延后附加的上下文仍会保留。
|
||||
`ABORTED` 携带模型可见文本 `Error: tool call aborted`,并且只在工具主体已经调用后使用,包括工具主体完成后环绕包装层或后置策略监听器等待期间发生的取消。已开始的工具主体抛出 signal 的 reason,或不具备 `HarnessError` 身份、name 为 `AbortError` 的 `Error` 时,结果保留该 message,并携带 `{ name: 'AbortError', code: 'ABORTED' }`。`tools/execute` 包装层在调用方取消后抛出这类值时按同样方式归类,工具主体尚未开始时为 `ABORTED_BEFORE_DISPATCH`。拒绝、其他包装层失败、其他工具失败或后置策略失败比通用取消更具体。timeout-policy 自身拥有的超时仍为 `TOOL_TIMEOUT`,成功结果被取消替换前延后附加的上下文仍会保留。
|
||||
|
||||
### 进入时已中止会在物化后短路
|
||||
|
||||
|
||||
+8
-8
@@ -15,20 +15,20 @@
|
||||
en: 6af228b03e5e533f
|
||||
zh: 276a522af6be5d7a
|
||||
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/one-module-system-one-plugin-governor:
|
||||
en: 575aad62490f32e9
|
||||
zh: a6c18eb63965fc1e
|
||||
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: 0a4240d88cca240a
|
||||
zh: 8f5f1527caf571cd
|
||||
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/the-loading-flow-end-to-end:
|
||||
en: dd05aa1ee608c414
|
||||
zh: 2863ced0086e3122
|
||||
en: 1f7db6ecfc0b0831
|
||||
zh: f6bf37dc921a7d40
|
||||
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/live-graph-reconciliation:
|
||||
en: 37e2fa1fe5cb2b95
|
||||
zh: 80e513db87709cb4
|
||||
en: ab9577214d7b2f2b
|
||||
zh: fc8f10fd8c90b34b
|
||||
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/hot-reload-one-driver-plugin-self-watched-bundles:
|
||||
en: c1fdcb3e6f074a7a
|
||||
zh: b08c7b1ff25acb09
|
||||
en: e6a0bee3d31cd2c6
|
||||
zh: 7f7384c5d1a74751
|
||||
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/package-ownership:
|
||||
en: 94ca0d09e6fd1e3a
|
||||
zh: d5949a2bdec795ba
|
||||
|
||||
@@ -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. Every module body side effect, CSS injection included, lives inside the factory closure and runs 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 — owned `<style data-plugin>` tag ids, 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`.
|
||||
|
||||
@@ -70,9 +70,11 @@ Why is the roster yml rows and not a scan? Because which plugins compose into a
|
||||
4. `settled` = every entry created + `loader.await()` quiescent + the boot audit. The audit lists each import-failed, FAILED, or PENDING fiber with its activation error or missing services. It exists because cordis inject waits have no timeout. An inactive entry on the browser required list rejects startup; other inactive entries produce one console warning ([startup policy](2026-09-09-consumer-owned-startup-strictness.md)).
|
||||
5. The framework-free loading page projects real fiber states via `internal/status`. After the audit accepts the tree, the kernel calls `ctx.uiRenderer.mount(container)` and replaces the page with the real UI in one pass.
|
||||
|
||||
Stylesheet metadata and renderer ownership follow the [module metadata decision](2026-11-05-client-module-metadata.md); module loading retains the producer without evaluating it.
|
||||
|
||||
### Live graph reconciliation
|
||||
|
||||
The modules controller owns exactly the Loader entries created from the boot manifest. Full Host snapshots update its module descriptors and reconcile those entries; other Loader contributors retain ownership. New modules arrive through single-resource URLs because replaying a startup batch could register an existing factory twice. Removal uses Loader deletion, then drains the captured fiber before removing unused modules and styles. Declared and observed transitive requests keep shared modules alive. Factory revision tracking is independent of entry activation because a download or materialization can finish without creating an entry. Graph updates invalidate stale factories and failed arrival targets without managed entries, clearing their styles before any consumer imports its dependencies; rebuilt frames also reconcile entries missing after import failures.
|
||||
The modules controller owns exactly the Loader entries created from the boot manifest. Full Host snapshots update its module descriptors and reconcile those entries; other Loader contributors retain ownership. New modules arrive through single-resource URLs because replaying a startup batch could register an existing factory twice. Removal uses Loader deletion, then drains the captured fiber before removing unused module records. Declared and observed transitive requests keep shared modules alive. Factory revision tracking is independent of entry activation because a download or materialization can finish without creating an entry. Graph updates invalidate stale factories and failed arrival targets without managed entries, notifying resource consumers before any consumer imports its dependencies; rebuilt frames also reconcile entries missing after import failures.
|
||||
|
||||
The Host SSE adapter forwards existing graph-change notifications and sends the current full graph on connection. The graph describes desired browser entries, not Host cleanup completion: Host lifecycle ordering belongs to its Loader, while each browser waits for its own removed fibers. Graph reconciliation and rebuilt code share one page-owned queue. Local generations prevent stale downloads from mounting; opaque revisions are compared only for equality. The settings inventory reports page-local errors and can retry the same graph without changing Host enablement. This preserves unrelated page state and avoids both an application restart and a second plugin executor. Electron's independent installation flow remains outside this mechanism.
|
||||
|
||||
@@ -88,8 +90,8 @@ On the browser side, the transport delegates code replacement to the same module
|
||||
2. `prefetch` — load that one-resource external script and register the fresh factory while the old fiber still serves. The initial multi-resource script never executes again.
|
||||
3. `registry.delete` — before touching the fiber. A bare fiber dispose trips the vendored Loader's self-dispose branch, which would disable the entry permanently.
|
||||
4. Drain the old fiber's disposers.
|
||||
5. Remove owned `<style data-plugin>` tags.
|
||||
6. Materialize the new exports through the module system, then call `entry.refresh()` to mount them through Loader. CSS re-injects after the old disposers drain; explicit materialization exposes the import error before Loader can reduce it to a console log.
|
||||
5. Renderer observes module invalidation and removes obsolete stylesheet resources.
|
||||
6. Materialize the new exports through the module system, then call `entry.refresh()` to mount them through Loader. Renderer installs metadata-provided styles after successful materialization; explicit materialization exposes the import error before Loader can reduce it to a console log.
|
||||
7. `fiber.await()` — rethrows loud.
|
||||
|
||||
Bootstrap replacement is rejected before invalidation or teardown: the module system retains its initial exports, so remounting its old code would reset consumers without applying the requested revision. The page reports the required reload and preserves the bootstrap fiber. Every non-bootstrap plugin shares the replacement semantics; an `immediately` row reloads exactly like a lazy one. Dependency cascade costs zero client code: a fiber's activation epoch strings its service providers' uids, so replacing a foundational provider such as connection re-loads every dependent through cordis itself — correct, if heavy.
|
||||
|
||||
@@ -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 还会提供其生成文件名——此外什么都不发生。模块体的一切副作用(包括 CSS 注入)都住在 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 直接写入记忆化表。最后这一抛是构建期纯度门禁在运行时的镜像。系统还保管逐模块簿记——名下 `<style data-plugin>` 标签 id、观测到的 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`。
|
||||
|
||||
@@ -70,9 +70,11 @@ Host 会快照每个已构建插件入口 bundle,并把每个调度阶段的
|
||||
4. `settled` = 每个 entry 已创建 + `loader.await()` 完全停稳 + 启动审计。审计列出每个 import 失败、FAILED 或 PENDING 的 fiber 及其激活错误或缺失的服务。它存在的理由:cordis 的 inject 等待没有超时。浏览器必需名单中的 entry 未激活会拒绝启动;其他未激活 entry 输出一条控制台警告([启动策略](2026-09-09-consumer-owned-startup-strictness.zh.md))。
|
||||
5. 不依赖框架的 loading 页经 `internal/status` 投影真实 fiber 状态。审计接受插件树后,内核调用 `ctx.uiRenderer.mount(container)`,一次切换到真实 UI。
|
||||
|
||||
样式元信息及 renderer 所有权遵循[模块元信息决定](2026-11-05-client-module-metadata.zh.md);模块加载保存生产函数而不求值。
|
||||
|
||||
### 动态图对账
|
||||
|
||||
modules 控制器只持有从启动清单创建的 Loader 条目。Host 的完整快照更新模块描述并对账这些条目;其他 Loader 贡献方保留自身所有权。新增模块通过单资源 URL 到达,因为重放启动 batch 可能重复注册现有 factory。移除使用 Loader 删除语义,随后等待已捕获 fiber 清理完毕,再移除未使用的模块与样式。已声明及已观察到的传递依赖使共享模块保持存活。Factory revision 的跟踪独立于条目激活,因为下载或物化完成后仍可能没有创建条目。图更新会在任何消费者导入依赖前,使未归属受管条目的陈旧 factory 和失败的到达目标失效,并清除其样式;重建帧也会对账因导入失败而缺失的条目。
|
||||
modules 控制器只持有从启动清单创建的 Loader 条目。Host 的完整快照更新模块描述并对账这些条目;其他 Loader 贡献方保留自身所有权。新增模块通过单资源 URL 到达,因为重放启动 batch 可能重复注册现有 factory。移除使用 Loader 删除语义,随后等待已捕获 fiber 清理完毕,再移除未使用的模块记录。已声明及已观察到的传递依赖使共享模块保持存活。Factory revision 的跟踪独立于条目激活,因为下载或物化完成后仍可能没有创建条目。图更新会在任何消费者导入依赖前,使未归属受管条目的陈旧 factory 和失败的到达目标失效,并通知资源消费者;重建帧也会对账因导入失败而缺失的条目。
|
||||
|
||||
Host SSE 适配器转发现有图变化通知,并在连接时发送当前完整图。图描述浏览器的目标条目,不代表 Host 清理完成:Host 生命周期顺序属于其 Loader,每个浏览器则等待自身被移除 fiber 的清理。图对账与代码重建共用一个页面队列。本地代际阻止过期下载挂载;不透明 revision 只比较相等。失败页面报告本地错误,并可重试同一张图而不改变 Host 启用状态。这保留了无关页面状态,也无需重启应用或引入第二套插件执行器。Electron 的独立安装流程不属于此机制。
|
||||
|
||||
@@ -88,8 +90,8 @@ Host SSE 适配器转发现有图变化通知,并在连接时发送当前完
|
||||
2. `prefetch`——加载该单资源外部脚本并登记新 factory,旧 fiber 此刻仍在服役。初始多资源脚本不会再次执行。
|
||||
3. `registry.delete`——先于任何 fiber 操作。裸做 fiber dispose 会触发 vendored Loader 的自 dispose 分支,把 entry 永久停用。
|
||||
4. 排空旧 fiber 的各 disposer。
|
||||
5. 移除名下的 `<style data-plugin>` 标签。
|
||||
6. 通过模块系统物化新导出,再调用 `entry.refresh()` 由 Loader 挂载。CSS 在旧 disposer 清理完成后重新注入;显式物化使导入错误能够被捕获,而不只留下 Loader 的控制台日志。
|
||||
5. Renderer 观察模块失效并移除过期样式资源。
|
||||
6. 通过模块系统物化新导出,再调用 `entry.refresh()` 由 Loader 挂载。成功物化后 Renderer 安装元信息提供的样式;显式物化使导入错误能够被捕获,而不只留下 Loader 的控制台日志。
|
||||
7. `fiber.await()`——让失败大声重抛。
|
||||
|
||||
Bootstrap 替换会在失效或卸载前被拒绝:模块系统保留其初始导出,重新挂载旧代码会重置消费者,却无法应用请求的 revision。页面会报告需要刷新,并保留 bootstrap fiber。所有非 bootstrap 插件都共享同一套替换语义;`immediately` 行的重载与 lazy 行分毫不差。依赖级联不花一行 client 代码:fiber 的激活纪元串接着它各服务提供方的 uid,因此替换 connection 等基础 provider 的 fiber 时,每个依赖方都会经 cordis 本身重新装载——行为正确,但代价较高。
|
||||
|
||||
+2
-2
@@ -9,8 +9,8 @@
|
||||
en: fa4d3622fb18dd58
|
||||
zh: 2b98640594c8344b
|
||||
/agent-note-one-harness-home-resolver/decision:
|
||||
en: 816e5109718bc4ae
|
||||
zh: af3f08f07c3cb761
|
||||
en: a9d9f7bf051341e9
|
||||
zh: cc1fed8d2b606276
|
||||
/agent-note-one-harness-home-resolver/alternatives-considered:
|
||||
en: b1c9535540171d47
|
||||
zh: 7df816d42945db94
|
||||
|
||||
@@ -21,9 +21,9 @@ One resolver owns the harness home, in `@deepseek-ai/dsh-home-paths`, single-roo
|
||||
explicit configured path > $DSH_HOME > ~/.dsh
|
||||
```
|
||||
|
||||
An empty or whitespace-only `$DSH_HOME` is treated as unset; otherwise `resolve('')` would silently place the home at the current working directory. The harness keeps all user data under one root; there is no XDG config/data/cache split. `dshHomePath(...segments)` joins deployment-owned children onto that root, and `dsh-app-boot` exposes it to Loader `!!js` config expressions before mounting entries, so shipped compositions derive `sessions` and `storages` without copying the resolver. `dshHomeDisplay()` names a resolved root symbolically for user-facing paths — `~/.dsh` for the default home, `$DSH_HOME` for any configured home — so the user-global `AGENTS.md` label never leaks an absolute machine path. It replaces agent-instructions's bespoke default-vs-`$DSH_HOME` check. Home is process policy rather than row configuration: `dsh-agent-instructions` accepts no home override, so a composition cannot point instruction loading at a root that sessions, skills, and storage would not read. `resolveAgentsHome()` and `agentsHomeDisplay()` apply the same precedence, tilde expansion, and symbolic labelling to the shared agent configuration root (`$DSH_AGENTS_HOME` or `~/.agents`), which stays outside the harness home because other agent tools share it ([shared agents root](2026-10-05-shared-agents-root-instructions.md)); `dsh-skill-filesystem` still accepts its own `dshHome` and `agentsHome` fields, which select its own skill roots and resolve through the shared resolver in the instruction-loading change.
|
||||
An empty or whitespace-only `$DSH_HOME` is treated as unset; otherwise `resolve('')` would silently place the home at the current working directory. The harness keeps all user data under one root; there is no split into separate XDG roots. `dshHomePath(...segments)` joins deployment-owned children onto that root, and `dsh-app-boot` exposes it to Loader `!!js` config expressions before mounting entries, so shipped compositions derive `sessions` and `storages` without copying the resolver. `dshHomeDisplay()` names a resolved root symbolically for user-facing paths — `~/.dsh` for the default home, `$DSH_HOME` for any configured home — so the user-global `AGENTS.md` label never leaks an absolute machine path. It replaces agent-instructions's bespoke default-vs-`$DSH_HOME` check. Home is process policy rather than row configuration: `dsh-agent-instructions` accepts no home override, so a composition cannot point instruction loading at a root that sessions, skills, and storage would not read. `resolveAgentsHome()` and `agentsHomeDisplay()` apply the same precedence, tilde expansion, and symbolic labelling to the shared agent configuration root (`$DSH_AGENTS_HOME` or `~/.agents`), which stays outside the harness home because other agent tools share it ([shared agents root](2026-10-05-shared-agents-root-instructions.md)); `dsh-skill-filesystem` still accepts its own `dshHome` and `agentsHome` fields, which select its own skill roots and resolve through the shared resolver in the instruction-loading change.
|
||||
|
||||
`dshCachePath(...segments)` derives paths below the resolved home's `cache` directory. An initial `{ dshHome }` option preserves a provider's explicit home override. It resolves paths without creating directories; callers own directory creation. `attachment-local` uses this helper for regenerable request-image variants while retaining durable attachment objects in their versioned storage tree, so clearing the cache cannot remove Session attachments. Existing request-image cache entries are left in place and are not read or copied; a cache miss regenerates the variant from its durable attachment.
|
||||
`dshPath(category, ...segments)` derives paths below a `config`, `data`, `state`, `cache`, or `backup` directory of that one root, and app-boot exposes it to Loader `!!js` expressions beside `dshHomePath`; the [home path categories proposal](../../proposed/architecture/2026-11-04-dsh-home-path-categories.md) owns the categories and which existing entries keep their top-level locations. `dshCachePath(...segments)` is `dshPath('cache', ...segments)`. An initial `{ dshHome }` option preserves a provider's explicit home override. It resolves paths without creating directories; callers own directory creation. `attachment-local` uses this helper for regenerable request-image variants while retaining durable attachment objects in their versioned storage tree, so clearing the cache cannot remove Session attachments. Existing request-image cache entries are left in place and are not read or copied; a cache miss regenerates the variant from its durable attachment.
|
||||
|
||||
`@deepseek-ai/dsh-home` is deleted. Home-owning providers and boot packages import `resolveDshHome` from `dsh-home-paths`; composition bundles contain only the resolved configuration rows.
|
||||
|
||||
|
||||
+2
-2
@@ -21,9 +21,9 @@ Status: implemented
|
||||
explicit configured path > $DSH_HOME > ~/.dsh
|
||||
```
|
||||
|
||||
空或仅含空白的 `$DSH_HOME` 被当作未设置处理;否则,`resolve('')` 会悄悄把 home 落在当前工作目录。harness 把所有用户数据都放在同一个根目录下;不存在 XDG 的 config/data/cache 拆分。`dshHomePath(...segments)` 将部署负责的子路径拼接到该根目录下,`dsh-app-boot` 在挂载条目前向 Loader `!!js` 配置表达式暴露它,因此出厂组合无需复制解析器即可派生 `sessions` 和 `storages`。`dshHomeDisplay()` 为面向用户的路径以符号形式命名已解析的根目录——默认 home 显示为 `~/.dsh`,任何已配置的 home 显示为 `$DSH_HOME`——这样用户全局的 `AGENTS.md` 标签就绝不会泄露机器上的绝对路径。它取代了 agent-instructions 中自定义的「默认值 vs `$DSH_HOME`」判断。home 属于进程策略而非配置行:`dsh-agent-instructions` 不接受 home 覆盖,因此组合无法把指令加载指向会话、skill 与存储不会读取的根目录。`resolveAgentsHome()` 与 `agentsHomeDisplay()` 对共享 agent 配置根目录(`$DSH_AGENTS_HOME` 或 `~/.agents`)采用相同的优先级、波浪号展开与符号化标签;该根目录位于 harness home 之外,因为其他 agent 工具会共享它([共享 agents 根目录](2026-10-05-shared-agents-root-instructions.zh.md));`dsh-skill-filesystem` 仍接受自己的 `dshHome` 与 `agentsHome` 字段,用于选择它自己的 skill 根目录,并在指令加载改动中改用共享解析器。
|
||||
空或仅含空白的 `$DSH_HOME` 被当作未设置处理;否则,`resolve('')` 会悄悄把 home 落在当前工作目录。harness 把所有用户数据都放在同一个根目录下;不拆分到各自独立的 XDG 根目录。`dshHomePath(...segments)` 将部署负责的子路径拼接到该根目录下,`dsh-app-boot` 在挂载条目前向 Loader `!!js` 配置表达式暴露它,因此出厂组合无需复制解析器即可派生 `sessions` 和 `storages`。`dshHomeDisplay()` 为面向用户的路径以符号形式命名已解析的根目录——默认 home 显示为 `~/.dsh`,任何已配置的 home 显示为 `$DSH_HOME`——这样用户全局的 `AGENTS.md` 标签就绝不会泄露机器上的绝对路径。它取代了 agent-instructions 中自定义的「默认值 vs `$DSH_HOME`」判断。home 属于进程策略而非配置行:`dsh-agent-instructions` 不接受 home 覆盖,因此组合无法把指令加载指向会话、skill 与存储不会读取的根目录。`resolveAgentsHome()` 与 `agentsHomeDisplay()` 对共享 agent 配置根目录(`$DSH_AGENTS_HOME` 或 `~/.agents`)采用相同的优先级、波浪号展开与符号化标签;该根目录位于 harness home 之外,因为其他 agent 工具会共享它([共享 agents 根目录](2026-10-05-shared-agents-root-instructions.zh.md));`dsh-skill-filesystem` 仍接受自己的 `dshHome` 与 `agentsHome` 字段,用于选择它自己的 skill 根目录,并在指令加载改动中改用共享解析器。
|
||||
|
||||
`dshCachePath(...segments)` 在解析出的主目录下的 `cache` 目录中派生路径。首个 `{ dshHome }` 选项保留提供方显式配置的主目录覆盖值。它只解析路径,不创建目录;目录创建由调用方负责。`attachment-local` 将此函数用于可重新生成的请求图片版本,持久附件对象仍保留在其带版本的存储树中,因此清空缓存不会删除 Session 附件。已有请求图片缓存条目保留在原处,不再读取或复制;缓存未命中时从持久附件重新生成请求版本。
|
||||
`dshPath(category, ...segments)` 在该根目录下的 `config`、`data`、`state`、`cache` 或 `backup` 目录中派生路径,app-boot 将它与 `dshHomePath` 一并暴露给 Loader `!!js` 表达式;类别定义以及哪些现有条目保留顶层位置由 [home 路径类别提案](../../proposed/architecture/2026-11-04-dsh-home-path-categories.zh.md)负责。`dshCachePath(...segments)` 等同于 `dshPath('cache', ...segments)`。首个 `{ dshHome }` 选项保留提供方显式配置的主目录覆盖值。它只解析路径,不创建目录;目录创建由调用方负责。`attachment-local` 将此函数用于可重新生成的请求图片版本,持久附件对象仍保留在其带版本的存储树中,因此清空缓存不会删除 Session 附件。已有请求图片缓存条目保留在原处,不再读取或复制;缓存未命中时从持久附件重新生成请求版本。
|
||||
|
||||
`@deepseek-ai/dsh-home` 被删除。拥有 home 配置的提供方与 boot 包从 `dsh-home-paths` 导入 `resolveDshHome`;组合包只包含解析后的配置行。
|
||||
|
||||
|
||||
+2
-2
@@ -18,5 +18,5 @@
|
||||
en: ca7c9088d0793e1e
|
||||
zh: ea648bac9e726c64
|
||||
/agent-note-what-stays-host-plane-once-presets-own-the-agent-plane/consequences:
|
||||
en: 0a426923c2a1f774
|
||||
zh: 29626804b99b35ff
|
||||
en: 23642f4d7c998de6
|
||||
zh: f968db2047e0f4ac
|
||||
+1
-1
@@ -40,4 +40,4 @@ Projection key presence is not a per-session capability signal ([session project
|
||||
|
||||
The context meter is a per-session fact independent of mount history. Presets resolve the host meter for token accounting while selecting their own compaction backend; `minimal` supports both automatic compaction and the human `/compact` command.
|
||||
|
||||
Production entry points must compose Agents explicitly; installing the registry alone does not bind them. An unjoined Agent receives no tools, prompt sections, or skills and reports no error.
|
||||
Production entry points must compose Agents explicitly; installing the registry alone does not bind them. An unjoined Agent receives none of the tools, prompt sections, or skills that presets own, and the missing join reports no error. The CUA provider registers outside the presets: it gives an unjoined Agent `cua_run_code` with its guidance and rejects that Agent's creation while the tool's program services are unavailable ([CUA program tool for Agents without a preset](2026-11-12-cua-program-tool-without-presets.md)).
|
||||
+1
-1
@@ -40,4 +40,4 @@ Status: implemented
|
||||
|
||||
context meter 是独立于挂载历史的逐会话事实。Preset 使用宿主 meter 进行 token 记账,并选择自己的压缩后端;`minimal` 同时支持自动压缩和用户 `/compact` 命令。
|
||||
|
||||
生产入口必须显式组装 Agent;仅安装注册表不会自动绑定。未加入的 Agent 不会获得工具、提示词段落或 skill,也不会报告错误。
|
||||
生产入口必须显式组装 Agent;仅安装注册表不会自动绑定。未加入的 Agent 不会获得 preset 所拥有的工具、提示词段落或 skill,未加入这一点也不会报告错误。CUA 提供方在 preset 之外注册:它为未加入的 Agent 提供 `cua_run_code` 及其指引,并在该工具的程序服务不可用时拒绝创建这个 Agent([未组合 preset 的 Agent 使用 CUA 程序工具](2026-11-12-cua-program-tool-without-presets.zh.md))。
|
||||
+2
-2
@@ -12,8 +12,8 @@
|
||||
en: a15c7c13f167e5ac
|
||||
zh: a15c7c13f167e5ac
|
||||
/agent-note-client-shell-layering-and-dynamic-package-boundaries/decision/layers-and-build-forms:
|
||||
en: a1750de2d48551af
|
||||
zh: ffea0b75c292f186
|
||||
en: e0d6260cc782acb9
|
||||
zh: 2ca2418d2b97bc03
|
||||
/agent-note-client-shell-layering-and-dynamic-package-boundaries/decision/shared-module-requests:
|
||||
en: 96661da17622132a
|
||||
zh: dab3424093130c2f
|
||||
|
||||
+3
-3
@@ -21,14 +21,14 @@ Shared UI libraries still expose synchronous TypeScript and React values to many
|
||||
| Layer | Members | Responsibility | Build and load form |
|
||||
| --- | --- | --- | --- |
|
||||
| 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 | `staticLinked` `lib/index.js`; no `dsh.client` row |
|
||||
| Static assembly libraries | Cordis, `ui-primitives`, `ui-slots` | Supply shared module identities and direct value APIs | ESM `lib/index.js`, merged and chunked by Vite; not Loader entries |
|
||||
| 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 |
|
||||
| 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, 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 static UI packages as development compilation inputs. `apps/web` consumes built package exports rather than aliases into workspace source.
|
||||
|
||||
The `staticLinked` preset leaves every bare specifier as an external import in `lib/index.js` and emits relative CSS assets beside it. The Vite host resolves and deduplicates those imports and decides final chunk boundaries. A static library therefore does not copy the host's bundling policy into its own artifact.
|
||||
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
|
||||
|
||||
|
||||
+3
-3
@@ -21,14 +21,14 @@ Client npm 依赖区段描述安装和开发关系,但不能可靠描述 bundl
|
||||
| 层 | 成员 | 职责 | 构建与加载形态 |
|
||||
| --- | --- | --- | --- |
|
||||
| Web 编译壳 | `apps/web` | 拥有 `index.html`、Vite 配置、dist chunk 和静态资源 | 从已构建 package export 组装最终浏览器产物 |
|
||||
| 启动内核 | `packages/client/web` | 拥有纯 DOM 启动页、模块系统接线、Cordis settle 和 renderer handoff | `staticLinked` `lib/index.js`;无 `dsh.client` row |
|
||||
| 静态装配库 | Cordis、`ui-primitives`、`ui-slots` | 提供共享模块身份和直接实体 API | ESM `lib/index.js`,由 Vite 合并拆分;不是 Loader entry |
|
||||
| 启动内核 | `packages/client/web` | 拥有纯 DOM 启动页、模块系统接线、Cordis settle 和 renderer handoff | `clientShell` ESM 入口;无 `dsh.client` row |
|
||||
| 静态装配库 | 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`、主题和功能插件 | 通过 Cordis service、slot 和 effect 参与应用 | 声明 `dsh.client`,产出自注册 `lib/client.js`,并保留 host graph entry |
|
||||
|
||||
`packages/client/web` 把 Cordis 保持为 matching peer 与开发依赖,并把 modules 和静态 UI 包作为开发期编译输入。`apps/web` 消费已构建 package export,不通过 alias 读取 workspace 源码。
|
||||
|
||||
`staticLinked` 预设让 `lib/index.js` 中每个 bare specifier 保持 external import,并在旁边输出相对 CSS 资产。Vite 宿主负责解析和去重这些 import,并决定最终 chunk 边界。静态库不会把宿主打包策略复制进自身产物。
|
||||
`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)定义资源所有权;静态库不采用动态插件的私有依赖打包策略。
|
||||
|
||||
### 共享模块请求
|
||||
|
||||
|
||||
+2
-2
@@ -18,8 +18,8 @@
|
||||
en: fb2c7bcde3b1672a
|
||||
zh: a05bd30be07e5413
|
||||
/agent-note-session-history-control-state-and-remote-event-transport/decision/general-remote-stream-model/remotestream:
|
||||
en: d55c2ce88400e448
|
||||
zh: 344d510ab946bb9f
|
||||
en: 867f3ac763f81d8d
|
||||
zh: a936269f2fc40f8d
|
||||
/agent-note-session-history-control-state-and-remote-event-transport/decision/general-remote-stream-model/remotesnapshotstream:
|
||||
en: f2c1d2b00d9554fd
|
||||
zh: c3e85cf344f7ef24
|
||||
|
||||
+1
-1
@@ -101,7 +101,7 @@ Domain Controllers use them through composition or thin adapters; Session and Wo
|
||||
|
||||
Each item carries a monotonic generation, that generation's `AbortSignal`, and `accept()`. A domain consumer calls `accept()` only after validating the opening cursor or baseline.
|
||||
|
||||
Only `RemoteStreamCarrierError` permits retry. When the Host remains available, one independent reopen is allowed; otherwise the stream waits for a new Connection generation. Business errors, protocol errors, and opening failures terminate immediately.
|
||||
Only a failure whose `code` is `gateway/carrier-lost` permits retry; `RemoteStreamCarrierError` carries that code, and a domain `ended` callback may return a plain `Error` with it. When the Host remains available, one independent reopen is allowed; otherwise the stream waits for a new Connection generation. Business errors, protocol errors, and opening failures terminate immediately.
|
||||
|
||||
`restart()` replaces only the current physical generation and preserves the logical stream. `dispose()` permanently ends the logical stream, pending retry, and iterator, then waits for quiescence.
|
||||
|
||||
|
||||
+1
-1
@@ -101,7 +101,7 @@ RemoteStream<Item>
|
||||
|
||||
每个 item 携带单调 generation、该 generation 的 `AbortSignal` 与 `accept()`。领域 consumer 只有在验证 opening cursor 或 baseline 后才调用 `accept()`。
|
||||
|
||||
只有 `RemoteStreamCarrierError` 可触发重试。Host 仍可用时允许一次独立重开;否则等待新的 Connection generation。业务错误、协议错误和 opening 失败直接终止。
|
||||
只有 `code` 为 `gateway/carrier-lost` 的失败可触发重试;`RemoteStreamCarrierError` 带有该 code,领域的 `ended` 回调也可以返回带该 code 的普通 `Error`。Host 仍可用时允许一次独立重开;否则等待新的 Connection generation。业务错误、协议错误和 opening 失败直接终止。
|
||||
|
||||
`restart()` 只淘汰当前物理 generation,保留 logical stream;`dispose()` 永久结束 logical stream、pending retry 与 iterator,并等待 quiescence。
|
||||
|
||||
|
||||
+2
-2
@@ -24,8 +24,8 @@
|
||||
en: b6f585ca87e1fc6f
|
||||
zh: 53fd58c3e93cf17c
|
||||
/agent-note-client-session-conversation-and-ui-ownership-layers/package-ownership:
|
||||
en: 89f75f7cc2fe0e6c
|
||||
zh: e50974fad3baf69c
|
||||
en: f3f1e545f7b15d9a
|
||||
zh: 80927e6b4e8ed5bc
|
||||
/agent-note-client-session-conversation-and-ui-ownership-layers/overall-data-flow:
|
||||
en: 002d9f406580684b
|
||||
zh: a86742c6c943ac85
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ Adding a target does not add a branch to the renderer or Session Controller. The
|
||||
| `api/session-controller/client` | Session objects, catalog, references, source counts, commands, projections, event windows, and Agent Contexts | Navigation, completion reminders, Conversation targets, React, Slots, Workspace |
|
||||
| `api/workspace-controller/client` | Workspace objects, ordering, archive state, commands, and snapshots | React, Session navigation policy, directory UI |
|
||||
| `client/ui-session` | Explicit Session scope, standard sources, `SessionProvider`, and effective pending interactions | Session transport, reference ownership, Conversation assembly, Approval/Question results, unified UI status |
|
||||
| `client/ui-session-status` | Unified UI status: running state, effective pending request, and completion reminders | Pending-interaction registration, Session transport, React |
|
||||
| `client/ui-session-status` | Unified UI status: running state, effective pending request, and completion reminders; Host reading records and their Client copy; main-view reading acknowledgement | Pending-interaction registration, Session transport, React |
|
||||
| `client/ui-workspace` | Workspace hook, browser UI, main-area reference, and cross-Controller navigation policy | Workspace transport, copies of Session data |
|
||||
| `client/ui-conversation` | Conversation core, registries, bindings, shell, input, composer, queue, and View navigation | Session transport, Chat/Trajectory snapshots |
|
||||
| `client/ui-chat` | Chat target, Node definitions, renderers, selection, details, and locale | Session lifecycle, generic View navigation, Trajectory, historical-image cache |
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ UI 层可以同时读取多个 Controller 做一次导航决定,但不得把
|
||||
| `api/session-controller/client` | 会话对象、目录、引用、来源计数、命令、投影、事件窗口与 Agent Context | 导航、完成提醒、Conversation target、React、Slot、Workspace |
|
||||
| `api/workspace-controller/client` | Workspace 对象、顺序、归档、命令和 snapshot | React、Session 导航策略、目录 UI |
|
||||
| `client/ui-session` | 显式会话作用域、标准数据源、`SessionProvider` 与有效待处理交互 | 会话传输、引用所有权、Conversation 组装、Approval/Question 结果、统一 UI 状态 |
|
||||
| `client/ui-session-status` | 统一 UI 状态:运行状态、有效待处理请求与完成提醒 | 待处理交互登记、会话传输、React |
|
||||
| `client/ui-session-status` | 统一 UI 状态:运行状态、有效待处理请求与完成提醒;宿主阅读记录及其前端副本;主视图阅读确认 | 待处理交互登记、会话传输、React |
|
||||
| `client/ui-workspace` | Workspace 钩子、浏览器 UI、主区域引用与跨控制器导航策略 | Workspace 传输、会话数据副本 |
|
||||
| `client/ui-conversation` | Conversation core、registry、binding、shell、input、composer、queue 和 View 导航 | Session transport、Chat/Trajectory snapshot |
|
||||
| `client/ui-chat` | Chat target、Node definitions、renderer、selection、details 和 locale | Session 生命周期、通用 View 导航、Trajectory、历史图片 cache |
|
||||
|
||||
+6
-6
@@ -9,14 +9,14 @@
|
||||
en: 01293500639c9d79
|
||||
zh: 6d19e4843955c811
|
||||
/agent-note-browser-launch-token-authentication/decision:
|
||||
en: 51885594bdeb6f0c
|
||||
zh: 9c2e41ad79ccdd08
|
||||
en: 0c437d201b8668d5
|
||||
zh: 2c1b3e67b38a5012
|
||||
/agent-note-browser-launch-token-authentication/verification:
|
||||
en: 189b36d0fc5f3a17
|
||||
zh: 08993cb585204fc0
|
||||
en: 51fe0a5b45693654
|
||||
zh: 69c82207975fa421
|
||||
/agent-note-browser-launch-token-authentication/alternatives-considered:
|
||||
en: 5275c87f19fe6eee
|
||||
zh: ccb922367c4bb3e2
|
||||
/agent-note-browser-launch-token-authentication/consequences:
|
||||
en: af55274a2f345cdd
|
||||
zh: 4d1810141ef03bae
|
||||
en: 5d69529b50c1ff32
|
||||
zh: 5fc371b5cde4783e
|
||||
@@ -10,15 +10,15 @@ The Web Host runs tool-capable Sessions with the current operating-system user's
|
||||
|
||||
## Decision
|
||||
|
||||
Browser callers follow this decision; independent CLI/MCP admission is owned by the [API connect decision](2026-10-09-operator-scoped-connect-handshake.md).
|
||||
The default browser Token implementation follows this decision and is provided by [`dsh-host-authentication-token`](../../../../packages/host/authentication-token/README.md); independent CLI/MCP admission is owned by the [API connect decision](2026-10-09-operator-scoped-connect-handshake.md). The [Provider decision](2026-11-07-browser-authentication-providers.md) defines independent authentication ownership and equal Token, Desktop, and Remote extension points while retaining this credential protocol; the Remote product itself is not implemented.
|
||||
|
||||
`dsh-client-connection` authenticates the complete Host API before dispatch. Every API Proxy method, Remote unary call, generic Connection channel, and Remote WebSocket stream requires the same browser session; endpoint ownership and method names do not alter authority. The existing Host/Origin checks run first and retain their DNS-rebinding and cross-site-request role, returning 403 when they fail. A trusted Host without a valid browser session receives 401. The browser-trust rules remain owned by the [carrier-level browser trust decision](2026-07-28-api-browser-trust-boundary.md).
|
||||
`dsh-client-connection` authenticates the complete Host API before dispatch. Every API Proxy method, Remote unary call, generic Connection channel, and Remote WebSocket stream requires an authenticated Peer; endpoint ownership and method names do not alter authority. The existing Host/Origin checks run first and retain their DNS-rebinding and cross-site-request role, returning 403 when they fail. A trusted Host without valid credentials receives 401. The browser-trust rules remain owned by the [carrier-level browser trust decision](2026-07-28-api-browser-trust-boundary.md).
|
||||
|
||||
Each Host process generates a random launch token, retained by the root application context across Connection hot reloads. `dsh-web-app` prints and opens the normal root URL with that token in the query once per process. `frontend-static` asks Connection to authorize index responses: only `GET /?token=...` exchanges the process token for a cookie, then redirects to clean `./`; the token is not accepted on API paths or in an Authorization header. An obsolete token paired with a valid cookie redirects to clean `./`. Missing and invalid credentials receive one minimal 401 response. Static non-index assets remain public.
|
||||
The Token plugin generates one random launch token per Host root and retains it across plugin reloads. It contributes a signed entry URL through `webserver/entry-url`; WebApp supplies the ordinary base address and owns printing and opening entries once per root application according to its startup configuration. The plugin handles the root exchange through `webserver/request`: `GET /?token=...` exchanges the process token for a cookie and redirects to clean `./`. An obsolete token paired with a valid default cookie also redirects to clean `./`. The plugin registers its Cookie verifier with `connection.authentication`, and `frontend-static` uses the admitted Peer to render the index. Default-token requests with missing or invalid credentials receive the minimal 401 response; static non-index assets remain public. API token handling remains with the independent `/connect` handshake.
|
||||
|
||||
The cookie is a signed, authority-bound bearer. Its deterministic name and signed payload both include the normalized hostname plus port, so one Harness home can run independent Web ports without cookie collisions. The payload carries safe-integer issue and expiry times under an absolute lifetime; `cookieMaxAgeDays` defaults to 30. The cookie is host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`. The HTTP listener omits `Secure`. There is no logout operation.
|
||||
|
||||
The HMAC secret is a versioned `grant` record at `client-connection/browser-session` in `ctx.credentials`; the local provider stores it in `$DSH_HOME/.credentials.yaml`. Connection loads or creates the record during activation and retains the secret for synchronous request verification. An active Connection continues using its loaded secret if the durable record changes; the next activation loads the replacement or creates a missing record, so deleting the record and restarting the process revokes every existing cookie. Invalid owner payloads fail loud instead of being replaced. The launch token itself is never persisted and changes on every process start, while an unexpired cookie remains valid across restarts on the same authority.
|
||||
The HMAC secret is a versioned `grant` record at `client-connection/browser-session` in `ctx.credentials`; the local provider stores it in `$DSH_HOME/.credentials.yaml`. The Token plugin loads or creates the record during activation and retains the secret for synchronous request verification. An active Token plugin continues using its loaded secret if the durable record changes; the next activation loads the replacement or creates a missing record, so deleting the record and restarting the process revokes every existing cookie. Invalid owner payloads fail loud instead of being replaced. The launch token itself is never persisted and changes on every process start, while an unexpired cookie remains valid across restarts on the same authority.
|
||||
|
||||
The in-page Web Worker preview exposes no network socket. Its page-owned `postMessage` tunnel enters the real route first, then retries a 401 or 403 through the worker-local fetch handler. This keeps Connection interceptors while limiting the authentication bypass to the page that created the Host worker.
|
||||
|
||||
@@ -26,7 +26,7 @@ The shipped CLI accepts concrete local bind addresses but rejects wildcard addre
|
||||
|
||||
## Verification
|
||||
|
||||
Unit coverage pins process-token retention across Connection reloads, one secret load per activation, synchronous verification without credential-provider reads, cookie attributes, HMAC and payload validation, authority and lifetime checks, record deletion taking effect on the next activation, invalid durable records, and cleanup of obsolete token URLs backed by valid cookies. Host transport suites pin uniform 401/403 behavior for generic RPC, Typert Remote HTTP, exact Fetch routes, and WebSocket upgrade paths. The frontend real-composition test boots credentials, Connection, webserver, and static serving through Loader and proves token exchange before index reads while static assets remain public. Packed-worker tests prove portable cookie encoding and worker-local retry for both authentication and trust rejection. A real-CLI test starts `dsh web` twice on one port with a temporary `DSH_HOME`, proves that forged `Host: localhost` is unauthenticated, calls `settings/describe` with the exchanged cookie, observes a new process token, and reuses the old cookie after restart.
|
||||
Unit coverage pins process-token retention across Token plugin reloads, one secret load per activation, synchronous verification without credential-provider reads, cookie attributes, HMAC and payload validation, authority and lifetime checks, record deletion taking effect on the next activation, invalid durable records, and cleanup of obsolete token URLs backed by valid cookies. Host transport suites pin uniform 401/403 behavior for generic RPC, Typert Remote HTTP, exact Fetch routes, and WebSocket upgrade paths. The frontend real-composition test boots credentials, Connection, the Token plugin, webserver, and static serving through Loader and proves token exchange before index reads while static assets remain public. Packed-worker tests prove portable cookie encoding and worker-local retry for both authentication and trust rejection. A real-CLI test starts `dsh web` twice on one port with a temporary `DSH_HOME`, proves that forged `Host: localhost` is unauthenticated, calls `settings/describe` with the exchanged cookie, observes a new process token, and reuses the old cookie after restart.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
@@ -44,7 +44,7 @@ Unit coverage pins process-token retention across Connection reloads, one secret
|
||||
|
||||
Possession of the browser cookie authorizes the complete tool-capable Host API, matching the authority the Web application exposes after Session creation. `Host` does not grant a higher method tier, and a method migration between API Proxy and Typert Remote cannot change its caller set.
|
||||
|
||||
The persistent secret makes cookies survive restarts but gives a stolen cookie up to the configured absolute lifetime. Deleting the record and restarting the process is the global revocation mechanism; the active Connection intentionally avoids credential-provider work on each request. An HTTP listener permits plaintext cookie transmission if its authority is reachable over an unencrypted network. The startup URL contains a process credential and must be treated as sensitive output; runtime diagnostics do not repeat it.
|
||||
The persistent secret makes cookies survive restarts but gives a stolen cookie up to the configured absolute lifetime. Deleting the record and restarting the process is the global revocation mechanism; the active Token verifier uses its loaded secret for each request. An HTTP listener permits plaintext cookie transmission if its authority is reachable over an unencrypted network. The startup URL contains a process credential and must be treated as sensitive output; runtime diagnostics do not repeat it.
|
||||
|
||||
The decision partially supersedes the authentication deferral and unauthenticated non-loopback consequences in the [browser trust note](2026-07-28-api-browser-trust-boundary.md). That note remains active authority for media-type, Host, Origin, Fetch-Metadata, and configured-authority validation. No active Agent Note is archived: the overlap is partial and both security rules retain future decision value.
|
||||
|
||||
|
||||
+6
-6
@@ -10,15 +10,15 @@ Web Host 以当前操作系统用户的权限运行具有工具能力的 Session
|
||||
|
||||
## 决策
|
||||
|
||||
浏览器调用方遵循本决策;独立 CLI/MCP 接纳由 [API connect 决策](2026-10-09-operator-scoped-connect-handshake.zh.md)定义。
|
||||
默认浏览器 Token 实现遵循本决策,由 [`dsh-host-authentication-token`](../../../../packages/host/authentication-token/README.zh.md) 提供;独立 CLI/MCP 接纳由 [API connect 决策](2026-10-09-operator-scoped-connect-handshake.zh.md)定义。[Provider 决策](2026-11-07-browser-authentication-providers.zh.md)定义独立认证归属和平级 Token、Desktop、Remote 扩展接入,同时保留本凭据协议;Remote 产品本身尚未实现。
|
||||
|
||||
`dsh-client-connection` 在分发前认证完整 Host API。每个 API Proxy 方法、Remote 一元调用、通用 Connection channel 和 Remote WebSocket stream 都要求同一个浏览器会话;endpoint 所有权与方法名称不改变 authority。既有 Host/Origin 校验先执行,继续负责 DNS rebinding 和跨站请求防御,失败时返回 403。Host 可信但没有有效浏览器会话时返回 401。浏览器信任规则仍由[载体级浏览器信任决策](2026-07-28-api-browser-trust-boundary.zh.md)持有。
|
||||
`dsh-client-connection` 在分发前认证完整 Host API。每个 API Proxy 方法、Remote 一元调用、通用 Connection channel 和 Remote WebSocket stream 都要求已认证 Peer;endpoint 所有权与方法名称不改变 authority。既有 Host/Origin 校验先执行,继续负责 DNS rebinding 和跨站请求防御,失败时返回 403。Host 可信但没有有效凭据时返回 401。浏览器信任规则仍由[载体级浏览器信任决策](2026-07-28-api-browser-trust-boundary.zh.md)持有。
|
||||
|
||||
每个 Host 进程生成随机启动令牌,并由应用根 context 跨 Connection 热重载保留。`dsh-web-app` 每个进程只打印并打开一次 query 中带该令牌的普通根 URL。`frontend-static` 请求 Connection 授权 index 响应:只有 `GET /?token=...` 会把进程令牌交换为 cookie,再重定向到干净的 `./`;API 路径和 Authorization header 都不接受该令牌。过时令牌如果同时带有有效 cookie,会重定向到干净的 `./`。缺失与无效凭据得到同一份最小 401 响应。非 index 静态资产保持公开。
|
||||
Token 插件为每个 Host 根生成一个随机启动令牌,并跨插件重载保留。它通过 `webserver/entry-url` 贡献带签名的入口 URL;WebApp 提供普通基地址,并按自身启动配置负责在每个根应用中打印和打开入口一次。插件通过 `webserver/request` 处理根路径交换:`GET /?token=...` 把进程令牌交换为 cookie,再重定向到干净的 `./`。过时令牌同时带有有效默认 cookie 时,也重定向到干净的 `./`。插件向 `connection.authentication` 注册 Cookie 验证器,`frontend-static` 使用准入 Peer 渲染 index。默认 Token 请求缺失或携带无效凭据时得到最小 401 响应;非 index 静态资产保持公开。API Token 处理仍归独立的 `/connect` 握手。
|
||||
|
||||
cookie 是签名且绑定 authority 的 bearer。确定性名称与签名 payload 都包含规范化 hostname 和 port,因此同一 Harness home 可以在不同 Web port 运行而不发生 cookie 冲突。payload 在绝对有效期内携带安全整数形式的签发与过期时间;`cookieMaxAgeDays` 默认为 30。cookie 是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`。HTTP 监听器不设置 `Secure`。这里没有 logout 操作。
|
||||
|
||||
HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` 的版本化 `grant` 记录;本地提供方将其存入 `$DSH_HOME/.credentials.yaml`。Connection 在激活期间加载或创建该记录,并保留密钥以同步校验请求。持久记录发生变化后,当前 Connection 继续使用已加载的密钥;下一次激活会加载替换记录或创建缺失记录,因此删除记录并重启进程会撤销全部既有 cookie。无效 owner payload 会明确失败,而不是被覆盖。启动令牌本身绝不持久化并在每次进程启动时变化;未过期 cookie 则能在相同 authority 上跨重启继续有效。
|
||||
HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` 的版本化 `grant` 记录;本地提供方将其存入 `$DSH_HOME/.credentials.yaml`。Token 插件在激活期间加载或创建该记录,并保留密钥以同步校验请求。持久记录发生变化后,当前 Token 插件继续使用已加载的密钥;下一次激活会加载替换记录或创建缺失记录,因此删除记录并重启进程会撤销全部既有 cookie。无效 owner payload 会明确失败,而不是被覆盖。启动令牌本身绝不持久化并在每次进程启动时变化;未过期 cookie 则能在相同 authority 上跨重启继续有效。
|
||||
|
||||
页内 Web Worker preview 不暴露网络 socket。其由页面持有的 `postMessage` tunnel 先进入真实 route,收到 401 或 403 后再经 worker 本地 fetch handler 重试。这样既保留 Connection interceptor,又把认证绕过限制在创建 Host worker 的页面内。
|
||||
|
||||
@@ -26,7 +26,7 @@ HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session`
|
||||
|
||||
## 验证
|
||||
|
||||
单元覆盖 Connection 重载时保留进程令牌、每次激活只加载一次密钥、无需读取凭据提供方的同步校验、cookie 属性、HMAC 与 payload 校验、authority 与有效期校验、记录删除在下一次激活时生效、无效持久记录,以及用有效 cookie 清理过时令牌 URL。Host 传输套件固定通用 RPC、Typert Remote HTTP、精确 Fetch 路由和 WebSocket upgrade 路径上一致的 401/403 行为。frontend 真实组合测试经 Loader 启动 credentials、Connection、webserver 与静态服务,证明读取 index 前完成令牌交换,同时静态资产仍公开。打包 worker 测试证明 cookie 编码可移植,并覆盖认证与信任拒绝后的 worker 本地重试。真实 CLI 测试在临时 `DSH_HOME` 上用同一端口两次启动 `dsh web`,证明伪造 `Host: localhost` 仍未认证,以交换所得 cookie 调用 `settings/describe`,观测新的进程令牌,并在重启后复用旧 cookie。
|
||||
单元覆盖 Token 插件重载时保留进程令牌、每次激活只加载一次密钥、无需读取凭据提供方的同步校验、cookie 属性、HMAC 与 payload 校验、authority 与有效期校验、记录删除在下一次激活时生效、无效持久记录,以及用有效 cookie 清理过时令牌 URL。Host 传输套件固定通用 RPC、Typert Remote HTTP、精确 Fetch 路由和 WebSocket upgrade 路径上一致的 401/403 行为。frontend 真实组合测试经 Loader 启动 credentials、Connection、Token 插件、webserver 与静态服务,证明读取 index 前完成令牌交换,同时静态资产仍公开。打包 worker 测试证明 cookie 编码可移植,并覆盖认证与信任拒绝后的 worker 本地重试。真实 CLI 测试在临时 `DSH_HOME` 上用同一端口两次启动 `dsh web`,证明伪造 `Host: localhost` 仍未认证,以交换所得 cookie 调用 `settings/describe`,观测新的进程令牌,并在重启后复用旧 cookie。
|
||||
|
||||
## 曾考虑的替代方案
|
||||
|
||||
@@ -44,7 +44,7 @@ HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session`
|
||||
|
||||
持有浏览器 cookie 就能调用完整的工具型 Host API,这与 Web 应用在创建 Session 后暴露的 authority 一致。`Host` 不授予更高的方法层级,方法在 API Proxy 与 Typert Remote 之间迁移也不会改变调用者集合。
|
||||
|
||||
持久密钥使 cookie 跨重启生效,也让被盗 cookie 最多保有配置的绝对有效期。删除记录并重启进程是全局撤销机制;当前 Connection 刻意避免在每个请求上访问凭据提供方。如果 HTTP listener 的 authority 经未加密网络可达,cookie 就可能以明文传输。启动 URL 含进程凭据,必须视为敏感输出;运行时诊断不会重复它。
|
||||
持久密钥使 cookie 跨重启生效,也让被盗 cookie 最多保有配置的绝对有效期。删除记录并重启进程是全局撤销机制;当前 Token 验证器在每个请求上使用已加载的密钥。如果 HTTP listener 的 authority 经未加密网络可达,cookie 就可能以明文传输。启动 URL 含进程凭据,必须视为敏感输出;运行时诊断不会重复它。
|
||||
|
||||
本决策部分取代[浏览器信任说明](2026-07-28-api-browser-trust-boundary.zh.md)中的认证延期与未认证非 loopback 后果。该说明仍是媒体类型、Host、Origin、Fetch-Metadata 和配置 authority 校验的有效权威。没有 active Agent Note 被归档:重叠只发生在局部,两条安全规则都保有未来决策价值。
|
||||
|
||||
|
||||
+2
-2
@@ -24,8 +24,8 @@
|
||||
en: e2de83d10542f93b
|
||||
zh: 3855b38fc8c48ea3
|
||||
/agent-note-client-session-references-reference-sources-and-ui-status/decision/unified-ui-session-status:
|
||||
en: 07ea04b9ca50dd8f
|
||||
zh: e025fcea4c9f0fb9
|
||||
en: 45038468e95179f9
|
||||
zh: ac8f2f098f5b2427
|
||||
/agent-note-client-session-references-reference-sources-and-ui-status/decision/explicit-providers-and-consumer-lifetimes:
|
||||
en: 04802baa0147fec1
|
||||
zh: b86037bf2e4bc936
|
||||
|
||||
@@ -96,22 +96,16 @@ Window-level consumers may inspect source markers. Session business operations s
|
||||
| --- | --- | --- |
|
||||
| `running` | `boolean` or `undefined` | Latest known Session running fact; absence of a baseline is not confirmed idle |
|
||||
| `pendingInteraction` | `SessionPendingInteraction` or `undefined` | Effective domain-owned request, or absence when no request is pending |
|
||||
| `completionUnread` | `boolean` | UI reminder for an observed stop that has not been acknowledged |
|
||||
| `completionUnread` | `boolean` | Host reading record carries a manual unread mark or an unacknowledged completed turn |
|
||||
| `completionFailed` | `boolean` | The Session is unread and its latest completed turn ended with an execution error |
|
||||
|
||||
Source counts remain authoritative in `SessionListState.byId[id].retainedBy`; UI status reads them for acknowledgement policy without owning another reference registry. Titles, Workspace associations, history, queues, and projection data remain with their existing owners.
|
||||
|
||||
Pending domains retain `SessionPendingInteractionMap`, request identities, precedence, publication disposers, and teardown delegation in `ui-session`, which publishes each Session's effective request read-only as `ctx.uiSession.pendingInteractions`. The unified status includes the same effective request object; it does not copy requests or create a second pending registry. Workspace status indicators and Conversation composer selection read `useSessionStatus` instead of separate `useSessionPendingInteraction` and `useCompletedSessionIds` hooks.
|
||||
|
||||
Completion tracking subscribes to the existing `api-session/status` events so a running-to-idle transition is not lost in batched catalog snapshots. Host-list rows (`ids`) establish initial and reconnect running baselines; synthetic catalog and retained rows preserve independently observed status. A pending empty catalog is not evidence that Sessions disappeared. The update rules are:
|
||||
Running tracking subscribes to the existing `api-session/status` events so a running-to-idle transition is not lost in batched catalog snapshots. Host-list rows (`ids`) establish initial and reconnect running baselines; synthetic catalog and retained rows preserve independently observed status. A pending empty catalog is not evidence that Sessions disappeared, and removing a Session clears its running baseline; pending-request teardown stays with the request's domain.
|
||||
|
||||
- An initial idle baseline does not create a completion reminder.
|
||||
- Observing running clears an earlier reminder and records the running baseline.
|
||||
- A known running-to-idle transition sets `completionUnread` only when the Session lacks main-view ownership.
|
||||
- Acquiring main-view ownership clears the reminder; retaining from an unrelated source does not.
|
||||
- Releasing main-view ownership does not manufacture a reminder for an earlier stop.
|
||||
- Removing a Session clears its completion reminder and running baseline; pending-request teardown stays with the request's domain.
|
||||
|
||||
The reminder denotes an observed stop, not successful task completion or completion of a particular queued message. Main-view ownership preserves selection-based acknowledgement even while a global panel temporarily hides the Conversation. The design has no `ui-session/view-presence` event, mounted-Provider index, or implicit acknowledgement from Provider mount.
|
||||
Completion reminders follow the Host reading records described in [Host-memory Session reading state](../feature/2026-10-23-session-reading-memory.md), which supersedes this note's earlier Client-local reminder rules: running changes and main-view ownership neither set nor clear a reminder, and the visible main view acknowledges a completed turn only after its body arrives. The reminder denotes a completed turn, not successful task completion or completion of a particular queued message. Main-view ownership preserves selection-based acknowledgement even while a global panel temporarily hides the Conversation. The design has no `ui-session/view-presence` event, mounted-Provider index, or implicit acknowledgement from Provider mount.
|
||||
|
||||
The Session Controller publishes running and reference-source facts but owns no completion-reminder set, `consumeCompletion` method, or pending-interaction presentation. Reference acquisition does not execute completion-reminder business logic.
|
||||
|
||||
|
||||
@@ -96,22 +96,16 @@ Controller 将来源计数与每个活跃代的引用共同管理。每个来源
|
||||
| --- | --- | --- |
|
||||
| `running` | `boolean` 或 `undefined` | 最新已知的 Session 运行事实;缺少基线不表示已确认 idle |
|
||||
| `pendingInteraction` | `SessionPendingInteraction` 或 `undefined` | 领域拥有的有效请求;没有待处理请求时缺失 |
|
||||
| `completionUnread` | `boolean` | 已观察到停止、但尚未确认的 UI 提醒 |
|
||||
| `completionUnread` | `boolean` | 宿主阅读记录带有手动未读标记或尚未确认的完成轮次 |
|
||||
| `completionFailed` | `boolean` | Session 未读,且最近完成的轮次以执行错误结束 |
|
||||
|
||||
来源计数以 `SessionListState.byId[id].retainedBy` 为准;UI 状态读取它以执行确认策略,不维护另一套引用注册表。标题、Workspace 关联、历史、队列和投影数据保留在各自的既有所有者中。
|
||||
|
||||
待处理领域在 `ui-session` 中保留 `SessionPendingInteractionMap`、请求身份、优先级、发布清理函数与卸载委托,`ui-session` 以只读的 `ctx.uiSession.pendingInteractions` 发布每个 Session 的有效请求。统一状态包含同一个有效请求对象,不复制请求,也不创建第二套待处理注册表。Workspace 状态指示器与 Conversation composer 选择读取 `useSessionStatus`,不再分别读取 `useSessionPendingInteraction` 和 `useCompletedSessionIds` 钩子。
|
||||
|
||||
完成跟踪订阅已有 `api-session/status` 事件,避免 running 到 idle 的变化在合批目录快照中丢失。Host 列表行(`ids`)建立初始与重连的 running 基线;目录合成行与 retained 行保留独立观察到的状态。pending 状态下的空目录不能证明 Session 已消失。更新规则如下:
|
||||
运行跟踪订阅已有 `api-session/status` 事件,避免 running 到 idle 的变化在合批目录快照中丢失。Host 列表行(`ids`)建立初始与重连的 running 基线;目录合成行与 retained 行保留独立观察到的状态。pending 状态下的空目录不能证明 Session 已消失;移除 Session 时清除其运行基线,待处理请求的清理仍属于请求领域。
|
||||
|
||||
- 初始 idle 基线不产生完成提醒。
|
||||
- 观察到 running 时清除旧提醒,并记录运行基线。
|
||||
- 从已知 running 变为 idle 时,仅在 Session 没有主视图持有的情况下设置 `completionUnread`。
|
||||
- 获得主视图持有时清除提醒;无关来源的 retain 不清除提醒。
|
||||
- 释放主视图持有不会为更早的一次停止补造提醒。
|
||||
- 移除 Session 时清除其完成提醒与运行基线;待处理请求的清理仍属于请求领域。
|
||||
|
||||
提醒表示观察到的一次停止,不代表任务成功,也不代表某条排队消息完成。即使全局面板暂时隐藏 Conversation,主视图所有权仍保持基于选择的确认语义。本设计不提供 `ui-session/view-presence` 事件、已挂载 Provider 索引或 Provider 挂载时的隐式确认。
|
||||
完成提醒跟随[宿主内存中的会话阅读状态](../feature/2026-10-23-session-reading-memory.zh.md)所述的宿主阅读记录,该记录取代本记录早先的前端本地提醒规则:运行变化和主视图持有都不会设置或清除提醒,可见的主视图只在正文到达后确认完成的轮次。提醒表示完成的一个轮次,不代表任务成功,也不代表某条排队消息完成。即使全局面板暂时隐藏 Conversation,主视图所有权仍保持基于选择的确认语义。本设计不提供 `ui-session/view-presence` 事件、已挂载 Provider 索引或 Provider 挂载时的隐式确认。
|
||||
|
||||
Session Controller 发布运行与引用来源事实,但不拥有完成提醒集合、`consumeCompletion` 方法或待处理交互展示。引用获取不执行完成提醒业务逻辑。
|
||||
|
||||
|
||||
@@ -72,8 +72,8 @@
|
||||
en: 607a1afd89892d15
|
||||
zh: a0aa85124340458c
|
||||
/agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/decision/security-and-validation:
|
||||
en: 2426665452a6a37b
|
||||
zh: 282572d66e17a237
|
||||
en: 0683589c4c144620
|
||||
zh: 29c23acf6d6fef51
|
||||
/agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/decision/in-process-and-worker-carriers:
|
||||
en: df4ae60d8403cdbb
|
||||
zh: 70c6024a2a9a1e84
|
||||
|
||||
@@ -305,7 +305,7 @@ Credit frames wait until a consumer that needs sustained high-volume uplink appe
|
||||
|
||||
| Item | Rule |
|
||||
| --- | --- |
|
||||
| Authentication | Same as today: `connection.requestRejection(req)` at upgrade; descriptor and lookup-parameter validation at open. Uplink items belong to an already authenticated stream and are not authenticated again |
|
||||
| Authentication | WebServer admission supplies the Peer at upgrade; descriptor and lookup-parameter validation runs at open. Uplink items belong to an already authenticated stream and are not authenticated again |
|
||||
| Peer | Admitted at upgrade as one `PeerScope`; `invocation.peer` of every stream on that socket is that Peer |
|
||||
| Item validation | With an uplink codec, every item is decoded strictly, and a failure fails the whole stream with the existing `gateway/input-invalid` (details `{ endpoint, field: 'uplink' }`); without a codec, only JSON-safety validation applies |
|
||||
| Frame size | A single frame keeps the `maxPayload` of `ws`; the inbox limit bounds the accumulated total |
|
||||
|
||||
@@ -305,7 +305,7 @@ credit 帧留待需要持续大流量上行的消费者出现时再加;inbox
|
||||
|
||||
| 项 | 规则 |
|
||||
| --- | --- |
|
||||
| 鉴权 | 与今天相同:升级时 `connection.requestRejection(req)`;打开时描述符与查找参数校验。上行项属于一条已鉴权的流,不重复鉴权 |
|
||||
| 鉴权 | 升级时由 WebServer 准入提供 Peer;打开时校验描述符与查找参数。上行项属于一条已鉴权的流,不重复鉴权 |
|
||||
| Peer | 升级时接纳为一个 `PeerScope`,该 socket 上所有流的 `invocation.peer` 都是它 |
|
||||
| 项校验 | 有 uplink codec 时逐项严格解码,失败即整条流以既有的 `gateway/input-invalid` 失败(details `{ endpoint, field: 'uplink' }`);无 codec 时只做 JSON 安全校验 |
|
||||
| 帧大小 | 单帧沿用 `ws` 的 `maxPayload`;inbox 上限限制累计量 |
|
||||
|
||||
+2
-2
@@ -15,5 +15,5 @@
|
||||
en: d6f40bf02df37ab7
|
||||
zh: e5b85ce9d41e8754
|
||||
/agent-note-ship-experimental-capabilities-as-optional-bundles/consequences:
|
||||
en: 49e2c3f9f641c38b
|
||||
zh: 3aa772fb43c4bb6e
|
||||
en: 1fb52c4b3af8d88b
|
||||
zh: 6ec20abd592b2e08
|
||||
+1
-1
@@ -34,4 +34,4 @@ Computer Use is a shipped optional bundle in the experimental group. Its bundle
|
||||
|
||||
Official discovery does not imply experimental status or a different plugin lifecycle. Switching a bundle off keeps its installed files; failed activation retains the existing saved-selection behavior. Bundle rows are ordinary Host rows with their usual switches. Individual and combined composition tests cover the Host rows and every preset's tool catalog; live switching and recorded Sessions cover activation and model-visible behavior.
|
||||
|
||||
Computer Use keeps its permission service and native provider on the Host and registers tools in Agent scopes. The preset named by `agentPreset` receives raw `cua`; other composed presets receive the [CUA program tool](2026-11-09-cua-program-tool.md). Existing Agent events and `createScope()` maintain current, new and resumed Agents. Preset declarations remain unchanged. Only the explicit detail-page action changes the new-session default through the existing settings form; the activation switch does not configure PTC execution.
|
||||
Computer Use keeps its permission service and native provider on the Host and registers tools in Agent scopes. The preset named by `agentPreset` receives raw `cua`; other Agents receive the [CUA program tool](2026-11-09-cua-program-tool.md). Existing Agent events and `createScope()` maintain current, new and resumed Agents. Preset declarations remain unchanged. Only the explicit detail-page action changes the new-session default through the existing settings form; the activation switch does not configure PTC execution.
|
||||
+1
-1
@@ -34,4 +34,4 @@ Computer Use 是 experimental 包组内随安装提供的可选组合包。组
|
||||
|
||||
官方发现不表示实验性状态,也不引入不同的插件生命周期。关闭 bundle 保留已安装文件;激活失败保留现有的已保存选择行为。Bundle 行是普通 Host 行,使用常规开关。独立与组合测试覆盖 Host 行及每个预设的工具目录;实时切换与已记录 Session 覆盖激活和模型可见行为。
|
||||
|
||||
Computer Use 将权限服务和原生提供方保留在 Host,并在 Agent 作用域中注册工具。`agentPreset` 指定的 preset 获得原始 `cua`;其他已组合的 preset 获得 [CUA 程序工具](2026-11-09-cua-program-tool.zh.md)。现有 Agent 事件和 `createScope()` 维护当前、新建和恢复的 Agent,preset 声明保持不变。只有详情页的显式操作通过现有设置表单修改新会话默认模式,启用开关不配置 PTC 执行方式。
|
||||
Computer Use 将权限服务和原生提供方保留在 Host,并在 Agent 作用域中注册工具。`agentPreset` 指定的 preset 获得原始 `cua`;其他 Agent 获得 [CUA 程序工具](2026-11-09-cua-program-tool.zh.md)。现有 Agent 事件和 `createScope()` 维护当前、新建和恢复的 Agent,preset 声明保持不变。只有详情页的显式操作通过现有设置表单修改新会话默认模式,启用开关不配置 PTC 执行方式。
|
||||
+2
-2
@@ -18,8 +18,8 @@
|
||||
en: 518206f94d82993d
|
||||
zh: c6cab3b2f71dd18b
|
||||
/agent-note-incremental-tool-argument-scanning-and-argument-order-during-preparation/decision/argument-declaration-order:
|
||||
en: 0fd7c9f0b8cf6a28
|
||||
zh: 7d410403283b9996
|
||||
en: caae19337804cef4
|
||||
zh: 887186eeb8bd36f8
|
||||
/agent-note-incremental-tool-argument-scanning-and-argument-order-during-preparation/alternatives-considered:
|
||||
en: 7a033f81c557c58f
|
||||
zh: 2ec66b0db6cf5d9e
|
||||
|
||||
@@ -49,7 +49,7 @@ Third-party tools receive the same view without registration or a separate subsc
|
||||
|
||||
### Argument declaration order
|
||||
|
||||
`tool-bash` and `tool-pwsh` declare `description` before `command` and include the ordering instruction. Both `parameters` declarations of `run_code` put `description` before `code` and share a parameter description requesting that generation order for TypeScript and Python. Write/edit declare `file_path` first and ask for it before `content` or `old_string`/`new_string` in the path parameter description. Read retains its leading `file_path`; other tools retain their argument order.
|
||||
`tool-bash` and `tool-pwsh` declare `description` before `command` and include the ordering instruction. `run_code` puts `code` before `description` in both its static parameters and program-format-aware schema; it does not require a JSON member order. Write/edit declare `file_path` first and ask for it before `content` or `old_string`/`new_string` in the path parameter description. Read retains its leading `file_path`; other tools retain their argument order.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ Assembler 为同一输入和生命周期角色共享一个不可变 Match 及其
|
||||
|
||||
### 参数声明顺序
|
||||
|
||||
`tool-bash`、`tool-pwsh` 在 `command` 前声明 `description`,并包含顺序指令。`run_code` 两处 `parameters` 将 `description` 放在 `code` 前,共用的参数描述要求 TypeScript 和 Python 都按此顺序生成。write/edit 首先声明 `file_path`,并在路径参数描述中要求先生成它,再生成 `content` 或 `old_string`/`new_string`。read 保留首位的 `file_path`;其他工具保留原有参数顺序。
|
||||
`tool-bash`、`tool-pwsh` 在 `command` 前声明 `description`,并包含顺序指令。`run_code` 的静态参数与按程序格式投影的 schema 都将 `code` 放在 `description` 前,不要求 JSON 成员顺序。write/edit 首先声明 `file_path`,并在路径参数描述中要求先生成它,再生成 `content` 或 `old_string`/`new_string`。read 保留首位的 `file_path`;其他工具保留原有参数顺序。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
|
||||
+4
-4
@@ -9,8 +9,8 @@
|
||||
en: 3658160e034e0e58
|
||||
zh: 980d922aded8713b
|
||||
/agent-note-peer-scoped-connect-handshake/decision:
|
||||
en: 414dfe949a53c4d9
|
||||
zh: 7e6efdd57f2eb240
|
||||
en: 6d84e6633c7f2aa8
|
||||
zh: 11d09a4efb5cf570
|
||||
/agent-note-peer-scoped-connect-handshake/decision/admission-and-ownership:
|
||||
en: 95ad4c8c433fdc9b
|
||||
zh: 379ccd5e077d7dee
|
||||
@@ -27,5 +27,5 @@
|
||||
en: 81ce03ab4e1fd0d4
|
||||
zh: c2729e7e2db56f67
|
||||
/agent-note-peer-scoped-connect-handshake/consequences:
|
||||
en: 91f5f80f733c174c
|
||||
zh: 76cbb31b0d2e8764
|
||||
en: 52b687e9b5906c59
|
||||
zh: 9eb9c740e2873f70
|
||||
+2
-2
@@ -10,7 +10,7 @@ Automatically subscribing automation clients to forwarded events lets method-onl
|
||||
|
||||
## Decision
|
||||
|
||||
Browsers retain their existing signed Cookie, root launch-token exchange, shared `connection.browserPeer` with owner principal and `interactions: 'answer'`, and recovery behavior. Only API callers create independent Peers through `GET /connect?token=<launch-token>&interactions=answer|none`. The endpoint is API-only, defaults to `none`, rejects invalid or repeated declarations with 400, and retains Host/Origin checks and token authentication. It returns 302 with the Remote Mux destination and an API Cookie.
|
||||
Browsers retain their existing signed Cookie, root launch-token exchange, the Token Provider's shared Peer with owner principal and `interactions: 'answer'`, and recovery behavior. Only API callers create independent Peers through `GET /connect?token=<launch-token>&interactions=answer|none`. The endpoint is API-only, defaults to `none`, rejects invalid or repeated declarations with 400, and retains Host/Origin checks and token authentication. It returns 302 with the Remote Mux destination and an API Cookie.
|
||||
|
||||
### Admission and ownership
|
||||
|
||||
@@ -52,4 +52,4 @@ The [recorded approval scenario](../../../../apps/web/tests/approval-composer.e2
|
||||
|
||||
Unconnected API records need not be promptly reclaimed; resource-heavy additions to idle Peers require revisiting that choice. API Cookies cannot restore a Peer after its socket closes or the Host restarts. Browser Cookie format and authentication behavior remain unchanged, with no reauthentication migration. API and browser Cookies use the same authority-specific name, so API callers keep their own Cookie storage rather than exchanging credentials in a shared browser jar. Any launch-token holder may request `answer`; this is interaction participation, not user isolation.
|
||||
|
||||
The [duplex-stream decision](2026-09-19-remote-duplex-stream.md) retains Peer scopes and stream framing. The [browser authentication decision](2026-08-24-browser-token-authentication.md) retains browser token, signature, authority, and lifetime semantics; only independent API admission is added here. Both records remain active.
|
||||
The [duplex-stream decision](2026-09-19-remote-duplex-stream.md) retains Peer scopes and stream framing. The [browser authentication decision](2026-08-24-browser-token-authentication.md) retains browser token, signature, authority, and lifetime semantics; only independent API admission is added here. Both records remain active. The [Provider integration](2026-11-07-browser-authentication-development.md) owns the current registration and Socket-middleware placement without replacing this protocol and lifetime decision.
|
||||
+2
-2
@@ -10,7 +10,7 @@ Status: implemented
|
||||
|
||||
## 决策
|
||||
|
||||
浏览器保留现有签名 Cookie、根路径 launch token 交换、共享 `connection.browserPeer` 和恢复行为。只有 API 调用方通过 `GET /connect?token=<launch-token>&interactions=answer|none` 创建独立 Peer。该端点仅供 API 使用,默认 `none`,非法或重复声明返回 400,并保留 Host/Origin 检查和 token 认证。它返回 302、Remote Mux 目标地址和 API Cookie。
|
||||
浏览器保留现有签名 Cookie、根路径 launch token 交换、Token Provider 持有的共享 owner Peer(`interactions: 'answer'`)和恢复行为。只有 API 调用方通过 `GET /connect?token=<launch-token>&interactions=answer|none` 创建独立 Peer。该端点仅供 API 使用,默认 `none`,非法或重复声明返回 400,并保留 Host/Origin 检查和 token 认证。它返回 302、Remote Mux 目标地址和 API Cookie。
|
||||
|
||||
### 接纳与所有权
|
||||
|
||||
@@ -52,4 +52,4 @@ Connection 测试覆盖 API 发布、Cookie 校验、闲置保留、连接所有
|
||||
|
||||
未建联的 API 记录不要求及时回收;若为空闲 Peer 增加重资源,必须重新评估这一取舍。连接关闭或 Host 重启后,API Cookie 不能恢复 Peer。浏览器 Cookie 格式与认证行为保持不变,无需重新认证迁移。API 与浏览器 Cookie 使用同一 authority 专属名称,因此 API 调用方维护自己的 Cookie 存储,不在共享浏览器 Cookie jar 中交换凭证。任何 launch token 持有者都可以请求 `answer`;这是交互参与,不是用户隔离。
|
||||
|
||||
[双工流决策](2026-09-19-remote-duplex-stream.zh.md)继续定义 Peer 作用域和流帧格式。[浏览器认证决策](2026-08-24-browser-token-authentication.zh.md)保留浏览器 token、签名、authority 与有效期语义;本记录只增加独立 API 接纳。两份既有记录继续保留。
|
||||
[双工流决策](2026-09-19-remote-duplex-stream.zh.md)继续定义 Peer 作用域和流帧格式。[浏览器认证决策](2026-08-24-browser-token-authentication.zh.md)保留浏览器 token、签名、authority 与有效期语义;本记录只增加独立 API 接纳。两份既有记录继续保留。[Provider 接入说明](2026-11-07-browser-authentication-development.zh.md)拥有当前注册与 Socket 中间件的实现位置,不取代本协议与生命周期决策。
|
||||
+2
-2
@@ -30,8 +30,8 @@
|
||||
en: 99ee505e82fa9c7c
|
||||
zh: 448bc0e160424cbf
|
||||
/agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/consequences:
|
||||
en: 53d72faa09e78410
|
||||
zh: a5224e4662a4846b
|
||||
en: ed424571c81bcb91
|
||||
zh: 9b79bf03741c1c21
|
||||
/agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/testing:
|
||||
en: 532918df1acd147d
|
||||
zh: e476c090d183d0a4
|
||||
+1
-1
@@ -81,7 +81,7 @@ The Worker's structural stubs throw errors carrying `ERR_FEATURE_UNAVAILABLE_ON_
|
||||
|
||||
## Consequences
|
||||
|
||||
The Preview boots the composition the served Web deployment boots. With no bundle enabled, the Worker composition differs from the served Web composition only by the jsonl platform override, and enabling any bundle skips no patch. The Plugins page and Settings → Built-in plugins list every `OPTIONAL_BUNDLES` entry with its title and icon and no metadata error. Switching each of the 11 optional bundles on and then off returns `applied` both times; after enabling, every enabled row it changes is active, and after disabling, the plugin list returns to its prior rows. Enabling session-titles disables `@deepseek-ai/dsh-session-title-first-prompt-llm` (row `session-title-llm`) and enables `@deepseek-ai/dsh-session-title-all-prompts-llm`, as in the served Web deployment; enabling inspector-profile runs Session Inspector and starts the NodeJS Inspector degraded. Degradation requires `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`, so a served `dsh web` runs the full Inspector.
|
||||
The Preview boots the composition the served Web deployment boots. With no bundle enabled, the Worker composition differs from the served Web composition only by the jsonl platform override, and enabling any bundle skips no patch. The Plugins page lists every `OPTIONAL_BUNDLES` entry with its title and icon and no metadata error. Switching each of the 11 optional bundles on and then off returns `applied` both times; after enabling, every enabled row it changes is active, and after disabling, the plugin list returns to its prior rows. Enabling session-titles disables `@deepseek-ai/dsh-session-title-first-prompt-llm` (row `session-title-llm`) and enables `@deepseek-ai/dsh-session-title-all-prompts-llm`, as in the served Web deployment; enabling inspector-profile runs Session Inspector and starts the NodeJS Inspector degraded. Degradation requires `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`, so a served `dsh web` runs the full Inspector.
|
||||
|
||||
Size (MiB, measured): the base image is 9.20 (12.79 with pack-time composition and eager chunks, −28%) including 11 optional bundles, plus 5 lazy tar archives totaling 4.45 (pdf 2.88, excel 1.39, terminal 0.13, frontmatter 0.05, Inspector bottom panel 0.00). The base image contains no lazily loaded chunk, and the page fetches an archive only when it requests the chunk.
|
||||
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ Worker 的结构化 stub 抛出带 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 的错
|
||||
|
||||
## 后果
|
||||
|
||||
Preview 启动的组合与正式 Web 相同。不开 bundle 时,Worker 组合与正式 Web 只差 jsonl 的平台覆盖;开任一 bundle 都没有被跳过的补丁。插件页和“设置 → 内置插件”列出全部 `OPTIONAL_BUNDLES`,每个都显示标题和图标,没有元信息错误。11 个 optional bundle 逐个开启再关闭,两次都返回 `applied`;开启后它改动的每个启用行都是 active,关闭后插件列表恢复原样。启用 session-titles 会禁用 `@deepseek-ai/dsh-session-title-first-prompt-llm`(行 `session-title-llm`)并启用 `@deepseek-ai/dsh-session-title-all-prompts-llm`,与正式 Web 一致;启用 inspector-profile 后 Session Inspector 运行,NodeJS Inspector 降级启动。降级以 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 为前提,所以正常 `dsh web` 运行完整的 Inspector。
|
||||
Preview 启动的组合与正式 Web 相同。不开 bundle 时,Worker 组合与正式 Web 只差 jsonl 的平台覆盖;开任一 bundle 都没有被跳过的补丁。插件页列出全部 `OPTIONAL_BUNDLES`,每个都显示标题和图标,没有元信息错误。11 个 optional bundle 逐个开启再关闭,两次都返回 `applied`;开启后它改动的每个启用行都是 active,关闭后插件列表恢复原样。启用 session-titles 会禁用 `@deepseek-ai/dsh-session-title-first-prompt-llm`(行 `session-title-llm`)并启用 `@deepseek-ai/dsh-session-title-all-prompts-llm`,与正式 Web 一致;启用 inspector-profile 后 Session Inspector 运行,NodeJS Inspector 降级启动。降级以 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 为前提,所以正常 `dsh web` 运行完整的 Inspector。
|
||||
|
||||
体积(MiB,实测):基础镜像 9.20(打包期组合且 chunk 随启动下载时为 12.79,−28%),含 11 个 optional bundle;另有 5 个 lazy tar 共 4.45(pdf 2.88、excel 1.39、terminal 0.13、frontmatter 0.05、inspector 底部面板 0.00)。基础镜像不含懒加载 chunk,页面请求 chunk 时才拉取对应 archive。
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-05-client-module-metadata.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-05-client-module-metadata.md
|
||||
/agent-note-client-metadata-and-renderer-owned-stylesheet-installation:
|
||||
en: 4f12a147e4cbe9a6
|
||||
zh: 8021e4c1c8fd2d4b
|
||||
/agent-note-client-metadata-and-renderer-owned-stylesheet-installation/problem:
|
||||
en: 590dbd303b44e903
|
||||
zh: b536f88e6fcdbce2
|
||||
/agent-note-client-metadata-and-renderer-owned-stylesheet-installation/decision:
|
||||
en: a52f47f300542068
|
||||
zh: 261fdf1cdc37e95d
|
||||
/agent-note-client-metadata-and-renderer-owned-stylesheet-installation/alternatives-considered:
|
||||
en: 7e410e5f19c4ded2
|
||||
zh: f09d8d8ae2e7ac93
|
||||
/agent-note-client-metadata-and-renderer-owned-stylesheet-installation/consequences:
|
||||
en: 2db1d05ddc19891c
|
||||
zh: b5affd079824a7cd
|
||||
@@ -0,0 +1,33 @@
|
||||
# Agent Note: Client metadata and renderer-owned stylesheet installation
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-05-client-module-metadata.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
A script's execution environment need not be its presentation document. CSS injection embedded in JavaScript factories couples those destinations and makes module loading responsible for DOM cleanup. Inferring stylesheet ownership from React components would add component-level tracking without reliable source-file identity.
|
||||
|
||||
## Decision
|
||||
|
||||
Client artifacts contain `id` and `factory`, with optional `meta` and a `chunk` name for dynamic package-local chunks. `meta()` returns resource descriptions; `stylesheets` is an optional path-keyed record whose values expose independently evaluated `text(context)` functions. Resource paths identify stylesheets, not components. There is no stylesheet dependency field.
|
||||
|
||||
Modules owns JavaScript exports, module identity, owner ids, and observed dependency edges. It retains metadata functions without evaluating them and publishes generic module-record changes. Renderer owns metadata/text caches, dependency-ordered stylesheet collection, path deduplication, and main-document nodes. It explicitly installs existing resources before React mounting, updates them on module changes, and releases styles after the root unmounts. Component lifetimes do not own styles.
|
||||
|
||||
Static library builds keep their index artifact as ordinary ESM with all imports and dynamic imports for final shell assembly, and add the `__$dsh_client_module_manifest` export carrying the same manifest. The boot shell itself remains ordinary ESM. Modules wraps the existing carrier loading hook in its built-in Main environment; optional Realm providers do not change default startup or select plugin placement.
|
||||
|
||||
This decision refines the resource handling in the [loading model](2026-07-23-client-plugin-loading-model.md) and the artifact description in [shell layering](2026-08-15-client-shells-and-dynamic-packages.md). Their module identity, bootstrap, and dependency separation remain active; neither note is fully superseded.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**CSS DOM operations inside each factory.** They target the script's globals and hide presentation effects in module evaluation; metadata separates data production from installation.
|
||||
|
||||
**Component analysis, Hooks, or Slot ownership metadata.** The required lifetime is module-level, so precise component tracking adds allocation and cleanup without a required capability.
|
||||
|
||||
**Reuse the dynamic plugin's private-dependency bundling for static libraries.** It moves third-party lazy chunking and font delivery into package builds, changing the established shell dependency policy. Static libraries retain that policy instead.
|
||||
|
||||
**Document Scope and an early Realm activation phase.** Neither is required when all modules use the existing Main carrier and all styles target the main document. Isolation requests, environment allocation, and multiple presentation destinations remain separate work.
|
||||
|
||||
## Consequences
|
||||
|
||||
Modules has no stylesheet query or subscription API. A stylesheet failure is reported by the renderer consumer, not a JavaScript factory failure: the renderer leaves out the failing stylesheet, reports it once, and installs the rest, so one module cannot block application mounting or the styles of modules that load later. Live replacement keeps the previous records in `activeRecords()` until the replaced runtime has been torn down, so a running plugin keeps its styles through a pending or failed download. Styles for materialized but currently invisible components remain installed until module invalidation or renderer disposal. Source-level business imports still receive the original exports through factory-backed `require`.
|
||||
@@ -0,0 +1,33 @@
|
||||
# Agent Note: Client 元信息与 Renderer 持有的样式安装
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-05-client-module-metadata.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
脚本执行环境不一定是其呈现文档。JavaScript factory 内的 CSS 注入把两者耦合,并让模块加载负责 DOM 清理。从 React 组件推断样式归属会增加组件级跟踪,却无法获得可靠的源文件对应关系。
|
||||
|
||||
## Decision
|
||||
|
||||
Client 产物包含 `id` 和 `factory`,可选带有 `meta`,动态包内 chunk 另带 `chunk` 名称。`meta()` 返回资源描述;可选的 `stylesheets` 是以路径为键的字典,每个值提供独立求值的 `text(context)` 函数。资源路径标识样式表,而不是组件。当前没有样式表依赖字段。
|
||||
|
||||
Modules 拥有 JavaScript 导出、模块身份、owner id 和观察到的依赖边。它保存元信息函数而不求值,发布通用的模块记录变化。Renderer 拥有元信息/文本缓存、依赖有序的样式集合、路径去重与主文档节点。它在 React 挂载前显式安装已有资源,随模块变化更新,并在根卸载后释放样式。组件生命周期不拥有样式。
|
||||
|
||||
静态库构建把 index 产物保持为普通 ESM,保留所有 import 与动态 import 交给最终外壳组装,并增加携带相同 manifest 的 `__$dsh_client_module_manifest` 导出。启动外壳本身保持普通 ESM。Modules 用内建 Main 环境包装原有载体加载 hook;可选 Realm 提供方不改变默认启动,也不选择插件放置。
|
||||
|
||||
本决定细化[加载模型](2026-07-23-client-plugin-loading-model.zh.md)中的资源处理,以及[外壳分层](2026-08-15-client-shells-and-dynamic-packages.zh.md)中的产物描述。两份记录的模块身份、自举和依赖分离仍然有效,没有完全被取代。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**每个 factory 内操作 CSS DOM。** 这会使用脚本的全局对象,并把呈现副作用藏在模块求值中;元信息将数据生成与安装分离。
|
||||
|
||||
**组件分析、Hook 或 Slot 来源元信息。** 所需生命周期是模块级,精确组件跟踪会增加分配和清理,却没有对应的必要能力。
|
||||
|
||||
**静态库复用动态插件的私有依赖打包。** 这会把第三方惰性拆包和字体交付移到包构建,改变既有外壳依赖策略。静态库因此保留原策略。
|
||||
|
||||
**Document Scope 与提前 Realm 激活阶段。** 所有模块使用原 Main 载体、所有样式装到主文档时,不需要这两者。隔离请求、环境分配和多个呈现目的地属于独立工作。
|
||||
|
||||
## Consequences
|
||||
|
||||
Modules 没有样式查询或订阅 API。样式失败由 renderer 消费方报告,不是 JavaScript factory 失败:renderer 不安装失败的样式,报告一次,并安装其余样式,因此单个模块不会阻止应用挂载,也不会影响之后加载的模块的样式。实时替换期间,旧记录保留在 `activeRecords()` 中,直到被替换的运行时完成卸载,因此下载未完成或失败时,运行中的插件仍保有样式。已物化但当前不可见组件的样式保留到模块失效或 renderer 销毁。源码业务 import 仍通过 factory 支持的 `require` 取得原有导出。
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
# Bilingual-pair consistency record for 2026-11-07-browser-authentication-development.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-07-browser-authentication-development.md
|
||||
/agent-note-authentication-provider-integration:
|
||||
en: 1a29efbb24021a72
|
||||
zh: be3ad79af7975a72
|
||||
/agent-note-authentication-provider-integration/problem:
|
||||
en: 670cfd5061a9aa5a
|
||||
zh: 98598c1e45236ed2
|
||||
/agent-note-authentication-provider-integration/decision:
|
||||
en: a15c7c13f167e5ac
|
||||
zh: a15c7c13f167e5ac
|
||||
/agent-note-authentication-provider-integration/decision/register-a-provider-and-own-its-peer:
|
||||
en: 7305dc1791116cf6
|
||||
zh: f23cd0b8161522ee
|
||||
/agent-note-authentication-provider-integration/decision/declare-route-admission-and-consume-the-selected-peer:
|
||||
en: e2b17a8dff46e81c
|
||||
zh: 2391ed8fdf502a30
|
||||
/agent-note-authentication-provider-integration/decision/use-scoped-webserver-events:
|
||||
en: 3f191940167f3f9e
|
||||
zh: 6e4f20d1f66f5454
|
||||
/agent-note-authentication-provider-integration/decision/keep-socket-policy-with-the-issuing-product:
|
||||
en: 59235b955e65e342
|
||||
zh: 76d9314d0a738438
|
||||
/agent-note-authentication-provider-integration/decision/let-webapp-publish-complete-entry-urls:
|
||||
en: 0676f301d5aec364
|
||||
zh: 0ef43eba7bfe2f01
|
||||
/agent-note-authentication-provider-integration/testing:
|
||||
en: c783cb006f9962a4
|
||||
zh: 79bf36b25665e49c
|
||||
/agent-note-authentication-provider-integration/alternatives-considered:
|
||||
en: 868953274abd81e8
|
||||
zh: 1b2890de876a6db6
|
||||
/agent-note-authentication-provider-integration/consequences:
|
||||
en: cf654878d39ce4bc
|
||||
zh: 435687a8da20f294
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
# Agent Note: Authentication Provider integration
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-07-browser-authentication-development.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
In the built-in authentication design, Connection combined BrowserAuth with its transport API, and route owners called its admission helpers. WebApp obtained a tokenized address through Connection. Splitting credential implementations requires concrete registration, route, event, and startup usage that does not put Token knowledge back into a transport or protocol handler.
|
||||
|
||||
The [Provider decision](2026-11-07-browser-authentication-providers.md) owns the rationale, credential compatibility, and equal treatment of Token, Desktop, and future Remote implementations. This note owns their integration with the final APIs.
|
||||
|
||||
## Decision
|
||||
|
||||
### Register a Provider and own its Peer
|
||||
|
||||
The Connection plugin provides the independent nested `connection.authentication` Service. A Provider plugin injects both `connection` and `connection.authentication`: the former creates Peers, while the latter owns registration and credential verification. The access path is a real Cordis service, not a getter constructing a temporary registry object.
|
||||
|
||||
This complete function-plugin example receives a trusted in-process verifier and principal from its Host. Its `Config.verify` is an illustrative application input, not a new DSH API or a substitute for implementing the credential algorithm.
|
||||
|
||||
```ts
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { ConnectionTrustRequest, Principal } from '@deepseek-ai/dsh-client-connection'
|
||||
|
||||
export const name = 'example-authentication'
|
||||
export const inject = ['connection', 'connection.authentication']
|
||||
|
||||
export interface Config {
|
||||
principal: Principal
|
||||
verify(request: ConnectionTrustRequest): boolean
|
||||
}
|
||||
|
||||
export function apply(ctx: Context, config: Config): void {
|
||||
const peer = ctx.connection.createPeer({ principal: config.principal })
|
||||
ctx.connection.authentication.register({
|
||||
authenticate(request) {
|
||||
return config.verify(request) ? peer : undefined
|
||||
},
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
`createPeer` owns the Peer under the calling plugin scope; `register` owns the registration under that same caller scope. A shared-identity Provider retains one Peer as above. A session-based Provider instead retains its own credential-to-Peer records and returns the corresponding existing Peer. The Host fixes `principal` and optional `interactions` at creation; neither is a client-selected authorization claim.
|
||||
|
||||
`register` returns an asynchronous disposer whose call synchronously withdraws the record. Authentication snapshots registration order, skips records withdrawn during verification, and rechecks a returned Peer and the request before accepting. New registrations participate in subsequent requests. `authenticate` returns the first live Peer,401 for ordinary refusal, or503 when a verifier failed and none succeeded. Source rejection remains Connection's separate403 decision. The [implementation](../../../../packages/client/connection/src/authentication.ts) contains these lifecycle checks.
|
||||
|
||||
### Declare route admission and consume the selected Peer
|
||||
|
||||
`register`, `registerFallback`, and `registerUpgrade` accept `auth: 'anonymous' | 'required' | 'deny'` or a synchronous selector. The default is `required`. WebServer matches first, applies policy, obtains Connection's source and credential decision, and passes the selected Peer to the handler. `deny` rejects without invoking authentication; with no authorization listener, `required` returns503 and `anonymous` permits access.
|
||||
|
||||
The example below registers ordinary business handlers. The Host supplies `Config.upgrade`, its existing protocol implementation; it is not another framework operation. The HTTP assertion reflects this route's `required` policy, while the shared handler type also supports anonymous routes with no Peer.
|
||||
|
||||
```ts
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
|
||||
|
||||
export const name = 'example-protected-routes'
|
||||
export const inject = ['webServer']
|
||||
|
||||
export interface Config {
|
||||
upgrade: WebUpgradeRoute['handler']
|
||||
}
|
||||
|
||||
export function apply(ctx: Context, config: Config): void {
|
||||
ctx.effect(() => ctx.webServer.register({
|
||||
kind: 'exact',
|
||||
path: '/identity',
|
||||
auth: 'required',
|
||||
handler(_req, res, peer) {
|
||||
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })
|
||||
res.end(peer!.id)
|
||||
},
|
||||
}))
|
||||
ctx.effect(() => ctx.webServer.registerUpgrade({
|
||||
path: '/example/socket',
|
||||
auth: 'required',
|
||||
handler: config.upgrade,
|
||||
}))
|
||||
}
|
||||
```
|
||||
|
||||
HTTP handlers receive `(req, res, peer?)`, upgrade handlers receive `(req, socket, head, peer?)`, and resources retain `resource(request, peer?)`. Business handlers do not run another Provider pass. Direct administration routes outside Gateway, including Inspector and open-in-app, require an owner Peer before accessing Host resources. Trusted in-process `readResource(request, peer)` keeps its explicit Peer without network source or credential checks, but still honors `deny`. Admission failures carry `Cache-Control: no-store`.
|
||||
|
||||
### Use scoped WebServer events
|
||||
|
||||
Every WebServer event has the corresponding WebServer as its Cordis thisArg. Request dispatch uses the service instance; WebApp entry collection passes `ctx.webServer`. Ordinary listeners match the `webServer` isolation of that subject, including the existing index-injection event. `{ global: true }` explicitly receives events across service isolations in the same application. Peer data does not select event listeners. The [WebServer reference](../../../../packages/host/webserver/README.md) defines custom-carrier obligations.
|
||||
|
||||
| Event | Mode | Final integration |
|
||||
|---|---|---|
|
||||
| `webserver/request` | waterfall | Runs before route selection; Token exchanges root Token queries, and the account plugin handles its validated OAuth callback |
|
||||
| `webserver/authorize` | bail | Resolves the matched route's source and credential admission; the first decision wins |
|
||||
| `webserver/upgrade` | waterfall | Runs after admission and before the protocol handler, carrying the already selected Peer |
|
||||
| `webserver/index-inject` | emit | Collects page or Worker startup data for the supplied Peer within the server isolation |
|
||||
| `webserver/entry-url` | emit | Collects complete entry URLs for the supplied base address within the server isolation |
|
||||
|
||||
Waterfall listeners own the response or Socket when they handle a request; otherwise they await `next()`. Exceptions are contained by the carrier and end that response or Socket. Source policy is not disabled for every anonymous route to accommodate a login protocol.
|
||||
|
||||
The account plugin registers a temporary callback listener before generic admission. It matches the initiating redirect URI's authority and exact path, then preserves GET, single state/code values, constant-time state comparison, active-attempt checks, expiry, cancellation, and S256 PKCE. Thus a valid cross-site browser return can finish without bypassing those checks or weakening unrelated anonymous routes. The listener leaves with the attempt; it does not import a WebServer implementation helper.
|
||||
|
||||
### Keep Socket policy with the issuing product
|
||||
|
||||
Token's listener sits beside its `/connect` route and acts only on `/api/remote.mux`. It recognizes its own API Peer by map identity, rejects a second mux Socket with409, and synchronously removes the credential before awaiting Peer and Socket cleanup. Closing an Inspector CDP Socket does not claim or revoke that API session. Other Providers retain their own lifetime policies; Gateway only performs protocol upgrade with the supplied Peer.
|
||||
|
||||
An upgrade fixes the Peer for that connection. Later HTTP requests authenticate again. Token's shared browser Peer survives individual Socket closure; an API Peer follows its existing mux lifetime. Already-admitted unary calls retain their cancellation scope. The [mux regression](../../../../packages/api/gateway/tests/operator-connect.host.spec.ts) and [API connect decision](2026-10-09-operator-scoped-connect-handshake.md) cover this distinction.
|
||||
|
||||
### Let WebApp publish complete entry URLs
|
||||
|
||||
WebApp keeps `publicUrl`, `printUrl`, and `openBrowser`; both output flags default true. After Loader settlement and startup audit, it emits `webserver/entry-url` with its WebServer subject, ordinary base URL, and an initially empty `WebEntryUrl[]`. Each entry carries `label`, complete `url`, and boolean `open`.
|
||||
|
||||
Token contributes its signed `dsh web` URL without reading WebApp services. A Provider with no user-facing entry contributes nothing; another product can contribute its own label and complete URL. WebApp prints each `label: url` line when enabled, and opens only the first `open: true` entry when browser opening is enabled outside SSH. An empty list causes no output or browser opening. The process credential remains sensitive even though the integration exposes no raw Token getter.
|
||||
|
||||
Desktop's parent owns a fresh private credential per Host process and delivers it before ready. The Desktop Provider creates its Peer and registers verification through the same authentication Service. Electron uses its locally assembled `authenticationCookie`; runtime smoke and other parent-process consumers do not attempt a Token exchange using the ordinary ready URL. Renderer startup data and the wire ready message contain no private credential.
|
||||
|
||||
## Testing
|
||||
|
||||
| Affected behavior | Before | Final behavior and coverage |
|
||||
|---|---|---|
|
||||
| Provider registration | Only built-in BrowserAuth supplied network identity | Ordered independent verifiers select one live Peer; scope unload, verifier failure, and cancellation are covered by [authentication tests](../../../../packages/client/connection/tests/authentication.host.spec.ts) |
|
||||
| HTTP and upgrade integration | Consumers called Connection admission | Route auth supplies the Peer once; real [Provider transport tests](../../../../packages/api/gateway/tests/authentication-provider.host.spec.ts) exercise both carriers |
|
||||
| Server isolation | Route tables were per instance; index injection was root-wide | All five events use the WebServer subject; [server](../../../../packages/host/webserver/tests/event-isolation.host.spec.ts) and [application](../../../../packages/bundle/web-app/tests/event-isolation.host.spec.ts) tests cover ordinary and global listeners and a preserved external Host |
|
||||
| Browser OAuth return | The callback validated state and PKCE | The scoped pre-route callback retains validation and accepts real cross-site navigation; [account tests](../../../../packages/credentials/deepseek-account/tests/account.spec.ts) retain wrong-Host and SSH-forwarding coverage, and [Chromium](../../../../apps/web/tests/account-login.e2e.ts) asserts the actual Fetch Metadata header |
|
||||
| Startup output | WebApp printed/opened one Connection-produced login URL | [Startup tests](../../../../packages/bundle/web-app/tests/startup.host.spec.ts) cover ordered entries, first eligible opening, empty lists, readiness and SSH suppression |
|
||||
| Desktop runtime consumers | A tokenized ready URL was exchanged for a Cookie | [Runtime smoke tests](../../../../apps/desktop/tests/smoke-runtime.spec.ts) use the private Cookie on the HTTP probes; [built Remote tests](../../../../packages/api/remotes/tests/built-lib.e2e.ts) collect the current Provider's entry and pass the admitted Peer |
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Keep authentication behind per-request wrappers on Connection.** A separately registered Service exposes its ownership and required injection directly; it does not allocate a facade each time a consumer reads authentication.
|
||||
|
||||
**Add another route table or a request-context container.** Existing WebServer registrations already own dispatch, and Peer is the identity consumed downstream. Route policy and a trailing Peer parameter keep those owners intact.
|
||||
|
||||
**Pass an extra WebServer field in every request.** Cordis already supports a service subject and isolation filter. Using that mechanism also scopes page injection and entry collection without adding payload fields.
|
||||
|
||||
**Give Token the WebApp address service or browser opener.** That creates a reverse dependency on the composing bundle. WebApp owns publication timing and actions; Providers contribute complete entries through the shared event.
|
||||
|
||||
## Consequences
|
||||
|
||||
Credential implementations need no Gateway change, but custom carriers must emit events with their WebServer subject and pass the admitted Peer to protocol handlers. Plugins consuming the nested authentication service declare `connection.authentication` in their injections. Explicitly global event listeners remain responsible for whether sharing data across server instances is appropriate.
|
||||
|
||||
Removing a Provider registration and disposing its Peer are distinct operations. A product that shares one Peer also shares its termination scope; a product with independent credentials owns its own Peer records and revocation policy. The integration adds neither a universal Socket policy nor another authentication privilege tier.
|
||||
|
||||
The [Provider decision](2026-11-07-browser-authentication-providers.md) owns protocol compatibility and deployment consequences. The [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.md) owns manual configuration migration and carrier updates; this record describes the implemented integration rather than a future Remote product.
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
# Agent Note: 认证 Provider 接入
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-07-browser-authentication-development.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
在内置认证设计中,Connection 同时包含 BrowserAuth 和传输 API,路由 owner 调用它的准入辅助方法。WebApp 通过 Connection 取得带 Token 的地址。拆分凭据实现需要明确的注册、路由、事件和启动用法,不能把 Token 知识重新放回传输或协议 handler。
|
||||
|
||||
[Provider 决策](2026-11-07-browser-authentication-providers.zh.md)拥有动机、凭据兼容性,以及 Token、Desktop 和未来 Remote 实现的平级处理规则。本文记录它们与最终 API 的接线。
|
||||
|
||||
## Decision
|
||||
|
||||
### 注册 Provider 并持有 Peer
|
||||
|
||||
Connection 插件提供独立嵌套服务 `connection.authentication`。Provider 插件同时注入 `connection` 和 `connection.authentication`:前者创建 Peer,后者拥有注册与凭据验证。该访问路径是真正的 Cordis 服务,不是构造临时注册表对象的 getter。
|
||||
|
||||
下面的完整函数插件示例由 Host 提供可信进程内验证器和 principal。其中 `Config.verify` 是示例的应用输入,不是新 DSH API,也不代替具体凭据算法的实现。
|
||||
|
||||
```ts
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { ConnectionTrustRequest, Principal } from '@deepseek-ai/dsh-client-connection'
|
||||
|
||||
export const name = 'example-authentication'
|
||||
export const inject = ['connection', 'connection.authentication']
|
||||
|
||||
export interface Config {
|
||||
principal: Principal
|
||||
verify(request: ConnectionTrustRequest): boolean
|
||||
}
|
||||
|
||||
export function apply(ctx: Context, config: Config): void {
|
||||
const peer = ctx.connection.createPeer({ principal: config.principal })
|
||||
ctx.connection.authentication.register({
|
||||
authenticate(request) {
|
||||
return config.verify(request) ? peer : undefined
|
||||
},
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
`createPeer` 将 Peer 归入调用插件的作用域,`register` 将注册归入相同调用方作用域。共享身份的 Provider 像示例一样持有一个 Peer;按会话区分的 Provider 则持有自己的凭据到 Peer 记录,并返回对应的已有 Peer。Host 在创建时固定 `principal` 和可选 `interactions`,两者都不是客户端自行声明的授权信息。
|
||||
|
||||
`register` 返回异步 disposer,调用时同步撤销记录。认证读取注册顺序快照,跳过验证过程中撤销的记录,并在采用结果前复核 Peer 与请求。新注册参与后续请求。`authenticate` 返回首个存活 Peer、普通拒绝的401,或存在验证故障且无人成功时的503。来源拒绝仍是 Connection 单独作出的403决策。[实现](../../../../packages/client/connection/src/authentication.ts)包含这些生命周期检查。
|
||||
|
||||
### 声明路由准入并使用选定的 Peer
|
||||
|
||||
`register`、`registerFallback` 与 `registerUpgrade` 接受 `auth: 'anonymous' | 'required' | 'deny'` 或同步选择器,默认值为 `required`。WebServer 先匹配路由、应用策略,再取得 Connection 的来源与凭据决策,并把选定 Peer 交给 handler。`deny` 不调用认证即拒绝;没有准入监听者时,`required` 返回503,`anonymous` 允许访问。
|
||||
|
||||
下面的示例注册普通业务 handler。Host 提供 `Config.upgrade`,即业务已有的协议实现,并非另一个框架操作。HTTP 中的断言对应此路由的 `required` 策略;公共 handler 类型同时支持没有 Peer 的匿名路由。
|
||||
|
||||
```ts
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
|
||||
|
||||
export const name = 'example-protected-routes'
|
||||
export const inject = ['webServer']
|
||||
|
||||
export interface Config {
|
||||
upgrade: WebUpgradeRoute['handler']
|
||||
}
|
||||
|
||||
export function apply(ctx: Context, config: Config): void {
|
||||
ctx.effect(() => ctx.webServer.register({
|
||||
kind: 'exact',
|
||||
path: '/identity',
|
||||
auth: 'required',
|
||||
handler(_req, res, peer) {
|
||||
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })
|
||||
res.end(peer!.id)
|
||||
},
|
||||
}))
|
||||
ctx.effect(() => ctx.webServer.registerUpgrade({
|
||||
path: '/example/socket',
|
||||
auth: 'required',
|
||||
handler: config.upgrade,
|
||||
}))
|
||||
}
|
||||
```
|
||||
|
||||
HTTP handler 接收 `(req, res, peer?)`,upgrade handler 接收 `(req, socket, head, peer?)`,resource 保留 `resource(request, peer?)`。业务 handler 不再遍历 Provider。Gateway 之外的直接管理路由(包括 Inspector 和 open-in-app)在访问 Host 资源前要求 owner Peer。可信进程内 `readResource(request, peer)` 保留显式 Peer,不执行网络来源或凭据检查,但仍遵守 `deny`。准入拒绝响应携带 `Cache-Control: no-store`。
|
||||
|
||||
### 使用有作用域的 WebServer 事件
|
||||
|
||||
每个 WebServer 事件都以对应 WebServer 为 Cordis thisArg。请求分发使用该服务实例,WebApp 入口收集传入 `ctx.webServer`。普通监听器匹配该 subject 的 `webServer` isolation,包括已有的 index 注入事件。`{ global: true }` 明确接收同一应用中跨服务隔离的事件。Peer 数据不选择事件监听器。[WebServer 参考](../../../../packages/host/webserver/README.zh.md)定义自定义载体的要求。
|
||||
|
||||
| 事件 | 模式 | 最终接线 |
|
||||
|---|---|---|
|
||||
| `webserver/request` | waterfall | 在路由选择前执行;Token 处理根 Token query 交换,账号插件处理经过校验的 OAuth 回调 |
|
||||
| `webserver/authorize` | bail | 判断已匹配路由的来源与凭据准入,采用首个决策 |
|
||||
| `webserver/upgrade` | waterfall | 在准入后、协议 handler 前执行,携带已选定的 Peer |
|
||||
| `webserver/index-inject` | emit | 在服务器隔离范围内,为传入 Peer 收集页面或 Worker 启动数据 |
|
||||
| `webserver/entry-url` | emit | 在服务器隔离范围内,为传入基地址收集完整入口 URL |
|
||||
|
||||
Waterfall 监听器处理请求时拥有响应或 Socket,否则等待 `next()`。异常由载体容纳,并结束对应响应或 Socket。为支持登录协议,不会对所有匿名路由关闭来源策略。
|
||||
|
||||
账号插件在通用准入前注册临时回调监听器。它匹配发起登录时 redirect URI 的 authority 和精确路径,再保留 GET、单值 state/code、常量时间 state 比较、活动尝试检查、有效期、取消和 S256 PKCE。因此合法跨站浏览器返回可以完成,而不绕过这些校验,也不放宽无关匿名路由。监听器随尝试结束而移除,不导入 WebServer 实体辅助函数。
|
||||
|
||||
### Socket 策略归凭据签发产品
|
||||
|
||||
Token 监听器位于 `/connect` 路由旁,仅处理 `/api/remote.mux`。它按映射表对象身份识别自己的 API Peer,以409拒绝第二条 mux Socket,并在等待 Peer 和 Socket 清理前同步移除凭据。关闭 Inspector CDP Socket 不会认领或撤销该 API 会话。其他 Provider 保留各自生命周期策略;Gateway 只以传入的 Peer 执行协议升级。
|
||||
|
||||
Upgrade 为该连接固定 Peer,后续 HTTP 请求重新认证。Token 的浏览器共享 Peer 不随单条 Socket 关闭而结束,API Peer 则遵循已有 mux 生命周期。已经准入的一元调用保留自身取消作用域。[mux 回归](../../../../packages/api/gateway/tests/operator-connect.host.spec.ts)和 [API connect 决策](2026-10-09-operator-scoped-connect-handshake.zh.md)覆盖这个区别。
|
||||
|
||||
### WebApp 发布完整入口 URL
|
||||
|
||||
WebApp 保留 `publicUrl`、`printUrl` 和 `openBrowser`,两个输出开关默认均为 true。Loader 装配结束并完成启动审计后,它发出 `webserver/entry-url`,传入自己的 WebServer subject、普通基地址和初始为空的 `WebEntryUrl[]`。每条入口包含 `label`、完整 `url` 和布尔值 `open`。
|
||||
|
||||
Token 不读取 WebApp 服务,只贡献带签名的 `dsh web` URL。没有用户入口的 Provider 不贡献条目,其他产品可以贡献自己的 label 和完整 URL。启用打印时,WebApp 逐行输出 `label: url`;启用浏览器打开且不在 SSH 下时,只打开首个 `open: true` 条目。空列表不产生输出或浏览器打开。即使接线未公开原始 Token getter,进程凭据仍是敏感信息。
|
||||
|
||||
Desktop 父进程为每个 Host 进程持有新私有凭据,并在 ready 前交付。Desktop Provider 创建 Peer,通过相同认证服务注册验证。Electron 使用本地组装的 `authenticationCookie`;runtime smoke 等父进程消费者不使用普通 ready URL 尝试 Token 交换。Renderer 启动数据和 wire ready 消息不含私有凭据。
|
||||
|
||||
## Testing
|
||||
|
||||
| 受影响行为 | 原行为 | 最终行为与覆盖 |
|
||||
|---|---|---|
|
||||
| Provider 注册 | 只有内置 BrowserAuth 提供网络身份 | 有序独立验证器选择一个存活 Peer;[认证测试](../../../../packages/client/connection/tests/authentication.host.spec.ts)覆盖作用域卸载、验证故障和取消 |
|
||||
| HTTP 与 upgrade 接入 | 消费者调用 Connection 准入 | 路由 auth 一次提供 Peer;真实 [Provider 传输测试](../../../../packages/api/gateway/tests/authentication-provider.host.spec.ts)覆盖两种载体 |
|
||||
| 服务器隔离 | 路由表按实例持有,index 注入覆盖 root | 五个事件均使用 WebServer subject;[服务器](../../../../packages/host/webserver/tests/event-isolation.host.spec.ts)和[应用](../../../../packages/bundle/web-app/tests/event-isolation.host.spec.ts)测试覆盖普通/global 监听器及保留的外部 Host |
|
||||
| 浏览器 OAuth 返回 | 回调校验 state 与 PKCE | 有作用域的前置回调保留校验,并接受真实跨站导航;[账号测试](../../../../packages/credentials/deepseek-account/tests/account.spec.ts)保留错误 Host 和 SSH 转发覆盖,[Chromium](../../../../apps/web/tests/account-login.e2e.ts)断言实际 Fetch Metadata header |
|
||||
| 启动输出 | WebApp 打印/打开一个 Connection 生成的登录 URL | [启动测试](../../../../packages/bundle/web-app/tests/startup.host.spec.ts)覆盖按序入口、首个可打开项、空列表、就绪和 SSH 抑制 |
|
||||
| Desktop runtime 消费者 | 以带 Token 的 ready URL 交换 Cookie | [Runtime smoke 测试](../../../../apps/desktop/tests/smoke-runtime.spec.ts)在 HTTP 探针中使用私有 Cookie;[产物 Remote 测试](../../../../packages/api/remotes/tests/built-lib.e2e.ts)收集当前 Provider 入口,并传递准入 Peer |
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**在 Connection 上保留逐请求认证包装。** 独立注册的 Service 直接表达所有权和必需注入,不在每次消费者读取认证时分配 facade。
|
||||
|
||||
**增加另一张路由表或请求上下文容器。** 现有 WebServer 注册已拥有分发,Peer 就是下游消费的身份。路由策略和末尾 Peer 参数保留这些 owner。
|
||||
|
||||
**给每个请求增加 WebServer 字段。** Cordis 已支持服务 subject 与隔离过滤。采用该机制也能限制页面注入和入口收集的作用域,而不增加 payload 字段。
|
||||
|
||||
**让 Token 持有 WebApp 地址服务或浏览器 opener。** 这会反向依赖组装它的 bundle。WebApp 拥有发布时机和动作,Provider 通过共同事件贡献完整入口。
|
||||
|
||||
## Consequences
|
||||
|
||||
凭据实现不需要改变 Gateway,但自定义载体必须以自己的 WebServer subject 发事件,并把准入 Peer 传给协议 handler。消费嵌套认证服务的插件在注入中声明 `connection.authentication`。显式全局事件监听器仍负责判断跨服务器实例共享数据是否合适。
|
||||
|
||||
撤销 Provider 注册和释放其 Peer 是不同操作。共享一个 Peer 的产品也共享其终止范围;使用独立凭据的产品持有自己的 Peer 记录和撤销策略。此接线不增加通用 Socket 策略或另一层认证权限等级。
|
||||
|
||||
[Provider 决策](2026-11-07-browser-authentication-providers.zh.md)拥有协议兼容性和部署后果。[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.zh.md)拥有手动配置迁移和载体更新说明;本记录描述已经实现的接线,而非未来 Remote 产品。
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
# Bilingual-pair consistency record for 2026-11-07-browser-authentication-providers.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-07-browser-authentication-providers.md
|
||||
/agent-note-peer-based-authentication-providers:
|
||||
en: dc115ba91f14e5b5
|
||||
zh: f1a833e5cc9b5de4
|
||||
/agent-note-peer-based-authentication-providers/problem:
|
||||
en: f4a95ed5454d059d
|
||||
zh: 20c3ffeac8ec2b6f
|
||||
/agent-note-peer-based-authentication-providers/decision:
|
||||
en: a15c7c13f167e5ac
|
||||
zh: a15c7c13f167e5ac
|
||||
/agent-note-peer-based-authentication-providers/decision/independent-authentication-and-equal-providers:
|
||||
en: 3bc63d9822e90803
|
||||
zh: 0763d1106b8e36ea
|
||||
/agent-note-peer-based-authentication-providers/decision/identity-authorization-and-lifetime-remain-separate:
|
||||
en: ec74d7af014cd9e5
|
||||
zh: 04495d74691073a8
|
||||
/agent-note-peer-based-authentication-providers/decision/effects-on-http-events-and-startup:
|
||||
en: 6b2742912d440682
|
||||
zh: ec3c7fd3993f1367
|
||||
/agent-note-peer-based-authentication-providers/decision/preserved-protocols-and-explicit-limits:
|
||||
en: d5fb7d9f70ccb9a8
|
||||
zh: 5e78c868370deffd
|
||||
/agent-note-peer-based-authentication-providers/testing:
|
||||
en: 1ae7c77c7388883a
|
||||
zh: eb2145ec79691f81
|
||||
/agent-note-peer-based-authentication-providers/alternatives-considered:
|
||||
en: aa5de8e27414700b
|
||||
zh: 35604d226908afc2
|
||||
/agent-note-peer-based-authentication-providers/consequences:
|
||||
en: 61065aecfda88a3c
|
||||
zh: 518f3f76ef167a31
|
||||
@@ -0,0 +1,85 @@
|
||||
# Agent Note: Peer-based authentication Providers
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-07-browser-authentication-providers.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
The Host serves tool-capable operations, so a reachable address cannot establish caller identity. Browser login, Desktop access, and remote invitation or pairing flows need different credential implementations without giving each transport a different authorization model.
|
||||
|
||||
Before this separation, WebServer owned HTTP and upgrade listeners and their per-instance route tables. Connection constructed the built-in BrowserAuth, checked request sources, verified browser and API Cookies, and managed the existing API Peer attachment. Route owners called Connection admission methods themselves. WebApp asked Connection to add the launch token to its advertised address, then printed or opened that URL. The old `webserver/index-inject` event broadcast within the Cordis root independently of the route tables.
|
||||
|
||||
That arrangement made the default Token implementation part of the generic connection service. Another authentication product needed the same Peer result but could not supply its own verifier through a common registration interface.
|
||||
|
||||
## Decision
|
||||
|
||||
### Independent authentication and equal Providers
|
||||
|
||||
ConnectionAuthentication is an independent Service in the Connection package, registered as `connection.authentication` and accessed through `ctx.connection.authentication`. It owns credential-verifier registration and selection. Connection retains request-source policy, Peer creation, and RPC/Fetch operations; WebServer enforces route admission and supplies the selected Peer to handlers. Gateway and RemoteAccess authorize operations using that Peer.
|
||||
|
||||
An AuthenticationProvider synchronously returns an existing live Peer or `undefined`. ConnectionAuthentication tries Providers in actual registration order and accepts the first live result. An ordinary refusal or ended Peer permits a later Provider to succeed; an exception also permits later success. With no success, ordinary refusal returns401 and a verification failure returns503. Request cancellation stops admission. This is one selection pass, not a priority or privilege ranking between credential kinds.
|
||||
|
||||
| Access method | Credential implementation | Peer ownership |
|
||||
|---|---|---|
|
||||
| Web and API Token | The Token plugin verifies its process-token exchanges and signed Cookies | Browser v1 Cookies share a plugin-owned Peer; `/connect` v2 Cookies identify an existing independent API Peer |
|
||||
| Desktop | The Desktop Provider verifies the private credential delivered over parent–Host IPC | One Peer belongs to the Provider for that owned Host process |
|
||||
| Remote | The same Provider interface accepts a product's invitation or pairing verifier | The product determines its own principal, credentials, and Peer lifetime; the Remote product itself is not implemented |
|
||||
|
||||
The shared authentication extension is complete independently of the future Remote product. The [integration note](2026-11-07-browser-authentication-development.md) gives a typed Provider example and the route and event usage.
|
||||
|
||||
### Identity, authorization, and lifetime remain separate
|
||||
|
||||
The Host fixes `peer.principal` when creating the Peer; the client cannot choose it through a request field. Authentication establishes that identity, not permission for every operation. RemoteAccess continues to evaluate business permissions, and `peer.interactions` continues to control forwarded-event participation rather than an authentication level.
|
||||
|
||||
Each registering plugin owns its registration, and each Peer creator owns the Peer scope. Credential withdrawal prevents later authentication; ending a Peer also ends its Peer-scoped communication. Already-admitted unary requests retain their request-level cancellation semantics. Asynchronous Provider preparation can affect actual registration order, so deployments cannot infer a separate priority from credential names.
|
||||
|
||||
### Effects on HTTP, events, and startup
|
||||
|
||||
WebServer route registrations declare `anonymous`, `required`, or `deny`; omission means `required`. Protected handlers receive the Peer selected by centralized admission rather than calling each verifier. Anonymous routes skip credentials but still undergo the active Connection source policy. Trusted in-process resource reads retain their explicit Peer and still honor `deny`.
|
||||
|
||||
All five `webserver/*` events carry the corresponding WebServer as their Cordis dispatch subject. Ordinary listeners follow `webServer` service isolation; explicit `global: true` listeners opt out. This applies to request admission, upgrade middleware, the existing page-injection event, and entry-URL collection. Service isolation is a composition mechanism, not a sandbox for same-process plugins.
|
||||
|
||||
The Token plugin owns root Token exchange and `/connect` issuance. Its upgrade middleware claims its API Peers only at `/api/remote.mux`, preserving one Socket per API Peer, duplicate409, and synchronous credential revocation before asynchronous cleanup. Inspector and other upgrade routes do not claim that lifecycle. WebApp owns readiness, `printUrl` and `openBrowser` (both default true), SSH suppression, and publication: it collects complete entries, prints them in order, and opens only the first eligible one. No entries means no output or opening.
|
||||
|
||||
### Preserved protocols and explicit limits
|
||||
|
||||
The [browser Token protocol](2026-08-24-browser-token-authentication.md) retains the process token, signed authority-bound Cookie, persistent `client-connection/browser-session` signing record, expiry checks, and listener-controlled `Secure` attribute. The [API connect decision](2026-10-09-operator-scoped-connect-handshake.md) retains independent API Peers, HTTP before Socket attachment, interaction participation, and mux cleanup. A valid v2 Cookie can also authenticate a protected page; page access does not create another credential tier.
|
||||
|
||||
Desktop uses its private credential directly rather than exchanging a Token URL. The renderer receives ordinary addresses and startup data, not the private credential; the wire `ready` message contains no secret. Desktop can also offer Token login and its printed entry URL. Normal shutdown or parent disconnection while awaiting the Desktop credential ends startup without a fatal authentication error; invalid or repeated credentials remain failures.
|
||||
|
||||
Token activation failure may leave the application running without that Provider; it never grants unauthenticated access to a protected route. Token owns `cookieMaxAgeDays`, default30 days. Operators manually move an old Connection setting to Token: the old location is not migrated or rejected and does not affect the Token lifetime. The [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.md) owns that migration.
|
||||
|
||||
## Testing
|
||||
|
||||
The before/after comparison uses the original built-in-authentication design as its baseline.
|
||||
|
||||
| Affected behavior | Before | Final behavior |
|
||||
|---|---|---|
|
||||
| Credential selection | Connection directly used BrowserAuth | Token and Desktop use the same ordered Provider service; another Provider can succeed after refusal or failure |
|
||||
| Protected HTTP and upgrades | Route owners invoked Connection admission | Route policy centralizes admission and passes one selected Peer to the handler |
|
||||
| Credential persistence | Browser Cookies survived restart; API Peers did not | The same Token formats, authority checks, restart behavior, and API retention rules remain |
|
||||
| API lifecycle Socket | Gateway attachment owned one API Peer | Token's mux middleware retains duplicate409 and close-time revocation without claiming other upgrades |
|
||||
| Event scope | Routes were instance-owned; page injection broadcast | WebServer subjects filter all five events by service isolation, with an explicit global escape |
|
||||
| Browser startup | WebApp printed/opened one Connection-produced URL | WebApp keeps its defaults and readiness rules while publishing ordered Provider contributions |
|
||||
| Desktop startup | Desktop exchanged the launch URL for a Cookie | Desktop uses private IPC credentials; normal early shutdown is acknowledged |
|
||||
|
||||
The [Connection tests](../../../../packages/client/connection/tests/authentication.host.spec.ts), [real transport composition](../../../../packages/api/gateway/tests/authentication-provider.host.spec.ts), [mux lifecycle tests](../../../../packages/api/gateway/tests/operator-connect.host.spec.ts), and [WebApp isolation tests](../../../../packages/bundle/web-app/tests/event-isolation.host.spec.ts) cover these behaviors. The integration note covers callback and custom-carrier verification.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Keep Token-specific operations inside Connection.** This couples every authentication product to the default credential implementation. A generic credential registry returns the Peer already consumed by the transport and authorization layers.
|
||||
|
||||
**Return a boolean or a binding identifier and resolve the Peer later.** A boolean leaves identity unresolved; a binding identifier adds another mapping and owner. Providers already own their Peers, so successful verification returns that object directly.
|
||||
|
||||
**Authenticate separately in each HTTP and upgrade handler.** Repeated checks can disagree and omit new routes. Route policy and centralized admission make the requirement explicit while leaving endpoint-specific tickets and input validation with the endpoint.
|
||||
|
||||
**Put product Socket policy in a Peer subtype or binding API.** The single-Socket rule belongs to `/connect`'s mux session, not every Peer. Business-owned upgrade middleware preserves that rule without a generic Peer policy flag or a Gateway dependency on Token.
|
||||
|
||||
## Consequences
|
||||
|
||||
Adding a credential implementation does not change Gateway dispatch or the existing Peer protocol. Provider initialization, credential storage, login interaction, and session lifetime remain product responsibilities. Default Token and Desktop use the same interface that a Remote product can adopt, without claiming that invitation or approval UI already exists.
|
||||
|
||||
Central route admission changes the default for previously unclassified routes to `required`; public endpoints need explicit policy. Instance-scoped events prevent an isolated WebServer from inheriting another server's ordinary listeners, but a deliberately global listener remains application-wide. A credential-bearing entry URL is sensitive output even though no raw Token getter is exposed.
|
||||
|
||||
This decision partially extends the implementation ownership in the browser Token, API connect, and [request-source policy](2026-07-28-api-browser-trust-boundary.md) records. Those records remain active for their credential, lifecycle, and security rationale; none is fully superseded or archived.
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
# Agent Note: 基于 Peer 的认证 Provider
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-07-browser-authentication-providers.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
Host 提供具备工具执行能力的操作,因此可达地址不能建立调用方身份。浏览器登录、Desktop 访问和远程邀请或配对需要不同的凭据实现,但不应为每种传输建立不同的授权模型。
|
||||
|
||||
拆分前,WebServer 拥有 HTTP 与 upgrade 监听器及各实例的路由表。Connection 构造内置 BrowserAuth,检查请求来源、验证浏览器与 API Cookie,并管理已有的 API Peer 关联。路由 owner 自行调用 Connection 准入方法。WebApp 请求 Connection 为公告地址附加启动 Token,再打印或打开该 URL。旧 `webserver/index-inject` 事件在 Cordis root 内广播,与路由表的实例范围无关。
|
||||
|
||||
这种关系把默认 Token 实现放进了通用连接服务。其他认证产品同样需要返回 Peer,却没有公共注册接口可以接入自己的验证器。
|
||||
|
||||
## Decision
|
||||
|
||||
### 独立认证与平级 Provider
|
||||
|
||||
ConnectionAuthentication 是 Connection 包内的独立 Service,注册名为 `connection.authentication`,通过 `ctx.connection.authentication` 访问。它拥有凭据验证器注册与选择。Connection 保留请求来源策略、Peer 创建和 RPC/Fetch 操作;WebServer 执行路由准入并向 handler 传递选定的 Peer。Gateway 与 RemoteAccess 使用该 Peer 授权操作。
|
||||
|
||||
AuthenticationProvider 同步返回已存在且存活的 Peer 或 `undefined`。ConnectionAuthentication 按实际注册顺序尝试 Provider,采用首个存活结果。普通拒绝或已结束 Peer 允许后续 Provider 成功;异常也不阻止后续成功。无人成功时,普通拒绝返回401,存在验证故障则返回503。请求取消终止准入。这是一次选择过程,不是凭据种类之间的优先级或权限等级。
|
||||
|
||||
| 访问方式 | 凭据实现 | Peer 所有权 |
|
||||
|---|---|---|
|
||||
| Web 与 API Token | Token 插件验证进程 Token 交换和签名 Cookie | 浏览器 v1 Cookie 共享插件持有的 Peer;`/connect` v2 Cookie 标识已有的独立 API Peer |
|
||||
| Desktop | Desktop Provider 验证通过父进程—Host IPC 交付的私有凭据 | 一个 Peer 属于该自有 Host 进程的 Provider |
|
||||
| Remote | 同一个 Provider 接口可接收产品自己的邀请或配对验证器 | 产品决定自己的 principal、凭据和 Peer 生命周期;Remote 产品本身尚未实现 |
|
||||
|
||||
公共认证扩展能力已经完成,不取决于未来 Remote 产品的完成状态。[接入说明](2026-11-07-browser-authentication-development.zh.md)提供带类型的 Provider 示例及路由、事件用法。
|
||||
|
||||
### 身份、授权与生命周期相互独立
|
||||
|
||||
Host 在创建 Peer 时固定 `peer.principal`;客户端不能通过请求字段选择它。认证建立该身份,不代表允许所有操作。RemoteAccess 继续判断业务权限,`peer.interactions` 继续控制转发事件参与方式,而不是认证等级。
|
||||
|
||||
注册由调用插件拥有,Peer 作用域由创建者拥有。凭据撤销阻止后续认证,结束 Peer 也结束其作用域内的通信。已经准入的一元请求保留请求级取消语义。Provider 异步准备可能影响实际注册顺序,因此部署不能从凭据名称推导另一套优先级。
|
||||
|
||||
### HTTP、事件与启动的变化
|
||||
|
||||
WebServer 路由注册声明 `anonymous`、`required` 或 `deny`,省略时为 `required`。受保护的 handler 接收集中准入选定的 Peer,不再自行调用各个验证器。匿名路由免凭据,但仍经过活动 Connection 的来源策略。可信进程内资源读取保留显式 Peer,并继续遵守 `deny`。
|
||||
|
||||
五个 `webserver/*` 事件均以对应 WebServer 为 Cordis 分发 subject。普通监听器遵循 `webServer` 服务隔离;显式 `global: true` 监听器跳过该过滤。请求准入、upgrade 中间件、已有页面注入事件和入口 URL 收集均采用该规则。服务隔离是组合机制,不是同进程插件的安全沙箱。
|
||||
|
||||
Token 插件拥有根 Token 交换和 `/connect` 签发。它的 upgrade 中间件仅在 `/api/remote.mux` 上认领自己的 API Peer,保留每个 API Peer 一个 Socket、重复409,以及在异步清理前同步撤销凭据的行为。Inspector 与其他 upgrade 路由不认领该生命周期。WebApp 拥有就绪、`printUrl` 与 `openBrowser`(两者默认 true)、SSH 抑制和发布:收集完整入口,按序打印,只打开首个可自动打开的入口。没有入口则不输出、不打开。
|
||||
|
||||
### 保留的协议与明确限制
|
||||
|
||||
[浏览器 Token 协议](2026-08-24-browser-token-authentication.zh.md)保留进程 Token、绑定 authority 的签名 Cookie、持久 `client-connection/browser-session` 签名记录、有效期检查和由监听协议决定的 `Secure` 属性。[API connect 决策](2026-10-09-operator-scoped-connect-handshake.zh.md)保留独立 API Peer、HTTP 先于 Socket 关联、交互参与方式和 mux 清理。有效 v2 Cookie 也可认证受保护页面;页面访问不建立另一层凭据等级。
|
||||
|
||||
Desktop 直接使用私有凭据,不交换 Token URL。Renderer 接收普通地址与启动数据,不接收私有凭据;wire `ready` 消息不含秘密。Desktop 也可提供 Token 登录及其打印入口 URL。等待 Desktop 凭据时的正常 shutdown 或父通道断连不会导致致命认证错误;非法或重复凭据仍然失败。
|
||||
|
||||
Token 激活失败允许应用缺少该 Provider 继续运行,但不授予受保护路由的未认证访问。Token 拥有 `cookieMaxAgeDays`,默认为30天。用户手动将旧 Connection 设置移到 Token:旧位置既不会自动迁移,也不会被拒绝,并且不影响 Token 有效期。[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.zh.md)拥有迁移说明。
|
||||
|
||||
## Testing
|
||||
|
||||
前后对比以原内置认证设计为基线。
|
||||
|
||||
| 受影响行为 | 原行为 | 最终行为 |
|
||||
|---|---|---|
|
||||
| 凭据选择 | Connection 直接使用 BrowserAuth | Token 与 Desktop 使用同一个有序 Provider 服务;前项拒绝或故障后其他 Provider 仍可成功 |
|
||||
| 受保护 HTTP 与 upgrade | 路由 owner 调用 Connection 准入 | 路由策略集中执行准入,并向 handler 传递一个选定的 Peer |
|
||||
| 凭据持久化 | 浏览器 Cookie 可跨重启,API Peer 不可 | Token 格式、authority 检查、重启行为和 API 保留规则保持 |
|
||||
| API 生命周期 Socket | Gateway 关联拥有一个 API Peer | Token 的 mux 中间件保留重复409和关闭时撤销,不认领其他 upgrade |
|
||||
| 事件范围 | 路由按实例持有,页面注入广播 | WebServer subject 按服务隔离过滤五个事件,同时保留显式 global 出口 |
|
||||
| 浏览器启动 | WebApp 打印/打开一个由 Connection 生成的 URL | WebApp 保留默认值与就绪规则,发布 Provider 按序贡献的入口 |
|
||||
| Desktop 启动 | Desktop 交换启动 URL 取得 Cookie | Desktop 使用私有 IPC 凭据,并确认正常的早期关闭 |
|
||||
|
||||
[Connection 测试](../../../../packages/client/connection/tests/authentication.host.spec.ts)、[真实传输组合](../../../../packages/api/gateway/tests/authentication-provider.host.spec.ts)、[mux 生命周期测试](../../../../packages/api/gateway/tests/operator-connect.host.spec.ts)与 [WebApp 隔离测试](../../../../packages/bundle/web-app/tests/event-isolation.host.spec.ts)覆盖这些行为。接入说明补充回调与自定义载体的验证。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**将 Token 专属操作保留在 Connection 内。** 这会让每个认证产品依赖默认凭据实现。通用凭据注册表直接返回传输与授权层已经使用的 Peer。
|
||||
|
||||
**返回布尔值或绑定标识,再解析 Peer。** 布尔值无法确定身份,绑定标识则增加映射与 owner。Provider 已经持有自己的 Peer,验证成功直接返回该对象。
|
||||
|
||||
**每个 HTTP 与 upgrade handler 分别认证。** 重复检查可能不一致,也可能漏掉新路由。路由策略与集中准入明确表达要求,端点专属票据和输入校验仍由端点负责。
|
||||
|
||||
**将业务 Socket 策略放入 Peer 子类或绑定 API。** 单 Socket 规则属于 `/connect` 的 mux 会话,不属于所有 Peer。业务拥有的 upgrade 中间件保留该规则,不需要通用 Peer 策略标志,也不让 Gateway 依赖 Token。
|
||||
|
||||
## Consequences
|
||||
|
||||
新增凭据实现不改变 Gateway 分发或已有 Peer 协议。Provider 初始化、凭据存储、登录交互和会话生命周期仍由产品负责。默认 Token 与 Desktop 使用未来 Remote 产品也能采用的同一接口,但不声称邀请或审批 UI 已经存在。
|
||||
|
||||
集中路由准入把此前未分类路由的默认策略设为 `required`,公开端点需要显式声明策略。按实例作用域分发的事件阻止隔离 WebServer 接收另一台服务器的普通监听器,但显式全局监听器仍覆盖应用。即使没有公开原始 Token getter,含凭据的入口 URL 仍属于敏感输出。
|
||||
|
||||
本决策只部分扩展浏览器 Token、API connect 与[请求来源策略](2026-07-28-api-browser-trust-boundary.zh.md)记录中的实现归属。原记录继续保留凭据、生命周期和安全规则的独立理由,没有任何一份被完全取代或归档。
|
||||
@@ -9,8 +9,8 @@
|
||||
en: 6050884223e0e491
|
||||
zh: eb808c298c9fb652
|
||||
/agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/decision:
|
||||
en: ab004152e8a43f7d
|
||||
zh: 2eb2de8b91d8c405
|
||||
en: 582920b339db00ef
|
||||
zh: 9713fe2d524832c0
|
||||
/agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/alternatives-considered:
|
||||
en: 7bba46bed1b1baa3
|
||||
zh: 54f31bd327ee222d
|
||||
|
||||
@@ -12,7 +12,7 @@ Computer Use training data should come from several agent harnesses, not only fr
|
||||
|
||||
`@deepseek-ai/dsh-cua-mcp` is an experimental bundle in `OPTIONAL_BUNDLES` that composes the standalone `cua-mcp` profile from one insert over the empty root. A profile manifest that selects it as the only bundle is the whole installation step: the launcher loads an existing manifest without consulting `PROFILE_TEMPLATES`, and the installation already ships the bundle, so no pnpm or registry access is involved. It is the only MCP application path; no package bin or SDK escape exists, and the bundle stays out of `PROFILE_TEMPLATES` because templates cannot name experimental packages.
|
||||
|
||||
The server runs inside the profile process and calls `ctx.tools.execute` with the connection's Agent and no model step. One stdio connection owns one Agent: creation before the stdio transport opens, disposal at stdin EOF. Each program call runs as that Agent's maintenance activity, so Agent disposal cancels an in-flight call and waits for it and its nested calls before the Session closes. Agent ownership already selects the retained program process, native connection, and session-scoped grants, so connection lifetime and state lifetime coincide. The empty default preset `cua-mcp` gives that Agent `cua_run_code` and nothing else, because the provider registers program tools only for composed presets. The Agent works in a dedicated workspace, `DSH_CUA_WORKSPACE` or `cua-mcp/workspace` under the Harness home: an Agent's working directory is the `workspace-write` root of its programs, and the directory a client launches the server from can be `/`.
|
||||
The server runs inside the profile process and calls `ctx.tools.execute` with the connection's Agent and no model step. One stdio connection owns one Agent: creation before the stdio transport opens, disposal at stdin EOF. Each program call runs as that Agent's maintenance activity, so Agent disposal cancels an in-flight call and waits for it and its nested calls before the Session closes. Agent ownership already selects the retained program process, native connection, and session-scoped grants, so connection lifetime and state lifetime coincide. The empty default preset `cua-mcp` composes no model-facing rows, and the provider gives that Agent `cua_run_code` because it is not on the preset named by `agentPreset`. The Agent works in a dedicated workspace, `DSH_CUA_WORKSPACE` or `cua-mcp/workspace` under the Harness home: an Agent's working directory is the `workspace-write` root of its programs, and the directory a client launches the server from can be `/`.
|
||||
|
||||
Three tools form the surface. `cua_run_code` is the Agent's DSH registration served through the protocol server's low-level `tools/list` and `tools/call` handlers: each listing projects name, description, and parameters from the tool registry, and a call passes its arguments to the tool executor unchanged inside the Agent's initiator scope, so the provider's definition is the only schema, `description` is required as that definition declares, and validation and unknown names are answered by DSH; the one trim is the registration's sandbox-escalation fields, which the projection omits and a call may not name. `cua_get_api_reference` returns the `cua` API reference, the provider's guidance registered for the Agent, and keeps no state, so any conversation on the connection can read it at any time. `cua_reset` ends the Agent's program environment and keeps the Agent: the frontend cancels the running program and calls `ctx.cuaPrograms.release`, with which the provider's program runtime releases the environment of that state owner and which the CUA provider exposes beside `screenshotRequestTarget`; the next program starts a fresh process, while the native connection and the session's consent decisions stay. The frontend orders its own calls around the release: a reset answers after the cancelled program has settled, and programs wait for a release in progress. The projection delivers each inspected screenshot as the request version the program observed, so coordinates in program text match the delivered image. The provider's new `screenshotTarget` configuration replaces the model-route lookup that a profile without a model cannot satisfy.
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ Computer Use 的训练数据应来自多个 agent harness,而不只是 DSH 会
|
||||
|
||||
`@deepseek-ai/dsh-cua-mcp` 是 `OPTIONAL_BUNDLES` 中的实验性组合包:它在空 profile 根上用一次 insert 组成独立的 `cua-mcp` profile。只选它这一个组合包的 profile manifest 就是全部安装步骤:启动器加载已存在的 manifest 时不查 `PROFILE_TEMPLATES`,而安装本身已自带该组合包,因此不涉及 pnpm 或 registry。这是唯一的 MCP 应用路径;没有包 bin 或 SDK 逃逸,该组合包不进入 `PROFILE_TEMPLATES`,因为模板不能引用实验包。
|
||||
|
||||
服务器运行在 profile 进程内,带着连接的 Agent、不经模型步骤地调用 `ctx.tools.execute`。一个 stdio 连接拥有一个 Agent:在 stdio 传输打开之前创建,stdin EOF 时销毁。每次程序调用都作为该 Agent 的维护活动运行,因此 Agent 销毁时会取消进行中的调用,并等它及其嵌套调用结算之后才关闭 Session。Agent 归属已经决定了保留的程序进程、本机连接和会话级授权,因此连接生命周期与状态生命周期重合。空的默认 preset `cua-mcp` 让该 Agent 只获得 `cua_run_code`,因为提供方只为已组合 preset 注册程序工具。该 Agent 在专用工作区中工作,即 `DSH_CUA_WORKSPACE`,未设置时为 Harness home 下的 `cua-mcp/workspace`:Agent 的工作目录就是其程序的 `workspace-write` 根,而客户端启动服务器的目录可能是 `/`。
|
||||
服务器运行在 profile 进程内,带着连接的 Agent、不经模型步骤地调用 `ctx.tools.execute`。一个 stdio 连接拥有一个 Agent:在 stdio 传输打开之前创建,stdin EOF 时销毁。每次程序调用都作为该 Agent 的维护活动运行,因此 Agent 销毁时会取消进行中的调用,并等它及其嵌套调用结算之后才关闭 Session。Agent 归属已经决定了保留的程序进程、本机连接和会话级授权,因此连接生命周期与状态生命周期重合。空的默认 preset `cua-mcp` 不组合任何面向模型的条目;该 Agent 不使用 `agentPreset` 指定的 preset,因此提供方为它提供 `cua_run_code`。该 Agent 在专用工作区中工作,即 `DSH_CUA_WORKSPACE`,未设置时为 Harness home 下的 `cua-mcp/workspace`:Agent 的工作目录就是其程序的 `workspace-write` 根,而客户端启动服务器的目录可能是 `/`。
|
||||
|
||||
工具面由三个工具构成。`cua_run_code` 就是该 Agent 的 DSH 注册项,经协议服务器的低层 `tools/list` 与 `tools/call` handler 提供:每次列表都从工具注册表投影名称、描述和参数,调用则在 Agent 的 initiator 作用域内把参数原样交给工具执行器,因此提供方的定义是唯一 schema,`description` 按该定义必填,校验与未知名称由 DSH 回答;唯一的剪裁是注册项中的沙箱提权字段,投影省略它们,调用也不得指定。`cua_get_api_reference` 返回 `cua` API 参考,即提供方为该 Agent 注册的指引;它不保存状态,因此连接上的任何对话随时都能读取。`cua_reset` 结束该 Agent 的程序环境并保留 Agent:前端取消正在运行的程序,再调用 `ctx.cuaPrograms.release`,由提供方的程序运行时释放该 state owner 的环境,CUA 提供方把它与 `screenshotRequestTarget` 一起暴露;下一个程序在新进程中启动,本机连接和本会话的授权决定保留。前端围绕这次释放安排自己的调用:reset 在被取消的程序结算之后才返回,程序则等待进行中的释放。投影把每张被 inspect 的截图按程序观察到的请求版本交付,使程序文本中的坐标与交付的图片一致。提供方新增的 `screenshotTarget` 配置取代了没有模型的 profile 无法满足的模型路由查询。
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
en: 87ce83e36a6ab68e
|
||||
zh: 8aa98dc7dae03c41
|
||||
/agent-note-cua-programs-outside-the-ptc-preset/decision:
|
||||
en: 13e079e19b5f2d6d
|
||||
zh: 2ce9b6aa981162d7
|
||||
en: a9124b9053b16a12
|
||||
zh: 7d4005cbca138015
|
||||
/agent-note-cua-programs-outside-the-ptc-preset/alternatives-considered:
|
||||
en: b5d8e00cbe4b53ae
|
||||
zh: 4ef81611150a8d75
|
||||
|
||||
@@ -10,7 +10,7 @@ Computer Use needs reusable application and window objects in Standard and other
|
||||
|
||||
## Decision
|
||||
|
||||
CUA keeps `agentPreset: ptc` as the default selector for its raw `cua` tool. Every other composed preset receives `cua_run_code`; Agents without a composed preset receive neither tool. `agentPreset: false` retains global raw-tool registration. A base owner uses Agent scopes for registration and disposal, so enabling and disabling the provider affects existing and later Agents without editing presets. Raw registration depends only on base CUA services and preset selection. The private program producer publishes and withdraws its definition by identity; private dependency loss or startup failure leaves raw tools and prompts available.
|
||||
CUA keeps `agentPreset: ptc` as the default selector for its raw `cua` tool. Every other composed preset receives `cua_run_code`. Agents without a composed preset receive it as well; [CUA program tool for Agents without a preset](2026-11-12-cua-program-tool-without-presets.md) supersedes their original exclusion. `agentPreset: false` retains global raw-tool registration. A base owner uses Agent scopes for registration and disposal, so enabling and disabling the provider affects existing and later Agents without editing presets. Raw registration depends only on base CUA services and preset selection. The private program producer publishes and withdraws its definition by identity; private dependency loss or startup failure leaves raw tools and prompts available.
|
||||
|
||||
`cua_run_code` composes the shared [program-tool factory](../../../../packages/core/tool-executor-ptc/README.md) with one isolated Node `persistent-in-memory` runtime owned by the CUA provider. Agent `stateOwner` identities select separate retained processes. Its only binding is the private `tools.cua` definition; the model calls ordinary session tools directly. Nested CUA operations retain tool policy, guards, dispatch events, and image admission. Programs select text and screenshots through `inspect(...values)`, following the [explicit output decision](2026-11-09-explicit-ptc-output.md). The provider releases held keys when either program tool settles. Provider unload drains its own CUA programs before native teardown; releasing input held by other PTC programs does not wait for their unrelated work. State is in memory, separate from the profile's PTC state, and released with its Agent or provider.
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ Computer Use 需要在标准及其他 preset 中复用应用和窗口对象,
|
||||
|
||||
## 决策
|
||||
|
||||
CUA 保留 `agentPreset: ptc`,用默认选择器指定获得原始 `cua` 工具的 preset。其他已组合的 preset 获得 `cua_run_code`;未组合 preset 的 agent(智能体)不获得这两个工具。`agentPreset: false` 保留全局原始工具注册。基础注册的所有者通过 Agent 作用域管理注册和销毁,因此启停提供方会影响已有和后续 Agent,无需修改 preset。原始工具的注册只依赖基础 CUA 服务和 preset 选择。私有程序工具的提供方按定义对象的身份发布和撤回其定义;私有依赖缺失或启动失败时,原始工具和提示词仍然可用。
|
||||
CUA 保留 `agentPreset: ptc`,用默认选择器指定获得原始 `cua` 工具的 preset。其他已组合的 preset 获得 `cua_run_code`。未组合 preset 的 agent(智能体)也获得该工具;[未组合 preset 的 Agent 使用 CUA 程序工具](2026-11-12-cua-program-tool-without-presets.zh.md)取代了原先不为它们注册工具的决定。`agentPreset: false` 保留全局原始工具注册。基础注册的所有者通过 Agent 作用域管理注册和销毁,因此启停提供方会影响已有和后续 Agent,无需修改 preset。原始工具的注册只依赖基础 CUA 服务和 preset 选择。私有程序工具的提供方按定义对象的身份发布和撤回其定义;私有依赖缺失或启动失败时,原始工具和提示词仍然可用。
|
||||
|
||||
`cua_run_code` 将共享[程序工具工厂](../../../../packages/core/tool-executor-ptc/README.zh.md)与 CUA 提供方持有的单个隔离 Node `persistent-in-memory` 运行时组合。Agent 的 `stateOwner` 身份选择各自独立的保留进程。它只绑定私有 `tools.cua` 定义;模型直接调用其他普通会话工具。嵌套 CUA 操作保留工具策略、guard、派发事件和图像接纳。程序通过 `inspect(...values)` 选择文字和截图,遵循[显式输出决策](2026-11-09-explicit-ptc-output.zh.md)。任一程序工具结束时,提供方都会释放该程序仍按住的键。提供方卸载时,先等待自己持有的 CUA 程序结束再清理原生资源;释放其他 PTC 程序持有的输入时,不等待这些程序中的其他工作。状态保存在内存中,独立于 profile 的 PTC 状态,随所属 Agent 或提供方释放。
|
||||
|
||||
|
||||
+2
-2
@@ -60,8 +60,8 @@
|
||||
en: 725a4139f28961c3
|
||||
zh: b32da1bf86095e65
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/integration:
|
||||
en: b05235293c504467
|
||||
zh: 48f5f534812a12b3
|
||||
en: 95a34d296530789b
|
||||
zh: 04d1da9e16718ac4
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/alternatives-considered:
|
||||
en: e548d12c174bb44e
|
||||
zh: 9f67908a564d6f78
|
||||
|
||||
@@ -426,7 +426,7 @@ The `scoped-repl` format connects the evaluator with only the changes the connec
|
||||
| `configuration.ts` in `ptc-runtime-node` (used by CUA to merge settings) | `resolvePersistentExecution` returns `executionMode`, `scriptPersistence`, and `replScoped` to merge together: `script` keeps retained VM Scripts with `replScoped: false`, `scoped-repl` yields `replScoped: true`, and function bodies and REPL statements yield `persistent-in-memory` with the constant `SCOPED_REPL_BY_DEFAULT`, currently true, replacing a stale profile value. That constant also sets the omitted default in `config.ts`, so changing it changes one line; `config.ts` imports this function from `configuration.ts`, which is itself a published package entry, and `configuration.ts` imports only the `Config` type, so the build emits no shared chunk |
|
||||
| Documentation, snapshots, and tests | Package README configuration, behavior, and known limitations; the config catalog; the snapshot scenario `ptc-scoped-repl`; a built-artifact e2e case with `replScoped: true` |
|
||||
|
||||
tool-executor-ptc is unchanged: for every format other than `function-body` it uses its printing guidance. The model guidance states the exact behavior above, especially: output uses `inspect(...)`, in a sentence shared with the other modes; top-level `return` is unsupported; copies happen when a call starts and earlier code is unaffected; shared mutable state belongs in objects; an assignment without declaration changes only the copy, including for earlier `const` names; a `let`, `const`, or `class` redeclaration cannot read the earlier value of its name, so assign to the name or use a new one to compute from it; a `var` redeclaration starts from the earlier value; when a call fails, an unfinished `let`, `const`, `class`, or `var` redeclaration keeps the earlier value; a `var` inside a block is also a top-level name of the call, while other block declarations stay in their block; modules load only with `import()`, whose relative specifiers resolve from the directory of the environment's first call. Tests pin the model guidance verbatim.
|
||||
tool-executor-ptc is unchanged: for every format other than `function-body` it uses its printing guidance. The model guidance describes the behavior above as rules for writing programs rather than as a list of edge cases: output uses `inspect(...)`, in a sentence shared with the other modes; top-level `return` is unsupported; each call runs one program in its own top-level scope, and its top-level declarations and the names it received are copied, not referenced, into later programs, so objects stay shared; in one program, either use a copied name or declare it again, never both; assigning to a copied name, including an earlier `const`, changes only this program's copy; do not declare `var` inside blocks, because a block-level `var` changes which value later programs copy; earlier functions and still-running code keep the values they captured, so shared mutable state belongs in objects; when a program fails before a declaration of an existing name finishes, later programs keep the earlier value; modules load only with `import()`, without `require` or `module`, and relative import specifiers resolve from the directory of the environment's first program, while `process.cwd()` and relative file paths follow each program's directory. The shared retained-state sentences say to await tools and child processes before the program ends, because the formats that retain state have no top-level `return`. Tests pin the model guidance verbatim.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
@@ -426,7 +426,7 @@ REPL 用 Node 的 `domain` 接住程序启动的异步工作里抛出的错误
|
||||
| `ptc-runtime-node` 的 `configuration.ts`(CUA 用它合并配置) | `resolvePersistentExecution` 返回 `executionMode`、`scriptPersistence`、`replScoped` 三个字段,一起合并:`script` 保持持久化的 VM Script,`replScoped: false`;`scoped-repl` 为 `replScoped: true`;函数体和 REPL 语句为 `persistent-in-memory` 加常量 `SCOPED_REPL_BY_DEFAULT`(目前为 true),覆盖 profile 里残留的值。这个常量同时决定 `config.ts` 里省略时的默认值,改它只改一行;`config.ts` 从 `configuration.ts` 导入这个函数,而 `configuration.ts` 本身也是包的发布入口;`configuration.ts` 只导入 `Config` 类型,所以打包不会生成共用的 chunk |
|
||||
| 文档、快照和测试 | 包 README 的配置项、行为说明和"已知限制"、config catalog、快照场景 `ptc-scoped-repl`;构建产物的 e2e 含 `replScoped: true` 用例 |
|
||||
|
||||
tool-executor-ptc 没有改动:格式不是 `function-body` 时,它自动使用"打印输出"那套说明。模型说明写明上面的精确行为,尤其是:输出用 `inspect(...)`,这句和其他模式共用;不支持顶层 `return`;每次调用开始时拷贝、旧代码不受影响;需要共享的可变状态放进对象;不声明直接赋值只改拷贝,前面的 `const` 也可以这样赋值;`let`、`const`、`class` 重新声明的初始化表达式读不到同名旧值,要在旧值上计算就直接赋值或换个名字;`var` 重新声明从旧值开始;调用中途失败时,没执行完的 `let`、`const`、`class`、`var` 重新声明保留旧值;块里的 `var` 也算这次调用的顶层名字,其他块里的声明只属于它的块;只能用 `import()`,相对路径按这个环境第一次调用的目录解析。测试整段逐字比对模型说明。
|
||||
tool-executor-ptc 没有改动:格式不是 `function-body` 时,它自动使用"打印输出"那套说明。模型说明把上面的行为写成编写程序的规则,而不是逐条列出边界情况:输出用 `inspect(...)`,这句和其他模式共用;不支持顶层 `return`;每次调用在自己的顶层作用域里执行一段程序,它的顶层声明和继承来的名字以拷贝而不是引用的方式传给之后的程序,因此对象仍然共享;同一段程序里,对一个名字要么使用拷贝来的值,要么重新声明,不要两者都做;给拷贝来的名字赋值(包括前面的 `const`)只改这段程序的拷贝;不要在块里声明 `var`,因为块里的 `var` 会改变之后的程序拷贝到的值;之前的函数和仍在运行的代码保留它们捕获的值,需要共享的可变状态放进对象;程序在对已有名字的声明完成前失败时,之后的程序保留旧值;只能用 `import()`,没有 `require` 和 `module`,import 的相对路径按这个环境第一段程序的目录解析,`process.cwd()` 和读写文件的相对路径跟随每段程序的目录。保留状态的共用句子要求在程序结束前等待工具调用和子进程,因为保留状态的几种格式都不支持顶层 `return`。测试整段逐字比对模型说明。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-12-cua-program-tool-without-presets.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-12-cua-program-tool-without-presets.md
|
||||
/agent-note-cua-program-tool-for-agents-without-a-preset:
|
||||
en: a18ebca264083c7d
|
||||
zh: d9e71d8e2a33e0ca
|
||||
/agent-note-cua-program-tool-for-agents-without-a-preset/problem:
|
||||
en: ebd7cb462c9e5edc
|
||||
zh: 9e2b414a7b7bba57
|
||||
/agent-note-cua-program-tool-for-agents-without-a-preset/decision:
|
||||
en: 65dbe63470c13968
|
||||
zh: b1fd3bca1b2b0716
|
||||
/agent-note-cua-program-tool-for-agents-without-a-preset/alternatives-considered:
|
||||
en: dbb95968d21a5497
|
||||
zh: 8f7e7690d4af8683
|
||||
/agent-note-cua-program-tool-for-agents-without-a-preset/consequences:
|
||||
en: 065387a5d5bb45dd
|
||||
zh: 5b12a55c767e2234
|
||||
@@ -0,0 +1,31 @@
|
||||
# Agent Note: CUA program tool for Agents without a preset
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-12-cua-program-tool-without-presets.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
The SDK, headless, and ACP applications create Agents without joining an Agent preset, and their profiles mount no preset registry. A native CUA provider configured with a preset ID registered no tool for those Agents, so its default configuration and the Computer Use bundle had no effect there. `agentPreset: false` supplied only the raw `cua` tool. A Host whose model calls ordinary tools directly had no configuration that supplied `cua_run_code`.
|
||||
|
||||
## Decision
|
||||
|
||||
When `agentPreset` is a preset ID, only Agents on that preset receive raw `cua`. Every other Agent receives `cua_run_code`, including Agents without a composed preset and every Agent of a composition without the preset registry. The registry is an optional dependency of the provider: the provider recomputes the tool form of each live Agent when the registry loads or unloads, and without the registry no Agent counts as being on the configured preset. `agentPreset: false` still registers raw `cua` globally and creates no program runtime.
|
||||
|
||||
This partially supersedes [CUA programs outside the PTC preset](2026-11-09-cua-program-tool.md), which gave Agents without a composed preset neither tool. That note still owns the program tool's runtime, its initialization, and the choice of one tool form per Agent. It also changes one consequence recorded in [What stays host-plane once presets own the agent plane](2026-08-10-host-plane-ownership-after-presets.md), where an Agent that joined no preset received no tool. That note still owns the rule that entry points join Agents explicitly and that no check rejects an Agent for joining no preset.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Keeping no tool for Agents without a preset** preserves the earlier default. Its only effect on these Hosts was that enabling Computer Use changed nothing and reported nothing.
|
||||
|
||||
**A provider field that selects the tool form for these Agents** leaves the default configuration without effect, requires each such Host to set two fields, and adds a combination that is invalid beside a preset ID.
|
||||
|
||||
**Joining a preset in the SDK server** covers one of the three Hosts, changes a non-experimental package, and requires each deployment to declare an empty preset whose ID differs from `agentPreset`.
|
||||
|
||||
**Selecting the form from the tool executor** requires the executor interface to identify program executors, which it does not.
|
||||
|
||||
**Creating the Agent without the tool and logging a warning while the program services are unavailable** hides the failure on the Hosts this decision serves: an SDK or headless caller would receive a completed run without Computer Use and no error. The provider instead keeps the rule it applies to Agents on other presets: creation waits for the dedicated runtime and rejects while that runtime or the `workingDirectory` service is unavailable, for example after invalid runtime settings or in a composition without `workingDirectory`. This differs from the check that [What stays host-plane once presets own the agent plane](2026-08-10-host-plane-ownership-after-presets.md) rejected. That check would have rejected every Agent that joins no preset, which is how the SDK server, the ACP bridge, and the headless bundle create all of their Agents. The provider rejects only while it cannot supply the tool its configuration selects, and `agentPreset: false` removes the dependency on the program runtime.
|
||||
|
||||
## Consequences
|
||||
|
||||
Hosts without presets obtain `cua_run_code` from the default configuration; Web and Desktop sessions always join a preset and are unaffected. On a Host without presets, Agent creation waits for the dedicated program runtime and rejects while its services are unavailable. A PTC executor mounted on such a Host exposes `tools.cua_run_code` inside `run_code` unless the provider sets `agentPreset: false`. The [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.2/cua-agents-without-preset/guide.md) lists the migration. Unit tests cover compositions with and without the registry and the registry's loading and unloading; recorded SDK and headless Sessions cover the assembled request and program execution, the headless one through the PTC tool executor.
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
# Agent Note: 未组合 preset 的 Agent 使用 CUA 程序工具
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-12-cua-program-tool-without-presets.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
SDK、headless 和 ACP 应用创建 Agent 时不组合 Agent preset,它们的 profile 也不挂载 preset 注册表。以 preset ID 配置的原生 CUA 提供方不为这些 Agent 注册任何工具,因此其默认配置和 Computer Use 组合包在这些 Host 上不起作用。`agentPreset: false` 只提供原始 `cua` 工具。模型直接调用普通工具的 Host 没有任何配置可以获得 `cua_run_code`。
|
||||
|
||||
## 决策
|
||||
|
||||
`agentPreset` 为 preset ID 时,只有使用该 preset 的 Agent 获得原始 `cua`。其他 Agent 都获得 `cua_run_code`,包括未组合 preset 的 Agent,以及没有 preset 注册表的组合中的全部 Agent。注册表是提供方的可选依赖:注册表加载或卸载时,提供方重新计算每个存活 Agent 的工具形态;没有注册表时,任何 Agent 都不算使用所配置的 preset。`agentPreset: false` 仍全局注册原始 `cua`,并且不创建程序运行时。
|
||||
|
||||
这部分取代 [PTC preset 之外的 CUA 程序](2026-11-09-cua-program-tool.zh.md)中未组合 preset 的 Agent 不获得任何工具的决定。原记录继续负责程序工具的运行时、初始化,以及每个 Agent 只使用一种工具形态的选择。本决策还改变了[Host 平面说明](2026-08-10-host-plane-ownership-after-presets.zh.md)记录的一项后果:此前未加入 preset 的 Agent 不获得任何工具。该记录继续负责入口显式让 Agent 加入,以及没有检查会因为 Agent 未加入 preset 而拒绝它这两条规则。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**未组合 preset 的 Agent 仍不获得工具**保留了原先的默认行为。它在这些 Host 上的唯一效果是启用 Computer Use 后没有任何变化,也没有任何提示。
|
||||
|
||||
**在提供方配置中增加字段,为这些 Agent 选择工具形态**会让默认配置仍然不起作用,要求每个这类 Host 设置两个字段,并增加一种与 preset ID 并用时无效的组合。
|
||||
|
||||
**在 SDK server 中组合 preset** 只覆盖三个 Host 中的一个,需要修改非实验性的包,并要求每个部署声明一个 ID 与 `agentPreset` 不同的空 preset。
|
||||
|
||||
**按工具执行器选择形态**需要执行器接口标识程序执行器,而该接口没有这项信息。
|
||||
|
||||
**程序服务不可用时照常创建 Agent、不注册该工具并记录警告**会在本决策所服务的 Host 上掩盖失败:SDK 或 headless 的调用方会得到一次没有 Computer Use 的完整运行,并且收不到任何错误。提供方因此沿用它对使用其他 preset 的 Agent 采用的规则:创建时等待专用运行时,在该运行时或 `workingDirectory` 服务不可用时拒绝创建,例如运行时设置无效,或组合中没有 `workingDirectory`。这与[Host 平面说明](2026-08-10-host-plane-ownership-after-presets.zh.md)否决的检查不同。那项检查会拒绝所有未加入 preset 的 Agent,而 SDK server、ACP 桥和 headless bundle 创建的 Agent 全部如此。提供方只在无法提供其配置所选的工具时拒绝创建,并且 `agentPreset: false` 可以去掉对程序运行时的依赖。
|
||||
|
||||
## 后果
|
||||
|
||||
不组合 preset 的 Host 使用默认配置即可获得 `cua_run_code`;Web 和 Desktop 会话都会组合 preset,不受影响。在不组合 preset 的 Host 上,创建 Agent 时会等待专用程序运行时,其所需服务不可用时创建失败。这类 Host 挂载 PTC 执行器时,`run_code` 内会出现 `tools.cua_run_code`,除非提供方设置 `agentPreset: false`。迁移步骤见[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.2/cua-agents-without-preset/guide.zh.md)。单元测试覆盖有注册表和没有注册表的组合,以及注册表的加载与卸载;已记录的 SDK 会话和 headless 会话覆盖组装后的请求和程序执行,其中 headless 会话经由 PTC 工具执行器。
|
||||
@@ -9,23 +9,23 @@
|
||||
en: 4b312be894531bee
|
||||
zh: d655648ea5843ef5
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision:
|
||||
en: 109e418dd92ead24
|
||||
zh: e2564f0f98cc4641
|
||||
en: 920a552af96d95a9
|
||||
zh: b619aa830dc29750
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/per-program-execution-controls:
|
||||
en: da694641e1d009de
|
||||
zh: 9d7492d39039af66
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/the-registry-owns-the-mode:
|
||||
en: 4cd76a34f4712e1a
|
||||
zh: 303ef72a18644d7c
|
||||
en: 33acc5b7393514f8
|
||||
zh: b58db10dc096e3bd
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/the-run-code-tool-and-the-dispatch-bridge:
|
||||
en: 69e4683ac3150bdf
|
||||
zh: d8eaa12eaba6d67e
|
||||
en: 13fc9291d3d49020
|
||||
zh: 62220faa32e6b412
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/observability-tool-ptc-dispatch:
|
||||
en: 951fb03a27841eea
|
||||
zh: 38928d1ca859eced
|
||||
en: 5b49e09f358f6425
|
||||
zh: cc6a7e889ce6428c
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/the-ptc-runtime-seam:
|
||||
en: 4c423f4e9cef6055
|
||||
zh: 5c23a3637eb420c0
|
||||
en: f4684560af65cfbb
|
||||
zh: 1b1d6222eec05a2e
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/the-node-process-runtime:
|
||||
en: b2a8d7d654d1832b
|
||||
zh: 5852a2a3660e5a2e
|
||||
@@ -33,8 +33,8 @@
|
||||
en: d62b41a6a5c58e5f
|
||||
zh: ef72c5a9b32b370e
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/what-the-model-sees:
|
||||
en: 109d4c326bfcf572
|
||||
zh: 9f6be5afc281054d
|
||||
en: e49585967dea8dcc
|
||||
zh: 6f8e4b6d1e00aa17
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/consequences:
|
||||
en: 761eb6c1aeb7af18
|
||||
zh: 5434456a3d0a1b65
|
||||
@@ -45,5 +45,5 @@
|
||||
en: e78530994a88d14f
|
||||
zh: 49f64c7f1421f507
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/risks:
|
||||
en: d58925bdb912de23
|
||||
zh: d3a70237d656e5a4
|
||||
en: a194c1f84b7291ed
|
||||
zh: 72856312bca4421d
|
||||
@@ -19,7 +19,7 @@ Tool presentation belongs to the registry that owns tool visibility: implementin
|
||||
Three decisions, each elaborated in its own section below:
|
||||
|
||||
1. **PTC mode is a first-class presentation mode of `ToolRuntime`** (`dsh-tools`), selected by a validated `mode` config: `'native'` (the default, contributing the visible capability schemas) or `'ptc'` (the registry contributes only its reserved `run_code` transport plus a generated SDK `.d.ts` in the system prompt). The registry constructs its canonical contribution at the source; the cooperative prompt-assembly result remains authoritative, and the logged request header records exactly that returned presentation.
|
||||
2. **Code execution is a capability seam** — `packages/ptc-runtime/` contains the Service Definition package `@deepseek-ai/dsh-ptc-runtime`, which owns `ctx.ptcRuntime` ([capability seams](../architecture/2026-06-13-capability-seams.md); Consumer = `dsh-tools`, with core-consumes-a-seam precedent in `agent-loop` → `dsh-llm`). The runtime knows nothing about tools: it is handed a program and named async bindings, runs the program, and reports `{ value, logs, error? }`. Language and substrate are backend properties, so a future Python or container backend is another Service Provider package, not a redesign.
|
||||
2. **Code execution is a capability seam** — `packages/ptc-runtime/` contains the Service Definition package `@deepseek-ai/dsh-ptc-runtime`, which owns `ctx.ptcRuntime` ([capability seams](../architecture/2026-06-13-capability-seams.md); Consumer = `dsh-tool-executor-ptc`). The runtime knows nothing about tools: it receives a program and named async bindings, runs the program, and reports output, an optional completion and an optional failure. Substrate and source language remain provider properties; the [TypeScript-only executor decision](../simplification/2026-11-12-typescript-only-ptc.md) owns supported tool-execution languages.
|
||||
3. **The shipped implementation is `@deepseek-ai/dsh-ptc-runtime-node`**: each program runs in a fresh managed Node process under the calling Session's resolved sandbox policy. Direct Node APIs remain available within that policy; named host bindings cross a separately validated control channel.
|
||||
|
||||
This note owns PTC presentation, composition and settlement. The [typed tool-return decision](2026-07-20-ptc-typed-tool-returns.md) owns generated outputs, ordinary canonical binding values, `ToolCallError` and lossless runtime output. The [explicit output decision](../architecture/2026-11-09-explicit-ptc-output.md) owns TypeScript completion suppression and text/image selection. The [sandboxed Node decision](../architecture/2026-09-11-sandboxed-node-ptc-runtime.md) supersedes the worker execution, trust posture and budget realization while preserving this note's consumer rules.
|
||||
@@ -38,7 +38,7 @@ The [Node execution decision](../architecture/2026-09-11-sandboxed-node-ptc-runt
|
||||
|
||||
**Interaction with `toolOrder`:** a configured `systemPrompt.toolOrder` naming native capabilities rejects every assembly under `mode: 'ptc'`, because those names are outside that mode's wire-validation universe. This is correct behavior, not a bug: a deployment using PTC mode updates its order config or drops it.
|
||||
|
||||
**SDK prompt section.** In `'ptc'`, the lazy `tools:sdk` section in the tool-guidance order band renders the loaded runtime's language declarations plus fixed usage instructions for the scope's visible capabilities (TypeScript by default; the [language-dispatch note](../../archived/feature/2026-07-31-ptc-language-dispatch.md) added Python and the `ctx.ptcRuntime.language` renderer table). It shares lookup and execution visibility, excludes `run_code`, and sorts tools lexicographically for byte-stable output.
|
||||
**SDK prompt section.** In `'ptc'`, the lazy `tools:sdk` section in the tool-guidance order band renders TypeScript declarations plus fixed usage instructions for the scope's visible capabilities. It shares lookup and execution visibility, excludes `run_code`, and sorts tools lexicographically for byte-stable output.
|
||||
|
||||
**Assembly ownership.** `tools:sdk` enters the trusted `system-prompt/assemble` presentation waterfall as a normal section, while `run_code` stays a provider-owned declaration that the waterfall cannot remove or replace. A scoped `tools:sdk` section may shadow the global default before dispatch, and a listener may remove or replace the section. Whoever changes it owns preserving a viable PTC mode protocol when the deployment expects PTC mode to remain usable; no restoration pass overrides deliberate composition.
|
||||
|
||||
@@ -50,7 +50,7 @@ Under `'ptc'` the registry owns `run_code` as a reserved presentation transport
|
||||
|
||||
1. **Build bindings.** One run-scoped signal follows outer cancellation and is aborted whenever the run settles. Each visible tool binding snapshots lossless-JSON arguments, enters the native-contract dispatch pool (the [live-parallel reference](../../../../packages/core/tools/README.md) owns the scheduling design), executes with a deterministic call id and the outer token as `parent`, defers returned contexts through the outer execution, and logs the `tool/ptc-dispatch-start`/`tool/ptc-dispatch` pair, the settle side carrying the full rendered result content. Success returns the consumer-facing value, including program Images for the selected TypeScript bindings; failure becomes the program-visible `ToolCallError`. Every sub-call retains its own immutable execution identity and traverses the full tool pipeline.
|
||||
2. **Runs resolved inputs:** `ctx.ptcRuntime.run(ctx.ptcRuntime.resolve(request))`. The request carries the program, bindings, run-scoped signal, calling Session cwd and applicable resolved file policy. The run-scoped signal connects outer settlement to execution cancellation.
|
||||
3. **Settle after quiescence.** When the runtime settles, the bridge aborts outstanding work and drains the dispatch queue before returning. TypeScript success returns captured logs as canonical output and projects inspected images into durable `tool/result.content`; other language consumers also render their completion value. The result card reads that content directly. A runtime failure becomes `CodeRunFailedError`; backend rejection uses the registry's normal error boundary. Both produce structured error results, and no sub-call can append after `run_code` settles.
|
||||
3. **Settle after quiescence.** When the runtime settles, the bridge aborts outstanding work and drains the dispatch queue before returning. Success returns captured logs as canonical output and projects inspected images into durable `tool/result.content`. The result card reads that content directly. A runtime failure becomes `CodeRunFailedError`; backend rejection uses the registry's normal error boundary. Both produce structured error results, and no sub-call can append after `run_code` settles.
|
||||
|
||||
**Sub-call contexts are deferred through the parent.** Injecting inside `run_code` would break parent call/result adjacency, so `ToolRunContext.deferContext()` collects every sub-result `additionalContexts` entry in dispatch order. The registry carries that array even when the program later throws, and the loop appends each entry only after the outer result and every sibling result in the step. An outer post-execute block discards tool-deferred entries and exposes only contexts explicitly attached by the blocking decision.
|
||||
|
||||
@@ -64,7 +64,7 @@ Under `'ptc'` the registry owns `run_code` as a reserved presentation transport
|
||||
|
||||
Each sub-dispatch appends a log-only `tool/ptc-dispatch-start` event at pool entry and a `tool/ptc-dispatch` settle event containing parent and child call ids, tool identity, normalized arguments, and the complete rendered `content`/`isError` outcome. It remains outside model history but available to persistence and UIs. Appends occur inside the open `run_code` turn. Direct executions without an agent still run but cannot log the event.
|
||||
|
||||
New sub-calls use `<parent>:ptc:<n>` ids, numbered by tool-call attempt. Invalid arguments consume a number without a dispatch event, so logged ids may have gaps. All call ids are opaque to consumers: migration preserves every historical id byte-for-byte, including `:code:` substrings, so dispatch pairs, spill references, and other correlations remain intact. The [explicit output decision](../architecture/2026-11-09-explicit-ptc-output.md) owns TypeScript image presentation; other language consumers attribute forwarded image contexts to `{ kind: 'ptc-mode' }`.
|
||||
New sub-calls use `<parent>:ptc:<n>` ids, numbered by tool-call attempt. Invalid arguments consume a number without a dispatch event, so logged ids may have gaps. All call ids are opaque to consumers: migration preserves every historical id byte-for-byte, including `:code:` substrings, so dispatch pairs, spill references, and other correlations remain intact. The [explicit output decision](../architecture/2026-11-09-explicit-ptc-output.md) owns image presentation. Additional contexts retain `{ kind: 'ptc-mode' }` attribution.
|
||||
|
||||
The [V2-to-V3 PTC specification](../../../../packages/session/session-format-v2-to-v3/README.md#ptc-vocabulary) owns exact historical tag and attribution conversion; [native V3 admission](../../../../packages/session/session-format-v2-to-v3/README.md#native-v3-admission) owns predecessor-tag refusal. These are not runtime aliases: an opaque extension must not acquire PTC lifecycle meaning merely through a version change.
|
||||
|
||||
@@ -72,7 +72,7 @@ The [V2-to-V3 PTC specification](../../../../packages/session/session-format-v2-
|
||||
|
||||
`dsh-ptc-runtime` owns `PtcRuntime` and the [request, resolved-spec, binding and result types](../../../../docs/subsystems/ptc-runtime.md). `resolve(request)` validates supported cwd, timeout and policy choices and supplies deployment defaults; `run(spec)` executes complete inputs. Named async bindings and optional rejection constructors keep registry-specific tool names outside the runtime.
|
||||
|
||||
`language` selects the SDK renderer and `run_code` flavor; an unsupported language fails assembly. `isolation` identifies the substrate, not its authority. `sandboxMode` indicates whether the consumer can pass a resolved Session file policy. Missing runtimes fail PTC assembly, while native presentation does not require one.
|
||||
The selected executor requires `language: 'typescript'` during schema reads and execution, without falling back to native tools. `isolation` identifies the substrate, not its authority. `sandboxMode` indicates whether the consumer can pass a resolved Session file policy. Missing runtimes fail PTC assembly, while native presentation does not require one.
|
||||
|
||||
Program outcomes resolve as result fields; caller misuse may reject. Lossless binding values cross under provider-owned transport limits. The sandbox mode, denial and enforcement facts are independent from success or failure.
|
||||
|
||||
@@ -88,7 +88,7 @@ The selected OS backend constrains direct Node effects under the same policy use
|
||||
|
||||
### What the model sees
|
||||
|
||||
The SDK declares the loaded runtime's source format and visible tool bindings, instructs the model to call tools through `await tools.name(args)` and catch rejected tool calls when needed, and presents language-specific output instructions. TypeScript selects output through `inspect`; the Python flavor retains return and print output. Independent read-only calls may overlap under `Promise.all` or `asyncio.gather`, mutating calls run alone in submission order, and dependent work sequences with `await`. The declaration prefix can be as large as native schemas, but remains stable for provider caching.
|
||||
The SDK declares the runtime's TypeScript source format and visible tool bindings, instructs the model to call tools through `await tools.name(args)` and catch rejected tool calls when needed, and selects output through `inspect`. Independent read-only calls may overlap under `Promise.all`, mutating calls run alone in submission order, and dependent work sequences with `await`. The declaration prefix can be as large as native schemas, but remains stable for provider caching.
|
||||
|
||||
The transport's own `description` and both SDK instruction flavors open by naming `code` and `description` as the call's two required arguments. Prose that describes the call as passing a program leaves the second argument discoverable only through the parameter schema, and a model that emits `{code}` alone loses the whole written program to an `INVALID_ARGS` rejection.
|
||||
|
||||
@@ -135,6 +135,6 @@ The optional [Node in-memory execution mode](../architecture/2026-09-23-best-eff
|
||||
|
||||
**Large binding values can still exhaust memory.** The Node provider bounds control frames, outstanding arguments and queued writes, while a host binding can allocate its result before those checks. Lossless JSON transfer and the outer output ledger do not create a process-wide allocation quota.
|
||||
|
||||
**Sub-dispatch overlap is bounded by tool safety claims, not by the caller.** A program's `Promise.all` or `asyncio.gather` buys wall-clock parallelism only across calls the tool itself classifies concurrency-safe; a run of exclusive calls still costs its round-trips in sequence, and models may over-expect. Both flavors' SDK instructions state the real contract. This note shipped the serialized placeholder that made the risk absolute; the [live-parallel reference](../../../../packages/core/tools/README.md) owns the scheduler and its overlap cap.
|
||||
**Sub-dispatch overlap is bounded by tool safety claims, not by the caller.** A program's `Promise.all` buys wall-clock parallelism only across calls the tool itself classifies concurrency-safe; a run of exclusive calls still costs its round-trips in sequence, and models may over-expect. The SDK instructions state this constraint; the [live-parallel reference](../../../../packages/core/tools/README.md) owns the scheduler and its overlap cap.
|
||||
|
||||
**Elapsed deadlines include awaited work.** Nested tools and approval waits consume the program's elapsed budget. The host stops execution on expiry and awaits managed cleanup; it does not meter process-tree CPU consumption. The sandboxed Node decision records current defaults and deferred timeout questions.
|
||||
@@ -19,7 +19,7 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一
|
||||
三项决策,各自在下方独立小节中展开:
|
||||
|
||||
1. **PTC mode 是 `ToolRuntime`(`dsh-tools`)的一等呈现模式**,通过经校验的 `mode` 配置选择:`'native'`(默认,贡献可见能力 schema)或 `'ptc'`(注册表仅贡献其保留的 `run_code` 传输通道加一份生成的 SDK `.d.ts` 到系统提示词中)。注册表在源头构建其规范贡献;协作式提示词组装的结果仍具权威性,记录在日志中的请求头精确反映该返回的呈现。
|
||||
2. **代码执行是一个能力 seam**——`packages/ptc-runtime/` 包含 Service Definition 包 `@deepseek-ai/dsh-ptc-runtime`,拥有 `ctx.ptcRuntime`([能力 seam](../architecture/2026-06-13-capability-seams.zh.md);消费方 = `dsh-tools`,core 消费 seam 的先例见 `agent-loop` → `dsh-llm`)。运行时对工具一无所知:它接收一段程序和命名的异步绑定,执行程序,报告 `{ value, logs, error? }`。语言和基底是后端属性,因此未来的 Python 或容器后端只是另一个 Service Provider 包,而非重新设计。
|
||||
2. **代码执行是一个能力 seam**——`packages/ptc-runtime/` 包含 Service Definition 包 `@deepseek-ai/dsh-ptc-runtime`,拥有 `ctx.ptcRuntime`([能力 seam](../architecture/2026-06-13-capability-seams.zh.md);消费方为 `dsh-tool-executor-ptc`)。运行时对工具一无所知:它接收程序和命名的异步绑定,执行程序,并报告输出、可选完成值与可选失败。执行基底和源码语言仍是提供方属性;[仅支持 TypeScript 的执行器决定](../simplification/2026-11-12-typescript-only-ptc.zh.md)拥有工具执行所支持的语言。
|
||||
3. **交付的实现是 `@deepseek-ai/dsh-ptc-runtime-node`**:每个程序在全新的受管 Node 进程中,按调用 Session 的已解析沙箱策略运行。直接 Node API 在该策略内仍可使用;具名 Host 绑定通过单独验证的控制通道调用。
|
||||
|
||||
本说明负责 PTC 呈现、组合与结算。[类型化工具返回决策](2026-07-20-ptc-typed-tool-returns.zh.md)负责生成输出、普通规范绑定值、`ToolCallError` 与无损运行时输出。[显式输出决策](../architecture/2026-11-09-explicit-ptc-output.zh.md)负责 TypeScript 完成值抑制及文本/图片选择。[沙箱 Node 决策](../architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md)取代 worker 执行、信任姿态与预算实现,同时保留本说明的消费方规则。
|
||||
@@ -38,7 +38,7 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一
|
||||
|
||||
**与 `toolOrder` 的交互:** 如果配置的 `systemPrompt.toolOrder` 引用了原生能力名称,在 `mode: 'ptc'` 下会拒绝所有组装,因为那些名称不在该模式的协议校验范围内。这是正确行为而非 bug:使用 PTC mode 的部署需要更新其 order 配置或移除它。
|
||||
|
||||
**SDK 提示词段。** 在 `'ptc'` 下,tool-guidance order band 中的惰性 `tools:sdk` 段为当前 scope 的可见能力渲染所加载运行时语言的声明加固定的使用说明(默认 TypeScript;[语言分发 note](../../archived/feature/2026-07-31-ptc-language-dispatch.md) 加入了 Python 与按 `ctx.ptcRuntime.language` 选择的渲染器表)。它共享查找和执行可见性,排除 `run_code`,并按字典序排列工具以获得字节稳定的输出。
|
||||
**SDK 提示词段。** 在 `'ptc'` 下,tool-guidance order band 中的惰性 `tools:sdk` 段为当前 scope 的可见能力渲染 TypeScript 声明与固定使用说明。它共享查找和执行可见性,排除 `run_code`,并按字典序排列工具以获得字节稳定的输出。
|
||||
|
||||
**组装所有权。** `tools:sdk` 作为正常段进入受信任的 `system-prompt/assemble` 展示 waterfall,而 `run_code` 仍是提供方持有的声明,waterfall 不能移除或替换它。一个 scoped 的 `tools:sdk` 段可以在分发前遮蔽全局默认值,监听器也可以移除或替换该段。修改它的人有责任在部署期望 PTC mode 可用时保持协议面的完整性;没有恢复 pass 会覆盖有意的组合。
|
||||
|
||||
@@ -50,7 +50,7 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一
|
||||
|
||||
1. **构建绑定。** 一个 run 级别的 signal 跟随外层取消,并在 run 结算时被 abort。每个可见工具绑定都会对无损 JSON 参数创建快照,进入原生约定的分发池(调度设计由[实时并行 参考](../../../../packages/core/tools/README.zh.md) 负责),以确定性的 call id 和外层 token 作为 `parent` 执行,通过外层 execution 延后返回的上下文,并记录 `tool/ptc-dispatch-start`/`tool/ptc-dispatch` 事件对,其中结算侧携带完整渲染后的结果内容。成功时返回面向消费方的值,包括指定 TypeScript 绑定的程序 Image;失败则变为程序可见的 `ToolCallError`。每个子调用保留自己不可变的执行标识,并遍历完整的工具流水线。
|
||||
2. **运行已解析输入:** `ctx.ptcRuntime.run(ctx.ptcRuntime.resolve(request))`。请求携带程序、绑定、运行级信号、调用 Session 的 cwd 与适用的已解析文件策略。运行级信号将外层结算与执行取消关联。
|
||||
3. **完全停稳后结算。** 运行时结算后,桥接层 abort 未完成的工作并排空分发队列后再返回。TypeScript 成功结果将捕获日志作为规范输出,并将显式展示的图片投影到持久化的 `tool/result.content`;其他语言消费方还会渲染完成值。结果卡片直接读取该内容。运行时失败变为 `CodeRunFailedError`;后端拒绝使用注册表的正常错误边界。两者都产生结构化的错误结果,且 `run_code` 结算后不允许子调用追加。
|
||||
3. **静止后结算。** 运行时结算后,桥接层中止未完成工作并排空分发队列,再返回结果。成功时以捕获日志作为规范输出,并将检查展示的图片投影到持久化的 `tool/result.content`。结果卡片直接读取该内容。运行时失败转为 `CodeRunFailedError`;后端 rejection 使用注册表的常规错误边界。两者都产生结构化错误结果,且 `run_code` 结算后任何子调用都不能再追加记录。
|
||||
|
||||
**子调用上下文通过父调用延后。** 在 `run_code` 内部注入会破坏父调用/结果的相邻性,因此 `ToolRunContext.deferContext()` 按分发顺序收集每个子结果的 `additionalContexts` 条目。即使程序后来抛出异常,注册表仍携带该数组;循环只在外层结果与步骤中所有兄弟结果之后追加每个条目。外层 post-execute 阻止会丢弃工具延后的条目,只暴露阻止 decision 显式附加的上下文。
|
||||
|
||||
@@ -64,7 +64,7 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一
|
||||
|
||||
每次子分发在进入分发池时追加一个仅日志的 `tool/ptc-dispatch-start` 事件,并以一个 `tool/ptc-dispatch` 结算事件收尾,后者包含父子 call id、工具标识、规范化参数以及完整渲染后的 `content`/`isError` 结果。它不进入模型历史,但可供持久化和 UI 使用。追加发生在开放的 `run_code` 轮次内。没有 agent 的直接执行仍然运行,但无法记录该事件。
|
||||
|
||||
新子调用使用 `<parent>:ptc:<n>` id,按工具调用尝试编号。无效参数在没有分发事件时仍消耗编号,因此日志中的 id 可能有空缺。所有调用 id 对消费方均不透明:迁移逐字节保留每个历史 id,包括 `:code:` 子串,使分发事件对、spill 引用和其他关联保持完整。[显式输出决策](../architecture/2026-11-09-explicit-ptc-output.zh.md)负责 TypeScript 图片呈现;其他语言消费方将转发的图片上下文归属为 `{ kind: 'ptc-mode' }`。
|
||||
新子调用使用 `<parent>:ptc:<n>` id,按工具调用尝试编号。无效参数消耗编号但不产生分发事件,因此日志 id 可以有空缺。所有调用 id 对消费方均不透明:迁移逐字节保留每个历史 id,包括 `:code:` 子串,使分发配对、spill 引用与其他关联保持完整。[显式输出决定](../architecture/2026-11-09-explicit-ptc-output.zh.md)拥有图片呈现。附加上下文保留 `{ kind: 'ptc-mode' }` 归属。
|
||||
|
||||
[V2 到 V3 PTC 规范](../../../../packages/session/session-format-v2-to-v3/README.zh.md#ptc-vocabulary)负责精确的历史标签与归属转换;[原生 V3 准入](../../../../packages/session/session-format-v2-to-v3/README.zh.md#native-v3-admission)负责前代标签拒绝。这些不是运行时别名:不透明扩展不能仅因版本变化就获得 PTC 生命周期含义。
|
||||
|
||||
@@ -72,7 +72,7 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一
|
||||
|
||||
`dsh-ptc-runtime` 负责 `PtcRuntime` 与[请求、已解析 spec、绑定及结果类型](../../../../docs/subsystems/ptc-runtime.zh.md)。`resolve(request)` 验证支持的 cwd、timeout 与策略选择并补全部署默认值;`run(spec)` 执行完整输入。具名异步绑定和可选拒绝构造器使运行时不必了解注册表特定的工具名称。
|
||||
|
||||
`language` 选择 SDK 渲染器与 `run_code` flavor;不支持的语言使组装失败。`isolation` 标识执行基底,不标识权限。`sandboxMode` 表示消费方能否传入已解析 Session 文件策略。缺少运行时使 PTC 组装失败,native 呈现则不需要运行时。
|
||||
已选中的执行器在读取 schema 和执行时要求 `language: 'typescript'`,不回落到 native 工具。`isolation` 标识执行基底,不标识权限。`sandboxMode` 表示消费方能否传入已解析 Session 文件策略。缺少运行时使 PTC 组装失败,native 呈现则不需要运行时。
|
||||
|
||||
程序结果以字段返回;调用方误用可以拒绝。无损绑定值在提供方自己的传输限制下跨越。沙箱模式、拒绝与强制事实独立于成功或失败。
|
||||
|
||||
@@ -88,7 +88,7 @@ Node 提供方擦除可擦除 TypeScript,在配置的文件系统/子进程
|
||||
|
||||
### 模型看到的内容
|
||||
|
||||
SDK 声明所加载运行时的源码格式和可见工具绑定,指示模型通过 `await tools.name(args)` 调用工具、在需要时捕获被拒绝的工具调用,并提供各语言的输出说明。TypeScript 通过 `inspect` 选择输出;Python flavor 保留 return 和 print 输出。相互独立的只读调用可通过 `Promise.all` 或 `asyncio.gather` 重叠,有副作用的调用按提交顺序单独运行,有依赖的工作用 `await` 排序。声明前缀可能与原生 schema 一样大,但对提供方缓存保持稳定。
|
||||
SDK 声明运行时的 TypeScript 源码格式和可见工具绑定,指示模型通过 `await tools.name(args)` 调用工具、在需要时捕获被拒绝的工具调用,并通过 `inspect` 选择输出。相互独立的只读调用可通过 `Promise.all` 重叠,有副作用的调用按提交顺序单独运行,有依赖的工作用 `await` 排序。声明前缀可能与原生 schema 一样大,但对提供方缓存保持稳定。
|
||||
|
||||
传输自身的 `description` 与两种 flavor 的 SDK 说明都以点名 `code` 和 `description` 这两个必填参数开头。把该调用描述成「传入一个程序」的散文会让第二个参数只能从参数 schema 中发现,而只发出 `{code}` 的模型会因 `INVALID_ARGS` 被拒,连同已写好的整个程序一起丢失。
|
||||
|
||||
@@ -135,6 +135,6 @@ SDK 声明所加载运行时的源码格式和可见工具绑定,指示模型
|
||||
|
||||
**大型绑定值仍可能耗尽内存。** Node 提供方限制控制帧、未完成参数和排队写入,而 Host 绑定可以在这些检查前分配其结果。无损 JSON 传输与外层输出账本不构成进程级分配配额。
|
||||
|
||||
**子分发的重叠由工具自身的安全声明限定,而非由调用方决定。** 程序里的 `Promise.all` 或 `asyncio.gather` 只在工具自己分类为并发安全的调用之间换来挂钟并行性;一串 exclusive 调用仍要按顺序付出各自的往返开销,模型可能过度期望。两种 flavor 的 SDK 说明都陈述了真实约定。本 note 交付的是使该风险绝对化的序列化占位实现;调度器及其重叠上限由[实时并行 参考](../../../../packages/core/tools/README.zh.md) 负责。
|
||||
**子分发的重叠由工具自身的安全声明限定,而非由调用方决定。** 程序里的 `Promise.all` 只在工具自己分类为并发安全的调用之间换来挂钟并行性;一串 exclusive 调用仍要按顺序付出各自的往返开销,模型可能过度期望。SDK 说明陈述了这项限制;调度器及其重叠上限由[实时并行 参考](../../../../packages/core/tools/README.zh.md) 负责。
|
||||
|
||||
**经过时间截止包括被等待的工作。** 嵌套工具和审批等待消耗程序的经过时间预算。Host 在截止到期时停止执行并等待受管清理;它不计量进程树 CPU 消耗。沙箱 Node 决策记录当前默认值与延后评估的 timeout 问题。
|
||||
@@ -9,8 +9,8 @@
|
||||
en: e2403bc358c4e14b
|
||||
zh: dd37923097a3b24c
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/decision:
|
||||
en: 6dd62ee16c69536c
|
||||
zh: aec9fa1c74be28e5
|
||||
en: 6e6b4ee0a37a7a9a
|
||||
zh: 9f9ee75e55f58958
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/decision/generated-sdk:
|
||||
en: 30583e9ac6715952
|
||||
zh: 3a85c9482abf574c
|
||||
@@ -18,14 +18,14 @@
|
||||
en: 8b10f08e67ca9323
|
||||
zh: e57adb520049f407
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/decision/outer-result-and-output-ledger:
|
||||
en: d57456d76fed9c6d
|
||||
zh: 453775faad48588c
|
||||
en: e48ef4dbe1ac9a1e
|
||||
zh: b87b0c0a3f1c2a4e
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/decision/typed-handles-and-lifetime:
|
||||
en: b2b9318c2812e3a4
|
||||
zh: 73cf34bfd487e2f1
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/decision/persistence-metadata-and-spill:
|
||||
en: 2c3ad4ec376ed2d5
|
||||
zh: 49e8206a4c17b1b3
|
||||
en: c6c4c3162b4c5f8e
|
||||
zh: fb6704409ba8b4a2
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/testing:
|
||||
en: 81a4355914c918cf
|
||||
zh: 36aa414cd382ff9c
|
||||
|
||||
@@ -14,7 +14,7 @@ The [canonical tool-output contract](../../../../packages/core/tools/README.md)
|
||||
|
||||
## Decision
|
||||
|
||||
PTC mode is a typed projection of the visible tool registry. Ordinary successful bindings resolve to the final canonical `JsonValue` after post-execute policy, while failed bindings reject with a real `ToolCallError`. Intermediate values remain inside the run and cross the process boundary whole. The [explicit output decision](../architecture/2026-11-09-explicit-ptc-output.md) owns TypeScript Image bindings, completion suppression and selection of visible text and images. Other language consumers retain completion rendering and deferred image-bearing content.
|
||||
PTC mode is a typed projection of the visible tool registry. Ordinary successful bindings resolve to the final canonical `JsonValue` after post-execute policy, while failed bindings reject with a real `ToolCallError`. Intermediate values remain inside the run and cross the process boundary whole. The [explicit output decision](../architecture/2026-11-09-explicit-ptc-output.md) owns TypeScript Image bindings, completion suppression and selection of visible text and images. The [TypeScript-only executor decision](../simplification/2026-11-12-typescript-only-ptc.md) owns supported languages.
|
||||
|
||||
This note owns the return and failure contract layered on the original [PTC mode foundation](2026-06-15-ptc.md). The unified schema vocabulary is owned by the [JSON-value schema DSL reference](../../../../packages/core/tools/README.md), and Native rendering and policy projection remain owned by the canonical-output note.
|
||||
|
||||
@@ -57,7 +57,7 @@ Ordinary binding arguments and JSON resolutions are revalidated as lossless JSON
|
||||
|
||||
### Outer result and output ledger
|
||||
|
||||
Runtime consumers that retain completions receive exact lossless JSON: `undefined` omits the completion and `null` is an explicit result. TypeScript `run_code` requests completion discard and returns captured logs plus optional sandbox facts as its canonical value; selected images enter its rendered content separately. Other language consumers also expose `result?: JsonValue`. Their renderer emits logs first, renders a string result raw, and renders every other JSON root with an iterative pretty printer. Total indentation is capped at ten characters and deeper subtrees remain compact, keeping traversal stack-safe and formatted size linear in the canonical JSON size.
|
||||
Runtime consumers that retain completions receive exact lossless JSON: `undefined` omits the completion and `null` is an explicit result. TypeScript `run_code` requests completion discard and returns captured logs plus optional sandbox facts as its canonical value; selected images enter its rendered content separately.
|
||||
|
||||
`NodePtcRuntime` replaces the former independent log and value caps with configurable `maxOutputBytes`, defaulting to `67_108_864` bytes. The worker charges captured logs by their exact JSON-string serialization and preflights the detached completion or program exception against the remaining combined budget before posting a terminal message. A giant thrown string or stack therefore crosses the worker port only as the fixed `output-limit` diagnostic. The host repeats the hostile-peer ledger for forged traffic and native pipe writes the worker cannot observe. Fixed `PtcRunResult` field names, braces, the bounded error-kind tag, and later presentation whitespace are deliberately outside this variable-payload ledger. Neither stage materializes an over-limit serialized completion. A result at or below the cap is exact. A completion that cannot survive lossless JSON snapshotting fails as `invalid-output`; a value, diagnostic, or combined outcome over the cap fails as `output-limit` rather than becoming inspected or truncated text.
|
||||
|
||||
@@ -73,7 +73,7 @@ Temporary Cordis Plugins follow the same rule: `cordis_mount` returns `{ id, plu
|
||||
|
||||
### Persistence, metadata, and spill
|
||||
|
||||
Nested dispatch logs the sub-call's full rendered `content`/`isError` on `tool/ptc-dispatch` but does not persist canonical values. TypeScript programs select images for the outer `tool/result.content` through explicit inspection. Other language consumers defer successful image-bearing content as source-attributed user messages after the outer result. The normal Session events make these model-visible inputs reconstructable. The [PTC mode note](2026-06-15-ptc.md) owns durable event names and historical identity preservation; replay cannot recreate intermediate canonical program values.
|
||||
Nested dispatch logs the sub-call's full rendered `content`/`isError` on `tool/ptc-dispatch` but does not persist canonical values. TypeScript programs select images for the outer `tool/result.content` through explicit inspection. The normal Session events make these model-visible inputs reconstructable. The [PTC mode note](2026-06-15-ptc.md) owns durable event names and historical identity preservation; replay cannot recreate intermediate canonical program values.
|
||||
|
||||
The opaque `exec.parent` token marks nested calls. Presentation metadata and generic or tool-owned spill projections skip those calls; their canonical values never enter context. The Client can derive [nested terminal cards](../../../../packages/client/ui-tool/README.md) from raw dispatch events without metadata. The outer `run_code` call produces the model-facing result and may spill its final post-policy presentation; `run_code` intentionally declares neither a result presenter nor presentation metadata, so UI adapters complete the card through their generic raw-content fallback using durable `tool/result.content`.
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ PTC mode 过去会把每个嵌套工具的结果从 `ContentBlock[]` 重新投
|
||||
|
||||
## 决策
|
||||
|
||||
PTC mode 是可见工具注册表的类型化投影。普通成功绑定调用解析为 post-execute 策略处理后的最终规范 `JsonValue`,失败的绑定调用则以真正的 `ToolCallError` 拒绝 Promise。中间值保留在运行中,并完整跨越进程边界。[显式输出决策](../architecture/2026-11-09-explicit-ptc-output.zh.md)负责 TypeScript Image 绑定、完成值抑制及可见文本和图片的选择。其他语言消费方保留完成值渲染和含图片内容的延后转发。
|
||||
PTC mode 是可见工具注册表的类型化投影。普通成功绑定调用解析为 post-execute 策略处理后的最终规范 `JsonValue`,失败的绑定调用则以真正的 `ToolCallError` 拒绝 Promise。中间值保留在运行中,并完整跨越进程边界。[显式输出决策](../architecture/2026-11-09-explicit-ptc-output.zh.md)负责 TypeScript Image 绑定、完成值抑制及可见文本和图片的选择。[仅支持 TypeScript 的执行器决定](../simplification/2026-11-12-typescript-only-ptc.zh.md)拥有受支持语言。
|
||||
|
||||
本文档定义叠加在原始 [PTC mode 基础](2026-06-15-ptc.zh.md)之上的返回值与失败约定。统一 schema 词汇由 [JSON 值 schema DSL reference](../../../../packages/core/tools/README.zh.md)负责定义;Native 渲染与策略投影仍由规范输出 Agent Note 负责定义。
|
||||
|
||||
@@ -57,7 +57,7 @@ PTC mode 通过运行时请求中的 `{ name: "ToolCallError", memberNamePropert
|
||||
|
||||
### 外层结果与输出账本
|
||||
|
||||
保留完成值的运行时消费方接收精确无损 JSON:`undefined` 省略完成值,`null` 是显式结果。TypeScript `run_code` 请求丢弃完成值,将捕获日志和可选沙箱信息作为规范值返回;所选图片单独进入渲染内容。其他语言消费方还提供 `result?: JsonValue`。其渲染器先输出日志,字符串结果保持原文,其他 JSON 根值使用迭代式美化渲染器。总缩进长度上限为十个字符,更深子树保持紧凑格式,使遍历不受调用栈深度限制,且格式化大小与规范 JSON 大小呈线性关系。
|
||||
保留完成值的运行时消费方接收精确无损 JSON:`undefined` 省略完成值,`null` 是显式结果。TypeScript `run_code` 请求丢弃完成值,将捕获日志和可选沙箱信息作为规范值返回;所选图片单独进入渲染内容。
|
||||
|
||||
`NodePtcRuntime` 以可配置的 `maxOutputBytes` 取代彼此独立的日志与值上限,默认值为 `67_108_864` 字节。worker 会将已捕获日志序列化为 JSON 字符串后的精确字节数计入账本,并在发送终态消息前,根据组合账本的剩余额度预检分离后的完成值或程序异常。因此,即使抛出的字符串或堆栈极大,通过 worker 端口的也只会是固定的 `output-limit` 诊断。宿主侧会针对伪造流量以及 worker 无法观察的原生管道写入,重复执行这套面向不可信对端的账本校验。固定的 `PtcRunResult` 字段名、花括号、有界的错误类型标签及后续展示空白有意不计入这份可变负载账本。这两个阶段都不会实际生成超出上限的完成值序列化结果。结果不超过上限时会保持精确。完成值无法通过无损 JSON 快照时,以 `invalid-output` 失败;值、诊断或包含日志的组合结果超过上限时,以 `output-limit` 失败,而不会变成检查格式化后或截断的文本。
|
||||
|
||||
@@ -73,7 +73,7 @@ PTC mode 通过运行时请求中的 `{ name: "ToolCallError", memberNamePropert
|
||||
|
||||
### 持久化、元数据与 spill
|
||||
|
||||
嵌套分发在 `tool/ptc-dispatch` 上记录子调用完整渲染后的 `content`/`isError`,但不会持久化规范值。TypeScript 程序通过显式展示为外层 `tool/result.content` 选择图片。其他语言消费方将成功的含图片内容作为带来源归属的用户消息,延后到外层结果之后。普通 Session 事件使这些模型可见输入可以重建。[PTC mode note](2026-06-15-ptc.zh.md)负责持久事件名称与历史标识保留规则;回放无法重建程序的规范中间值。
|
||||
嵌套分发在 `tool/ptc-dispatch` 上记录子调用完整渲染后的 `content`/`isError`,但不会持久化规范值。TypeScript 程序通过显式展示为外层 `tool/result.content` 选择图片。普通 Session 事件使这些模型可见输入可以重建。[PTC mode note](2026-06-15-ptc.zh.md)负责持久事件名称与历史标识保留规则;回放无法重建程序的规范中间值。
|
||||
|
||||
不透明的 `exec.parent` token 用于标识嵌套调用。展示元数据以及通用或工具自有的 spill 投影都会跳过这些调用;它们的规范值永远不会进入上下文。Client 可以从原始分发事件派生[嵌套 terminal 卡片](../../../../packages/client/ui-tool/README.zh.md),无需元数据。外层 `run_code` 调用产生面向模型的结果,并且可能对 post-policy 处理后的最终展示执行 spill;`run_code` 有意既不声明结果展示器,也不声明展示元数据,因此 UI 适配器会通过通用的原始内容回退机制,使用持久化的 `tool/result.content` 补全该卡片。
|
||||
|
||||
|
||||
+2
-2
@@ -15,5 +15,5 @@
|
||||
en: 1e2239783738cec2
|
||||
zh: 5f248eee47de376e
|
||||
/agent-note-session-change-request-bindings/consequences:
|
||||
en: a2960e50ec52c9b6
|
||||
zh: fd23f4fe1137787d
|
||||
en: 2786b1dffa995c14
|
||||
zh: c124420915da5aae
|
||||
@@ -30,4 +30,4 @@ After each push result, and when a caller such as the forge panel reports the br
|
||||
|
||||
## Consequences
|
||||
|
||||
Bindings appear without model cooperation for the common `gh pr create`, `gh pr view`, `gh pr edit`, `gh pr checkout`, and `git push` flows and add no model tokens. Commands run through scripts, aliases, or other command-line tools are not recognized, and a change request opened elsewhere for a branch appears only after another push, another report of that branch, or a `track`. Another provider adds its own access and URL forms behind the same provider contract without changing the binding rules or the polling. The host needs `gh` signed in for each GitHub host.
|
||||
Bindings appear without model cooperation for the common `gh pr create`, `gh pr view`, `gh pr edit`, `gh pr checkout`, and `git push` flows and add no model tokens. Commands run through scripts, aliases, or other command-line tools are not recognized, and a change request opened elsewhere for a branch appears only after another push, another report of that branch, or a `track`. Another provider adds its own access and URL forms behind the same provider contract and registers its CLI's commands as a [command rule](2026-11-11-forge-provider-command-rules.md), without changing the polling. The host needs `gh` signed in for each GitHub host.
|
||||
@@ -30,4 +30,4 @@ Status: implemented
|
||||
|
||||
## Consequences
|
||||
|
||||
在常见的 `gh pr create`、`gh pr view`、`gh pr edit`、`gh pr checkout` 与 `git push` 流程中,绑定无需模型配合即可出现,且不增加模型 token。通过脚本、别名或其他命令行工具运行的命令无法识别;在别处为某个分支打开的变更请求,要等到下一次推送、再次报告该分支或 `track` 之后才会出现。新的提供方在同一提供方契约之后加入自己的访问方式与 URL 形式,无需改变绑定规则或轮询。宿主需要为每个 GitHub 主机登录 `gh`。
|
||||
在常见的 `gh pr create`、`gh pr view`、`gh pr edit`、`gh pr checkout` 与 `git push` 流程中,绑定无需模型配合即可出现,且不增加模型 token。通过脚本、别名或其他命令行工具运行的命令无法识别;在别处为某个分支打开的变更请求,要等到下一次推送、再次报告该分支或 `track` 之后才会出现。新的提供方在同一提供方契约之后加入自己的访问方式与 URL 形式,并把其 CLI 的命令注册为[命令规则](2026-11-11-forge-provider-command-rules.zh.md),无需改变轮询。宿主需要为每个 GitHub 主机登录 `gh`。
|
||||
@@ -0,0 +1,31 @@
|
||||
# Bilingual-pair consistency record for 2026-10-23-session-reading-memory.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-10-23-session-reading-memory.md
|
||||
/agent-note-host-memory-session-reading-state:
|
||||
en: d0d93ca91b0bfd16
|
||||
zh: 55f67f2074612e4d
|
||||
/agent-note-host-memory-session-reading-state/problem:
|
||||
en: 61f665a6dc1bc503
|
||||
zh: 3421cf192528179e
|
||||
/agent-note-host-memory-session-reading-state/decision:
|
||||
en: a15c7c13f167e5ac
|
||||
zh: 63bcc2ef60c2f344
|
||||
/agent-note-host-memory-session-reading-state/decision/package-structure:
|
||||
en: e22765435a1ab422
|
||||
zh: 7ac9fbcea4c15387
|
||||
/agent-note-host-memory-session-reading-state/decision/client-dependency-rules:
|
||||
en: e38746215940a163
|
||||
zh: a4e343dac7942aa2
|
||||
/agent-note-host-memory-session-reading-state/decision/host-records:
|
||||
en: ea1b8aa4ed60f04c
|
||||
zh: 9c979b7b40eacb3e
|
||||
/agent-note-host-memory-session-reading-state/decision/automatic-acknowledgement:
|
||||
en: 64f9e14597dbc3d4
|
||||
zh: e2d20a5105c9d950
|
||||
/agent-note-host-memory-session-reading-state/alternatives-considered:
|
||||
en: 755d2e5eb626b445
|
||||
zh: 898f83b86d2e2209
|
||||
/agent-note-host-memory-session-reading-state/consequences:
|
||||
en: 01f6beaeff1e6c7f
|
||||
zh: 1fdee75b2c4bf646
|
||||
@@ -0,0 +1,58 @@
|
||||
# Agent Note: Host-memory Session reading state
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-10-23-session-reading-memory.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Clients connected to the same Host need consistent reading reminders, including completions that end while every Client is offline. Automatic acknowledgements must not clear unseen completions or manual unread marks. Reading activity must not change model history. The reminders appear in the Client Session status table that [`@deepseek-ai/dsh-client-ui-session-status`](../../../../packages/client/ui-session-status/README.md) owns, so the reading records, their Client follower, and the table that consumes them need one owner whose Client face may follow a Host Remote stream.
|
||||
|
||||
## Decision
|
||||
|
||||
### Package structure
|
||||
|
||||
`@deepseek-ai/dsh-client-ui-session-status` owns the feature on both faces, following the Host-and-Client package precedent of ui-trajectory:
|
||||
|
||||
| Face | Service | Responsibility |
|
||||
|---|---|---|
|
||||
| Host (`.`) | `ctx.sessionStatus` (`SessionStatusService`) | Keeps one reading record per Session in an in-memory Map; the `sessionStatus` Remote namespace serves `mark` and `follow`; failures use `session-status/not-found` and `session-status/unavailable` |
|
||||
| Client (`./client`) | `ctx.uiSession.sessionStatus` (service name `uiSession.sessionStatus`) | Follows the Host reading stream, builds the status table with `completionUnread` and `completionFailed`, exposes `mark` and `readingReady`, and acknowledges main-view reading |
|
||||
|
||||
The Client copy of the reading records is a package-internal module: it exports no value or type and provides no Client service of its own, so consumers such as ui-workspace and ui-conversation depend only on `ctx.uiSession.sessionStatus` and the exported status types. The Web bundle's single `ui-session-status` row loads both faces, api/remotes mounts the package's `/remote` descriptor, and the Web client lists the package among its required boot entries. ui-session, pending-interaction registration, and `ctx.uiSession.pendingInteractions` stay unchanged.
|
||||
|
||||
### Client dependency rules
|
||||
|
||||
Following the Host stream needs the Gateway's `RemoteSnapshotStream` at runtime. `verify-client-packages` lets a `packages/client` feature package request rows under `packages/api/` through `dsh.client.external`, while still rejecting requests for another feature plugin's row; the Remote API group is infrastructure, not a feature plugin. The package requests only `@deepseek-ai/dsh-api-gateway/client`. The stream runs only while `ctx.remoteAccess` allows `sessionStatus/follow`; that endpoint is owner-only for LiveShare, so a viewer page opens no stream, keeps `readingReady` false, and reports no synchronization failure.
|
||||
|
||||
`RemoteStream` decides reconnection by the stable error code `gateway/carrier-lost` rather than by `instanceof RemoteStreamCarrierError`. The class carries that code, so existing callers keep their behavior, and the package's `ended` callback returns a plain `Error` with the code, typed by the exported `RemoteStreamCarrierFailure` type, without importing the class. The code is produced only inside the Client process: a `RemoteError` returned by the Host terminates the stream even when it carries the same code.
|
||||
|
||||
### Host records
|
||||
|
||||
The Host service owns one in-memory record per Session and derives the latest ended turn and its failure flag from `turn/end` events itself. Mutations update the Map synchronously. Read actions carry the Client-observed completed turn; the Host advances the read position monotonically and never beyond its known completion. Automatic acknowledgements leave manual unread unchanged; explicit marks replace it in Host processing order. Only the ordered baseline and whole-record change stream updates the Client, so mutation replies need no record or revision.
|
||||
|
||||
Cold Session marks read metadata without opening history. A Session without a record reads as read, so history neither needs a startup scan nor distinguishes a cold Session from a live zero-turn one. Shutdown closes followers and clears records. A pending metadata lookup rejects its mark after disposal rather than delaying teardown for an in-memory write.
|
||||
|
||||
### Automatic acknowledgement
|
||||
|
||||
Only a visible, focused main view acknowledges reading, after a rendering frame and evidence that the body reached the completed turn. Window focus advances only the natural read position. A main-view switch to a different Session, including the first selection after a page load, clears that Session's existing manual reminder once its body arrives; the check waits for a ready reading baseline. Window focus, a replaced binding for the same Session, and activity in the open Session do not clear it, so a mark made in the open Session stays until the view leaves and returns. Later automatic acknowledgements preserve manual marks, including those received while the body loads. Keeping the rule inside the acknowledgement plugin avoids a cross-package reading event and changes to the Conversation body. While the visible, focused main view retains an open Session, the status table does not show that Session's unacknowledged completion, so its row does not flash unread before the acknowledgement round trip; manual marks stay visible, and the reminder returns when the window loses focus or the view moves away first. Archived rows read as read and offer no reading mark.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- **ui-session reads reading state:** the base UI package would depend on a feature package, and every UI above it could not start without the reading plugin.
|
||||
- **A separate reading package with a Client service:** consumers would see a second reading API beside `ctx.uiSession.sessionStatus`, and the status table would depend on another package's service only to fold its records.
|
||||
- **An api-group reading package beside the client table:** splits one feature across two packages whose Host contract, Client follower, and table evolve together; the relaxed external rule lets the client package follow the stream itself.
|
||||
- **Reimplementing the snapshot protocol over `ctx.remote.$stream`:** duplicates Gateway-owned baseline and reconnection logic in a feature package.
|
||||
- **Importing `RemoteStreamCarrierError` into the client package:** a feature package would depend on a Gateway class identity for one retry decision; a stable code states the decision without class identity across separately bundled modules.
|
||||
- **Host face in the shared base bundle:** profiles without a Web Client would run a reading service no Client reads, and the Host face would load from a different bundle than its Client face.
|
||||
- **Frontend memory or local storage:** cannot provide one authority for browsers and Desktop clients, or collect completions while all frontends are offline.
|
||||
- **Persistent Host records:** preserve reminders across Host restarts but require a separate lifecycle design for Session checkpoints, domain ownership, backend shutdown, and failed writes. This implementation deliberately limits ownership to memory; persistence is a separate change.
|
||||
- **Reading events in the Session log:** mix viewer intent with model history and require loading cold histories for metadata-only actions.
|
||||
- **Revision-based conditional writes:** prevent delayed explicit actions from replacing newer manual intent, but require conflict responses, revision bookkeeping and unary-result reconciliation. Session reminders accept Host processing order instead. A read-position cursor still prevents unseen completions from being acknowledged.
|
||||
- **Message ID cursor:** identifies a message but does not order completed turns, including failures without a new assistant message. The existing completed-turn number directly represents this feature's unit of progress.
|
||||
|
||||
## Consequences
|
||||
|
||||
Browser refresh and temporary disconnect preserve reminders while this Host service runs. Host restart or plugin reload resets every reading record and treats existing history as read; a turn that failed before the restart leaves no outcome, so marking that Session unread shows the ordinary reminder. Profiles without the Web bundle run no reading service. There are no read-state files, storage-domain dependencies, checkpoint writes, or cross-process synchronization guarantees. Reminders remain for detached Sessions until the service stops; reclaiming records requires a Session deletion lifecycle.
|
||||
|
||||
Concurrent explicit actions have last-processed semantics; an entry acknowledgement can clear another manual mark that arrives before it is processed. Verification covers two followers, monotonic read positions and manual-mark preservation during automatic acknowledgements, a first completion after manual marks, access-driven rebaselines, shutdown with a pending metadata lookup, service reload, independence from Session flush, and the failure flag of a completing turn. Client tests cover the reading stream's baseline replacement and terminal failure, delayed body delivery, manual marks during loading, and manual-reminder clearing on main-view switches but not on window focus or a replaced binding. Gateway tests cover reconnection for a plain error carrying the carrier code and termination without it. Persistent restart recovery, crash consistency, storage-provider ordering, and cross-process writers require separate validation before persistence is enabled. The main-view retention signal does not distinguish every settings or auxiliary panel; that visibility refinement remains part of the notification work.
|
||||
@@ -0,0 +1,58 @@
|
||||
# Agent Note: 宿主内存中的会话阅读状态
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-10-23-session-reading-memory.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
连接同一宿主的前端需要一致的阅读提醒,包括所有前端都离线时结束的轮次。自动阅读确认不能清除尚未看到的完成提醒或手动未读标记。阅读行为不能改变模型历史。这些提醒显示在 [`@deepseek-ai/dsh-client-ui-session-status`](../../../../packages/client/ui-session-status/README.zh.md) 拥有的前端会话状态表中,因此阅读记录、它的前端订阅方和使用它的状态表需要同一个归属方,而且其前端面能够订阅宿主 Remote 流。
|
||||
|
||||
## 决策
|
||||
|
||||
### 包结构
|
||||
|
||||
`@deepseek-ai/dsh-client-ui-session-status` 在两个面上拥有该功能,沿用 ui-trajectory 同时提供宿主面和前端面的先例:
|
||||
|
||||
| 面 | 服务 | 职责 |
|
||||
|---|---|---|
|
||||
| 宿主(`.`) | `ctx.sessionStatus`(`SessionStatusService`) | 在内存 Map 中为每个会话保存一条阅读记录;Remote 命名空间 `sessionStatus` 提供 `mark` 和 `follow`;失败使用 `session-status/not-found` 和 `session-status/unavailable` |
|
||||
| 前端(`./client`) | `ctx.uiSession.sessionStatus`(服务名 `uiSession.sessionStatus`) | 订阅宿主阅读流,构建含 `completionUnread` 和 `completionFailed` 的状态表,提供 `mark` 和 `readingReady`,并确认主视图已读 |
|
||||
|
||||
前端的阅读记录副本是包内部模块:它不导出任何值或类型,也不提供自己的前端服务,因此 ui-workspace、ui-conversation 等使用方只依赖 `ctx.uiSession.sessionStatus` 和导出的状态类型。Web bundle 中唯一的 `ui-session-status` 行加载两个面,api/remotes 挂载本包的 `/remote` 描述,Web 前端把本包列为启动必需入口。ui-session、待交互登记和 `ctx.uiSession.pendingInteractions` 保持不变。
|
||||
|
||||
### 前端依赖规则
|
||||
|
||||
订阅宿主流在运行时需要 Gateway 的 `RemoteSnapshotStream`。`verify-client-packages` 允许 `packages/client` 下的功能包通过 `dsh.client.external` 请求 `packages/api/` 下的行,但仍拒绝请求另一个功能插件的行;Remote API 组是基础设施,不是功能插件。本包只请求 `@deepseek-ai/dsh-api-gateway/client`。只有 `ctx.remoteAccess` 允许 `sessionStatus/follow` 时才运行该流;该端点在 LiveShare 中仅限所有者,因此查看者页面不打开该流,`readingReady` 保持 false,也不报告同步失败。
|
||||
|
||||
`RemoteStream` 按稳定的 error code `gateway/carrier-lost` 判断是否重连,而不是按 `instanceof RemoteStreamCarrierError`。该 class 自带这个 code,现有调用方行为不变;本包的 `ended` 回调返回带该 code 的普通 `Error`,用导出的 `RemoteStreamCarrierFailure` 类型描述,而不导入该 class。该 code 只在前端进程内产生:宿主返回的 `RemoteError` 即使带有相同 code 也会终止流。
|
||||
|
||||
### 宿主记录
|
||||
|
||||
宿主服务在内存中为每个会话保存一条记录,自己从 `turn/end` 事件取得最近结束的轮次及其失败标记。修改同步更新 Map。已读请求携带前端已看到的完成轮次;宿主单调推进阅读位置,且不越过已知完成位置。自动确认保留手动未读,主动标记按宿主处理顺序替换它。前端只通过有序基线和整条记录的更新流取得状态,修改回复不需要记录或版本。
|
||||
|
||||
对冷会话的标记只读取元信息,不打开历史。没有记录的会话按已读处理,因此历史既不需要启动扫描,也不需要区分冷会话和零轮次的活跃会话。关闭时结束订阅并清空记录;尚在等待元信息的标记请求会在查询返回后被拒绝,不会为了内存写入延迟卸载。
|
||||
|
||||
### 自动确认
|
||||
|
||||
只有可见且聚焦的主视图会确认阅读,并等待一次渲染帧及正文已到达完成轮次的证据。窗口聚焦只推进自然已读位置。主视图切换到另一个会话(包括页面加载后的首次选中)时,会在正文到达后清除该会话已有的手动提醒;检查会等待阅读基线就绪。窗口聚焦、同一会话更换 binding 以及在已打开会话中的操作都不会清除它,因此在已打开会话中做的标记会保留到视图切走再切回。后续自动确认保留手动标记,包括正文加载期间收到的标记。把规则留在确认插件内部,可以避免跨包的阅读事件,也不需要修改 Conversation 正文。可见且聚焦的主视图持有某个已打开的会话时,状态表不显示该会话尚未确认的完成轮次,避免在确认往返完成前闪现未读;手动标记照常显示,窗口失焦或视图先行切走时提醒会重新出现。归档行按已读处理,不提供阅读标记。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
- **ui-session 读取阅读状态:** 基础 UI 包会依赖功能包,阅读插件缺席时其上的所有界面都无法启动。
|
||||
- **单独的阅读包并提供前端服务:** 使用方会在 `ctx.uiSession.sessionStatus` 之外看到第二套阅读 API,状态表也只为汇总记录而依赖另一个包的服务。
|
||||
- **在前端状态表旁另建 api 组阅读包:** 把一个功能拆到两个包中,而宿主接口、前端订阅方和状态表同步演进;放宽 external 规则后,前端包可以自己订阅该流。
|
||||
- **在 `ctx.remote.$stream` 之上重写快照协议:** 会在功能包中复制 Gateway 负责的基线与重连逻辑。
|
||||
- **在前端包中导入 `RemoteStreamCarrierError`:** 功能包会为一次重试判断依赖 Gateway 的 class 身份;稳定的 code 能表达这一判断,而不依赖跨独立打包模块的 class 身份。
|
||||
- **宿主面放在共享基础 bundle:** 没有 Web 前端的 profile 会运行无人读取的阅读服务,宿主面也会与前端面从不同的 bundle 加载。
|
||||
- **前端内存或本地存储:** 无法为浏览器和 Desktop 前端提供共同的权威状态,也无法收集所有前端离线期间的完成提醒。
|
||||
- **宿主持久化记录:** 能够让提醒跨宿主重启保留,但需要单独设计会话检查点、存储域归属、后端关闭及写入失败的生命周期。本实现将状态限制在内存,持久化另行实现。
|
||||
- **在会话日志中记录阅读事件:** 会把使用者意图混入模型历史,并使只需元信息的操作也要加载冷会话历史。
|
||||
- **按版本条件写入:** 可防止延迟的主动操作覆盖较新的手动意图,但需要冲突响应、版本维护和请求响应的状态合并。会话提醒接受宿主处理顺序,仍保留阅读位置以防误读新完成内容。
|
||||
- **消息 ID 游标:** 只能定位消息,不能直接排序已完成轮次,也不能覆盖未产生新助手消息的失败。已有完成轮次直接对应本功能的进度单位。
|
||||
|
||||
## 结果
|
||||
|
||||
宿主服务运行期间,刷新浏览器或临时断线会保留提醒。宿主重启或插件重载会重置全部阅读记录,并把已有历史视为已读;重启前失败的轮次不留下结果,因此把该会话标为未读时显示普通提醒。不含 Web bundle 的 profile 不运行阅读服务。没有阅读状态文件、存储域依赖、检查点写入或跨进程同步保证。会话从内存卸载后,其提醒保留到服务停止;回收记录需要会话删除生命周期。
|
||||
|
||||
并发主动操作以宿主最后处理的操作为准;进入视图的确认可能清除处理前到达的另一条手动标记。验证覆盖双订阅、单调阅读位置与自动确认保留手动标记、手动标记后的首次完成、访问权限变化后的新基线、元信息查询期间关闭、服务重载、不依赖会话刷盘,以及结束轮次的失败标记。前端测试覆盖阅读流的基线替换与终态失败、正文延迟、加载期间的手动标记,以及主视图切换时清除手动提醒、窗口聚焦或更换 binding 时不清除。Gateway 测试覆盖带 carrier code 的普通错误会重连、不带 code 时终止。启用持久化前,需单独验证重启恢复、崩溃一致性、存储提供方关闭顺序和跨进程写入。当前主视图保留信号不能区分所有设置或辅助面板;该可见性细化仍属于通知工作的范围。
|
||||
@@ -0,0 +1,61 @@
|
||||
# Bilingual-pair consistency record for 2026-11-11-deepseek-chat-export-import.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-11-11-deepseek-chat-export-import.md
|
||||
/agent-note-import-deepseek-website-chat-exports:
|
||||
en: 28f67da94fa101de
|
||||
zh: e532503740e4516e
|
||||
/agent-note-import-deepseek-website-chat-exports/problem:
|
||||
en: bb08ceef4dc54b8b
|
||||
zh: ff1a4235fadd19ee
|
||||
/agent-note-import-deepseek-website-chat-exports/decision:
|
||||
en: d80db86d5c5fb6c0
|
||||
zh: 786606a16d47635c
|
||||
/agent-note-import-deepseek-website-chat-exports/decision/user-flow:
|
||||
en: 3bb8080e42c2da26
|
||||
zh: eb67425c1715df6f
|
||||
/agent-note-import-deepseek-website-chat-exports/decision/package-layout:
|
||||
en: 08f6a8305084e5b3
|
||||
zh: 779f957ba5193525
|
||||
/agent-note-import-deepseek-website-chat-exports/decision/host-route-and-remote:
|
||||
en: ff13a60cd73612a1
|
||||
zh: a0e625b6d7e05041
|
||||
/agent-note-import-deepseek-website-chat-exports/decision/reading-the-export:
|
||||
en: 5069430168c5ae98
|
||||
zh: dc086ec1f236be9a
|
||||
/agent-note-import-deepseek-website-chat-exports/decision/selecting-the-conversations:
|
||||
en: 4628cc1e25d90a26
|
||||
zh: 8649b3e0b0210510
|
||||
/agent-note-import-deepseek-website-chat-exports/decision/linearizing-the-message-tree-selectbranch:
|
||||
en: 4ee78fb3a40ded8e
|
||||
zh: 3fda20e2db2cd37d
|
||||
/agent-note-import-deepseek-website-chat-exports/decision/message-chain-to-session-events-convertconversation:
|
||||
en: 542149b99f8d3ea5
|
||||
zh: c0fa9f8c545d54a2
|
||||
/agent-note-import-deepseek-website-chat-exports/decision/fragment-mapping:
|
||||
en: 98282c93efe3d169
|
||||
zh: 3b79663b9020ad7e
|
||||
/agent-note-import-deepseek-website-chat-exports/decision/reply-status-mapping:
|
||||
en: a2ce8fc69fb38cd3
|
||||
zh: b65234fce7922b96
|
||||
/agent-note-import-deepseek-website-chat-exports/decision/session-writes:
|
||||
en: b4d436e605cb2a24
|
||||
zh: e48735e9db5099ca
|
||||
/agent-note-import-deepseek-website-chat-exports/decision/client:
|
||||
en: 382e0c201bcde038
|
||||
zh: 710f67a5b0d89dc4
|
||||
/agent-note-import-deepseek-website-chat-exports/decision/realization:
|
||||
en: 8803b6ec2edc20e3
|
||||
zh: 43dfee5ffcfff4a2
|
||||
/agent-note-import-deepseek-website-chat-exports/decision/images:
|
||||
en: 3c185fa06a8c0af3
|
||||
zh: d51787e832337107
|
||||
/agent-note-import-deepseek-website-chat-exports/decision/testing:
|
||||
en: 7644a5531582a3d4
|
||||
zh: a8153a60ca46815d
|
||||
/agent-note-import-deepseek-website-chat-exports/alternatives-considered:
|
||||
en: 94b324f44acde29b
|
||||
zh: 549bdc73ae18a23a
|
||||
/agent-note-import-deepseek-website-chat-exports/consequences:
|
||||
en: ecbbfb4a245d89c9
|
||||
zh: 400f4469bf352ea0
|
||||
@@ -0,0 +1,266 @@
|
||||
# Agent Note: Import DeepSeek website chat exports
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-11-deepseek-chat-export-import.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
The "export all chats" action on the DeepSeek website (chat.deepseek.com) produces a `deepseek_data-*.zip`. Users want to bring these conversations into DSH and keep using them: browse the original questions, reasoning, and answers in the Web GUI, and continue any conversation with the model seeing its original context. Without an import, DSH can only start from a blank Session.
|
||||
|
||||
The export format (`export_format_version: 3`) differs from a DSH Session in four structural ways that the import must handle:
|
||||
|
||||
- Each conversation's `messages` form a tree linked by `parent_id` (regenerating a reply or editing a question creates a branch); a DSH Session is a linear append-only log.
|
||||
- Message `id` values increase only within one conversation and cannot be compared across conversations; `inserted_at` is not monotonic even within one conversation (an assistant reply is often a few milliseconds earlier than its user message).
|
||||
- The `fragments` of one assistant message interleave reasoning, web search, opened pages, and answer text; DSH expresses the same process with `assistant/message` plus `tool/call` / `tool/result` inside steps.
|
||||
- The export also contains template replies, failure states, encrypted link bodies, and notices that must **not** enter the model context.
|
||||
|
||||
One export can contain thousands of conversations and hundreds of megabytes of images; users need only the most recent conversations, in a Workspace they choose, and the Host must stay responsive while it imports them.
|
||||
|
||||
## Decision
|
||||
|
||||
The experimental package [`@deepseek-ai/dsh-deepseek-chat-import`](../../../../packages/experimental/deepseek-chat-import/README.md) has a Host face and a Client face:
|
||||
|
||||
- Host face: a `TypertRemoteService` that registers the exact upload route `POST /api/deepseek-chat-import/archive?workspaceId=…` on `ctx.connection.fetch` and the `@Remote limits()` method. The route buffers the uploaded ZIP in memory, imports the most recent conversations one at a time as stored DSH Sessions in the chosen Workspace, and streams progress.
|
||||
- Client face: an import button right of "New session" in the sidebar. It opens a dialog with an export file field (the browser-native file input, `accept=.zip`) and a Workspace field that renders the `workspace.picker` Factory from ui-workspace; the browser uploads the file and shows upload and import progress and the result.
|
||||
|
||||
The button position comes from the ui-sidebar HOC slot `sidebar.session.action`; the plugin wraps the New-session row content there and returns it followed by its button, so decorating the row adds no wrapper element. ui-sidebar does not hard-code the button, because the sidebar shell would then call the import plugin's Remote namespace and carry business logic. The Workspace field reuses the New-session Workspace menu as the `workspace.picker` Factory: existing Workspaces plus "Add workspace…", which runs the composed directory picker through the `workspace.picker.directoryFlow` hole.
|
||||
|
||||
The capability ships as an Official experimental optional bundle: the package declares `dsh.bundle.patch` with its own `deepseek-chat-import` row, is listed in `OPTIONAL_BUNDLES`, and is switched off until the user enables it on the Plugins page. The default Web composition does not mount it.
|
||||
|
||||
### User flow
|
||||
|
||||
1. The user enables "DeepSeek chat import" on the Plugins page, then clicks the import button right of "New session" (an icon button below the "New session" icon in the narrow sidebar). Only the owner sees the button.
|
||||
2. The dialog takes the ZIP file exported from the DeepSeek website (`deepseek_data-*.zip`) and the Workspace that receives the Sessions. The Workspace field preselects the current Session's Workspace; "Add workspace…" adds a new directory through the directory picker.
|
||||
3. On import, the browser first calls `limits()`; a file larger than `maxUploadBytes` is rejected before upload. A served page then shows the upload percentage, an indeterminate phase while the Host reads the archive, and "Importing n/K" while Sessions are written. A page whose Host runs in another execution context carries the archive over `__DSH_TRANSPORT__.fetch`, which reports no byte progress, so the dialog starts at the reading phase. Closing the dialog aborts the request.
|
||||
4. On success the dialog shows how many Sessions were imported into which Workspace, how many conversations exceeded the limit, and how many could not be imported, in singular or plural form.
|
||||
5. On failure the dialog shows the localized explanation of the failure reason, or the message of an unexpected error.
|
||||
6. However the attempt ends, the browser refreshes the Session list, so Sessions written before a failure or cancellation appear.
|
||||
|
||||
The user then opens any imported Session and sees the original questions, reasoning, search cards, and answers; a new message continues with the default model and the imported history as context.
|
||||
|
||||
### Package layout
|
||||
|
||||
| File | Responsibility |
|
||||
|---|---|
|
||||
| `src/types.ts` | Browser-safe wire types only: results, failure reasons, limits, the NDJSON answer lines, and the `deepseekChatImport/owner-only` Remote error code |
|
||||
| `src/protocol.ts` | `UPLOAD_PATH` and its document-relative form `UPLOAD_ROUTE` |
|
||||
| `src/format.ts` | zod validation of `manifest.json`, `chat_sessions/{id}.json`, and the fragment types the package maps; unknown fragment types stay for the converter to ignore |
|
||||
| `src/archive.ts` | `openExportArchive(bytes, maxEntryBytes, signal)`: the ZIP central directory, streaming passes over the archive bytes that inflate only the entries they are asked for, and a by-name read |
|
||||
| `src/conversation.ts` | Pure functions `selectBranch(file)` and `convertConversation(file, options)` from a message tree to seed events |
|
||||
| `src/importer.ts` | `importDeepseekChatExport(deps, request, signal)`: index selection, the image pass, the conversation pass, writes, and Workspace attachment |
|
||||
| `src/upload.ts` | `createUploadRoute(handler)`: request validation, bounded buffering, the streamed answer, and cancellation |
|
||||
| `src/index.ts` | `DeepseekChatImportService`, `Config`, the single import slot, and `@Remote limits()` |
|
||||
| `src/client/*` | Button, dialog, browser upload over the page carrier or XHR, locale dictionaries, slot registration |
|
||||
| `cordis.patch.yml` | The optional bundle row `deepseek-chat-import` |
|
||||
|
||||
`src/conversation.ts` reads no files, uses no services, and reads no clock; the caller injects every id, so it is deterministic under unit tests. `src/importer.ts` uses persistence, the projection cache, attachments, and the Workspace registry through an explicit dependency object, so its tests can use real JSONL persistence.
|
||||
|
||||
### Host route and Remote
|
||||
|
||||
```ts
|
||||
/** Deployment limits of the importer. */
|
||||
interface Config {
|
||||
/** Most Sessions one import writes, choosing the conversations the export index lists as most recently updated; default 1000. */
|
||||
maxSessions: number
|
||||
/** Largest export archive, in bytes, one upload may carry; default 512 MiB. */
|
||||
maxUploadBytes: number
|
||||
/** Largest declared uncompressed size, in bytes, of one archive entry; default 256 MiB. */
|
||||
maxEntryBytes: number
|
||||
/** Largest UTF-8 size, in bytes, of an imported title; default 80. */
|
||||
maxTitleBytes: number
|
||||
}
|
||||
```
|
||||
|
||||
`POST /api/deepseek-chat-import/archive?workspaceId=…` is an exact route on the shared API channel, so only owner Peers reach it. `limits()` refuses every caller that is not the owner with `deepseekChatImport/owner-only`, so a non-owner principal such as a shared-Session guest never imports. The route requires `content-type: application/octet-stream` (otherwise 415) and a non-empty `workspaceId` (otherwise 400); the shared handler answers other methods before the route runs.
|
||||
|
||||
The service owns one import slot. A request takes the slot or answers `busy`, resolves the Workspace (`workspace-not-found`), and reads the streaming body into one buffer sized from a valid `content-length`, growing it only when the body is longer than declared, until the body ends or exceeds `maxUploadBytes` (`too-large`). The upload is never written to disk. Each request owns an AbortController joined with the request signal and with cancellation of the response body. Unloading the plugin aborts the running import, including a body still uploading, and completes only after the import stops writing.
|
||||
|
||||
The answer is `application/x-ndjson` with `cache-control: no-store, no-transform`: progress lines `{ type: 'progress', done, total }`, then exactly one line `{ type: 'outcome', outcome }`, where `outcome` is `{ ok: true, value: DeepseekChatImportResult }` or `{ ok: false, error: { reason, message } }`. The Web server writes the body chunk by chunk, and the browser reads complete lines as they arrive, which also works when a proxy delivers the whole body at once. The browser validates every decoded line: it must be an object of a known `type` with the fields that type carries, so a `null`, a line missing `done`, or an outcome whose `ok` is not boolean fails the answer as invalid instead of throwing inside an `onload`/`onprogress` callback. `reason` is one of `too-large | unreadable-archive | missing-manifest | missing-index | unsupported-version | no-conversations | workspace-not-found | busy`. An unexpected failure is logged on the Host and ends the body without an outcome line, which the browser reports as an upload failure.
|
||||
|
||||
`attachments` and `sessionProjectionCache` are optional services read through `ctx.get()`: without the attachment service, images become synthetic file cards; without the projection cache, the list row of a cold Session cannot show its original title and activity time before it is first opened.
|
||||
|
||||
### Reading the export
|
||||
|
||||
- `openExportArchive` reads the central directory with fflate's asynchronous `unzip` and a filter that accepts nothing, so opening inflates no entry. Bytes that are not a readable ZIP fail with `unreadable-archive`. Entry names must be unique: a by-name read selects by name, so a duplicate name would inflate every match and bypass the per-entry limit; a duplicated name fails with `unreadable-archive`. Duplicate detection covers the central directory only: a second local file header renamed to an existing entry name is not detected, so the pass can deliver more conversations than the index lists, and the import does not guard the write count.
|
||||
- `manifest.json` and `chat_session_index.json` are read by name before the pass. A missing or damaged manifest fails with `missing-manifest` or `unreadable-archive`; a missing, damaged, or unparsable index fails with `missing-index`; an entry over `maxEntryBytes` fails with `too-large`; an `export_format_version` other than 3 fails with `unsupported-version`.
|
||||
- One streaming pass then inflates only the chosen conversation entries, in archive order, yielding to the event loop between 64 KiB chunks of archive bytes. Inflation is synchronous (`UnzipInflate`), so one chunk's output is produced before the pass yields; an entry that declares a small size but inflates past `maxEntryBytes` keeps inflating until it ends, and the limit then stops the bytes being kept, not the work. The central directory supplies each entry's declared sizes before inflation: an entry over `maxEntryBytes` is rejected without being inflated, and a stored entry whose declared size differs from the bytes it holds is rejected as damaged. An accepted entry is accumulated and delivered whole; more bytes than it declares or than `maxEntryBytes` rejects it.
|
||||
- The images of every chosen conversation are stored by a separate streaming pass before any conversation is parsed. That pass inflates only `chat_sessions/{id}_files/…` entries whose id the index selected, one at a time, and records the stored reference or the failure reason for each. Because it runs first, archive entry order does not matter and the conversation pass never reads an image by name.
|
||||
- A by-name read serves the manifest, the index, and a replacement conversation. Each call re-parses the whole central directory, so a replacement costs one directory scan for its conversation file; its images are collected by one further image pass, not one read per image. The read returns at most the bytes the entry declares, truncating an entry that inflates to more; the pass reports that same condition as a size failure.
|
||||
- Conversations are the `*.json` entries directly under `chat_sessions/` (not the `*_files/` subdirectories). An entry whose id the index does not select is skipped without being inflated. A chosen conversation is parsed and converted as it arrives; a conversation that is oversized, damaged, not JSON, or fails zod validation or conversion goes into `skipped`.
|
||||
|
||||
### Selecting the conversations
|
||||
|
||||
1. `chat_session_index.json` ranks the conversations the export carries: descending `updated_at`, then descending `inserted_at`, then ascending id. The import writes the newest `total = min(maxSessions, index rows)` of them, in archive order.
|
||||
2. Session persistence and Workspace membership order by Session time rather than by write order, so the archive order the pass writes in does not change the Session list.
|
||||
3. A conversation the archive does not carry, or one that fails conversion or storage, is reported in `skipped`; the next older conversation the index lists takes its place, fetched by name. `omittedByLimit` counts the conversations the index lists that no attempt reached.
|
||||
4. `sessionIds` lists the imported Sessions newest first by the index order, whatever order they were written in.
|
||||
|
||||
### Linearizing the message tree (`selectBranch`)
|
||||
|
||||
- The selected message is the one named by `current_message_id`. The chain is traced from it along `parent_id` to the root with `parent_id === null`, then reversed. Other branches are dropped; each conversation yields one Session.
|
||||
- When `current_message_id` is absent, null, or names no message, the message with the largest `id` is selected instead. Ids increase within a conversation and a child's id is always greater than its parent's, so that fallback is always a leaf.
|
||||
- An empty `messages` list, duplicate message ids, a `parent_id` naming a missing message, or a cycle makes the conversation invalid and puts it into `skipped`.
|
||||
|
||||
### Message chain to Session events (`convertConversation`)
|
||||
|
||||
Messages on the chain are grouped as one turn per USER message: a USER message and the ASSISTANT message right after it form a turn. An ASSISTANT message without a preceding USER message (only possible in malformed data) is dropped. A USER message whose reply has status `CONTENT_FILTER` is dropped together with that reply: neither node produces an event, nothing is displayed, and later turns are numbered without a gap. A chain ending with USER yields a last turn with only the question. User and assistant need not alternate strictly: an excluded reply produces no `assistant/message`, so the next question follows the previous one directly, matching the history of a DSH turn that received several steered messages. A conversation without any remaining turn fails conversion and goes into `skipped`.
|
||||
|
||||
Events of one turn:
|
||||
|
||||
| Order | Event | Notes |
|
||||
|---|---|---|
|
||||
| 1 | `turn/start {turn: n}` | Time of the USER message |
|
||||
| 2 | `step/start {turn: n, step: 1}` | In the first turn, followed by an empty `system/message` (`surfaceOp: 'append'`) as surface node 0 |
|
||||
| 3 | `user/message` (`surfaceOp: 'append'`) | `source: { kind: 'user' }`, content below |
|
||||
| 4 | Per step: `assistant/message` (`stream: []`), one `tool/call` / `tool/result` pair per tool call, `step/end`; the next step starts with `step/start` | Only for normally finished replies |
|
||||
| 5 | `step/end` (last step) | |
|
||||
| 6 | `turn/end` | `{ kind: 'completed' }` for a normal reply; `{ kind: 'error', error: { code, message } }` for an excluded or missing reply |
|
||||
|
||||
The empty system head derives no model message and renders no prompt card. The stored format accepts a `system/message` only as surface node 0 or after such a head, and every read of a stored log checks this; with the head in place, a resumed Agent replaces it with the real system prompt instead of appending a system message after the imported history.
|
||||
|
||||
A user message whose text is empty or whitespace and that has no attachment carries one text block with the empty string: the Turn and its row exist, and DeepSeek request serialization skips the empty user message, so that Turn's question is absent from the model context and a first Turn without text starts the request with its assistant message.
|
||||
|
||||
After the first turn, the conversation title appends `session/title { title, messageSeqs: [], source: { kind: 'user' } }`. The title is normalized with session-title's `normalizeSessionTitle`: whitespace collapses to single spaces and the text is truncated to `maxTitleBytes` UTF-8 bytes. A missing title, or one that normalizes to empty, writes no title event. The `user` source pins the title, so no title generation runs after import.
|
||||
|
||||
The assistant message `source` is `{ kind: 'model', provider: 'deepseek-chat-export', model: 'deepseek-chat-export' }` without `replayState`. The DeepSeek adapter sends such foreign reasoning as unsigned thinking, the existing cross-model history path. No `usage`, `request/header`, `request/context`, or `model/selection` is written: the first request after resume records an `initial` header with the deployment's default model and shows no model-switch notice.
|
||||
|
||||
`stream` is an empty array. The export has no per-token stream record, and a fabricated stream cannot satisfy the check that the stream reconstructs the content exactly; the empty array passes the existing checks, and the Web assistant row renders from `message.content`.
|
||||
|
||||
**Event times.** Each event's `time` is the `inserted_at` milliseconds of its export message, clamped to be non-decreasing in order of appearance (which absorbs the assistant reply that is a few milliseconds earlier than its question). Within one reply, each THINK with `elapsed_secs` advances the time cursor by that many milliseconds, and later steps use the advanced time, so step intervals reflect the original reasoning duration. The Session header's `createdAt` is the time of the first event.
|
||||
|
||||
### Fragment mapping
|
||||
|
||||
| Fragment | Message | Mapping | Enters model context |
|
||||
|---|---|---|---|
|
||||
| `REQUEST` | USER | Text of `user/message` | Yes |
|
||||
| `FILE` (image) | USER | `{ type: 'image', attachment }` when the `export_path` entry exists and the attachment service stored it; otherwise a synthetic file card, `{ type: 'file', attachment }` with a reference naming no stored object | The stored image on image-capable routes; otherwise the file handle text, whose named path holds no bytes |
|
||||
| `FILE` (not an image) | USER | Synthetic file card: `{ type: 'file', attachment }` whose reference is `attachmentId = sha256('deepseek-chat-export:' + file.id)`, `name = file_name`, `bytes = file_size` (0 when absent); the file body is not in the export, so no object exists for it and the handle's path holds nothing | Yes, as file handle text |
|
||||
| `THINK` | ASSISTANT | `{ type: 'reasoning', text }` in the current step; empty text is ignored | Yes (per adapter rules) |
|
||||
| `RESPONSE` | ASSISTANT | `{ type: 'text', text }` in the current step; empty text is ignored | Yes |
|
||||
| `TOOL_SEARCH` | ASSISTANT | `web_search` call with arguments `{"queries": [...]}`; the result body comes from `formatSearchOutput` of `dsh-tool-web`; `meta` is `{ sources: [{ url, title, snippet, publishedAt }], truncated: false }`, rendered as the standard search card. `WIP` is skipped as incomplete; `FAILED` yields `isError: true` with the fixed text `Error: the export records this search as failed.`; a missing `status` behaves as `FINISHED`. Ignored when every query is empty or blank | Yes |
|
||||
| `TOOL_OPEN` (with url) | ASSISTANT | `web_fetch` call with arguments `{"url": ...}`; the result body holds the title, URL, and a note that the page body is not in the export; with `status: FINISHED`, `meta` is `{ url, statusCode: 200, truncated: false }`, rendered as the standard fetch card; `FAILED` yields `isError: true`; `WIP` is ignored | Yes |
|
||||
| `TOOL_OPEN` (url null or empty) | ASSISTANT | Nothing: the exporter writes one all-null record with `stage_id` and `group_id` beside the real opens of a stage, which names no page | No |
|
||||
| `TOOL_FIND` | ASSISTANT | Nothing: the website shows the find as its own row, which has no counterpart message block | No |
|
||||
| `TOOL_IMAGE_SEARCH` | ASSISTANT | Nothing: the website shows no row for an image search, and the reply's reasoning already states what the model took from its results; the searched image is not in the export | No |
|
||||
| `READ_LINK` | ASSISTANT | One Markdown link line per result: `[title](url)`, the URL as its own text when the title is missing, the title alone when the URL is missing, and nothing for a result with neither; the body stays a signature that cannot be decrypted without the key | Yes (text) |
|
||||
| `TIP` | ASSISTANT | Nothing: a website notice rather than model output, shown by the website as a banner | No |
|
||||
| `CONTENT_RISK` | ASSISTANT | Ignored: a fixed disclaimer with no information | No |
|
||||
| `PARTIAL_FILE_READ` | ASSISTANT | Nothing: the website shows the partial read as its own row | No |
|
||||
| `TEMPLATE_RESPONSE` | ASSISTANT | Excludes the whole reply; `turn/end` carries the template text as the error message | No |
|
||||
| Unknown type | Any | Ignored | No |
|
||||
|
||||
**Step boundaries.** A fragment that carries a `stage_id` shares the open step while the value stays the same. A different value starts a new step only when the open step already holds a tool call; otherwise the open step adopts the new stage. A call-less step that is not the last would put two assistant messages in a row in the resumed history, which the live loop never produces, so a text-only step stays merged with the next call. A step opened by a fragment without a stage adopts the next stage it sees. Fragments without `stage_id` keep the older rule: THINK or RESPONSE after a tool call ends the current step and starts the next, and the records that do not carry a stage behave as text there. A `WIP` record is skipped and does not split a step. Consecutive tool fragments with one `stage_id` fall into one step, like one parallel call. Ignored fragments do not split steps, so "THINK, three TOOL_OPEN with null url, THINK" keeps one step holding both reasoning blocks.
|
||||
|
||||
For the website's search-while-thinking replies, `THINK, TOOL_SEARCH (stage 1), THINK, TOOL_OPEN×4 (stage 2), THINK, RESPONSE` maps to three steps: (1) reasoning + `web_search`; (2) reasoning + four `web_fetch`; (3) reasoning + answer. A directly consecutive `TOOL_SEARCH (stage 1)` then `TOOL_OPEN (stage 2)` without reasoning between them splits into two steps because the first step already holds the search call.
|
||||
|
||||
**Block order within a step.** One step's `assistant/message` carries its text blocks (reasoning, answers, link lines) before its tool-call blocks, each group in the order recorded. Text that the export records after a tool call in the same step is therefore stored before that call, while the step sequence and every cross-step order stay as exported. Interleaving text after a tool call inside one assistant message would not match any step the live loop produces.
|
||||
|
||||
**Ids.** Message ids and tool-call ids come from the caller-injected `createId()` (`randomUUID` in production); the `tool-call` block id, `tool/call.callId`, and the `source.callId` and `toolCallId` of the `tool/result` message are the same.
|
||||
|
||||
### Reply status mapping
|
||||
|
||||
The export documentation requires that messages other than `FINISHED` and template replies stay out of the model context. A reply withdrawn by content filtering (`CONTENT_FILTER`, shown as withdrawn on the website) is dropped with its question, as described above. Every other excluded reply writes no `assistant/message` and no `assistant/attempt` (the Web does not show attempts, and "user message + attempt + retryable error code" would make the GUI offer to continue generating). The user sees the turn's closing error row with its reason and code:
|
||||
|
||||
| Original reply | `turn/end.reason.error.code` | `message` (English, written to the log) |
|
||||
|---|---|---|
|
||||
| `FAILED` / `TIMEOUT` / `CONTEXT_LENGTH_EXCEEDED` / `INCOMPLETE` / `WIP` | `DEEPSEEK_EXPORT_FAILED` / `DEEPSEEK_EXPORT_TIMEOUT` / `DEEPSEEK_EXPORT_CONTEXT_LENGTH_EXCEEDED` / `DEEPSEEK_EXPORT_INCOMPLETE` / `DEEPSEEK_EXPORT_WIP` | The original reply ended with status "{STATUS}" and is excluded from the model context. |
|
||||
| Any other status | `DEEPSEEK_EXPORT_UNFINISHED_REPLY` | The same message with the status quoted |
|
||||
| Contains `TEMPLATE_RESPONSE` | `DEEPSEEK_EXPORT_TEMPLATE_RESPONSE` | The template text itself |
|
||||
| `FINISHED` without importable content | `DEEPSEEK_EXPORT_EMPTY_REPLY` | The original reply has no importable content. |
|
||||
| Chain ends with USER (no reply) | `DEEPSEEK_EXPORT_NO_REPLY` | The export contains no reply to this message. |
|
||||
|
||||
Error codes are fixed strings; text from the export appears only inside the message. These codes are outside the session-controller's continuable code set, so no "continue generating" appears. The question itself stays in context.
|
||||
|
||||
### Session writes
|
||||
|
||||
The import creates no live Agent and writes the persistence layer directly. Failures detected before the pass (an unreadable archive, a missing, oversized, or unsupported manifest or index, no importable conversation, an oversized upload) write nothing; an archive whose structure breaks during the pass fails as `unreadable-archive` after the Sessions delivered before the break were written. Each conversation is fully converted and seed-validated with `Session.create` before it is written; a conversation that fails is skipped and does not stop the others. Each chosen conversation is converted and written as its archive entry arrives, and a conversation a failure pulls in afterwards is read by name. For each conversation:
|
||||
|
||||
1. The import checks that the target Workspace is still registered and that its directory exists; otherwise it stops with `workspace-not-found`, and the Sessions written before remain.
|
||||
2. The conversation is converted with the image references the image pass already stored. An image whose conversation later fails conversion or seed validation is already stored and keeps no referencing event.
|
||||
3. `Session.create(id, seed, header)` runs the same seed validation as a live append (JSON serializable, consecutive seq, valid surface transitions, valid message fields); the detached validation instance is discarded.
|
||||
4. `ctx.sessionPersistence.create(header)` → `handle.append(events)` → `handle.flush()` → `handle.close()` (closed on failure too). The header is `{ version: SESSION_FORMAT_VERSION, id, createdAt, cwd, isSeeded: false }`, and `cwd` is the Workspace's canonical path. The stored events have no `session/end-seed`; the ordinary resume path appends that marker on first open.
|
||||
5. When the projection cache is available, `coldSnapshot(header, SessionLogOffset(0), events)` refreshes the cached row the sidebar reads (title, last question time, non-blank).
|
||||
6. `workspace.attachSession(id)`. When it fails, the conversation goes into `skipped` with the reason "stored as Session {id} but not added to the workspace"; `SessionPersistence` offers no removal, so that Session stays stored outside the Workspace.
|
||||
|
||||
The converted events are released before the next conversation, and the import yields to the event loop between conversations and checks cancellation at each step. A written Session appears in `session/list` like any other cold Session and opens through the ordinary resume path. The import adds no Session event type, does not change `SESSION_FORMAT_VERSION`, and needs no persistence-type acknowledgement.
|
||||
|
||||
### Client
|
||||
|
||||
- ui-sidebar declares the HOC slot `sidebar.session.action` (`scope: 'root'`, owner `{ wide: boolean }`) around the New-session row content, so an occupant receives that content as `children` and returns it, possibly wrapped, plus its own controls. The trigger renders right of "New session" (on the same row in the wide sidebar, where "New session" takes the remaining width; stacked below the "New session" icon in the narrow sidebar).
|
||||
- The plugin's Client face `$mount`s its own `/remote` contribution (the self-mounting form of `dsh-api-remote-access`, outside the `dsh-api-remotes` aggregate) and registers `ImportSessionsAction` as the `sidebar.session.action` layer. It renders the row content first, then its trigger, then the dialog; a Peer that may not import gets the row content unchanged, so the New-session button keeps rendering. The button shows only when `useRemoteAccess('deepseekChatImport/limits')` is true; the dialog is local state of the layer rendered through the `Modal` portal.
|
||||
- The upload uses `XMLHttpRequest` on a served page because Fetch exposes no upload progress. A page whose Host runs in another execution context (the static Cloudflare Pages preview) supplies `__DSH_TRANSPORT__.fetch`: the archive goes through that carrier with no byte progress, straight to the reading and importing phases. The URL is `UPLOAD_ROUTE` resolved against `document.baseURI`, so a path-prefixing proxy keeps working. A non-200 answer, an answer without an outcome line, a line that is not a valid protocol value, or a connection failure becomes the `upload-failed` outcome; a thrown error is shown with the unknown-failure copy.
|
||||
- The carrier selection does not reuse `@deepseek-ai/dsh-client-file-upload`. That package's service buffers the whole response, which would lose the streamed NDJSON progress, and its `post` method is not part of its public surface; keeping the selection here preserves both the progress lines and the package edge.
|
||||
- Copy goes through locale dictionaries in eight languages, with sentence case in English; summary lines have `.one` / `.other` forms chosen by `count === 1`.
|
||||
|
||||
### Realization
|
||||
|
||||
`sidebar.session.action` is an HOC layer rather than a list because the occupant decorates the row's content instead of rendering beside it: it receives that content as `children`, returns it, possibly wrapped, and adds its own controls without introducing a wrapper element. A list entry would render as a sibling of the row content, and the rail-in fade targets the slot outlet's children because the `display: contents` outlet anchor cannot carry an animation itself.
|
||||
|
||||
The obligation is contract-only. An occupant that adds nothing, or may not act, must return `children` unchanged, because the renderer only rescues a layer that throws. A layer may legitimately omit `children`, which removes the New-session button, so no runtime check replaces the obligation.
|
||||
|
||||
### Images
|
||||
|
||||
- The image pass walks every image entry of a chosen conversation in archive order, without parsing the conversation. It inflates only `chat_sessions/{id}_files/…` entries whose id the index selected, calls `ctx.attachments.saveImage({ data, mediaType, name })` with the entry's extension and file name, and records the reference or the failure reason under the entry name. An extension other than png / jpg / jpeg / webp / gif is recorded as unsupported without inflating the entry.
|
||||
- `convertConversation` emits an `image` block (before the text) for each `FILE` entry whose `export_path` the pass stored and a synthetic file card otherwise.
|
||||
- A missing, unsupported, oversized, damaged, or rejected image becomes a synthetic file card with one Host warning; the conversation still imports. A missing entry reports `not in the export`; a size, corruption, unsupported-type, or storage failure reports its own reason. Attachment storage deduplicates by content.
|
||||
- The pass stores every image entry of a chosen conversation before the branch is selected and before conversion. An image of a withdrawn round, of a dropped branch, or of a conversation whose conversion or `Session.create` seed validation later fails therefore stays stored without a referencing event. Neither `SessionPersistence` nor the attachment store offers a removal.
|
||||
|
||||
### Testing
|
||||
|
||||
| Layer | File | Coverage |
|
||||
|---|---|---|
|
||||
| Conversion | `tests/conversation.host.spec.ts` | `current_message_id` selection with the largest-id fallback; linearization by id; REQUEST / THINK / RESPONSE; `stage_id` step boundaries and search/open-page step boundaries; failed, unfinished, and status-less searches; dropped image searches, address-less opens, page finds, partial reads, and tips; Markdown link lines; turn errors and fixed codes for excluded replies; dropped content-filtered rounds; an empty text block in the first and later turns; title normalization; synthetic file cards; invalid trees. Output passes `Session.create`, and `deriveMessages` asserts the model history |
|
||||
| Archive | `tests/archive.host.spec.ts` | Entry listing, one-entry reads truncating to the declared size, the streaming pass, the declared-size limit with a highly compressible entry, misdeclared sizes, duplicate entry names, stored-entry size mismatches, damaged entries, cancellation |
|
||||
| Orchestration | `tests/importer.host.spec.ts` | Latest K oldest first with progress; a synthetic 2026-11-12 archive carrying every new field; oversized, damaged, and invalid conversation files; filling the limit after failures; a replacement chain that survives an invalid candidate; attach failures; Workspace removal; archive-level failures; cancellation; images stored by the image pass in any archive order, the synthetic file cards of unstored ones, and the absence of by-name image reads on the main path |
|
||||
| Route | `tests/upload.host.spec.ts` | Request validation; `too-large`; buffer sizing from the declared length; one import at a time; NDJSON lines; cancellation by the answer, the request, and unloading |
|
||||
| Resume | `tests/resume.host.spec.ts` | The production agent loop continues an imported Session; the model request holds the imported history without the withdrawn round |
|
||||
| Composition | `tests/composition.host.spec.ts` | Host booted through the Loader; owner-only `limits()`; an upload stores the Session in the Workspace; unloading during a paused import cancels it and completes only after it stops, with nothing written |
|
||||
| Client | `tests/import-sessions.client.spec.tsx`, `tests/mount.client.spec.ts`, `tests/upload.client.spec.ts` | Button visibility, Workspace preselection, progress bar and texts, plural summaries, failure and thrown-error copy, refresh after every attempt, NDJSON line reading and validation |
|
||||
| Bundle | `scripts/optional-bundles.spec.ts` | The bundle composes over the Web profile and resolves its title, description, and icon |
|
||||
| Snapshot | `apps/web/tests/deepseek-chat-import.e2e.ts`, `snapshots/web/deepseek-chat-import/` | A synthetic 2026-11-12 export with a branch, reasoning, a search and fetch pair, a read-link record, a content-filtered round, and an incomplete reply is uploaded through the route; one imported Session continues with one recorded model turn, and the persisted log replays keyless |
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Type a host path to the export.** The first design read a ZIP or an extracted directory from an absolute Host path and created a `<export>_workspace` directory next to it. Users must not type Host paths, a browser does not know them, and a remote Host has no access to the user's local download; the browser upload works the same for local and remote Hosts.
|
||||
|
||||
**List export files inside a chosen Workspace.** The user would place the ZIP in a Workspace directory and pick it from a Host-side listing. The user rejected this in favor of uploading the file directly from the browser.
|
||||
|
||||
**Stage uploads on disk.** Writing the upload to a temporary file would lift the memory bound but adds cleanup, crash residue, and a second copy of private data on the Host. The archive stays in memory, bounded by `maxUploadBytes`, and the service runs one import at a time.
|
||||
|
||||
**Decompress and validate all conversations before writing any.** This made "a rejected export writes nothing" true for conversion failures, but held every conversation file and converted log in memory at once and blocked the event loop for the whole import. Two streaming passes follow `chat_session_index.json`: one stores the images of the chosen conversations without decompressing any conversation, and one converts and writes each chosen conversation as it arrives.
|
||||
|
||||
**Report progress through a separate streaming Remote.** The route answer already streams through the Web server, so NDJSON lines on the same request need no second channel, keep progress and outcome ordered, and end with the request.
|
||||
|
||||
**Import the newest leaf only.** It is always a leaf and needs no extra field, but it silently imports a different branch than the one the user was viewing whenever the export was taken after switching back. `current_message_id` is the export's own linearization key, and the largest-id fallback keeps archives without it importable.
|
||||
|
||||
**Select by the selected message's `inserted_at`.** It is the time of the last imported event, but it needs every conversation's messages, so selection would decompress the whole archive before writing anything. `chat_session_index.json` carries the website's own update order and lets selection skip the conversations it does not choose; the cost is that the order follows renames and pins rather than the last imported event.
|
||||
|
||||
**Create live Agents through `ctx.agents.create({ seed })`.** It is the existing supported entry, but `createdAt` can only be the current time, so every imported Session would crowd the top of the sidebar, and importing thousands of conversations would create thousands of live Agents. Writing persistence directly keeps the original times and uses no runtime resources.
|
||||
|
||||
**One Session per branch, or branches inside DSH.** A DSH Session is a linear log; a Session per branch turns one website conversation into several hard-to-tell-apart Sessions. The requirement is the newest chain only.
|
||||
|
||||
**Keep the question of a content-filtered reply with an error row.** The website shows such rounds as withdrawn, and the user decided that neither node is imported; the remaining turns read as the user saw them.
|
||||
|
||||
**Write non-FINISHED or template replies as `assistant/attempt` or as `interrupted` `assistant/message`.** Attempts are invisible in the Web and, with retryable error codes, trigger "continue generating"; the content of an `interrupted` message enters the model context, which the export documentation forbids.
|
||||
|
||||
**Hard-code the import button in ui-sidebar.** The sidebar shell would depend on the import plugin's Remote namespace and carry a business branch; the slot costs one declaration and a small layout change.
|
||||
|
||||
**Add Session event types for TIP / CONTENT_RISK or the import origin.** That extends `SessionEventMap`, the persistence catalog, and the Web renderers beyond a small import; the notices do not change the answers.
|
||||
|
||||
**Mount the importer in the default Web composition.** The capability is experimental, and release packages must not depend on experimental packages. The optional bundle keeps the default product unchanged and offers the import to users who enable it.
|
||||
|
||||
## Consequences
|
||||
|
||||
The import brings website history into DSH with original titles, times, reasoning, and search cards, and the imported Sessions continue through the ordinary resume path. Host memory is bounded by the archive (`maxUploadBytes`) plus one entry (`maxEntryBytes`), one converted conversation, and the references of the stored images, and the event loop stays responsive between conversations. The price is that only conversations already written survive a cancellation or a mid-import failure, and a conversation a failure pulls in is read by name and gets one further image pass.
|
||||
|
||||
- **Cold writes are a production writer outside the agent loop.** The import uses fresh Session ids and closes each handle after writing, so it does not compete for ownership with live Sessions; if the persistence layer later assumes that every write goes through the agent loop (for example by registering derived state at creation), the import path must change with it.
|
||||
- **A Session stored but not attached stays stored.** `SessionPersistence` offers no removal; the import reports such a Session in `skipped` with its id.
|
||||
- **Historical tool calls have no tool records.** The imported `web_search` / `web_fetch` calls have no matching `request/header.tools` record. If a deployment does not register these tools, or a provider rejects history that references undeclared tools, the first request after resume fails; text-only mapping is the fallback.
|
||||
- **The fetch card's status code is inferred.** The export records only that the page opened, not an HTTP status; `statusCode: 200` makes the card show a successful fetch.
|
||||
- **Foreign reasoning is sent to the model again.** Imported reasoning is sent as unsigned thinking, which raises the input tokens of the first request after resume; the KV cache starts with that request.
|
||||
- **Re-import duplicates.** Importing the same export again writes new Sessions; the import does not record which conversations it already imported.
|
||||
- **The viewed branch decides the import.** `current_message_id` selects the chain, so an export taken after the user switched back to an older branch imports that branch; only an absent or unknown id falls back to the newest leaf.
|
||||
- **One export structure.** The importer targets the 2026-11-12 structure. Older v3 archives still import because the added fields are optional, but their `READ_LINK` no URL or title, so its link lines carry less (an older `TOOL_FIND` pattern is no longer read at all).
|
||||
- **`maxTitleBytes` is a separate setting.** The session-title service does not expose its limit, so a composition that changes session-title's `maxTitleBytes` sets the importer's field to the same value.
|
||||
- **Content given up.** Other branches, content-filtered rounds, `CONTENT_RISK` disclaimers, `TIP`, `TOOL_FIND`, and `PARTIAL_FILE_READ` records, encrypted `READ_LINK` bodies, search-result `snippet` and `site_name`, the `pinned` flag, non-image file bodies, per-token reasoning times, and `accumulated_token_usage` are not imported; token accounting after import uses estimates. The explanations of excluded replies and of a failed search are fixed English text.
|
||||
@@ -0,0 +1,266 @@
|
||||
# Agent Note: 导入 DeepSeek 官网会话导出
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-11-deepseek-chat-export-import.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
DeepSeek 官网(chat.deepseek.com)的“导出全部会话”产物是一个 `deepseek_data-*.zip`。用户希望把这些历史会话带进 DSH 继续使用:在 Web GUI 里浏览原有的提问、思考与回答,并在任意一条会话上接着对话,模型能看到原有的上下文。没有导入功能时,DSH 只能从空白会话开始。
|
||||
|
||||
导出格式(`export_format_version: 3`)与 DSH Session 有四点结构差异,导入必须逐一处理:
|
||||
|
||||
- 每个官网会话的 `messages` 是一棵靠 `parent_id` 连接的消息树(重新生成、编辑提问都会产生分叉);DSH Session 是线性的追加日志。
|
||||
- 消息 `id` 只在会话内自增,跨会话不可比较;`inserted_at` 在同一会话内也不单调(assistant 常比配对的 user 早几毫秒)。
|
||||
- 一条 assistant 消息的 `fragments` 交错记录思考、联网搜索、打开网页、正文等块;DSH 用 step 内的 `assistant/message` 加 `tool/call` / `tool/result` 表达同样的过程。
|
||||
- 产物还包含模板回答、失败状态、加密的链接正文、提示条等**不能**进入模型上下文的内容。
|
||||
|
||||
一个导出可能包含上千个会话和数百兆字节的图片;用户只需要最近的会话,并放进自己选择的工作区,而且 Host 在导入期间必须保持响应。
|
||||
|
||||
## Decision
|
||||
|
||||
实验性包 [`@deepseek-ai/dsh-deepseek-chat-import`](../../../../packages/experimental/deepseek-chat-import/README.zh.md) 同时提供 Host 与 Client 两个编译面:
|
||||
|
||||
- Host 面:一个 `TypertRemoteService`,在 `ctx.connection.fetch` 上注册精确上传路由 `POST /api/deepseek-chat-import/archive?workspaceId=…`,并提供 `@Remote limits()` 方法。路由把上传的 ZIP 缓存在内存中,把最近的会话逐个写成所选工作区中的持久化 DSH Session,并以流式方式报告进度。
|
||||
- Client 面:在侧栏“新建会话”右侧放一个导入按钮。点击后弹出对话框,包含导出文件字段(浏览器原生文件输入,`accept=.zip`)和工作区字段(渲染 ui-workspace 的 `workspace.picker` Factory);浏览器上传文件,显示上传与导入进度以及结果。
|
||||
|
||||
按钮位置通过 ui-sidebar 的 HOC slot `sidebar.session.action` 提供:插件在那里包裹新建会话行的内容,原样返回后追加自己的按钮,因此装饰该行不新增包裹元素。不在 ui-sidebar 里写死按钮,因为那样侧栏外壳要直接调用导入插件的 Remote 命名空间,把业务逻辑放进了外壳。工作区字段复用新建会话的工作区菜单,即 `workspace.picker` Factory:列出已有工作区,并提供“添加工作区…”,通过 `workspace.picker.directoryFlow` 洞运行已组合的目录选择器。
|
||||
|
||||
该能力作为 Official 实验性可选 bundle 发布:包本身声明 `dsh.bundle.patch` 并插入自己的 `deepseek-chat-import` 行,列入 `OPTIONAL_BUNDLES`,在用户于插件页启用之前保持关闭。默认 Web 组合不挂载它。
|
||||
|
||||
### 用户流程
|
||||
|
||||
1. 用户在插件页启用“DeepSeek 会话导入”,然后点击“新建会话”右侧的导入按钮(窄栏模式下是一个图标按钮,位于“新建会话”图标下方)。只有 owner 看得到这个按钮。
|
||||
2. 对话框需要 DeepSeek 官网导出的 ZIP 文件(`deepseek_data-*.zip`)以及接收会话的工作区。工作区字段预选当前会话所在的工作区;“添加工作区…”通过目录选择器添加新目录。
|
||||
3. 导入时,浏览器先调用 `limits()`;大于 `maxUploadBytes` 的文件在上传前就被拒绝。服务页面随后显示上传百分比、Host 读取压缩包时的不确定进度,以及写入会话时的“正在导入 n/K”。Host 跑在页面之外执行上下文中的页面经 `__DSH_TRANSPORT__.fetch` 携带压缩包,该载体不报告字节进度,因此对话框从读取阶段开始。关闭对话框会中止请求。
|
||||
4. 成功后对话框以单数或复数形式显示导入了多少个会话、导入到哪个工作区、多少个会话超出上限、多少个会话无法导入。
|
||||
5. 失败时对话框显示该失败原因的本地化说明,或意外错误的信息。
|
||||
6. 无论导入以何种方式结束,浏览器都会刷新会话列表,使失败或取消之前已写入的会话出现在列表中。
|
||||
|
||||
用户随后打开任一导入的会话,看到原始的提问、思考、搜索卡片和回答;发送新消息时,Agent 以默认模型和导入的历史为上下文继续。
|
||||
|
||||
### 包结构
|
||||
|
||||
| 文件 | 职责 |
|
||||
|---|---|
|
||||
| `src/types.ts` | 只放浏览器安全的线上类型:结果、失败原因、上限、NDJSON 应答行,以及 `deepseekChatImport/owner-only` Remote 错误码 |
|
||||
| `src/protocol.ts` | `UPLOAD_PATH` 及其相对文档的形式 `UPLOAD_ROUTE` |
|
||||
| `src/format.ts` | 用 zod 校验 `manifest.json`、`chat_sessions/{id}.json` 和本包映射的 fragment 类型;未知 fragment 类型原样保留给转换器忽略 |
|
||||
| `src/archive.ts` | `openExportArchive(bytes, maxEntryBytes, signal)`:ZIP 中央目录、只解压调用方所需条目的流式扫描,以及按名读取单个条目 |
|
||||
| `src/conversation.ts` | 纯函数 `selectBranch(file)` 与 `convertConversation(file, options)`:消息树到种子事件 |
|
||||
| `src/importer.ts` | `importDeepseekChatExport(deps, request, signal)`:索引选择、图片扫描、会话扫描、写入与附加工作区 |
|
||||
| `src/upload.ts` | `createUploadRoute(handler)`:请求校验、有界缓存、流式应答与取消 |
|
||||
| `src/index.ts` | `DeepseekChatImportService`、`Config`、单一导入槽位与 `@Remote limits()` |
|
||||
| `src/client/*` | 按钮、对话框、经页面载体或 XHR 的浏览器上传、locale 字典、slot 注册 |
|
||||
| `cordis.patch.yml` | 可选 bundle 的 `deepseek-chat-import` 行 |
|
||||
|
||||
`src/conversation.ts` 不读文件、不访问服务、不取当前时间,所有 id 由调用方注入,可以确定性地单测。`src/importer.ts` 通过一个显式的依赖对象使用持久化、投影缓存、附件服务与工作区注册表,单测可以接真实的 JSONL 持久化。
|
||||
|
||||
### Host 路由与 Remote
|
||||
|
||||
```ts
|
||||
/** Deployment limits of the importer. */
|
||||
interface Config {
|
||||
/** Most Sessions one import writes, choosing the conversations the export index lists as most recently updated; default 1000. */
|
||||
maxSessions: number
|
||||
/** Largest export archive, in bytes, one upload may carry; default 512 MiB. */
|
||||
maxUploadBytes: number
|
||||
/** Largest declared uncompressed size, in bytes, of one archive entry; default 256 MiB. */
|
||||
maxEntryBytes: number
|
||||
/** Largest UTF-8 size, in bytes, of an imported title; default 80. */
|
||||
maxTitleBytes: number
|
||||
}
|
||||
```
|
||||
|
||||
`POST /api/deepseek-chat-import/archive?workspaceId=…` 是共享 API 通道上的精确路由,只有 owner Peer 能访问。`limits()` 以 `deepseekChatImport/owner-only` 拒绝所有非 owner 调用方,因此共享会话的访客等非 owner principal 永远不能导入。路由要求 `content-type: application/octet-stream`(否则 415)和非空的 `workspaceId`(否则 400);其他方法在路由运行前就由共享处理器应答。
|
||||
|
||||
服务拥有一个导入槽位。请求先占用槽位,否则应答 `busy`;随后解析工作区(`workspace-not-found`),把流式请求体读入一个按有效 `content-length` 分配的缓冲区,只有请求体比声明的更长时才扩容,直到读完或超过 `maxUploadBytes`(`too-large`)。上传内容从不写入磁盘。每个请求拥有一个 AbortController,与请求信号以及应答体的取消合并。卸载插件会中止正在运行的导入(包括仍在上传的请求体),并且只有在导入停止写入后才完成卸载。
|
||||
|
||||
应答为 `application/x-ndjson`,带 `cache-control: no-store, no-transform`:先是进度行 `{ type: 'progress', done, total }`,然后恰好一行 `{ type: 'outcome', outcome }`,其中 `outcome` 为 `{ ok: true, value: DeepseekChatImportResult }` 或 `{ ok: false, error: { reason, message } }`。Web server 逐块写出应答体,浏览器在完整的行到达时读取,代理一次性交付整个应答体时同样可用。浏览器校验每一条解码后的行:必须是已知 `type` 的对象,并携带该类型对应的字段,因此 `null`、缺少 `done` 的行,或 `ok` 不是布尔值的 outcome 都会让应答以无效失败,而不是在 `onload`/`onprogress` 回调里抛错。`reason` 取 `too-large | unreadable-archive | missing-manifest | missing-index | unsupported-version | no-conversations | workspace-not-found | busy` 之一。意外失败会记入 Host 日志,并在没有 outcome 行的情况下结束应答体,浏览器将其报告为上传失败。
|
||||
|
||||
`attachments` 与 `sessionProjectionCache` 是通过 `ctx.get()` 读取的可选服务:缺少附件服务时图片变成伪造的文件卡片;缺少投影缓存时,冷会话的列表行在会话首次打开前不显示原标题与活动时间。
|
||||
|
||||
### 读取导出产物
|
||||
|
||||
- `openExportArchive` 用 fflate 的异步 `unzip` 和一个不接受任何条目的 filter 读取中央目录,打开阶段不解压任何条目。不是可读 ZIP 的字节报 `unreadable-archive`。条目名必须唯一:按名读取按名字选择,重名会让所有同名条目一起解压,绕过逐条上限;重名同样报 `unreadable-archive`。重复检测只覆盖中央目录:第二个本地文件头改成已有条目名时不会被发现,因此扫描可以交付比索引列出的更多的会话,写入数量也没有额外限制。
|
||||
- `manifest.json` 与 `chat_session_index.json` 在扫描前按名读取。`manifest.json` 缺失或损坏分别报 `missing-manifest` 或 `unreadable-archive`;索引缺失、损坏或无法解析报 `missing-index`;条目超过 `maxEntryBytes` 报 `too-large`;`export_format_version` 不是 3 报 `unsupported-version`。
|
||||
- 随后一次流式扫描按压缩包顺序只解压被选中的会话条目,并在每 64 KiB 压缩包字节之间让出事件循环。解压是同步的(`UnzipInflate`),因此一个分块的输出在扫描让出之前就已产生;声明很小、实际解压超过 `maxEntryBytes` 的条目会一直解压到条目结束,上限此时只阻止字节被保留,而不阻止这部分工作。中央目录在解压前给出每个条目声明的大小:超过 `maxEntryBytes` 的条目不会被解压;未压缩(stored)条目声明的大小与实际字节不一致时按损坏拒绝。接受的条目整块累积后交付;产出超过条目声明大小或 `maxEntryBytes` 时拒绝。
|
||||
- 每个选中会话的图片由单独一次流式扫描在任何会话被解析之前保存。该扫描只解压 `chat_sessions/{id}_files/…` 中 id 属于索引所选会话的条目,一次一个,并记录每条目的已保存引用或失败原因。由于它先运行,压缩包条目顺序不影响结果,会话扫描也不再按名读取任何图片。
|
||||
- 按名读取用于 manifest、索引与补位会话。每次调用都会重新解析整个中央目录,因此一个补位会话会为其会话文件多出一次目录扫描;它的图片由再一次图片扫描收集,而不是每张图片读取一次。它最多返回条目声明的大小,解压结果更大时截断;扫描把同一情况报告为大小失败。
|
||||
- 会话来源是 `chat_sessions/` 下直接的 `*.json` 条目(不进入 `*_files/` 子目录)。索引未选中的条目不会被解压。选中的会话在到达时解析并转换;超过上限、已损坏、不是 JSON,或未通过 zod 校验与转换的会话记入 `skipped`。
|
||||
|
||||
### 选择会话
|
||||
|
||||
1. `chat_session_index.json` 为导出携带的会话排序:`updated_at` 降序,其次 `inserted_at` 降序,最后 id 升序。导入写入其中最新的 `total = min(maxSessions, 索引行数)` 个,按压缩包顺序。
|
||||
2. Session 持久化与工作区成员关系按会话时间而非写入顺序排序,因此扫描按压缩包顺序写入不会改变会话列表。
|
||||
3. 压缩包中没有的会话,或转换、存储失败的会话记入 `skipped`;由索引中下一个更旧的会话按名补位。`omittedByLimit` 统计索引列出但任何尝试都未触及的会话。
|
||||
4. `sessionIds` 按索引顺序从新到旧列出已导入的会话,与写入顺序无关。
|
||||
|
||||
### 分叉树线性化(`selectBranch`)
|
||||
|
||||
- 选中的消息是 `current_message_id` 指定的那条。从它沿 `parent_id` 回溯到 `parent_id === null` 的根,再反转,得到一条链。其他分支丢弃,每个会话只生成一个 Session。
|
||||
- `current_message_id` 缺失、为 `null` 或指向不存在的消息时,改选 `id` 最大的消息。消息 id 在会话内自增,子消息的 id 总大于父消息,所以这个兜底一定是叶子。
|
||||
- `messages` 为空、消息 id 重复、`parent_id` 指向不存在的消息或回溯出现环时,该会话无效并记入 `skipped`。
|
||||
|
||||
### 消息链到 Session 事件(`convertConversation`)
|
||||
|
||||
链上的消息按“每个 USER 消息开一个 turn”分组:USER 消息与紧随其后的 ASSISTANT 消息组成一个 turn。没有前置 USER 的 ASSISTANT 消息(只可能来自异常数据)被丢弃。回答状态为 `CONTENT_FILTER` 的 USER 消息与该回答一起丢弃:两个节点都不产生事件,界面上什么都不显示,后续 turn 的编号不留空缺。链以 USER 结尾时最后一个 turn 只有提问。不要求 user / assistant 严格交替:被排除的回答不会产生 `assistant/message`,下一个提问直接跟在上一个提问之后,这与 DSH 中一个 turn 收到多条 steer 消息的历史形态一致。没有剩余 turn 的会话转换失败并记入 `skipped`。
|
||||
|
||||
一个 turn 的事件序列:
|
||||
|
||||
| 顺序 | 事件 | 说明 |
|
||||
|---|---|---|
|
||||
| 1 | `turn/start {turn: n}` | 时间为 USER 消息时间 |
|
||||
| 2 | `step/start {turn: n, step: 1}` | 第一个 turn 中其后紧跟一个空的 `system/message`(`surfaceOp: 'append'`),作为 surface 节点 0 |
|
||||
| 3 | `user/message`(`surfaceOp: 'append'`) | `source: { kind: 'user' }`,内容见下 |
|
||||
| 4 | 每个 step 一组:`assistant/message`(`stream: []`)、每个工具调用一对 `tool/call` / `tool/result`、`step/end`;下一 step 以 `step/start` 开始 | 只用于正常完成的回答 |
|
||||
| 5 | `step/end`(最后一个 step) | |
|
||||
| 6 | `turn/end` | 正常回答为 `{ kind: 'completed' }`;被排除或缺失的回答为 `{ kind: 'error', error: { code, message } }` |
|
||||
|
||||
空的 system 头不产生模型消息,也不渲染提示卡片。存储格式只接受作为 surface 节点 0 或位于这样的头之后的 `system/message`,每次读取存储的日志都会检查这一点;有了这个头,恢复的 Agent 会用真实的系统提示替换它,而不是在导入的历史之后追加一条系统消息。
|
||||
|
||||
文本为空或只有空白、且没有附件的用户消息写入一个内容为空字符串的文本块:Turn 与它的行都存在,而 DeepSeek 请求序列化会跳过这条空用户消息,因此该轮提问不在模型上下文里;首轮没有文本时,请求会直接从它的 assistant 消息开始。
|
||||
|
||||
第 1 个 turn 结束后,会话标题追加 `session/title { title, messageSeqs: [], source: { kind: 'user' } }`。标题经 session-title 的 `normalizeSessionTitle` 规范化:空白折叠为单个空格,文本截断到 `maxTitleBytes` 个 UTF-8 字节。没有标题,或标题规范化后为空时,不写标题事件。`user` 来源会固定标题,导入后不会再触发标题生成。
|
||||
|
||||
Assistant 消息的 `source` 为 `{ kind: 'model', provider: 'deepseek-chat-export', model: 'deepseek-chat-export' }`,没有 `replayState`。DeepSeek adapter 把这类外来历史的 reasoning 按无签名 thinking 发送,这是已有的跨模型历史路径。不写 `usage`、`request/header`、`request/context`、`model/selection`:恢复后的首个请求记 `initial` header,使用部署的默认模型,不出现“模型已切换”提示。
|
||||
|
||||
`stream` 写空数组。导出不包含逐 token 的流记录,伪造的流无法满足“流精确重建内容”的校验;空数组能通过现有校验,Web 的 assistant 行从 `message.content` 渲染。
|
||||
|
||||
**事件时间。** 每个事件的 `time` 取对应导出消息的 `inserted_at` 毫秒值,并按出现顺序钳制为单调不减(吸收 assistant 比提问早几毫秒的情况)。在一个回答内部,每遇到一个带 `elapsed_secs` 的 THINK,时间游标前进对应的毫秒数,后续 step 使用前进后的时间,使 step 时间间隔反映原始思考耗时。Session header 的 `createdAt` 取第一个事件的时间。
|
||||
|
||||
### Fragment 映射
|
||||
|
||||
| Fragment | 所在消息 | 映射 | 进入模型上下文 |
|
||||
|---|---|---|---|
|
||||
| `REQUEST` | USER | `user/message` 的文本 | 是 |
|
||||
| `FILE`(图片) | USER | `export_path` 指向的条目存在且附件服务已保存时写 `{ type: 'image', attachment }`;否则写伪造的文件卡片 `{ type: 'file', attachment }`,引用不指向任何已保存对象 | 图片能力路由上是已保存图片;否则是文件句柄文本,其中给出的路径没有任何字节 |
|
||||
| `FILE`(非图片) | USER | 伪造的文件卡片:`{ type: 'file', attachment }`,引用为 `attachmentId = sha256('deepseek-chat-export:' + file.id)`、`name = file_name`、`bytes = file_size`(缺失时 0);本体不在导出里,因此不存在对应对象,句柄里的路径读不到内容 | 是,为文件句柄文本 |
|
||||
| `THINK` | ASSISTANT | 当前 step 的 `{ type: 'reasoning', text }`;空文本忽略 | 是(按 adapter 规则) |
|
||||
| `RESPONSE` | ASSISTANT | 当前 step 的 `{ type: 'text', text }`;空文本忽略 | 是 |
|
||||
| `TOOL_SEARCH` | ASSISTANT | `web_search` 调用:参数 `{"queries": [...]}`;结果正文由 `dsh-tool-web` 的 `formatSearchOutput` 生成;`meta` 为 `{ sources: [{ url, title, snippet, publishedAt }], truncated: false }`,渲染为标准搜索卡片。`WIP` 视为未完成并略去;`FAILED` 生成 `isError: true` 的结果,文本固定为 `Error: the export records this search as failed.`;缺少 `status` 时按 `FINISHED` 处理。查询全为空或空白时忽略 | 是 |
|
||||
| `TOOL_OPEN`(有 url) | ASSISTANT | `web_fetch` 调用:参数 `{"url": ...}`;结果正文为标题、URL 与“页面正文未包含在导出中”的说明;`status: FINISHED` 时 `meta` 为 `{ url, statusCode: 200, truncated: false }`,渲染为标准抓取卡片;`FAILED` 时结果为 `isError: true`;`WIP` 忽略 | 是 |
|
||||
| `TOOL_OPEN`(url 为 null 或空串) | ASSISTANT | 不生成任何内容:导出端会在一个 stage 的真实打开记录旁写一条全 null、只带 `stage_id` 和 `group_id` 的记录,它不指向任何页面 | 否 |
|
||||
| `TOOL_FIND` | ASSISTANT | 不生成任何内容:官网把它显示成单独一行,消息里没有对应的块 | 否 |
|
||||
| `TOOL_IMAGE_SEARCH` | ASSISTANT | 不生成任何内容:官网不为图搜显示任何一行,回复的思考里已经写明模型从结果中得到了什么;被搜索的图片本身不在导出里 | 否 |
|
||||
| `READ_LINK` | ASSISTANT | 每个结果一行 Markdown 链接:`[title](url)`;没有 title 时用 url 本身作文字,没有 url 时只写 title,两者都没有则跳过;正文仍是没有密钥无法解密的签名 | 是(文本) |
|
||||
| `TIP` | ASSISTANT | 不生成任何内容:这是官网界面的提示横幅,不是模型输出 | 否 |
|
||||
| `CONTENT_RISK` | ASSISTANT | 忽略:固定免责声明,没有信息量 | 否 |
|
||||
| `PARTIAL_FILE_READ` | ASSISTANT | 不生成任何内容:官网把它显示成单独一行 | 否 |
|
||||
| `TEMPLATE_RESPONSE` | ASSISTANT | 整个回答被排除,`turn/end` 以模板文本作为错误信息 | 否 |
|
||||
| 未知类型 | 任意 | 忽略 | 否 |
|
||||
|
||||
**Step 切分。** 带 `stage_id` 的 fragment 在取值不变时同属当前 step;只有工具 fragment 会开启或改变 stage,因此 stage 变化总是开新 step,带 stage 的 step 一定含工具调用。不是最后一个的 step 如果没有工具调用,续聊历史里就会出现两条相邻的 assistant 消息,而实时 agent loop 从不产生这种结构,因此只含文本的 step 会与下一次调用合并。不带 `stage_id` 的 fragment 沿用旧规则:工具调用之后再出现 THINK 或 RESPONSE 时结束当前 step 并开下一个,本身不带 stage 的记录按文本处理。`WIP` 记录被略过,不切分 step。连续多个 `stage_id` 相同的工具 fragment 落在同一个 step,相当于一次并行调用。被忽略的 fragment 不切分 step,因此“THINK、三个 url 为 null 的 TOOL_OPEN、THINK”仍是一个 step,只包含两个 reasoning 块。
|
||||
|
||||
以官网的“边想边搜”为例,`THINK, TOOL_SEARCH(stage 1), THINK, TOOL_OPEN×4(stage 2), THINK, RESPONSE` 映射为三个 step:①思考 + `web_search`;②思考 + 4 个 `web_fetch`;③思考 + 正文。中间没有思考时,紧邻的 `TOOL_SEARCH(stage 1)` 与 `TOOL_OPEN(stage 2)` 会拆成两个 step,因为第一个 step 已经持有搜索调用。
|
||||
|
||||
**Step 内的块顺序。** 一个 step 的 `assistant/message` 先放该 step 的文本块(思考、正文、链接行),再放工具调用块,两组各自保持记录顺序。因此导出中排在同一 step 工具调用之后的文本会存到该调用之前,而 step 顺序与所有跨 step 顺序仍与导出一致。把文本交叠到工具调用之后的同一条 assistant 消息里,不符合实时 loop 产生的任何 step。
|
||||
|
||||
**ID。** 消息 id、工具调用 id 都由调用方注入的 `createId()` 生成(生产用 `randomUUID`),`tool-call` 块 id、`tool/call.callId`、`tool/result` 消息的 `source.callId` 与 `toolCallId` 相同。
|
||||
|
||||
### 回答状态映射
|
||||
|
||||
导出文档要求非 `FINISHED` 的消息和模板回答不能进入模型上下文。被内容过滤撤回的回答(`CONTENT_FILTER`,官网显示为已撤回)按上文与其提问一起丢弃。其他被排除的回答都不写 `assistant/message`,也不写 `assistant/attempt`(Web 不展示 attempt,而且“用户消息 + attempt + 可重试错误码”会让 GUI 提示继续生成)。用户看到的是 turn 末尾的错误行,显示原因和代码:
|
||||
|
||||
| 原回答 | `turn/end.reason.error.code` | `message`(英文,写入日志) |
|
||||
|---|---|---|
|
||||
| `FAILED` / `TIMEOUT` / `CONTEXT_LENGTH_EXCEEDED` / `INCOMPLETE` / `WIP` | `DEEPSEEK_EXPORT_FAILED` / `DEEPSEEK_EXPORT_TIMEOUT` / `DEEPSEEK_EXPORT_CONTEXT_LENGTH_EXCEEDED` / `DEEPSEEK_EXPORT_INCOMPLETE` / `DEEPSEEK_EXPORT_WIP` | The original reply ended with status "{STATUS}" and is excluded from the model context. |
|
||||
| 其他任何状态 | `DEEPSEEK_EXPORT_UNFINISHED_REPLY` | 同样的说明,状态带引号 |
|
||||
| 含 `TEMPLATE_RESPONSE` | `DEEPSEEK_EXPORT_TEMPLATE_RESPONSE` | 模板文本本身 |
|
||||
| `FINISHED` 但没有任何可导入内容 | `DEEPSEEK_EXPORT_EMPTY_REPLY` | The original reply has no importable content. |
|
||||
| 链以 USER 结尾(没有回答) | `DEEPSEEK_EXPORT_NO_REPLY` | The export contains no reply to this message. |
|
||||
|
||||
错误码是固定字符串;来自导出的文本只出现在说明里。这些代码不在 session-controller 的可继续生成代码集合内,不会出现“继续生成”。提问本身保留在上下文里。
|
||||
|
||||
### Session 写入
|
||||
|
||||
导入不创建 live Agent,直接写持久化层。在扫描之前检测到的失败(压缩包不可读、manifest 缺失、超限或版本不支持、没有可导入的会话、上传超限)不写入任何内容;压缩包结构在扫描中途损坏时,会以 `unreadable-archive` 失败,而在那之前交付的会话已经写入。每个会话在写入前都完成转换,并经 `Session.create` 校验种子;失败的会话被跳过,不影响其他会话。每个选中的会话在压缩包条目到达时转换并写入;失败后补位的会话则按名读取。对每个会话:
|
||||
|
||||
1. 检查目标工作区仍已登记且目录存在;否则以 `workspace-not-found` 停止,之前写入的会话保留。
|
||||
2. 用图片扫描已保存的引用转换会话。转换或种子校验后来失败的会话,其图片已经保存,并且没有任何事件引用它们。
|
||||
3. `Session.create(id, seed, header)` 做与 live append 相同的种子校验(JSON 可序列化、seq 连续、surface 转换合法、消息字段合法),校验用的分离实例随即丢弃。
|
||||
4. `ctx.sessionPersistence.create(header)` → `handle.append(events)` → `handle.flush()` → `handle.close()`(失败时也关闭)。header 为 `{ version: SESSION_FORMAT_VERSION, id, createdAt, cwd, isSeeded: false }`,`cwd` 是工作区的规范路径。存储的事件不含 `session/end-seed`;首次打开时普通恢复路径追加该标记。
|
||||
5. 若投影缓存可用,`coldSnapshot(header, SessionLogOffset(0), events)` 刷新侧栏读取的缓存行(标题、最后提问时间、非空白)。
|
||||
6. `workspace.attachSession(id)`。失败时该会话以“stored as Session {id} but not added to the workspace”为原因记入 `skipped`;`SessionPersistence` 不提供删除,所以这个会话留在存储中、不属于该工作区。
|
||||
|
||||
转换得到的事件在处理下一个会话前释放;导入在会话之间让出事件循环,并在每一步检查取消。写入后的 Session 与其他冷 Session 一样出现在 `session/list` 中,打开时走普通的恢复路径。导入不新增 Session 事件类型,不改变 `SESSION_FORMAT_VERSION`,也不需要持久化类型确认。
|
||||
|
||||
### Client
|
||||
|
||||
- ui-sidebar 声明 HOC slot `sidebar.session.action`(`scope: 'root'`,owner `{ wide: boolean }`),包裹新建会话行的内容,占用方以 `children` 收到该内容,返回它(可再包裹)并附上自己的控件。导入按钮在“新建会话”按钮右侧渲染(宽栏同一行,“新建会话”按钮占剩余宽度;窄栏纵向排列在“新建会话”图标下方)。
|
||||
- 插件的 client 面 `$mount` 自己的 `/remote` 贡献(与 `dsh-api-remote-access` 相同的自挂载方式,不进入 `dsh-api-remotes` 聚合),作为 `sidebar.session.action` 层注册 `ImportSessionsAction`。它先渲染行内容,再渲染触发按钮,最后渲染对话框;不能导入的 Peer 会原样得到行内容,因此新建会话按钮继续渲染。按钮仅在 `useRemoteAccess('deepseekChatImport/limits')` 为真时显示;对话框是该层的本地状态,通过 `Modal` portal 渲染。
|
||||
- 服务页面上的上传使用 `XMLHttpRequest`,因为 Fetch 不提供上传进度。Host 跑在页面之外执行上下文中的页面(静态 Cloudflare Pages 预览)提供 `__DSH_TRANSPORT__.fetch`:压缩包经该载体传输,没有字节进度,直接进入读取与导入阶段。URL 是相对 `document.baseURI` 解析的 `UPLOAD_ROUTE`,因此加路径前缀的代理仍然可用。非 200 应答、没有 outcome 行的应答、不是合法协议值的行或连接失败归为 `upload-failed` 结果;抛出的错误以未知失败文案显示。
|
||||
- 载体选择没有复用 `@deepseek-ai/dsh-client-file-upload`。该包的服务会缓冲整个应答,流式 NDJSON 进度会丢失,而且它的 `post` 方法不在公开接口上;把选择留在本包内同时保住了进度行与包依赖边界。
|
||||
- 文案走 8 种语言的 locale 字典,英文用 sentence case;摘要行有 `.one` / `.other` 两种形式,按 `count === 1` 选择。
|
||||
|
||||
### Realization
|
||||
|
||||
`sidebar.session.action` 是 HOC 层而不是 list,因为占用方装饰的是行的内容,而不是渲染在旁边:它把该内容作为 `children` 接收、原样返回(可再包裹)并追加自己的控件,不新增包裹元素。list 条目会渲染为行内容的兄弟节点,而 rail-in 淡入作用于 slot outlet 的子节点,因为 `display: contents` 的 outlet 锚点本身无法承载动画。
|
||||
|
||||
这项义务只是契约。没有追加内容或无权操作的占用方必须原样返回 `children`,因为渲染器只兜住抛错的层。层也可以合法地不渲染 `children`,那会移除新建会话按钮,因此没有运行时检查能替代这项义务。
|
||||
|
||||
### 图片
|
||||
|
||||
- 图片扫描按压缩包顺序遍历选中会话的每个图片条目,不解析会话。它只解压 `chat_sessions/{id}_files/…` 中 id 属于索引所选会话的条目,以条目的扩展名与文件名调用 `ctx.attachments.saveImage({ data, mediaType, name })`,并按条目名记录引用或失败原因。扩展名不是 png / jpg / jpeg / webp / gif 时记为类型不支持,且不解压该条目。
|
||||
- `convertConversation` 为 `export_path` 已被扫描保存的每个 `FILE` 条目写一个 `image` 块(在文本之前),否则写伪造的文件卡片。
|
||||
- 单张图片缺失、类型不支持、超过上限、损坏或被拒绝时只把该图片写成伪造的文件卡片并记一条 Host 警告,会话照常导入。条目缺失报告 `not in the export`;大小、损坏、类型不支持或存储失败报告自身原因。附件存储按内容去重。
|
||||
- 图片扫描在选中分支与转换之前保存选中会话的每个图片条目。被撤回轮次的图片、导入丢弃的分支的图片,以及转换或 `Session.create` 种子校验后来失败的会话的图片,因此都会存成没有任何事件引用的附件。`SessionPersistence` 与附件存储都不提供删除。
|
||||
|
||||
### 测试
|
||||
|
||||
| 层 | 文件 | 覆盖 |
|
||||
|---|---|---|
|
||||
| 纯转换 | `tests/conversation.host.spec.ts` | `current_message_id` 选择与 id 最大兜底;按 id 线性化;REQUEST / THINK / RESPONSE;`stage_id` 与搜索/打开网页的 step 切分;失败、未完成与缺少状态的搜索;图搜与无地址的打开网页丢弃;页内查找、部分读取、提示均丢弃;Markdown 链接行;被排除回答的 turn-error 与固定错误码;丢弃被内容过滤的轮次;首个与后续 turn 的空文本块;标题规范化;伪造文件卡片;无效树。输出经 `Session.create` 校验,并用 `deriveMessages` 断言模型历史 |
|
||||
| 压缩包 | `tests/archive.host.spec.ts` | 列出条目、单条目读取按声明大小截断、流式扫描、用高压缩比条目验证声明大小上限、声明大小不实、重复条目名、stored 条目大小不一致、损坏条目、取消 |
|
||||
| 编排 | `tests/importer.host.spec.ts` | 带进度地从旧到新导入最近 K 个;携带全部新字段的 2026-11-12 合成归档;超限、损坏与无效的会话文件;失败后补足上限;补位链在某候选无效后继续;附加失败;工作区被移除;压缩包级失败;取消;图片由图片扫描保存(与压缩包顺序无关)或写成伪造文件卡片,主路径不按名读取图片 |
|
||||
| 路由 | `tests/upload.host.spec.ts` | 请求校验;`too-large`;按声明长度分配缓冲区;一次一个导入;NDJSON 行;由应答、请求与卸载触发的取消 |
|
||||
| 恢复 | `tests/resume.host.spec.ts` | 生产 agent loop 继续导入的会话;模型请求包含导入的历史,不含被撤回的轮次 |
|
||||
| 组合 | `tests/composition.host.spec.ts` | 经 Loader 启动 Host;`limits()` 只允许 owner;上传后会话存入工作区;导入暂停时卸载会取消导入,并且只有在导入停止后才完成,不写入任何内容 |
|
||||
| Client | `tests/import-sessions.client.spec.tsx`、`tests/mount.client.spec.ts`、`tests/upload.client.spec.ts` | 按钮出现条件、工作区预选、进度条与文案、单复数摘要、失败与抛错文案、每次尝试后刷新、NDJSON 行读取与校验 |
|
||||
| Bundle | `scripts/optional-bundles.spec.ts` | bundle 能叠加在 Web profile 上组合,并解析出标题、描述与图标 |
|
||||
| 快照 | `apps/web/tests/deepseek-chat-import.e2e.ts`、`snapshots/web/deepseek-chat-import/` | 经路由上传一个 2026-11-12 结构的合成导出,其中包含分支、思考、一对搜索与抓取、一条读取链接记录、一个被内容过滤的轮次和一个未完成的回答;一个导入的会话以一轮录制的模型回复继续,持久化日志可 keyless 回放 |
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**输入导出文件的 host 路径。** 最初的设计从 host 绝对路径读取 ZIP 或解压目录,并在旁边新建 `<export>_workspace` 目录。用户不应输入 host 路径,浏览器也不知道这个路径,远程 Host 也访问不到用户本地下载的文件;浏览器上传对本地和远程 Host 的行为相同。
|
||||
|
||||
**在所选工作区中列出导出文件。** 用户先把 ZIP 放进某个工作区目录,再从 Host 端列表中选择。用户否决了这一方案,选择直接从浏览器上传文件。
|
||||
|
||||
**把上传暂存到磁盘。** 把上传写进临时文件可以去掉内存上限,但要增加清理逻辑、留下崩溃残留,并在 Host 上多出一份私有数据。压缩包只保存在内存中,受 `maxUploadBytes` 约束,服务一次只运行一个导入。
|
||||
|
||||
**在写入任何会话之前解压并校验全部会话。** 这能让“被拒绝的导出不写入任何内容”对转换失败也成立,但要同时在内存中保留所有会话文件和转换后的日志,并在整个导入期间阻塞事件循环。跟随 `chat_session_index.json` 的两次流式扫描:一次在不解析任何会话的情况下保存选中会话的图片,另一次在会话到达时逐个转换并写入。
|
||||
|
||||
**通过单独的流式 Remote 报告进度。** 路由应答本身已经经由 Web server 流式传输,同一请求上的 NDJSON 行不需要第二个通道,能保持进度与结果的顺序,并随请求结束。
|
||||
|
||||
**只导入最新的叶子。** 它一定是叶子,也不需要额外字段,但导出如果是在用户切回较旧分支之后生成的,就会静默导入另一条分支。`current_message_id` 是导出自己的线性化依据,id 最大的兜底则让没有该字段的归档仍可导入。
|
||||
|
||||
**按选中消息的 `inserted_at` 选择。** 它直接表示最后一条导入事件的时间,但需要每个会话的消息,选择阶段就得先解压整个压缩包。`chat_session_index.json` 携带官网自己的更新顺序,让选择阶段跳过未选中的会话;代价是顺序跟随改标题与置顶,而不是最后一条导入事件。
|
||||
|
||||
**通过 `ctx.agents.create({ seed })` 创建 live Agent。** 它是现有的受支持入口,但 `createdAt` 只能是当前时间,导入的会话会全部挤在侧栏顶部;导入上千个会话还会同时创建上千个 live Agent。直接写持久化层保留原始时间,也不占用运行时资源。
|
||||
|
||||
**每个分支一个 Session,或在 DSH 中表达分叉。** DSH Session 是线性日志;为分支各建 Session 会让一个官网会话变成多个难以区分的会话。需求明确只导入最新链。
|
||||
|
||||
**保留被内容过滤回答的提问并写错误行。** 官网把这类轮次显示为已撤回,用户决定两个节点都不导入;剩下的轮次与用户在官网看到的一致。
|
||||
|
||||
**把非 FINISHED 回答或模板回答写成 `assistant/attempt`,或写成 `interrupted` 的 `assistant/message`。** attempt 在 Web 中不可见,并会和可重试错误码一起触发“继续生成”;`interrupted` 的消息内容会进入模型上下文,违反导出文档的约束。
|
||||
|
||||
**在 ui-sidebar 中写死导入按钮。** 侧栏外壳需要依赖导入插件的 Remote 命名空间,把业务分支放进外壳;slot 的成本是一个声明和少量布局改动。
|
||||
|
||||
**新增 Session 事件类型来展示 TIP / CONTENT_RISK 或记录导入来源。** 需要扩展 `SessionEventMap`、持久化目录和 Web 渲染器,超出小规模导入的范围;这些提示不影响回答内容。
|
||||
|
||||
**在默认 Web 组合中挂载导入器。** 该能力是实验性的,而 release 包不能依赖实验性包。可选 bundle 让默认产品保持不变,并向启用它的用户提供导入功能。
|
||||
|
||||
## Consequences
|
||||
|
||||
导入把官网历史带进 DSH,保留原始标题、时间、思考与搜索卡片,导入的会话通过普通恢复路径继续对话。Host 内存受压缩包(`maxUploadBytes`)加一个条目(`maxEntryBytes`)、一个转换后的会话以及已保存图片的引用约束,事件循环在会话之间保持响应。代价是取消或导入中途失败时只有已写入的会话保留,而且补位的会话要按名读取,并再跑一次图片扫描。
|
||||
|
||||
- **冷写入是 agent loop 之外的生产写入方。** 导入使用全新的 Session id 且写完即关闭句柄,不与 live Session 竞争所有权;如果持久化层以后假设所有写入都经过 agent loop(例如在创建时注册额外的派生状态),导入路径需要同步更新。
|
||||
- **已存储但未附加的会话会留在存储中。** `SessionPersistence` 不提供删除;导入在 `skipped` 中报告这样的会话及其 id。
|
||||
- **历史工具调用没有工具记录。** 导入的 `web_search` / `web_fetch` 调用没有对应的 `request/header.tools` 记录。若部署未注册这两个工具,或某个提供方拒绝引用未声明工具的历史,恢复时的首个请求会失败;退路是只映射文本。
|
||||
- **抓取卡片的状态码是推断值。** 导出只记录页面打开成功,没有 HTTP 状态码;`statusCode: 200` 让卡片按成功抓取显示。
|
||||
- **外来 reasoning 会重新发给模型。** 导入的思考内容按无签名 thinking 发送,增加恢复后首个请求的输入 token;KV cache 从该请求开始建立。
|
||||
- **重复导入产生重复会话。** 再次导入同一导出会写入新的会话;导入不记录哪些会话已经导入过。
|
||||
- **用户正在查看的分支决定导入内容。** `current_message_id` 选中导入链,因此用户切回较旧分支后再导出时,导入的就是那条分支;只有字段缺失或指向不存在的消息时才回退到最新的叶子。
|
||||
- **只针对一种导出结构。** 导入器面向 2026-11-12 结构。该结构新增的字段按可选读取,所以更旧的 v3 归档仍能导入,但其中的 `READ_LINK` 没有 url 与 title,链接行能写出的内容更少(更旧的 `TOOL_FIND` 查找词已不再读取)。
|
||||
- **`maxTitleBytes` 是单独的设置。** session-title 服务不公开它的上限,因此修改 session-title 的 `maxTitleBytes` 的组合需要把导入器的这个字段设为相同的值。
|
||||
- **放弃的内容。** 其他分支、被内容过滤的轮次、`CONTENT_RISK` 免责声明、`TIP`、`TOOL_FIND` 与 `PARTIAL_FILE_READ` 记录、`READ_LINK` 的加密正文、搜索结果的 `snippet` 与 `site_name`、`pinned` 标记、非图片文件本体、思考的逐 token 时间、`accumulated_token_usage` 都不导入;导入后的 token 计量使用估算值。被排除回答和失败搜索的说明是固定英文文本。
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-11-forge-provider-command-rules.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-11-11-forge-provider-command-rules.md
|
||||
/agent-note-forge-provider-command-rules:
|
||||
en: 1b602c42430a77b4
|
||||
zh: 8109a6a56901fb89
|
||||
/agent-note-forge-provider-command-rules/problem:
|
||||
en: 29def264f0ee5401
|
||||
zh: 829cdb87861757f5
|
||||
/agent-note-forge-provider-command-rules/decision:
|
||||
en: 17e84e777b0d7380
|
||||
zh: 2cc4720c9437a839
|
||||
/agent-note-forge-provider-command-rules/alternatives-considered:
|
||||
en: a5bdd96f8e814246
|
||||
zh: 29a4f0026cd9abaf
|
||||
/agent-note-forge-provider-command-rules/consequences:
|
||||
en: 506047cfeb4645d3
|
||||
zh: b587240a69b46b8a
|
||||
@@ -0,0 +1,33 @@
|
||||
# Agent Note: Forge provider command rules
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-11-forge-provider-command-rules.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
[Session change request bindings](2026-10-09-session-change-request-bindings.md) recognized `gh` commands inside forge-session, so every new code host's CLI, such as `glab`, meant editing forge-session, and numeric selectors such as `glab mr view 7 -R group/app` need knowledge of that CLI's options and URL forms. Recognition feeds a Session projection, so it must stay deterministic for replay and checkpoints, and a provider enabled after a Session ran its commands should still bind them.
|
||||
|
||||
## Decision
|
||||
|
||||
Each provider registers a declarative `ForgeCommandRule` with `ctx.forgeSession.registerCommands`: its executable, creation subcommands, reference and raw API request subcommand groups with their own options, change request page path, JSON URL members, and a pure `select` that maps one parsed command to a URL or a read-only lookup. An API request, such as `glab api`, binds only the change request its path names, since its output can list many. [forge-github](../../../../packages/experimental/forge-github/src/commands.ts) registers `gh` and [forge-gitlab](../../../../packages/experimental/forge-gitlab/src/commands.ts) registers `glab`. forge-session keeps the shared parts: the literal shell tokenizer, option parsing, output reading, lookups in the call's shell, and the projection.
|
||||
|
||||
The `forgeChangeRequests` state version derives from the recognized rules, `5 × 2^32` plus a hash of the sorted `id@version` pairs, so a checkpoint folded under another rule set is discarded and the log folds again. A registration that changes the set releases the projection and registers it at the new version, then refreshes watchers; the released handle stays readable during the swap. Ending a registration keeps its rule recognized until the service restarts or another rule replaces its id or executable.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Recognition per CLI inside forge-session.** Every provider change would edit forge-session, and its tests would own other CLIs' option sets.
|
||||
|
||||
**Rules on `ForgeProvider`.** forge-session could read rules from `ctx.forge`, but the forge Service Definition would carry a field that only one Consumer uses.
|
||||
|
||||
**Rules for later events only.** Folding only events after a registration skips the commands a Session ran before the provider loaded.
|
||||
|
||||
**A fixed state version.** Folding with whatever rules are loaded breaks the rule that a restored checkpoint plus suffix replay equals full replay once the rules change.
|
||||
|
||||
**Rebuilding on unregistration.** Providers unload before forge-session at shutdown, so every exit would checkpoint a smaller rule set and every start would refold every Session.
|
||||
|
||||
**Option parsing in each provider.** The token walk would repeat in every provider.
|
||||
|
||||
## Consequences
|
||||
|
||||
A new provider rule or a raised rule version refolds every Session once; until a Session is opened again, the Session list shows no cached bindings for it, and re-registration emits no projection change event, so an open Session's summary shows the refolded bindings after a later event. Providers own their rule versions. Unloading a provider at runtime leaves its commands recognized until restart, though they run no lookup; starting without it removes the bindings that only its commands made, while binding records stay. Each start registers the projection without rules and once more after the providers register theirs. The [forge-session README](../../../../packages/experimental/forge-session/README.md#use-this-package) owns the recognition rules.
|
||||
@@ -0,0 +1,33 @@
|
||||
# Agent Note: Forge 提供方命令规则
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-11-forge-provider-command-rules.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
[Session 变更请求绑定](2026-10-09-session-change-request-bindings.zh.md)在 forge-session 内部识别 `gh` 命令,因此每接入一个代码托管平台的 CLI(如 `glab`)都要修改 forge-session;而 `glab mr view 7 -R group/app` 这类数字编号需要了解该 CLI 的选项与 URL 形式。识别结果供 Session 投影使用,因此必须在重放与检查点下保持确定;提供方在 Session 执行过命令之后才启用时,也应能绑定这些命令。
|
||||
|
||||
## Decision
|
||||
|
||||
每个提供方通过 `ctx.forgeSession.registerCommands` 注册一条声明式的 `ForgeCommandRule`:其可执行文件、创建子命令、各带选项的引用子命令组与原始 API 请求子命令组、变更请求页面路径、JSON URL 成员,以及一个纯函数 `select`,把一条解析后的命令映射为 URL 或只读查询。API 请求(如 `glab api`)只绑定其路径指向的变更请求,因为其输出可能列出许多变更请求。[forge-github](../../../../packages/experimental/forge-github/src/commands.ts) 注册 `gh`,[forge-gitlab](../../../../packages/experimental/forge-gitlab/src/commands.ts) 注册 `glab`。forge-session 保留共用部分:字面量 shell 拆词、选项解析、输出读取、在调用所在 shell 中的查询,以及投影。
|
||||
|
||||
`forgeChangeRequests` 的状态版本由已识别规则派生,即 `5 × 2^32` 加上排序后 `id@version` 对的哈希,因此按其他规则集折叠的检查点会被丢弃,日志重新折叠。改变规则集的注册会释放投影并以新版本重新注册,再刷新监听方;切换期间已释放的句柄仍可读取。注册结束后,其规则仍被识别,直到服务重启或另一条规则替换其 id 或可执行文件。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**在 forge-session 内按 CLI 识别。**每次提供方变化都要修改 forge-session,其测试还要承担其他 CLI 的选项集。
|
||||
|
||||
**把规则放在 `ForgeProvider` 上。**forge-session 可以从 `ctx.forge` 读取规则,但 forge 的 Service Definition 就会带上只有一个 Consumer 使用的字段。
|
||||
|
||||
**规则只作用于之后的事件。**只折叠注册之后的事件,会漏掉 Session 在提供方加载之前执行的命令。
|
||||
|
||||
**固定的状态版本。**按当前加载的规则折叠,一旦规则变化,就违背了"恢复的检查点加后缀重放等于完整重放"这一规则。
|
||||
|
||||
**注销时重建。**关闭时提供方先于 forge-session 卸载,因此每次退出都会按更小的规则集写入检查点,每次启动都要重新折叠所有 Session。
|
||||
|
||||
**由各提供方解析选项。**逐词解析会在每个提供方中重复。
|
||||
|
||||
## Consequences
|
||||
|
||||
新增提供方规则或提高规则版本,会使每个 Session 重新折叠一次;Session 再次打开之前,Session 列表不显示它的缓存绑定;重新注册不发出投影变化事件,因此已打开 Session 的摘要要在后续事件之后才显示重新折叠的绑定。规则版本由提供方负责。运行时卸载提供方后,其命令仍被识别,直到重启,但不再执行反查;不加载该提供方启动时,只由其命令产生的绑定会消失,绑定记录保留。每次启动时投影先在没有规则的情况下注册,提供方注册规则后再注册一次。识别规则见 [forge-session README](../../../../packages/experimental/forge-session/README.zh.md#use-this-package)。
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-11-liveshare-owner-state-host-claim.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-11-11-liveshare-owner-state-host-claim.md
|
||||
/agent-note-one-host-claims-the-liveshare-owner-state:
|
||||
en: fe99c1b2c07f8b44
|
||||
zh: 127e08e92ec5fefe
|
||||
/agent-note-one-host-claims-the-liveshare-owner-state/problem:
|
||||
en: 547680b92db88db1
|
||||
zh: 46db5e6498aa1a25
|
||||
/agent-note-one-host-claims-the-liveshare-owner-state/decision:
|
||||
en: 16acf8f131c35b82
|
||||
zh: afed5f4b4c0dcb7a
|
||||
/agent-note-one-host-claims-the-liveshare-owner-state/alternatives-considered:
|
||||
en: 451b3983c32e8c1d
|
||||
zh: 3b44b6b8782db1be
|
||||
/agent-note-one-host-claims-the-liveshare-owner-state/consequences:
|
||||
en: b88da2957ada40b3
|
||||
zh: 2d624911e24755e5
|
||||
@@ -0,0 +1,35 @@
|
||||
# Agent Note: one host claims the LiveShare owner state
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-11-liveshare-owner-state-host-claim.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
The LiveShare owner state — the persisted shares, the Relay registrations they hold, and the forks recorded beside them — is addressed by the Host's DSH home, not by the process serving it. A second Host that starts on that home restores the same shares and re-registers them with the Liveshare server, which moves each registration onto the new connection. The earlier Host's authority reads then answer for a registration the server has moved, fence the share, and, with it, stop the owner's own turn. The state needed one named owner per directory that does not depend on every Host agreeing to ignore the others.
|
||||
|
||||
## Decision
|
||||
|
||||
`claimOwnerHost` (packages/experimental/liveshare/src/host/owner-host-claim.ts) writes `owner-host.json` beside the owner state file and names the process serving it. The holder restores, registers, and changes the shares; every other Host loads the records and publishes nothing. The claim is taken once at mount: a Host that loses it to a successor detects that on its next read, because a share operation re-reads the file instead of trusting the claim it took. A lost claim turns every modifying `liveshareShares` operation into the typed refusal `liveshareShares/owner-state-held`, and leaves reads available, so a non-holding Host still shows the owner what is shared. It imports a credential — its own sign-in — but claims and re-registers nothing.
|
||||
|
||||
The rules are the ones the [session write lease](2026-08-31-cross-process-session-write-lease.md) settled: ownership carries no expiry, contention is a typed answer rather than a crash, and a record left by a process that is gone is reclaimed. Three properties differ, because this directory is not session data:
|
||||
|
||||
- **The claim is advisory, and it gates Relay registrations rather than file writes.** The state file's own registry locking keeps concurrent writes from dropping durable entries, so the claim protects no share data and no Session log. Its whole purpose is that one process owns the server-side registrations at a time.
|
||||
- **There is deliberately no deadline.** A deadline exists to expropriate a stalled holder, and a wedged Host here keeps only its own registrations; a takeover would register the shares from a second connection while the stalled holder still believes it owns them. A holder that stops serving therefore keeps the state until its process exits.
|
||||
- **A record naming this process is reclaimed.** Every Host in one process shares the same owner state, so a second mount inside one process must not find itself fenced out by its own pid.
|
||||
|
||||
The record is published as one whole file: it is written under a temporary name and then hard-linked to the claim path, so the link publishes the record it names or fails because a claim is there, and no reader ever sees a half-written claim. Taking the claim against a live holder throws `OwnerHostClaimHeldError`; the Host reports that holder's pid and continues without the state rather than failing to start. Teardown releases the claim last, after the tunnel and worker registrations have stopped, so a successor cannot start registering the same shares while the holder is still withdrawing them.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**A lease with an expiry, renewal, and takeover** — the shape a distributed lock usually takes, and the one this repository's Session writes replaced with a kernel lock. Renewal traffic and a takeover race would buy nothing here: no write is torn by a second owner, and the only cost of a stalled holder is that its own shares serve until the process exits.
|
||||
|
||||
**Doing nothing and letting every Host serve the shares** — the defect itself: whichever Host registers last wins the registration, and the other fences the share and stops the owner's turn, so two running Hosts make the owner's own Session stop without anyone asking for it.
|
||||
|
||||
**A kernel lock held for the life of the process** — the Session write lease's own mechanism, which recovers on crash with no record at all. It cannot express "this Host lost the state to a successor" to a Host that must keep running and serving reads, and it would report contention by failing acquisition rather than by naming a pid the owner can act on. The record is also what a later Host reads to say which process to stop.
|
||||
|
||||
**Refusing to start beside a live holder** — a second Host is a legitimate way to look at what this machine shares, and failing its mount would take the rest of that DSH home's startup down with the claim.
|
||||
|
||||
## Consequences
|
||||
|
||||
Two Hosts on one DSH home now have one authoritative server registration each share, and the non-holding Host answers a modifying operation with a refusal that names the holder rather than silently diverging. The holder's death frees the state at the next Host start; until then the state is unreachable, which is the deliberate cost of not expropriating a stalled holder. Pid reuse can name the claim's holder wrongly: the next Host then runs without the shares until that unrelated process exits or the record is removed, and nothing is lost when it recovers. The claim compares nothing outside this DSH home, so it remains an advisory guard for one user's state directory, not a multi-host authorization service — nothing stops a Host pointed at another home from registering the same shares with the server.
|
||||
@@ -0,0 +1,35 @@
|
||||
# Agent Note:单一宿主认领 LiveShare 房主状态
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-11-liveshare-owner-state-host-claim.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
LiveShare 的房主状态——持久化的分享、它们持有的 Relay 注册、以及旁边记录的 fork——按宿主所在的 DSH home 寻址,而不是按服务它的进程寻址。在同一 home 上启动的第二个宿主会恢复同样的分享并把它们重新注册到 Liveshare 服务器,服务器随之把每条注册挪到新连接上。先前宿主的权限读取于是对着一条已被挪走的注册作答,围栏该分享,并连带停掉房主自己的回合。这份状态需要一个按目录命名、且不依赖各宿主自觉忽略彼此的归属者。
|
||||
|
||||
## 决定
|
||||
|
||||
`claimOwnerHost`(packages/experimental/liveshare/src/host/owner-host-claim.ts)在房主状态文件旁写 `owner-host.json`,记录服务它的进程。持有者恢复、注册并改动分享;其它宿主只加载记录,不发布任何东西。认领在挂载时只取一次:被后继者夺走的宿主会在下一次读取时发现,因为分享操作会重读该文件,而不是相信启动时取到的认领。丢失的认领会把每个会修改记录的 `liveshareShares` 操作变成类型化的拒绝 `liveshareShares/owner-state-held`,读操作保持可用,因此非持有宿主仍能向房主展示哪些内容被分享。它会导入凭据——那是它自己的登录——但不认领、也不重新注册任何东西。
|
||||
|
||||
规则沿用[会话写租约](2026-08-31-cross-process-session-write-lease.zh.md)确立的那套:所有权不设过期、竞争给出类型化回答而不是崩溃、进程已消失留下的记录会被收回。有三处不同,因为这个目录不是会话数据:
|
||||
|
||||
- **认领是建议性的,且它把关的是 Relay 注册而不是文件写入。** 状态文件自身的 registry 文件锁已防止并发写入丢掉持久条目,所以这条认领不保护任何分享数据或会话日志。它的全部目的是让一个进程在某一时刻独有服务器端的注册。
|
||||
- **刻意没有过期时限。** 时限存在的意义是夺取卡住的持有者,而卡住的宿主在这里只持有自己的注册;夺取会让分享从第二条连接重新注册,而卡住的持有者仍相信自己拥有它们。因此停止服务的持有者会一直持有该状态,直到它的进程退出。
|
||||
- **记录指向本进程时会被收回。** 同一进程内的所有宿主共享同一份房主状态,所以同一进程里的第二次挂载不能因为自己的 pid 而被挡在外面。
|
||||
|
||||
记录作为整份文件发布:先写到临时名,再硬链接到认领路径,于是该链接要么发布它所命名的记录,要么因已有认领而失败,任何读取方都看不到写了一半的认领。对活跃持有者认领会抛出 `OwnerHostClaimHeldError`;宿主报告该持有者的 pid 并在没有该状态的情况下继续,而不是启动失败。退出时最后才释放认领,即在 tunnel 与 worker 的注册停止之后,这样后继者不会在持有者仍在撤销注册时就开始注册同样的分享。
|
||||
|
||||
## 备选方案
|
||||
|
||||
**带过期、续期与夺取的租约**——分布式锁通常的形态,也是本仓库的会话写入用内核锁替换掉的那个。续期流量和夺取竞争在这里买不到任何东西:第二个所有者不会撕裂任何写入,卡住的持有者的唯一代价是它自己的分享服务到进程退出为止。
|
||||
|
||||
**什么都不做,让每个宿主都服务这些分享**——这正是那个缺陷:最后注册的宿主赢得注册,另一个宿主围栏该分享并停掉房主的回合,于是两个运行中的宿主会让房主自己的会话在无人要求的情况下停下。
|
||||
|
||||
**持进程终身的内核锁**——会话写租约自己的机制,崩溃后无需任何记录即可恢复。它无法向一个必须继续运行并服务读的宿主表达「该宿主已被后继者取代」;而且它只能以取锁失败来表达竞争,而不是给出一个房主能据以行动的 pid。记录同时也是后来的宿主用来告诉用户该停掉哪个进程的东西。
|
||||
|
||||
**活跃持有者存在时拒绝启动**——第二个宿主是查看本机分享了什么内容的正当方式,让它的挂载失败会把该 DSH home 其余部分的启动一起拖下水。
|
||||
|
||||
## 后果
|
||||
|
||||
同一 DSH home 上的两个宿主现在对每条分享只有一条权威的服务器注册,非持有宿主对修改类操作给出点名持有者的拒绝,而不是悄悄分叉。持有者死亡后,下一次宿主启动会释放该状态;在那之前状态不可达,这是不夺取卡住的持有者所刻意付出的代价。pid 复用可能把认领的持有者认错:下一个宿主于是没有这些分享地运行,直到那个无关进程退出或记录被移除,恢复时不会有任何东西丢失。认领不比较这个 DSH home 之外的任何东西,因此它仍是一个用户状态目录的建议性守卫,而不是多宿主授权服务——没有任何机制阻止一个指向其它 home 的宿主把同样的分享注册到服务器上。
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-12-typescript-only-ptc.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/simplification/2026-11-12-typescript-only-ptc.md
|
||||
/agent-note-typescript-only-ptc-tool-execution:
|
||||
en: c5baba9480713efd
|
||||
zh: 3bb75334bbb9d309
|
||||
/agent-note-typescript-only-ptc-tool-execution/problem:
|
||||
en: 388bf7cd25221f5c
|
||||
zh: 67fd11e0db13b0d9
|
||||
/agent-note-typescript-only-ptc-tool-execution/decision:
|
||||
en: ecff3310debb44fc
|
||||
zh: 7a6de9ba0d00fc8b
|
||||
/agent-note-typescript-only-ptc-tool-execution/alternatives-considered:
|
||||
en: ca76cf68b304f98e
|
||||
zh: 45b7dfbd7a05b3de
|
||||
/agent-note-typescript-only-ptc-tool-execution/consequences:
|
||||
en: c368f6deb55bec91
|
||||
zh: 870b34771af91c70
|
||||
@@ -0,0 +1,29 @@
|
||||
# Agent Note: TypeScript-only PTC tool execution
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-12-typescript-only-ptc.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
The Python tool SDK originally let a provider change the program language while retaining typed tool calls. Removing the experimental Python runtime left that presentation available to external providers, together with Python completion rendering and binding-name restrictions imposed on the Node provider. Shipped PTC compositions use TypeScript, so those paths maintain a second language without a repository-owned execution provider or profile replay.
|
||||
|
||||
## Decision
|
||||
|
||||
`dsh-tool-executor-ptc` supports TypeScript only. It removes Python schema rendering and exports, language dispatch, completion presentation, and Python-specific binding exclusions. Unsupported providers fail during prompt assembly or execution through the selected executor, or when a private program tool is created. The PTC selection remains active so an invalid provider cannot expose inherited native tools. TypeScript programs retain their SDK, parameters, explicit output selection, canonical nested results and cancellation behavior.
|
||||
|
||||
The runtime service remains independent of tools. Its source-language descriptor lets each consumer check its own requirements; direct runtime and workflow consumers retain completion values. The Harness Python SDK, runtime wheels and other tools' Python environments have separate consumers and remain supported.
|
||||
|
||||
The [PTC foundation](../feature/2026-06-15-ptc.md) and [typed returns](../feature/2026-07-20-ptc-typed-tool-returns.md) remain active for their independent dispatch, durability and value semantics. Their language-specific facts follow this decision. The [archived language-dispatch decision](../../archived/feature/2026-07-31-ptc-language-dispatch.md) remains frozen history.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Keep external Python providers working.** This preserves a capability after deleting its implementation, but still requires a renderer, alternate output semantics and cross-language naming restrictions. Full removal gives one supported tool-program language and a clear migration.
|
||||
|
||||
**Remove Python SDK and runtime packaging too.** Those packages launch the Harness and consume its public protocol; they do not execute Python PTC programs. Removing them would discard an independent supported client.
|
||||
|
||||
## Consequences
|
||||
|
||||
External Python PTC compositions must migrate to a TypeScript provider and rewrite their programs; the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.2/python-ptc-removal/guide.md) owns the steps. There is no Python compatibility branch. Reintroduction requires an owned provider, a concrete consumer need, language-specific rejection and output tests, and a shipped-profile replay.
|
||||
|
||||
Rejection tests mount the executor and compatibility selector through Cordis, then cover prompt assembly, schema projection, direct execution and the private factory. Built-export checks pin removal of Python renderers. Existing keyless TypeScript profile replays compare unchanged model prompts and execution output. Binding validation and real-process execution cover names that no longer need Python exclusions. Existing Session logs and committed historical generations retain their bytes.
|
||||
@@ -0,0 +1,29 @@
|
||||
# Agent Note: PTC 工具执行仅支持 TypeScript
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-12-typescript-only-ptc.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
Python 工具 SDK 最初让提供方能在保留类型化工具调用的同时更换程序语言。移除实验性 Python 运行时后,该呈现仍供外部提供方使用,并保留了 Python 完成值渲染以及施加于 Node 提供方的绑定命名限制。已发布 PTC 组合使用 TypeScript,因此这些路径维护着第二种语言,却没有仓库拥有的执行提供方或 profile 回放。
|
||||
|
||||
## Decision
|
||||
|
||||
`dsh-tool-executor-ptc` 仅支持 TypeScript。它移除 Python schema 渲染及导出、语言分发、完成值呈现与 Python 专属绑定排除规则。不支持的提供方在通过已选中的执行器组装提示词或执行程序时失败,也会在私有程序工具创建时失败。PTC 选择保持生效,避免无效提供方暴露继承的 native 工具。TypeScript 程序保留其 SDK、参数、显式输出选择、规范嵌套结果及取消行为。
|
||||
|
||||
运行时服务仍独立于工具。其源码语言描述符让每个消费方检查自身要求;直接运行时消费方与工作流消费方保留完成值。Harness Python SDK、运行时 wheel 与其他工具的 Python 环境有各自的消费方,继续受到支持。
|
||||
|
||||
[PTC 基础](../feature/2026-06-15-ptc.zh.md)与[类型化返回值](../feature/2026-07-20-ptc-typed-tool-returns.zh.md)仍因独立的分发、持久化及值语义而保持活跃。其中与语言有关的事实遵循本决定。[归档的语言分发决定](../../archived/feature/2026-07-31-ptc-language-dispatch.md)保持为冻结历史。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**保留外部 Python 提供方支持。** 这在删除实现后保留了能力,但仍需要渲染器、另一套输出语义和跨语言命名限制。彻底移除使工具程序只有一种受支持语言,并提供明确迁移路径。
|
||||
|
||||
**同时移除 Python SDK 与运行时打包。** 这些包启动 Harness 并消费其公共协议,并不执行 Python PTC 程序。移除它们会丢弃独立的受支持客户端。
|
||||
|
||||
## Consequences
|
||||
|
||||
外部 Python PTC 组合必须迁移到 TypeScript 提供方并改写程序;[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.2/python-ptc-removal/guide.zh.md)拥有具体步骤。不提供 Python 兼容分支。重新引入需要有明确负责方的提供方、具体消费需求、语言专属的拒绝与输出测试,以及已发布 profile 回放。
|
||||
|
||||
拒绝测试通过 Cordis 挂载执行器与兼容选择器,再覆盖提示词组装、schema 投影、直接执行与私有工厂。构建导出检查固定 Python 渲染器的移除。现有免密钥 TypeScript profile 回放比较保持不变的模型提示和执行输出。绑定验证与真实进程执行覆盖不再需要 Python 排除规则的名称。已有 Session 日志和已提交历史代际逐字节保留。
|
||||
@@ -0,0 +1,34 @@
|
||||
# Bilingual-pair consistency record for 2026-11-04-dsh-home-path-categories.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/proposed/architecture/2026-11-04-dsh-home-path-categories.md
|
||||
/agent-note-harness-home-path-categories:
|
||||
en: 007593701a0d6bf5
|
||||
zh: 3bf266378e3bba08
|
||||
/agent-note-harness-home-path-categories/problem:
|
||||
en: 3e98d90944daeb05
|
||||
zh: 596f750e878f3e69
|
||||
/agent-note-harness-home-path-categories/proposal:
|
||||
en: 76abf280dfdba9bc
|
||||
zh: 0ad29c3c67208086
|
||||
/agent-note-harness-home-path-categories/proposal/path-helper:
|
||||
en: 6f34630c5b05b0d7
|
||||
zh: 2106fdbf4f5ca852
|
||||
/agent-note-harness-home-path-categories/proposal/conventional-top-level-entries:
|
||||
en: 940f404152322a33
|
||||
zh: 5668927394d05723
|
||||
/agent-note-harness-home-path-categories/proposal/other-existing-entries:
|
||||
en: a8242fc3bbe3fe7a
|
||||
zh: b90f9e9deda18e78
|
||||
/agent-note-harness-home-path-categories/proposal/outside-the-home:
|
||||
en: 9d78c323d3f9d159
|
||||
zh: e11a87b74fe11e5c
|
||||
/agent-note-harness-home-path-categories/alternatives-considered:
|
||||
en: cfa4bc5557af4117
|
||||
zh: 7971e54d5770d9aa
|
||||
/agent-note-harness-home-path-categories/acceptance-criteria:
|
||||
en: bf87d444099ebb2b
|
||||
zh: 8315e6ddc07fe3c7
|
||||
/agent-note-harness-home-path-categories/risks:
|
||||
en: aa70b3a0243a1853
|
||||
zh: 64c74b62d3a42472
|
||||
@@ -0,0 +1,83 @@
|
||||
# Agent Note: Harness home path categories
|
||||
|
||||
Status: proposed
|
||||
|
||||
English | [中文](2026-11-04-dsh-home-path-categories.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Each package builds its own path under `$DSH_HOME` (default `~/.dsh`), so the home root mixes user configuration, durable records, logs, indexes, and downloads. A new service or plugin has no rule for where its files belong, and some owners resolve the home by hand: [liveshare](../../../../packages/experimental/liveshare/src/host/share-host.ts) reads `process.env.DSH_HOME` directly, and [migrate-sessions-to-v4](../../../../scripts/migrate-sessions-to-v4.ts) defaults to `~/.dsh/sessions` without reading `DSH_HOME`.
|
||||
|
||||
## Proposal
|
||||
|
||||
Group paths under `$DSH_HOME` by the kinds the [XDG Base Directory Specification](https://specifications.freedesktop.org/basedir/latest/) uses. Every category stays inside `$DSH_HOME`; the harness does not read `XDG_*` variables.
|
||||
|
||||
| Category | Holds | Losing it |
|
||||
|---|---|---|
|
||||
| `config` | Files a person writes or edits to configure the harness | Loses the user's configuration |
|
||||
| `data` | Durable records: user work, sign-ins, installed software | Loses user work, sign-ins, or installed software |
|
||||
| `state` | Records that persist across runs but are not user work: logs, indexes, ids, retained outputs | Resets history; the harness keeps working |
|
||||
| `cache` | Content the harness can rebuild or download again | Costs time or bandwidth only |
|
||||
| `backup` | Backup archives the harness writes, such as compressed copies of the home or a profile | Nothing; the archives are not read during normal operation |
|
||||
|
||||
There is no `runtime` category, the XDG kind for sockets and pid files, because no owner needs one under the home: locks sit beside the file they protect, and live sockets stay in the operating-system temporary directory because Unix socket paths have a length limit. `backup` is not an XDG kind: it gives backup archives one directory that users and cleanup tools can empty at any time without affecting a running harness or the records the archives copy.
|
||||
|
||||
### Path helper
|
||||
|
||||
[`dshPath(category, ...segments)`](../../../../packages/util/home-paths/src/index.ts) in `@deepseek-ai/dsh-home-paths` returns `<home>/<category>/<segments>` without creating directories; `dshPath({ category, dshHome }, ...segments)` resolves an explicit configured home. Loader `!!js` config expressions receive the same function beside `dshHomePath`. A new path under the home uses `dshPath` and passes its owner's directory name, normally the package name without the `@deepseek-ai/dsh-` prefix, as the first segment. `dshHomePath` remains for the existing top-level entries, and `dshCachePath` is `dshPath('cache', ...)`.
|
||||
|
||||
### Conventional top-level entries
|
||||
|
||||
Users open, edit, and script against these entries directly, and documentation across the repository names them, so they keep their current top-level locations and are not candidates for moving:
|
||||
|
||||
| Path under `$DSH_HOME` | Owner | Kind |
|
||||
|---|---|---|
|
||||
| `.env` | [app-boot](../../../../packages/boot/app-boot/README.md) environment layer | config |
|
||||
| `cordis.patch.yml` | [app-boot](../../../../packages/boot/app-boot/README.md) home patch layer | config |
|
||||
| `AGENTS.md` | [agent-instructions](../../../../packages/context/agent-instructions/README.md) | config |
|
||||
| `skills/` | [skill-filesystem](../../../../packages/skill/skill-filesystem/README.md) | config |
|
||||
| `.credentials.yaml` | [credentials-local](../../../../packages/credentials/credentials-local/README.md) | data |
|
||||
| `profiles/<name>/` | [app-boot](../../../../packages/boot/app-boot/README.md), plugin-manager, Desktop (`desktop` profile and its `lock`) | data |
|
||||
| `sessions/` | session-persistence-jsonl root in the base and sdk-minimal bundles | data |
|
||||
| `cache/` | already the `cache` category | cache |
|
||||
|
||||
Files inside a profile directory, such as `node_modules/`, `pnpm-lock.yaml`, `compatibility.json`, `.plugin-manager/`, `.plugin-market/repositories/`, `created-plugins/`, and `cua-*.lock`, stay with their profile because pnpm and the profile tools address them relative to it. The legacy `settings.yaml` importer keeps reading the home root because that file is the import source.
|
||||
|
||||
### Other existing entries
|
||||
|
||||
These entries have no user-facing convention. Each row names the category it belongs to; moving it is a separate change that needs a data migration plan:
|
||||
|
||||
| Current path under `$DSH_HOME` | Category | Owner | Why |
|
||||
|---|---|---|---|
|
||||
| `storages/` | `data` | storage-json root in the base bundle | Workspace, schedule, and other domain records; its `session_projcache` unit is a rebuildable cache, but storage-json has one root |
|
||||
| `attachments/v1/` | `data` | [attachment-local](../../../../packages/attachment/attachment-local/README.md) | User attachments; Session history records their absolute paths |
|
||||
| `dsh-runtimes/` | `data` | Desktop offline runtimes ([workspace-dependencies](../../../../packages/bundle/web-app/cordis.patch.yml)) | Installed software that may hold user additions |
|
||||
| `liveshare/` | `data` | [liveshare](../../../../packages/experimental/liveshare/README.md) owner state and credential | Holds management tokens |
|
||||
| `.anonymous-user-id` | `state` | [anonymous-user-id](../../../../packages/identity/anonymous-user-id/README.md) | Losing it only issues a new id |
|
||||
| `logs/` | `state` | CLI startup failure reports | Logs |
|
||||
| `llm-deepseek/files-v3.json` | `state` | [llm-deepseek](../../../../packages/llm/llm-deepseek/README.md) upload index | Derived index |
|
||||
| `office-kit/outputs/` | `state` | [office-kit](../../../../packages/document/office-kit/README.md) | Retained conversion outputs removed after their retention period |
|
||||
| `speech-to-text/sensevoice/` | `cache` | voice-input-bundle | Downloadable models |
|
||||
| `cache/attachments/` | `cache` | attachment-local request images | Already in `cache` |
|
||||
|
||||
### Outside the home
|
||||
|
||||
These locations are out of scope: `~/.agents` (`DSH_AGENTS_HOME`), shared with other agent tools; Electron `userData` and `logs`, managed by Electron; the Python SDK resource cache `~/.cache/deepseek-harness/resources` (`DSH_RESOURCE_CACHE`), shared across homes; spill and subprocess output directories under the operating-system temporary directory; and developer or release script state such as `~/.dsh-desktop-signing`.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Move every entry now.** A first draft moved all entries, including the conventional ones, into category directories with no fallback. It made every existing home look empty after an upgrade, broke absolute attachment paths recorded in Sessions, and renamed files users edit by hand. The conventional entries above now stay, and the remaining moves wait for a migration plan.
|
||||
|
||||
**Read `XDG_*` variables.** Splitting the home across `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, and similar roots would scatter one installation across several directories and break the single `DSH_HOME` override that tests, the SDK, and Desktop rely on; the [single harness home resolver](../../implemented/architecture/2026-07-24-single-harness-home-resolver.md) already rejected separate roots. The proposal borrows only the classification, inside that one root.
|
||||
|
||||
**Add a `runtime` category.** No current owner needs one; adding it would publish an unused value.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- New paths under `$DSH_HOME` are built with `dshPath` and land in one category directory.
|
||||
- Each move of an entry from "Other existing entries" ships with a migration that preserves existing user data, plus an upgrade guide.
|
||||
- The conventional top-level entries keep their locations.
|
||||
|
||||
## Risks
|
||||
|
||||
Until migrations land, the home holds both category directories and legacy top-level entries. Moving `attachments/` invalidates absolute paths in Session history unless the migration keeps the old location readable. Owners that resolve the home by hand do not pick up the helper until they are changed.
|
||||
@@ -0,0 +1,83 @@
|
||||
# Agent Note: harness home 路径类别
|
||||
|
||||
Status: proposed
|
||||
|
||||
[English](2026-11-04-dsh-home-path-categories.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
各个包在 `$DSH_HOME`(默认 `~/.dsh`)下自行构造路径,因此 home 根目录混杂着用户配置、持久记录、日志、索引和下载内容。新的服务或插件没有规则可以确定其文件应放在哪里,部分负责方还会手动解析 home:[liveshare](../../../../packages/experimental/liveshare/src/host/share-host.ts) 直接读取 `process.env.DSH_HOME`,[migrate-sessions-to-v4](../../../../scripts/migrate-sessions-to-v4.ts) 默认使用 `~/.dsh/sessions`,不读取 `DSH_HOME`。
|
||||
|
||||
## 方案
|
||||
|
||||
按照 [XDG Base Directory Specification](https://specifications.freedesktop.org/basedir/latest/) 使用的类型,对 `$DSH_HOME` 下的路径分组。每个类别都位于 `$DSH_HOME` 内;harness 不读取 `XDG_*` 变量。
|
||||
|
||||
| 类别 | 存放内容 | 丢失后果 |
|
||||
|---|---|---|
|
||||
| `config` | 用户为配置 harness 而编写或编辑的文件 | 丢失用户配置 |
|
||||
| `data` | 持久记录:用户工作成果、登录信息、已安装的软件 | 丢失用户工作成果、登录信息或已安装的软件 |
|
||||
| `state` | 跨运行保留但不属于用户工作成果的记录:日志、索引、id、保留的输出 | 历史被重置;harness 仍可正常工作 |
|
||||
| `cache` | harness 可以重新构建或重新下载的内容 | 仅耗费时间或带宽 |
|
||||
| `backup` | harness 写入的备份压缩包,例如 home 或 profile 的压缩副本 | 无影响;正常运行时不会读取这些压缩包 |
|
||||
|
||||
不设 `runtime` 类别(XDG 中用于 socket 和 pid 文件的类型),因为没有负责方需要在 home 下使用它:锁文件放在其保护的文件旁边,而活动的 socket 留在操作系统临时目录中,因为 Unix socket 路径有长度限制。`backup` 不是 XDG 的类型:它为备份压缩包提供一个目录,用户和清理工具可以随时清空,不影响运行中的 harness,也不影响被备份的记录。
|
||||
|
||||
### 路径辅助函数
|
||||
|
||||
`@deepseek-ai/dsh-home-paths` 中的 [`dshPath(category, ...segments)`](../../../../packages/util/home-paths/src/index.ts) 返回 `<home>/<category>/<segments>`,不创建目录;`dshPath({ category, dshHome }, ...segments)` 基于显式配置的 home 解析路径。Loader `!!js` 配置表达式在 `dshHomePath` 之外也可以使用同一个函数。home 下的新路径使用 `dshPath`,并把负责方的目录名作为第一个路径段传入,该目录名通常是去掉 `@deepseek-ai/dsh-` 前缀的包名。`dshHomePath` 继续用于现有的顶层条目,`dshCachePath` 等同于 `dshPath('cache', ...)`。
|
||||
|
||||
### 约定的顶层条目
|
||||
|
||||
用户会直接打开、编辑这些条目并在脚本中引用它们,仓库中的文档也提到它们,因此它们保留当前的顶层位置,不在迁移候选之列:
|
||||
|
||||
| `$DSH_HOME` 下的路径 | 负责方 | 类型 |
|
||||
|---|---|---|
|
||||
| `.env` | [app-boot](../../../../packages/boot/app-boot/README.zh.md) 环境层 | config |
|
||||
| `cordis.patch.yml` | [app-boot](../../../../packages/boot/app-boot/README.zh.md) home patch 层 | config |
|
||||
| `AGENTS.md` | [agent-instructions](../../../../packages/context/agent-instructions/README.zh.md) | config |
|
||||
| `skills/` | [skill-filesystem](../../../../packages/skill/skill-filesystem/README.zh.md) | config |
|
||||
| `.credentials.yaml` | [credentials-local](../../../../packages/credentials/credentials-local/README.zh.md) | data |
|
||||
| `profiles/<name>/` | [app-boot](../../../../packages/boot/app-boot/README.zh.md)、plugin-manager、Desktop(`desktop` profile 及其 `lock`) | data |
|
||||
| `sessions/` | base 和 sdk-minimal bundle 中的 session-persistence-jsonl 根目录 | data |
|
||||
| `cache/` | 已经是 `cache` 类别 | cache |
|
||||
|
||||
profile 目录内的文件,例如 `node_modules/`、`pnpm-lock.yaml`、`compatibility.json`、`.plugin-manager/`、`.plugin-market/repositories/`、`created-plugins/` 和 `cua-*.lock`,随所属 profile 保留,因为 pnpm 和 profile 工具按相对于 profile 的路径访问它们。旧版 `settings.yaml` 导入器继续读取 home 根目录,因为该文件是导入来源。
|
||||
|
||||
### 其他现有条目
|
||||
|
||||
这些条目没有面向用户的约定。每一行给出该条目所属的类别;迁移它属于单独的变更,需要数据迁移方案:
|
||||
|
||||
| `$DSH_HOME` 下的当前路径 | 类别 | 负责方 | 原因 |
|
||||
|---|---|---|---|
|
||||
| `storages/` | `data` | base bundle 中的 storage-json 根目录 | Workspace、schedule 及其他领域记录;其中 `session_projcache` 单元是可重建的缓存,但 storage-json 只有一个根目录 |
|
||||
| `attachments/v1/` | `data` | [attachment-local](../../../../packages/attachment/attachment-local/README.zh.md) | 用户附件;Session 历史记录了它们的绝对路径 |
|
||||
| `dsh-runtimes/` | `data` | Desktop 离线运行时([workspace-dependencies](../../../../packages/bundle/web-app/cordis.patch.yml)) | 已安装的软件,可能包含用户添加的内容 |
|
||||
| `liveshare/` | `data` | [liveshare](../../../../packages/experimental/liveshare/README.zh.md) 的所有者状态和凭据 | 存放管理令牌 |
|
||||
| `.anonymous-user-id` | `state` | [anonymous-user-id](../../../../packages/identity/anonymous-user-id/README.zh.md) | 丢失后只会生成新的 id |
|
||||
| `logs/` | `state` | CLI 启动失败报告 | 日志 |
|
||||
| `llm-deepseek/files-v3.json` | `state` | [llm-deepseek](../../../../packages/llm/llm-deepseek/README.zh.md) 上传索引 | 派生索引 |
|
||||
| `office-kit/outputs/` | `state` | [office-kit](../../../../packages/document/office-kit/README.zh.md) | 保留的转换输出,超过保留期后删除 |
|
||||
| `speech-to-text/sensevoice/` | `cache` | voice-input-bundle | 可下载的模型 |
|
||||
| `cache/attachments/` | `cache` | attachment-local 请求图片 | 已位于 `cache` 中 |
|
||||
|
||||
### home 之外
|
||||
|
||||
以下位置不在本提案范围内:`~/.agents`(`DSH_AGENTS_HOME`),与其他 agent 工具共享;Electron 的 `userData` 和 `logs`,由 Electron 管理;Python SDK 资源缓存 `~/.cache/deepseek-harness/resources`(`DSH_RESOURCE_CACHE`),在多个 home 之间共享;操作系统临时目录下的 spill 和子进程输出目录;以及开发者或发布脚本的状态,例如 `~/.dsh-desktop-signing`。
|
||||
|
||||
## 备选方案
|
||||
|
||||
**立即迁移所有条目。** 最初的草案把所有条目(包括约定的条目)都移入类别目录,且不提供回退。这样做会使每个现有 home 在升级后看起来为空,使 Session 中记录的附件绝对路径失效,并重命名用户手动编辑的文件。上述约定条目现在保持不动,其余迁移等待迁移方案。
|
||||
|
||||
**读取 `XDG_*` 变量。** 把 home 拆分到 `XDG_CONFIG_HOME`、`XDG_DATA_HOME` 等多个根目录,会让一次安装分散到多个目录,并破坏测试、SDK 和 Desktop 所依赖的单一 `DSH_HOME` 覆盖;[单一 harness home 解析器](../../implemented/architecture/2026-07-24-single-harness-home-resolver.zh.md)已经否决了拆分根目录。本提案只借用分类方式,并且仍在这一个根目录之内。
|
||||
|
||||
**增加 `runtime` 类别。** 当前没有负责方需要它;增加它会发布一个未使用的值。
|
||||
|
||||
## 验收标准
|
||||
|
||||
- `$DSH_HOME` 下的新路径使用 `dshPath` 构造,并落在某一个类别目录中。
|
||||
- 每次迁移“其他现有条目”中的条目时,都附带一个保留现有用户数据的迁移,以及一份升级指南。
|
||||
- 约定的顶层条目保留其位置。
|
||||
|
||||
## 风险
|
||||
|
||||
在迁移落地之前,home 中同时存在类别目录和旧的顶层条目。迁移 `attachments/` 会使 Session 历史中的绝对路径失效,除非迁移保持旧位置可读。手动解析 home 的负责方在被修改之前不会使用该辅助函数。
|
||||
@@ -17,7 +17,7 @@ Convert foreign failures where the dependency is owned. Node errno, SDK, protoco
|
||||
|
||||
## Tool failures
|
||||
|
||||
The tool registry keeps `error.name` and `error.code` on `tool/result` when the producer supplies them: a `HarnessError` thrown by the tool body, a pre-execute `deny`, guard denial, or post-execute block with `info` (including the registry's approval denials, `ApprovalError` with `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`), the registry's own cancellation result (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`, also applied to a signal reason or an `Error` named `AbortError` that the body throws after cancellation), or a `tools/execute` wrapper result such as the timeout policy's `TOOL_TIMEOUT`. Any other thrown value, and a guard denial or block without `info`, persist only text that retry policy, UI, and analytics cannot route on. Every expected failure reachable from a tool body therefore throws a `HarnessError`, normally the owning domain's subclass:
|
||||
The tool registry keeps `error.name` and `error.code` on `tool/result` when the producer supplies them: a `HarnessError` thrown by the tool body, a pre-execute `deny`, guard denial, or post-execute block with `info` (including the registry's approval denials, `ApprovalError` with `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`), the registry's own cancellation result (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`, also applied to a signal reason or an `Error` named `AbortError` that the body or a `tools/execute` wrapper throws after cancellation), or a `tools/execute` wrapper result such as the timeout policy's `TOOL_TIMEOUT`. Any other thrown value, and a guard denial or block without `info`, persist only text that retry policy, UI, and analytics cannot route on. Every expected failure reachable from a tool body therefore throws a `HarnessError`, normally the owning domain's subclass:
|
||||
|
||||
- Hand-checked argument constraints throw `ToolArgsError` (`INVALID_ARGS`) from `dsh-tools`.
|
||||
- Missing composition or caller context, such as an absent Agent, service, or open turn, throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`) from `dsh-tools`.
|
||||
|
||||
+1
-1
@@ -8,4 +8,4 @@ The merge checks run from three workflows named `Policy`, which run on `pull_req
|
||||
|
||||
The manual Desktop publication workflow selects the original successful `package` job attempt independently of `upload-artifact` archival status, then routes each retained build through `DESKTOP_PUBLISH_RUNNERS` to its original machine's unique label. Keep Windows run steps on native PowerShell and Mac run steps on the default POSIX shell; shared entrypoints are Node scripts. Test and production jobs use separate `desktop-test` and `desktop-production` approval Environments after a credential-free preparation job.
|
||||
|
||||
`Publish Desktop · Rollout & Website` reuses the same original-machine routing and approval Environments. Its preparation reads retained metadata and initial publication evidence without revalidating package binaries; it does not create release tags. Cache-only recovery uses the existing website approval and upload journal.
|
||||
`Publish Desktop · Rollout & Website` reuses the same original-machine routing and approval Environments. Its preparation reads retained metadata and initial publication evidence without revalidating package binaries; it does not create release tags. Cache-only recovery validates the prepared website approval digest and upload journal without another Environment approval. Rollout installs only publisher production dependencies in `desktop-rollout` and `website-rollout` checkouts; do not reuse the full-install publication checkouts. Both publication workflows run dependency-free preflights from `apps/desktop-publisher/src`. The required CI verdicts include isolated publisher installation checks: Linux/macOS in `ci.yml`, native Windows in `ci-windows.yml`.
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Daily stale pull-request reminders for the `Stale pull requests` workflow.
|
||||
*
|
||||
* A pull request's last activity is the latest of its creation, a commit, a force push, a reopen or ready-for-review
|
||||
* event, and a comment or review from a non-bot account. Other timeline events, such as mentions, labels and cross
|
||||
* references, do not count, so reminder comments never extend it. After 7 and 14 days without activity the workflow
|
||||
* comments once per stage and mentions the author. Activity starts a new cycle. Pull requests labelled `DO_NOT_CLOSE`
|
||||
* and pull requests opened by bots receive no reminders. The workflow never closes pull requests.
|
||||
*
|
||||
* Each run reads the timeline of every open pull request that is neither exempt nor bot-authored, because `updated_at`
|
||||
* also changes on events that are not activity. Each run posts at most `MAX_COMMENTS_PER_RUN` reminders, least recently
|
||||
* updated pull requests first, so a backlog spreads over several days within GitHub's content-creation limits. A failed
|
||||
* pull request is reported and skipped.
|
||||
*/
|
||||
|
||||
/** Label that exempts a pull request from reminders. */
|
||||
export const EXEMPT_LABEL = 'DO_NOT_CLOSE'
|
||||
|
||||
/** Days without activity after which each reminder is posted, in ascending order. */
|
||||
export const REMINDER_DAYS = [7, 14]
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000
|
||||
// GitHub asks integrations to wait at least one second between content-creating requests.
|
||||
const COMMENT_INTERVAL_MS = 1000
|
||||
const MAX_COMMENTS_PER_RUN = 100
|
||||
const MARKER = /<!-- stale-pr-reminder:(\d+) -->/
|
||||
// Review bots that use ordinary user accounts.
|
||||
const BOT_LOGINS = new Set(['ds-review-bot'])
|
||||
|
||||
const isBot = account => account?.type === 'Bot' || (account?.login ?? '').endsWith('[bot]') || BOT_LOGINS.has(account?.login)
|
||||
|
||||
/**
|
||||
* Returns the timestamps a timeline event contributes to the last activity.
|
||||
* @param {object} event GitHub issue timeline event.
|
||||
* @returns {string[]} ISO timestamps; empty for bot activity and events that are not activity.
|
||||
*/
|
||||
function activityTimes(event) {
|
||||
switch (event.event) {
|
||||
case 'committed':
|
||||
return [event.committer?.date].filter(Boolean)
|
||||
case 'head_ref_force_pushed':
|
||||
case 'reopened':
|
||||
case 'ready_for_review':
|
||||
return [event.created_at]
|
||||
case 'commented':
|
||||
return isBot(event.actor) ? [] : [event.created_at]
|
||||
case 'line-commented':
|
||||
case 'commit-commented':
|
||||
return (event.comments ?? []).filter(comment => !isBot(comment.user)).map(comment => comment.created_at)
|
||||
case 'reviewed':
|
||||
return isBot(event.user) ? [] : [event.submitted_at]
|
||||
default:
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects the reminder a pull request is due for.
|
||||
* @param {object} options
|
||||
* @param {string} options.createdAt Pull-request creation time.
|
||||
* @param {object[]} options.timeline Complete issue timeline of the pull request.
|
||||
* @param {Date} options.now Evaluation time.
|
||||
* @returns {number | undefined} Due reminder stage in days, or `undefined` when none is due.
|
||||
*/
|
||||
export function dueReminder({ createdAt, timeline, now }) {
|
||||
const times = [createdAt, ...timeline.flatMap(activityTimes)].map(time => Date.parse(time)).filter(Number.isFinite)
|
||||
const lastActivity = Math.max(...times)
|
||||
const due = REMINDER_DAYS.filter(days => now.getTime() - lastActivity >= days * DAY_MS).at(-1)
|
||||
if (due === undefined) return undefined
|
||||
const sent = timeline
|
||||
.filter(event => event.event === 'commented' && isBot(event.actor) && Date.parse(event.created_at) > lastActivity)
|
||||
.map(event => Number(MARKER.exec(event.body ?? '')?.[1]))
|
||||
return sent.some(days => days >= due) ? undefined : due
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the reminder comment.
|
||||
* @param {string} author Pull-request author login.
|
||||
* @param {number} days Reminder stage in days.
|
||||
* @returns {string} Comment body.
|
||||
*/
|
||||
export function reminderBody(author, days) {
|
||||
return [
|
||||
`<!-- stale-pr-reminder:${days} -->`,
|
||||
`@${author} This pull request has had no activity for ${days} days. Please update it, reply to keep it open, or close it if it is no longer needed. Add the \`${EXEMPT_LABEL}\` label, or ask a maintainer to add it, to stop these reminders.`,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
/**
|
||||
* Posts every due reminder on open pull requests of the workflow repository.
|
||||
* @param {object} options
|
||||
* @param {object} options.github Authenticated Octokit client from `actions/github-script`.
|
||||
* @param {object} options.context Workflow context from `actions/github-script`.
|
||||
* @param {object} options.core Actions toolkit core from `actions/github-script`.
|
||||
* @param {Date} [options.now] Evaluation time.
|
||||
* @param {(ms: number) => Promise<void>} [options.sleep] Delay between comments.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function remindStalePullRequests({ github, context, core, now = new Date(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) }) {
|
||||
const { owner, repo } = context.repo
|
||||
const pulls = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', sort: 'updated', direction: 'asc', per_page: 100 })
|
||||
let posted = 0
|
||||
let failed = 0
|
||||
for (const pull of pulls) {
|
||||
if (posted >= MAX_COMMENTS_PER_RUN) break
|
||||
if (isBot(pull.user)) continue
|
||||
if (pull.labels.some(label => label.name === EXEMPT_LABEL)) continue
|
||||
try {
|
||||
const timeline = await github.paginate(github.rest.issues.listEventsForTimeline, { owner, repo, issue_number: pull.number, per_page: 100 })
|
||||
const days = dueReminder({ createdAt: pull.created_at, timeline, now })
|
||||
if (days === undefined) continue
|
||||
if (posted > 0) await sleep(COMMENT_INTERVAL_MS)
|
||||
await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: reminderBody(pull.user.login, days) })
|
||||
posted++
|
||||
core.info(`#${pull.number}: posted the ${days}-day reminder`)
|
||||
} catch (error) {
|
||||
failed++
|
||||
core.warning(`#${pull.number}: ${error.message}`)
|
||||
}
|
||||
}
|
||||
if (failed > 0) core.setFailed(`${failed} pull requests failed; see the warnings above.`)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { dueReminder, reminderBody, remindStalePullRequests } from './remind.mjs'
|
||||
|
||||
const now = new Date('2026-11-30T00:00:00Z')
|
||||
const daysAgo = days => new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString()
|
||||
const human = { login: 'author', type: 'User' }
|
||||
const bot = { login: 'github-actions[bot]', type: 'Bot' }
|
||||
const comment = (actor, days, body = 'ok') => ({ event: 'commented', actor, created_at: daysAgo(days), body })
|
||||
const reminder = (days, stage) => comment(bot, days, reminderBody('author', stage))
|
||||
|
||||
test('no reminder is due within 7 days of the last activity', () => {
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(6), timeline: [], now }), undefined)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(30), timeline: [comment(human, 6)], now }), undefined)
|
||||
})
|
||||
|
||||
test('the latest due stage is posted once after the last activity', () => {
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(7), timeline: [], now }), 7)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(10), timeline: [reminder(3, 7)], now }), undefined)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7)], now }), 14)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [], now }), 14)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [reminder(20, 14)], now }), undefined)
|
||||
})
|
||||
|
||||
test('human activity restarts the cycle and bot activity does not', () => {
|
||||
const sentBefore = [reminder(30, 7), reminder(23, 14)]
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment(human, 8)], now }), 7)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'committed', committer: { date: daysAgo(3) } }], now }), undefined)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reviewed', user: human, submitted_at: daysAgo(3) }], now }), undefined)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'line-commented', comments: [{ user: human, created_at: daysAgo(3) }] }], now }), undefined)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'head_ref_force_pushed', actor: human, created_at: daysAgo(3) }], now }), undefined)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ci[bot]', type: 'Bot' }, 1)], now }), undefined)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ds-review-bot', type: 'User' }, 1)], now }), undefined)
|
||||
})
|
||||
|
||||
test('mentions, labels and cross references are not activity', () => {
|
||||
const at = (event, days) => ({ event, actor: human, created_at: daysAgo(days) })
|
||||
// GitHub records a `mentioned` event for the author right after each reminder.
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7), at('mentioned', 7 - 1e-5), at('subscribed', 7 - 1e-5)], now }), 14)
|
||||
assert.equal(dueReminder({ createdAt: daysAgo(20), timeline: [at('labeled', 1), at('cross-referenced', 1), at('review_requested', 1)], now }), 14)
|
||||
})
|
||||
|
||||
test('reminders mention the author and skip exempt and bot-authored pull requests', async () => {
|
||||
const pull = (number, overrides = {}) => ({ number, user: human, labels: [], created_at: daysAgo(20), updated_at: daysAgo(20), ...overrides })
|
||||
const pulls = [
|
||||
pull(1),
|
||||
pull(2, { labels: [{ name: 'DO_NOT_CLOSE' }] }),
|
||||
pull(3, { user: { login: 'dependabot[bot]', type: 'Bot' } }),
|
||||
// A bot comment or label refreshes `updated_at` without being activity.
|
||||
pull(4, { updated_at: daysAgo(1) }),
|
||||
pull(6),
|
||||
pull(5),
|
||||
]
|
||||
const comments = []
|
||||
const timelines = []
|
||||
const github = {
|
||||
rest: {
|
||||
pulls: { list: 'pulls' },
|
||||
issues: {
|
||||
listEventsForTimeline: 'timeline',
|
||||
createComment: async params => {
|
||||
if (params.issue_number === 6) throw new Error('locked')
|
||||
comments.push(params)
|
||||
},
|
||||
},
|
||||
},
|
||||
paginate: async (method, params) => {
|
||||
if (method === 'pulls') return pulls
|
||||
timelines.push(params.issue_number)
|
||||
return []
|
||||
},
|
||||
}
|
||||
const sleeps = []
|
||||
const warnings = []
|
||||
const failures = []
|
||||
const core = { info() {}, warning: message => warnings.push(message), setFailed: message => failures.push(message) }
|
||||
await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) })
|
||||
assert.deepEqual(timelines, [1, 4, 6, 5])
|
||||
assert.deepEqual(warnings, ['#6: locked'])
|
||||
assert.equal(failures.length, 1)
|
||||
assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5])
|
||||
assert.match(comments[0].body, /^<!-- stale-pr-reminder:14 -->\n@author This pull request has had no activity for 14 days\./)
|
||||
assert.deepEqual(sleeps, [1000, 1000, 1000])
|
||||
})
|
||||
|
||||
test('a run posts at most 100 reminders', async () => {
|
||||
const pulls = Array.from({ length: 105 }, (_, number) => ({ number, user: human, labels: [], created_at: daysAgo(20), updated_at: daysAgo(20) }))
|
||||
let comments = 0
|
||||
const github = {
|
||||
rest: { pulls: { list: 'pulls' }, issues: { listEventsForTimeline: 'timeline', createComment: async () => comments++ } },
|
||||
paginate: async method => method === 'pulls' ? pulls : [],
|
||||
}
|
||||
await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core: { info() {} }, now, sleep: async () => {} })
|
||||
assert.equal(comments, 100)
|
||||
})
|
||||
@@ -495,6 +495,9 @@ jobs:
|
||||
console.log(JSON.stringify({ arch: process.arch, cpus: os.cpus().length,
|
||||
memoryGiB: Math.round(os.totalmem() / 2 ** 30) }))"
|
||||
|
||||
# No archive cache: this manual matrix includes the persistent 64/96-core
|
||||
# fleet rows, and a `~` cache written by an ephemeral runner does not
|
||||
# restore into the preparation directory there.
|
||||
- name: Install and prepare Linux
|
||||
if: matrix.platform == 'linux'
|
||||
run: |
|
||||
|
||||
@@ -23,6 +23,39 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
windows-publisher:
|
||||
runs-on: >-
|
||||
${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-2vcpu-windows-2025'
|
||||
|| vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted'
|
||||
&& github.event.pull_request.user.login != 'dependabot[bot]'
|
||||
&& fromJSON('["self-hosted", "dsh-win-ci", "windows"]')
|
||||
|| 'dsh-windows-2025-16core' }}
|
||||
defaults:
|
||||
run:
|
||||
shell: pwsh
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/[email protected]
|
||||
with:
|
||||
persist-credentials: false
|
||||
path: publisher-isolated
|
||||
- uses: actions/[email protected]
|
||||
with:
|
||||
node-version: '24'
|
||||
- name: Check preflights before dependency installation
|
||||
working-directory: publisher-isolated
|
||||
run: node apps/desktop-publisher/tests/preinstall.mjs
|
||||
- uses: pnpm/[email protected]
|
||||
with:
|
||||
package_json_file: publisher-isolated/package.json
|
||||
dest: ${{ runner.temp }}/setup-pnpm-js-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }}
|
||||
- name: Install only publisher production dependencies
|
||||
working-directory: publisher-isolated
|
||||
run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts
|
||||
- name: Load publisher without Desktop or root development dependencies
|
||||
working-directory: publisher-isolated/apps/desktop-publisher
|
||||
run: node --import tsx tests/isolated-install.mjs
|
||||
|
||||
# Native builds and process tests block pull requests independently of coverage.
|
||||
# Observational checks reuse the successful build and remain non-blocking.
|
||||
# Dependabot PRs are excluded from the self-hosted pool and stay queued for
|
||||
@@ -30,6 +63,7 @@ jobs:
|
||||
# Blacksmith uses 2 vCPU for file-serial native tests and 16 for coverage
|
||||
# and the shared build/observational workspace.
|
||||
windows-build:
|
||||
needs: windows-publisher
|
||||
if: github.event_name == 'pull_request'
|
||||
runs-on: >-
|
||||
${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025'
|
||||
@@ -258,7 +292,7 @@ jobs:
|
||||
&& github.event.pull_request.user.login != 'dependabot[bot]'
|
||||
&& fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
|
||||
|| 'ubuntu-latest' }}
|
||||
needs: [windows-build, windows-native-tests]
|
||||
needs: [windows-publisher, windows-build, windows-native-tests]
|
||||
if: ${{ !cancelled() && github.event_name == 'pull_request' }}
|
||||
steps:
|
||||
- name: Fail if any needed job did not succeed
|
||||
|
||||
@@ -19,6 +19,42 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
publisher-isolated:
|
||||
strategy:
|
||||
max-parallel: 1
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [linux, macos]
|
||||
runs-on: >-
|
||||
${{ matrix.os == 'macos' && 'macos-latest'
|
||||
|| vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404'
|
||||
|| vars.DSH_CI_FAILOVER_LINUX == 'selfhosted'
|
||||
&& github.event.pull_request.user.login != 'dependabot[bot]'
|
||||
&& fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
|
||||
|| 'ubuntu-latest' }}
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/[email protected]
|
||||
with:
|
||||
persist-credentials: false
|
||||
path: publisher-isolated
|
||||
- uses: actions/[email protected]
|
||||
with:
|
||||
node-version: '24'
|
||||
- name: Check preflights before dependency installation
|
||||
working-directory: publisher-isolated
|
||||
run: node apps/desktop-publisher/tests/preinstall.mjs
|
||||
- uses: pnpm/[email protected]
|
||||
with:
|
||||
package_json_file: publisher-isolated/package.json
|
||||
dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
- name: Install only publisher production dependencies
|
||||
working-directory: publisher-isolated
|
||||
run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts
|
||||
- name: Load publisher without Desktop or root development dependencies
|
||||
working-directory: publisher-isolated/apps/desktop-publisher
|
||||
run: node --import tsx tests/isolated-install.mjs
|
||||
|
||||
|
||||
# Three enterprise jobs isolate coverage, static analysis, and the
|
||||
# build-backed consumer tail. The consumer job owns the only Linux build so
|
||||
@@ -179,6 +215,16 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-
|
||||
|
||||
# The persistent self-hosted pool keeps ~/.cache between jobs on its own
|
||||
# layout, so the archive cache follows the hosted-only pnpm store guard.
|
||||
- name: Restore verified bubblewrap archive
|
||||
id: bubblewrap-cache
|
||||
if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
|
||||
uses: actions/cache/[email protected]
|
||||
with:
|
||||
path: ~/.cache/dsh-ci/bubblewrap
|
||||
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
|
||||
|
||||
- name: Install dependencies and prepare bubblewrap
|
||||
run: |
|
||||
pnpm install --frozen-lockfile &
|
||||
@@ -192,6 +238,16 @@ jobs:
|
||||
if (( install_status != 0 )); then exit "$install_status"; fi
|
||||
exit "$sandbox_status"
|
||||
|
||||
# The save step is skipped on a hit. A restored archive whose digest fails
|
||||
# is re-downloaded but not re-saved (the key already exists), so a tampered
|
||||
# entry survives until eviction; that needs deliberate cache poisoning.
|
||||
- name: Save verified bubblewrap archive
|
||||
if: (vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]') && steps.bubblewrap-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/[email protected]
|
||||
with:
|
||||
path: ~/.cache/dsh-ci/bubblewrap
|
||||
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
|
||||
|
||||
- name: Run exhaustive coverage
|
||||
run: pnpm run check:ci:coverage
|
||||
|
||||
@@ -406,6 +462,16 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-playwright-
|
||||
|
||||
# The persistent self-hosted pool keeps ~/.cache between jobs on its own
|
||||
# layout, so the archive cache follows the hosted-only pnpm store guard.
|
||||
- name: Restore verified bubblewrap archive
|
||||
id: bubblewrap-cache
|
||||
if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
|
||||
uses: actions/cache/[email protected]
|
||||
with:
|
||||
path: ~/.cache/dsh-ci/bubblewrap
|
||||
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
|
||||
|
||||
- name: Install dependencies and prepare bubblewrap
|
||||
run: |
|
||||
pnpm install --frozen-lockfile &
|
||||
@@ -419,6 +485,13 @@ jobs:
|
||||
if (( install_status != 0 )); then exit "$install_status"; fi
|
||||
exit "$sandbox_status"
|
||||
|
||||
- name: Save verified bubblewrap archive
|
||||
if: (vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]') && steps.bubblewrap-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/[email protected]
|
||||
with:
|
||||
path: ~/.cache/dsh-ci/bubblewrap
|
||||
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
|
||||
|
||||
# Blacksmith's Ubuntu HTTP archive endpoints can be unreachable while HTTPS works.
|
||||
- name: Use HTTPS for Ubuntu archives on Blacksmith
|
||||
if: vars.DSH_CI_FAILOVER_LINUX == 'blacksmith'
|
||||
@@ -459,6 +532,7 @@ jobs:
|
||||
|
||||
|
||||
node-compat:
|
||||
needs: publisher-isolated
|
||||
if: github.event_name == 'pull_request'
|
||||
# Under the selfhosted leg this job admits only repository-owned PR code
|
||||
# to the persistent shared VM; the blacksmith branch targets ephemeral
|
||||
@@ -532,9 +606,26 @@ jobs:
|
||||
- name: Install (immutable)
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
# The persistent self-hosted pool keeps ~/.cache between jobs on its own
|
||||
# layout, so the archive cache follows the hosted-only pnpm store guard.
|
||||
- name: Restore verified bubblewrap archive
|
||||
id: bubblewrap-cache
|
||||
if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
|
||||
uses: actions/cache/[email protected]
|
||||
with:
|
||||
path: ~/.cache/dsh-ci/bubblewrap
|
||||
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
|
||||
|
||||
- name: Prepare bubblewrap (unrestrict userns)
|
||||
run: bash scripts/prepare-ci-bubblewrap.sh
|
||||
|
||||
- name: Save verified bubblewrap archive
|
||||
if: (vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]') && steps.bubblewrap-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/[email protected]
|
||||
with:
|
||||
path: ~/.cache/dsh-ci/bubblewrap
|
||||
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
|
||||
|
||||
- name: Run compatibility smokes
|
||||
env:
|
||||
DSH_BUILD_CLIENT_PROFILE: official
|
||||
@@ -572,7 +663,7 @@ jobs:
|
||||
&& github.event.pull_request.user.login != 'dependabot[bot]'
|
||||
&& fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
|
||||
|| 'ubuntu-latest' }}
|
||||
needs: [node-24, node-24-coverage, node-24-lint, node-24-bench, node-24-consumers, node-compat]
|
||||
needs: [publisher-isolated, node-24, node-24-coverage, node-24-lint, node-24-bench, node-24-consumers, node-compat]
|
||||
if: ${{ !cancelled() && github.event_name == 'pull_request' }}
|
||||
steps:
|
||||
- name: Fail if any needed job did not succeed
|
||||
|
||||
Loaded 100 of 2160 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user