Merge latest Team base and regenerate ownership references
This commit is contained in:
commit
300e0ded19
170 files changed
+4011
-178
No files matched your search
@@ -3418,7 +3418,7 @@ export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist'
|
||||
|
||||
- `inject`: `workingDirectory` · `sessionProjections`
|
||||
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
|
||||
- `source`: [`packages/subagent/subagent/src/index.ts:184`](../packages/subagent/subagent/src/index.ts)
|
||||
- `source`: [`packages/subagent/subagent/src/index.ts:181`](../packages/subagent/subagent/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Host configuration for continuable subagent capacity. */
|
||||
@@ -4228,7 +4228,7 @@ export interface PresetSelectionConfig {
|
||||
```ts config-catalog
|
||||
/** Optional subagent control tools. */
|
||||
export interface Config {
|
||||
/** Register `interrupt_agent` and its discovery guidance. Defaults to true; false leaves the service API available. */
|
||||
/** Register `interrupt_agent`. Defaults to true; false leaves the service API available. */
|
||||
interrupt?: boolean
|
||||
}
|
||||
```
|
||||
@@ -4870,6 +4870,7 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them.
|
||||
| `@deepseek-ai/dsh-experimental-browser-use-runtime` | — | [`packages/experimental/browser-use-runtime/src/index.ts`](../packages/experimental/browser-use-runtime/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-experimental-cot-translation-bundle` | — | [`packages/experimental/cot-translation-bundle/src/index.ts`](../packages/experimental/cot-translation-bundle/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-experimental-inspector-profile` | — | [`packages/experimental/inspector-profile/src/index.ts`](../packages/experimental/inspector-profile/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-experimental-liveshare-protocol` | — | [`packages/experimental/liveshare-protocol/src/index.ts`](../packages/experimental/liveshare-protocol/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-experimental-plugin-market-bundle` | — | [`packages/experimental/plugin-market-bundle/src/index.ts`](../packages/experimental/plugin-market-bundle/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-experimental-ralph-bundle` | — | [`packages/experimental/ralph-bundle/src/index.ts`](../packages/experimental/ralph-bundle/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-experimental-session-search` | — | [`packages/experimental/session-search/src/index.ts`](../packages/experimental/session-search/src/index.ts) |
|
||||
|
||||
@@ -3420,7 +3420,7 @@ export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist'
|
||||
|
||||
- `inject`: `workingDirectory` · `sessionProjections`
|
||||
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
|
||||
- `source`: [`packages/subagent/subagent/src/index.ts:184`](../packages/subagent/subagent/src/index.ts)
|
||||
- `source`: [`packages/subagent/subagent/src/index.ts:181`](../packages/subagent/subagent/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Host configuration for continuable subagent capacity. */
|
||||
@@ -4230,7 +4230,7 @@ export interface PresetSelectionConfig {
|
||||
```ts config-catalog
|
||||
/** Optional subagent control tools. */
|
||||
export interface Config {
|
||||
/** Register `interrupt_agent` and its discovery guidance. Defaults to true; false leaves the service API available. */
|
||||
/** Register `interrupt_agent`. Defaults to true; false leaves the service API available. */
|
||||
interrupt?: boolean
|
||||
}
|
||||
```
|
||||
@@ -4872,6 +4872,7 @@ export interface Config {
|
||||
| `@deepseek-ai/dsh-experimental-browser-use-runtime` | — | [`packages/experimental/browser-use-runtime/src/index.ts`](../packages/experimental/browser-use-runtime/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-experimental-cot-translation-bundle` | — | [`packages/experimental/cot-translation-bundle/src/index.ts`](../packages/experimental/cot-translation-bundle/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-experimental-inspector-profile` | — | [`packages/experimental/inspector-profile/src/index.ts`](../packages/experimental/inspector-profile/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-experimental-liveshare-protocol` | — | [`packages/experimental/liveshare-protocol/src/index.ts`](../packages/experimental/liveshare-protocol/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-experimental-plugin-market-bundle` | — | [`packages/experimental/plugin-market-bundle/src/index.ts`](../packages/experimental/plugin-market-bundle/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-experimental-ralph-bundle` | — | [`packages/experimental/ralph-bundle/src/index.ts`](../packages/experimental/ralph-bundle/src/index.ts) |
|
||||
| `@deepseek-ai/dsh-experimental-session-search` | — | [`packages/experimental/session-search/src/index.ts`](../packages/experimental/session-search/src/index.ts) |
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 3221d1076554001f
|
||||
zh: 29f166be6a5c04d9
|
||||
/development-guide/contributor-reference/typescript-project-layout:
|
||||
en: 160d39c13e71be8a
|
||||
zh: 306a9ef7b8f0359f
|
||||
en: 258eadaa4eecd5df
|
||||
zh: 6fc6de7b94c7b3e5
|
||||
/development-guide/contributor-reference/environment-variables:
|
||||
en: dba2c72ee6ffa930
|
||||
zh: b65c27fbb9129ec8
|
||||
|
||||
+1
-1
@@ -72,7 +72,7 @@ Host and Client stay two aggregate programs because both sides declaration-merge
|
||||
- A script that builds a repo-wide `ts.Program` seeds `tsconfig.host.json` or `tsconfig.client.json` explicitly — never the root solution, because flattening both aggregates into one program collides the `Context` merges.
|
||||
- A new package is registered in exactly one aggregate; only the split packages above carry both leaf configs, and the shared leaves are registered in both aggregates because each side must type-check the same source. Having both a Node loader entry and a browser entry is not a reason to split a package; an ordinary Client plugin produces both runtime artifacts during the Client build phase.
|
||||
|
||||
Six packages split Host and Client tsconfigs: `api/remotes`, `api/gateway`, `api/session-controller`, `api/workspace-controller`, `client/connection`, and `session-query/session-log-export`. `api/remotes`' Host entry participates in the Host Typert graph while its Client entry imports generated `/remote` declarations; `session-log-export` keeps Node archive production out of its browser controller. Each split package-root `tsconfig.json` is therefore only a solution, and the two aggregates and direct consumers reference `tsconfig.host.json` or `tsconfig.client.json` respectively. The workspace `constraints` gate walks the reachable Project Reference graph and checks each referencing project's own compiler face: a single-config target remains valid from either face, while a split target must name the matching leaf rather than its solution root or opposite leaf; it discovers split packages from the presence of both leaf configs, so a new split joins the gate automatically. The [`api-remotes` README](../packages/api/remotes/README.md) and [`session-log-export` README](../packages/session-query/session-log-export/README.md) explain their splits.
|
||||
Seven packages split Host and Client tsconfigs: `api/remotes`, `api/gateway`, `api/session-controller`, `api/workspace-controller`, `client/connection`, `session-query/session-log-export`, and `experimental/liveshare-protocol`. `api/remotes`' Host entry participates in the Host Typert graph while its Client entry imports generated `/remote` declarations; `session-log-export` keeps Node archive production out of its browser controller; `liveshare-protocol` keeps the Node wire codecs on its Host leaf and the browser viewer carrier on its Client leaf. Each split package-root `tsconfig.json` is therefore only a solution, and the two aggregates and direct consumers reference `tsconfig.host.json` or `tsconfig.client.json` respectively. The workspace `constraints` gate walks the reachable Project Reference graph and checks each referencing project's own compiler face: a single-config target remains valid from either face, while a split target must name the matching leaf rather than its solution root or opposite leaf; it discovers split packages from the presence of both leaf configs, so a new split joins the gate automatically. The [`api-remotes` README](../packages/api/remotes/README.md) and [`session-log-export` README](../packages/session-query/session-log-export/README.md) explain their splits.
|
||||
|
||||
`pnpm run build:artifacts` emits every artifact in the generated dependency order, checking and compiling only the package references of each compiler face:
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ Host 与 Client 保持两个 aggregate program,是因为两侧在相同键下
|
||||
- 构造全仓 `ts.Program` 的脚本显式以 `tsconfig.host.json` 或 `tsconfig.client.json` 为种子——根 solution 永不作为种子,因为把两个 aggregate 展平进一个 program 会撞上 `Context` 合并冲突。
|
||||
- 新包只登记进一个 aggregate;只有上述拆分包同时携带两个 leaf 配置,共享 leaf 因两侧需要对同一份源码做类型检查而登记进两个 aggregate。包同时具有 Node loader 入口和 browser 入口并不构成拆分理由;普通 Client 插件的两份运行时产物都在 Client 构建阶段生成。
|
||||
|
||||
拆分 Host/Client tsconfig 的包有六个:`api/remotes`、`api/gateway`、`api/session-controller`、`api/workspace-controller`、`client/connection` 与 `session-query/session-log-export`。`api/remotes` 的 Host 入口进入 Host Typert 图,而 Client 入口导入生成的 `/remote` 声明;`session-log-export` 则让 Node archive 生产代码不进入浏览器 controller。每个拆分包根 `tsconfig.json` 因此只作为 solution,两个 aggregate 和直接消费方分别引用 `tsconfig.host.json` 或 `tsconfig.client.json`。workspace `constraints` 门禁遍历可达的 Project Reference 图,并按各引用 project 自身的 compiler face 检查:只有单一配置的目标可由任一 face 引用,拆分配置的目标则必须引用匹配的 leaf,不得引用 solution 根或另一侧 leaf;该门禁按「两个 leaf 配置同时存在」自动发现拆分包,所以新拆分的包会自动纳入管辖。[`api-remotes` README](../packages/api/remotes/README.zh.md) 与 [`session-log-export` README](../packages/session-query/session-log-export/README.zh.md)分别说明其拆分。
|
||||
拆分 Host/Client tsconfig 的包有七个:`api/remotes`、`api/gateway`、`api/session-controller`、`api/workspace-controller`、`client/connection`、`session-query/session-log-export` 与 `experimental/liveshare-protocol`。`api/remotes` 的 Host 入口进入 Host Typert 图,而 Client 入口导入生成的 `/remote` 声明;`session-log-export` 则让 Node archive 生产代码不进入浏览器 controller;`liveshare-protocol` 把 Node 线路编解码放在 Host leaf、浏览器查看页载体放在 Client leaf。每个拆分包根 `tsconfig.json` 因此只作为 solution,两个 aggregate 和直接消费方分别引用 `tsconfig.host.json` 或 `tsconfig.client.json`。workspace `constraints` 门禁遍历可达的 Project Reference 图,并按各引用 project 自身的 compiler face 检查:只有单一配置的目标可由任一 face 引用,拆分配置的目标则必须引用匹配的 leaf,不得引用 solution 根或另一侧 leaf;该门禁按「两个 leaf 配置同时存在」自动发现拆分包,所以新拆分的包会自动纳入管辖。[`api-remotes` README](../packages/api/remotes/README.zh.md) 与 [`session-log-export` README](../packages/session-query/session-log-export/README.zh.md)分别说明其拆分。
|
||||
|
||||
`pnpm run build:artifacts` 按生成依赖顺序产出全部产物,只检查并编译各 compiler face 的包 reference:
|
||||
|
||||
|
||||
@@ -70,10 +70,10 @@ This matrix shows which packages dispatch each harness-owned event and which pac
|
||||
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:84`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
|
||||
| `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` |
|
||||
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:296`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
|
||||
| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:164`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` |
|
||||
| `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:140`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`tool-subagent`](../packages/subagent/tool-subagent) |
|
||||
| `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:146`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`tool-subagent`](../packages/subagent/tool-subagent) |
|
||||
| `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:156`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) |
|
||||
| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:161`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` |
|
||||
| `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:137`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`tool-subagent`](../packages/subagent/tool-subagent) |
|
||||
| `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:143`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`tool-subagent`](../packages/subagent/tool-subagent) |
|
||||
| `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:153`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) |
|
||||
| `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime`, [`working-directory`](../packages/session/working-directory) |
|
||||
| `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - |
|
||||
| `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime`, [`tool-subagent`](../packages/subagent/tool-subagent) |
|
||||
|
||||
@@ -72,10 +72,10 @@
|
||||
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:84`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
|
||||
| `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` |
|
||||
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:296`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
|
||||
| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:164`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` |
|
||||
| `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:140`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`tool-subagent`](../packages/subagent/tool-subagent) |
|
||||
| `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:146`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`tool-subagent`](../packages/subagent/tool-subagent) |
|
||||
| `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:156`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) |
|
||||
| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:161`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` |
|
||||
| `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:137`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`tool-subagent`](../packages/subagent/tool-subagent) |
|
||||
| `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:143`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`tool-subagent`](../packages/subagent/tool-subagent) |
|
||||
| `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:153`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) |
|
||||
| `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime`, [`working-directory`](../packages/session/working-directory) |
|
||||
| `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - |
|
||||
| `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime`, [`tool-subagent`](../packages/subagent/tool-subagent) |
|
||||
|
||||
@@ -281,6 +281,7 @@ flowchart TD
|
||||
pkg_experimental_cua_macos["experimental-cua-macos"]
|
||||
pkg_experimental_inspector["experimental-inspector"]
|
||||
pkg_experimental_inspector_profile["experimental-inspector-profile"]
|
||||
pkg_experimental_liveshare_protocol["experimental-liveshare-protocol"]
|
||||
pkg_experimental_plugin_market_bundle["experimental-plugin-market-bundle"]
|
||||
pkg_experimental_ptc_runtime_python["experimental-ptc-runtime-python"]
|
||||
pkg_experimental_ralph_bundle["experimental-ralph-bundle"]
|
||||
@@ -1592,6 +1593,7 @@ flowchart TD
|
||||
| [`experimental-cot-translation-bundle`](../packages/experimental/cot-translation-bundle) | `experimental` | — |
|
||||
| [`experimental-inspector`](../packages/experimental/inspector) | `experimental` | — |
|
||||
| [`experimental-inspector-profile`](../packages/experimental/inspector-profile) | `experimental` | — |
|
||||
| [`experimental-liveshare-protocol`](../packages/experimental/liveshare-protocol) | `experimental` | — |
|
||||
| [`experimental-plugin-market-bundle`](../packages/experimental/plugin-market-bundle) | `experimental` | — |
|
||||
| [`experimental-ralph-bundle`](../packages/experimental/ralph-bundle) | `experimental` | — |
|
||||
| [`experimental-session-inspector`](../packages/experimental/session-inspector) | `experimental` | — |
|
||||
|
||||
@@ -283,6 +283,7 @@ flowchart TD
|
||||
pkg_experimental_cua_macos["experimental-cua-macos"]
|
||||
pkg_experimental_inspector["experimental-inspector"]
|
||||
pkg_experimental_inspector_profile["experimental-inspector-profile"]
|
||||
pkg_experimental_liveshare_protocol["experimental-liveshare-protocol"]
|
||||
pkg_experimental_plugin_market_bundle["experimental-plugin-market-bundle"]
|
||||
pkg_experimental_ptc_runtime_python["experimental-ptc-runtime-python"]
|
||||
pkg_experimental_ralph_bundle["experimental-ralph-bundle"]
|
||||
@@ -1594,6 +1595,7 @@ flowchart TD
|
||||
| [`experimental-cot-translation-bundle`](../packages/experimental/cot-translation-bundle) | `experimental` | — |
|
||||
| [`experimental-inspector`](../packages/experimental/inspector) | `experimental` | — |
|
||||
| [`experimental-inspector-profile`](../packages/experimental/inspector-profile) | `experimental` | — |
|
||||
| [`experimental-liveshare-protocol`](../packages/experimental/liveshare-protocol) | `experimental` | — |
|
||||
| [`experimental-plugin-market-bundle`](../packages/experimental/plugin-market-bundle) | `experimental` | — |
|
||||
| [`experimental-ralph-bundle`](../packages/experimental/ralph-bundle) | `experimental` | — |
|
||||
| [`experimental-session-inspector`](../packages/experimental/session-inspector) | `experimental` | — |
|
||||
|
||||
@@ -255,8 +255,8 @@
|
||||
en: a622b15cc2598d51
|
||||
zh: 48e1b05956d63e26
|
||||
/tool-schema-catalog/deepseek-ai-dsh-tool-subagent-control/list-agents:
|
||||
en: 689f481655009bd6
|
||||
zh: bcab3a9ad0e8bd72
|
||||
en: 6ff6254e604397d2
|
||||
zh: 32b2f1ba4052b19e
|
||||
/tool-schema-catalog/deepseek-ai-dsh-tool-subagent-control/send-message:
|
||||
en: aaccc4f194398018
|
||||
zh: d918c1346a87a4b1
|
||||
|
||||
@@ -2237,7 +2237,7 @@ Source: [`packages/subagent/tool-subagent-control/src/index.ts`](../packages/sub
|
||||
|
||||
### `list_agents`
|
||||
|
||||
List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.
|
||||
List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
@@ -2243,7 +2243,7 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录
|
||||
|
||||
### `list_agents`
|
||||
|
||||
列出整个 Team:根代理和所有可达的可继续后代,包括调用方自身。行包含 id、描述和状态;后代行包含父级 id 和相对根的深度。可以向列为 running 或 inactive 的任意其他 Team 成员发送消息;只能中断自己的后代。running 表示正在工作;inactive 表示当前没有工作。自身仍在线时,直属子代理结束会收到通知,无需反复查询其状态。使用 send_message 继续对话。
|
||||
列出整棵 subagent 树:根代理和所有可达的可继续后代,包括调用方自身。行包含 id、描述和状态;后代行包含父级 id 和相对根的深度。可以向树中列为 running 或 inactive 的任意其他代理发送消息。running 表示正在工作;inactive 表示当前没有工作。自身仍在线时,直属子代理结束会收到通知,无需反复查询其状态。使用 send_message 继续对话。
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
+1
-1
@@ -134,7 +134,7 @@
|
||||
"docs:build": "tsx website/build.ts && pnpm run verify-doc-site-fragments",
|
||||
"docs:build:mpa": "tsx website/build.ts --mpa && pnpm run verify-doc-site-fragments",
|
||||
"docs:preview": "pnpm --filter @deepseek-ai/website run preview",
|
||||
"docs:check": "pnpm exec vitest run scripts/project-doc-site.spec.ts scripts/verify-doc-site-fragments.spec.ts website/tests/mermaid-viewer.spec.ts website/tests/image-viewer.spec.ts website/tests/code-groups.spec.ts website/tests/page-markdown-actions.spec.ts website/tests/raw-markdown.spec.ts && pnpm run docs:build",
|
||||
"docs:check": "pnpm exec vitest run scripts/project-doc-site.spec.ts scripts/verify-doc-site-fragments.spec.ts website/tests/mermaid-viewer.spec.ts website/tests/image-viewer.spec.ts website/tests/code-groups.spec.ts website/tests/page-markdown-actions.spec.ts website/tests/raw-markdown.spec.ts website/tests/table-filter.spec.ts && pnpm run docs:build",
|
||||
"website:dev": "pnpm run docs:dev",
|
||||
"website:build": "pnpm run docs:build",
|
||||
"verify-package-readme-limitations": "tsx scripts/verify-package-readme-limitations.ts",
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
en: b55aeb927737b90d
|
||||
zh: 0b215fcb5c2c7908
|
||||
/packages-experimental/packages:
|
||||
en: 895f169f8f3ebbc7
|
||||
zh: 62786c4876d97055
|
||||
en: 036d034ac12d686c
|
||||
zh: c748a9230fefee86
|
||||
/packages-experimental/related-documentation:
|
||||
en: 1cb9d3448d44e48d
|
||||
zh: cd326d70a746b896
|
||||
|
||||
@@ -66,6 +66,7 @@ Promotion requires a named product role, documented public behavior and limitati
|
||||
| [`api-speech-to-text`](api-speech-to-text/README.md) | Authenticated transient transcription Remote | `ctx.speechController` |
|
||||
| [`client-ui-voice-input`](client-ui-voice-input/README.md) | Microphone capture and guarded draft insertion | — |
|
||||
| [`plugin-market-bundle`](plugin-market-bundle/README.md) | Default-disabled optional custom plugin indexes: the index service and the Discover tab | — |
|
||||
| [`liveshare-protocol`](liveshare-protocol/README.md) | Wire frames and the identity contract shared by the owner bundle and the Relay | — |
|
||||
| [`voice-input-bundle`](voice-input-bundle/README.md) | Default-disabled optional voice input composition | — |
|
||||
| [`agent-team-profile`](agent-team-profile/README.md) | Agent Teams collaboration, tools, and Web UI bundle | — |
|
||||
| [`agent-team`](agent-team/README.md) | Named teammates with direct messages and a durable shared task board | `ctx.agentTeams` |
|
||||
|
||||
@@ -66,6 +66,7 @@ kind: "package-group"
|
||||
| [`api-speech-to-text`](api-speech-to-text/README.zh.md) | 带认证的临时转写 Remote | `ctx.speechController` |
|
||||
| [`client-ui-voice-input`](client-ui-voice-input/README.zh.md) | 麦克风录音与版本检查后的草稿插入 | — |
|
||||
| [`plugin-market-bundle`](plugin-market-bundle/README.zh.md) | 默认禁用的可选自定义插件索引:索引服务和「发现」标签页 | — |
|
||||
| [`liveshare-protocol`](liveshare-protocol/README.zh.md) | owner bundle 与 Relay 共用的线路帧与身份契约 | — |
|
||||
| [`voice-input-bundle`](voice-input-bundle/README.zh.md) | 默认禁用的可选语音输入组合 | — |
|
||||
| [`agent-team-profile`](agent-team-profile/README.zh.md) | Agent Teams 协作、工具与 Web UI 组合包 | — |
|
||||
| [`agent-team`](agent-team/README.zh.md) | 具名 teammate,成员之间直接消息与持久共享任务板 | `ctx.agentTeams` |
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 1d96f4897b1a5a28
|
||||
zh: 25ca08bc167d1e4a
|
||||
/deepseek-ai-dsh-creation-recommendations/understand-the-implementation:
|
||||
en: 0d0d8a48145e481c
|
||||
zh: 538989f861ddbb56
|
||||
en: 60e11c121350bb71
|
||||
zh: c8cfc6d26fb02811
|
||||
/deepseek-ai-dsh-creation-recommendations/further-exploration:
|
||||
en: 056d3e9b67fd628e
|
||||
zh: 71db00e1a971d495
|
||||
@@ -42,8 +42,8 @@
|
||||
en: c2046060f1ce1f08
|
||||
zh: 08e37f9f758939bc
|
||||
/deepseek-ai-dsh-creation-recommendations/known-limitations-and-deferred-work:
|
||||
en: 7f6c43730b74d1f5
|
||||
zh: 8fdd41c9abba4190
|
||||
en: f259b5a6e0326cb5
|
||||
zh: 682760d7d3df42de
|
||||
/deepseek-ai-dsh-creation-recommendations/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: 8ec3e73528ddb1a6
|
||||
@@ -0,0 +1,37 @@
|
||||
# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/experimental/liveshare-protocol/README.md
|
||||
/:
|
||||
en: efeee80d1665d7fc
|
||||
zh: 18c481ee3920a247
|
||||
/deepseek-ai-dsh-experimental-liveshare-protocol:
|
||||
en: 023b0ec3130c921a
|
||||
zh: 83a7492f544eed39
|
||||
/deepseek-ai-dsh-experimental-liveshare-protocol/summary:
|
||||
en: cf4bc338899afa65
|
||||
zh: e8376bead1d99529
|
||||
/deepseek-ai-dsh-experimental-liveshare-protocol/table-of-contents:
|
||||
en: 80b31a934611cb4a
|
||||
zh: 05f3f7f9cb2fd881
|
||||
/deepseek-ai-dsh-experimental-liveshare-protocol/use-this-package:
|
||||
en: bbff250eba0f1b89
|
||||
zh: 0a618f05cc88ee2b
|
||||
/deepseek-ai-dsh-experimental-liveshare-protocol/use-this-package/when-to-use-it:
|
||||
en: d3f965cdd4635ef2
|
||||
zh: cca0198bc469ba1d
|
||||
/deepseek-ai-dsh-experimental-liveshare-protocol/use-this-package/entry-point:
|
||||
en: 452b98f914e90804
|
||||
zh: 20c344a12a23f9c1
|
||||
/deepseek-ai-dsh-experimental-liveshare-protocol/understand-the-implementation:
|
||||
en: 2b683ba1b31c8ce5
|
||||
zh: 94ad38d16e83f823
|
||||
/deepseek-ai-dsh-experimental-liveshare-protocol/further-exploration:
|
||||
en: e773c21200a61a9d
|
||||
zh: 57108786433cf892
|
||||
/deepseek-ai-dsh-experimental-liveshare-protocol/known-limitations-and-deferred-work:
|
||||
en: eae54e021b06b41b
|
||||
zh: 23fffbaf6d34250a
|
||||
/deepseek-ai-dsh-experimental-liveshare-protocol/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: e88aeb617ffb74ea
|
||||
@@ -0,0 +1,93 @@
|
||||
---
|
||||
description: "Liveshare gateway frame codecs and the provider-neutral identity contract shared by the owner bundle and the Relay."
|
||||
kind: "package-library"
|
||||
---
|
||||
|
||||
# @deepseek-ai/dsh-experimental-liveshare-protocol
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
## Summary
|
||||
|
||||
`dsh-experimental-liveshare-protocol` gives the Liveshare owner bundle and the Relay one copy of what they must agree on: the owner/worker IPC frames, the gateway frames the Relay forwards without interpreting, the viewer carrier script the Relay places in the served page, and the provider-neutral identity contract with its loopback mock implementation. It exists so the owner bundle and the Relay share these definitions without either importing the other; the Relay never loads owner code. It depends on the stateless `dsh-brand` type library and declares `cordis` as a peer.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Use this package](#use-this-package)
|
||||
- [Understand the implementation](#understand-the-implementation)
|
||||
- [Further Exploration](#further-exploration)
|
||||
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
|
||||
- [Dev Note](#dev-note)
|
||||
|
||||
-----
|
||||
|
||||
<a id="use-this-package"></a>
|
||||
## Use this package
|
||||
|
||||
### When to use it
|
||||
|
||||
Import this package whenever code must speak the Liveshare wire or resolve one viewer identity: the owner host and its gateway worker, the Relay server and its acceptance tests. The root entry carries the wire codecs, the identity contract, the viewer carrier, and the viewer-state vocabulary; the mock provider lives in `src/identity/mock.ts` for tests only and no package entry exposes it. This is a library — no profile mounts it and no `cordis.yml` row names it.
|
||||
|
||||
### Entry point
|
||||
|
||||
```ts
|
||||
import { parseGatewayFrame, rawText, sendFrame } from '@deepseek-ai/dsh-experimental-liveshare-protocol'
|
||||
import { identityKeyOf, normalizeIdentity } from '@deepseek-ai/dsh-experimental-liveshare-protocol'
|
||||
```
|
||||
|
||||
The viewer carrier (`installViewerCarrier`) and the viewer-state vocabulary are published through the root entry, not through their own subpaths, because both faces of the owner page consume them together.
|
||||
|
||||
`parseGatewayFrame` returns one validated frame and answers `undefined` for malformed or unknown input, so a gateway this build does not understand cannot fail the connection. A caller that needs to answer the peer instead of leaving it waiting calls `unsupportedFrameRefusal`, which turns a frame this build cannot serve into the refusal to send back. `identityKeyOf` renders one actor as the `providerId:tenantId:subjectId` key every ACL comparison uses, and `normalizeIdentity` fills the documented `default` tenant for a provider that issues none.
|
||||
|
||||
Relay compatibility uses declared versions, capabilities, and explicit refusals, not per-release frame translation or common-subset negotiation. Independently deployed peers have no agreed historical support window, so version-specific shims would add an unbounded set of behaviors to maintain. Published optional Relay fields remain optional; capability names are added only for implemented behavior and are never renamed or reinterpreted.
|
||||
|
||||
-----
|
||||
|
||||
<a id="understand-the-implementation"></a>
|
||||
## Understand the implementation
|
||||
|
||||
<details>
|
||||
<summary>Implementation internals — click to expand</summary>
|
||||
|
||||
`tunnel-protocol.ts` defines the frames and nothing else: `sendFrame` takes any socket exposing `readyState` and `send`, so the package needs no socket dependency and both the owner gateway and the Relay pass their own `ws` instance. `identity/` holds the provider contract, the canonical ACL key codec, and the loopback `mock` provider. Neither half imports owner code, so the Relay can depend on this package without depending on the owner bundle.
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| [`src/index.ts`](src/index.ts) | Both faces re-exported for callers that want one import |
|
||||
| [`src/tunnel-protocol.ts`](src/tunnel-protocol.ts) | Owner/worker IPC frames, gateway frames, and their codecs |
|
||||
| [`src/viewer-carrier.ts`](src/viewer-carrier.ts) | Viewer-page carrier script and the owner page routes it forwards; reachable through the root entry |
|
||||
| [`src/viewer-states.ts`](src/viewer-states.ts) | Viewer state vocabulary and its answers, re-exported by the root entry |
|
||||
| [`src/identity/types.ts`](src/identity/types.ts) | Provider-neutral identity triple and `IdentityProvider` contract |
|
||||
| [`src/identity/keys.ts`](src/identity/keys.ts) | Canonical ACL key codec and the tenant normalization adapters apply before storing an identity |
|
||||
| [`src/identity/mock.ts`](src/identity/mock.ts) | Loopback identity provider for local runs and tests |
|
||||
| — | No runtime invariant companion is published because this package holds no mutable state and no registrations; this package's own specs exercise these codecs. |
|
||||
|
||||
</details>
|
||||
|
||||
-----
|
||||
|
||||
<a id="further-exploration"></a>
|
||||
## Further Exploration
|
||||
|
||||
- [Experimental packages](../README.md) — experimental package status.
|
||||
- The Liveshare owner bundle and the Relay consume these frames and ship separately.
|
||||
|
||||
-----
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
- Gateway requests require the Relay's authenticated actor outside the opaque body; frames without that actor are refused.
|
||||
- The Owner Host and worker ship together. The supervisor mints a branded UUID `registrationToken` per logical add, invalidates it on removal, and replays it only for the same retained registration after process restart. Lifecycle, requests, and cancellations echo that token with the share id; per-request `TunnelRequestToken` remains independent. IPC decoders refuse missing identities, and neither token enters Relay URLs or wire frames. Same-package IPC does not negotiate versions; Relay wire frames retain numeric ids and protocol version 1. Compatibility capabilities include `file-upload`, `actor-credential`, and `direct-connection`. An actor may carry an optional owner-verifiable `credential` (the protocol validates its type only; an owner verifies it before trusting the asserted identity, and absence keeps today's Relay-asserted semantics). A share spec may carry `connection`; absence reads as `{ mode: 'relay' }`, and a Relay that still owns the data path refuses a `direct` registration.: a relay registration that declares it may carry `allowsFileUpload` on the share support and access-state frames; every other peer keeps the stored value and a frame without the field reads as uploads off.
|
||||
- Owners declaring `share-access-state` receive committed, id-less ACL/mode/expiry snapshots with a durable monotonic version. The worker forwards snapshots only from its current socket; the Host clears authority on socket loss and refreshes the authenticated requests snapshot before external execution admission. An unavailable snapshot fails closed instead of borrowing persisted ACLs.
|
||||
- **Historical release support is not verified** — `tests/frames/v1` records concrete frames and refusal obligations, but does not identify a published Owner release. The gateway declares `LIVESHARE_PROTOCOL_VERSION` and implemented capabilities; the Relay rejects a declared mismatch and sends optional lifecycle frames only to declared consumers. These checks preserve recorded fields and explicit refusals, not a per-release translation or an unbounded support window.
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### Dev Note
|
||||
|
||||
<details>
|
||||
<summary>Working context for maintainers — click to expand</summary>
|
||||
|
||||
None.
|
||||
|
||||
</details>
|
||||
@@ -0,0 +1,93 @@
|
||||
---
|
||||
description: "owner bundle 与 Relay 共用的 Liveshare gateway 帧编解码,以及与 provider 无关的身份契约。"
|
||||
kind: "package-library"
|
||||
---
|
||||
|
||||
# @deepseek-ai/dsh-experimental-liveshare-protocol
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
## 概述
|
||||
|
||||
`dsh-experimental-liveshare-protocol` 让 Liveshare owner bundle 与 Relay 共用同一份必须一致的定义:owner/worker 的 IPC 帧、Relay 不解析只转发的 gateway 帧、Relay 放进被服务页面的查看页载体脚本,以及与 provider 无关的身份契约及其回环 mock 实现。它让 owner bundle 与 Relay 共享这些定义而不必互相依赖,Relay 也不会加载 owner 侧代码。它依赖无状态的 `dsh-brand` 类型库,并把 `cordis` 声明为 peer。
|
||||
|
||||
## 目录
|
||||
|
||||
- [使用本包](#use-this-package)
|
||||
- [理解实现](#understand-the-implementation)
|
||||
- [进一步探索](#further-exploration)
|
||||
- [已知限制与延期工作](#known-limitations-and-deferred-work)
|
||||
- [开发备注](#dev-note)
|
||||
|
||||
-----
|
||||
|
||||
<a id="use-this-package"></a>
|
||||
## 使用本包
|
||||
|
||||
### 何时使用
|
||||
|
||||
凡是需要说 Liveshare 线路协议或解析某个 viewer 身份的代码,都导入本包:owner host 及其 gateway worker、Relay server 及其验收测试。包根入口同时携带帧编解码、身份契约、查看页载体与查看页状态词汇;mock provider 位于 `src/identity/mock.ts`,仅供测试使用,任何包入口都不导出它。这是一个库——没有 profile 会挂载它,也没有 `cordis.yml` 行引用它。
|
||||
|
||||
### 入口
|
||||
|
||||
```ts
|
||||
import { parseGatewayFrame, rawText, sendFrame } from '@deepseek-ai/dsh-experimental-liveshare-protocol'
|
||||
import { identityKeyOf, normalizeIdentity } from '@deepseek-ai/dsh-experimental-liveshare-protocol'
|
||||
```
|
||||
|
||||
查看页载体(`installViewerCarrier`)与查看页状态词汇通过根入口发布,而不是各自的子路径,因为 owner 页面的两个面会一起消费它们。
|
||||
|
||||
`parseGatewayFrame` 返回一个校验通过的帧,对畸形或未知输入返回 `undefined`,因此本构建不认识的 gateway 帧不会让连接失败。需要回答对端而不是让它空等的调用方使用 `unsupportedFrameRefusal`,它把一个本构建无法服务的帧变成要回送的拒绝。`identityKeyOf` 把一个 actor 渲染成所有 ACL 比较使用的 `providerId:tenantId:subjectId` 键,`normalizeIdentity` 为不签发 tenant 的 provider 填入文档化的 `default`。
|
||||
|
||||
Relay 兼容性依靠声明版本、能力和明确拒绝,不提供逐发布版本的帧翻译或共同子集协商。独立部署的对端没有约定的历史支持窗口,因此逐版本适配会引入数量无界、需要持续维护的行为。已发布的可选 Relay 字段保持可选;能力名仅为已经实现的行为新增,绝不重命名或重新解释。
|
||||
|
||||
-----
|
||||
|
||||
<a id="understand-the-implementation"></a>
|
||||
## 理解实现
|
||||
|
||||
<details>
|
||||
<summary>实现细节——点击展开</summary>
|
||||
|
||||
`tunnel-protocol.ts` 只定义帧:`sendFrame` 接收任何带 `readyState` 与 `send` 的 socket,因此本包不需要 socket 依赖,owner gateway 与 Relay 各自传入自己的 `ws` 实例。`identity/` 持有 provider 契约、规范 ACL 身份键编解码,以及 loopback 用的 `mock` provider。两半都不导入 owner 代码,因此 Relay 可以依赖本包而不依赖 owner bundle。
|
||||
|
||||
| 文件 | 职责 |
|
||||
|---|---|
|
||||
| [`src/index.ts`](src/index.ts) | 为只想一次导入的调用方复出两个面 |
|
||||
| [`src/tunnel-protocol.ts`](src/tunnel-protocol.ts) | owner/worker IPC 帧、gateway 帧及其编解码 |
|
||||
| [`src/viewer-carrier.ts`](src/viewer-carrier.ts) | 查看页载体脚本及其转发的 owner 页面路由;经根入口引入 |
|
||||
| [`src/viewer-states.ts`](src/viewer-states.ts) | 查看页状态词汇及其应答,由根入口复出 |
|
||||
| [`src/identity/types.ts`](src/identity/types.ts) | 与 provider 无关的身份三元组与 `IdentityProvider` 契约 |
|
||||
| [`src/identity/keys.ts`](src/identity/keys.ts) | 规范 ACL 身份键编解码,以及 adapter 存入身份前的 tenant 规范化 |
|
||||
| [`src/identity/mock.ts`](src/identity/mock.ts) | 供本地运行与测试使用的 loopback 身份 provider |
|
||||
| — | 本包不持有可变状态、不做注册,因此不发布 runtime invariant companion;这些编解码由本包自己的测试覆盖。 |
|
||||
|
||||
</details>
|
||||
|
||||
-----
|
||||
|
||||
<a id="further-exploration"></a>
|
||||
## 进一步探索
|
||||
|
||||
- [实验性包](../README.zh.md)——实验性包状态。
|
||||
- Liveshare owner bundle 与 Relay 消费这些帧,单独发布。
|
||||
|
||||
-----
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
## 已知限制与延期工作
|
||||
|
||||
- 网关请求必须在不透明请求体之外携带 Relay 已认证主体;没有该主体的帧被拒绝。
|
||||
- Owner Host 与 worker 同包发布。Supervisor 为每次逻辑添加生成品牌化 UUID `registrationToken`,移除时使其失效,进程重启只为仍保留的同一注册重播该身份。生命周期、请求及取消事件回传该 token 与分享 ID;逐请求 `TunnelRequestToken` 独立存在。IPC 编解码拒绝缺失身份,两种 token 都不进入 Relay URL 或线协议帧。同包 IPC 不协商版本;Relay 线协议帧保留数字 ID 与协议版本 1。兼容能力包含 `file-upload`、`actor-credential` 与 `direct-connection`。actor 可携带可选的、owner 可验证的 `credential`(协议只校验类型;owner 在采信断言身份前自行验证,缺失时保持今天由 Relay 断言的语义)。分享 spec 可携带 `connection`;缺失读作 `{ mode: 'relay' }`,仍拥有数据面的 Relay 会拒绝 `direct` 注册。:声明它的 Relay 注册可在分享支持与 access-state 帧上携带 `allowsFileUpload`;其它 peer 保留已存值,而缺少该字段的帧读作上传关闭。
|
||||
- 声明 `share-access-state` 的 owner 接收已提交、无 id 的 ACL、模式与到期时间快照,快照携带持久单调版本。worker 只转发当前 socket 的快照;Host 在 socket 丢失后清空授权,并在外部执行准入前刷新已认证的请求快照。快照不可用时默认拒绝,不借用持久化 ACL。
|
||||
- **历史发布版本支持尚未核实**——`tests/frames/v1` 记录具体帧和拒绝义务,但没有标识已发布的 Owner 版本。网关声明 `LIVESHARE_PROTOCOL_VERSION` 与已实现能力;Relay 拒绝已声明的版本不匹配,仅向已声明消费者发送可选生命周期帧。这些检查保留已录字段和明确拒绝,不提供逐发布版本翻译或无限支持窗口。
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### 开发备注
|
||||
|
||||
<details>
|
||||
<summary>维护者工作上下文——点击展开</summary>
|
||||
|
||||
无。
|
||||
|
||||
</details>
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-experimental-liveshare-protocol",
|
||||
"description": "Liveshare wire frames and the identity contract shared by the owner bundle and the Relay",
|
||||
"version": "0.2.1-rc.3",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
|
||||
"directory": "packages/experimental/liveshare-protocol"
|
||||
},
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/types/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib/index.js",
|
||||
"lib/types/**/*.d.ts"
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@deepseek-ai/dsh-brand": "workspace:*"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "workspace:~"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/cordis": "workspace:~"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './types.ts'
|
||||
export * from './keys.ts'
|
||||
@@ -0,0 +1,72 @@
|
||||
/** Canonical ACL key for one identity triple, and the normalization every adapter applies first. */
|
||||
|
||||
import type { IdentityTriple } from './types.ts'
|
||||
|
||||
/**
|
||||
* Build the canonical identity key stored in share ACLs.
|
||||
*
|
||||
* The caller normalizes the identity first: {@link normalizeIdentity} fills the documented tenant
|
||||
* placeholder, while an unnormalized empty tenant renders an empty segment that
|
||||
* {@link identityFromKey} cannot parse.
|
||||
* @param identity Provider, tenant, and subject triple.
|
||||
* @returns Percent-encoded stable key with no user-controlled formatting.
|
||||
*/
|
||||
export function identityKeyOf(identity: IdentityTriple): string {
|
||||
return [
|
||||
encodeURIComponent(identity.providerId),
|
||||
encodeURIComponent(identity.tenantId),
|
||||
encodeURIComponent(identity.subjectId),
|
||||
].join(':')
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a canonical identity key created by {@link identityKeyOf}.
|
||||
* @param key Percent-encoded provider, tenant, and subject key.
|
||||
* @returns Identity triple, or undefined when the key is not canonical.
|
||||
*/
|
||||
export function identityFromKey(key: string): IdentityTriple | undefined {
|
||||
const parts = key.split(':')
|
||||
if (parts.length !== 3) return undefined
|
||||
try {
|
||||
const [providerId = '', tenantId = '', subjectId = ''] = parts.map(part => decodeURIComponent(part))
|
||||
if (providerId === '' || tenantId === '' || subjectId === '') return undefined
|
||||
return { providerId, tenantId, subjectId }
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tenant id recorded for a provider that issues no tenant of its own.
|
||||
*
|
||||
* An account adapter whose provider issues no tenant must reject an empty tenant instead of using
|
||||
* this placeholder; see {@link requireIdentityTenant}.
|
||||
*/
|
||||
export const IDENTITY_TENANT_PLACEHOLDER = 'default'
|
||||
|
||||
/**
|
||||
* Normalize one adapter-produced identity before Relay state stores it.
|
||||
* @param identity Provider-produced triple.
|
||||
* @param tenantFallback Tenant id used when the provider issued none.
|
||||
* @returns Normalized triple, or undefined when the provider or subject id is empty.
|
||||
*/
|
||||
export function normalizeIdentity<T extends IdentityTriple>(
|
||||
identity: T,
|
||||
tenantFallback: string = IDENTITY_TENANT_PLACEHOLDER,
|
||||
): T | undefined {
|
||||
if (identity.providerId === '' || identity.subjectId === '') return undefined
|
||||
if (identity.tenantId !== '') return identity
|
||||
if (tenantFallback === '') return undefined
|
||||
return { ...identity, tenantId: tenantFallback }
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate one adapter-produced identity whose provider must issue a tenant id.
|
||||
* @param identity Provider-produced triple.
|
||||
* @returns The same triple, or undefined when the provider, tenant, or subject id is empty.
|
||||
*/
|
||||
export function requireIdentityTenant<T extends IdentityTriple>(identity: T): T | undefined {
|
||||
return identity.providerId === '' || identity.tenantId === '' || identity.subjectId === ''
|
||||
? undefined
|
||||
: identity
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { normalizeIdentity } from './keys.ts'
|
||||
import type {
|
||||
IdentityActor,
|
||||
IdentityAuthorizationRequest,
|
||||
IdentityExchangeRequest,
|
||||
IdentityProvider,
|
||||
} from './types.ts'
|
||||
|
||||
/** One fixed local identity used by tests and loopback demos. */
|
||||
export interface MockIdentityPersona {
|
||||
readonly id: string
|
||||
readonly tenantId?: string
|
||||
readonly displayName?: string
|
||||
/** Avatar a provider would publish; absent stands for a provider that issues none. */
|
||||
readonly avatarUrl?: string
|
||||
}
|
||||
|
||||
/** Deterministic provider for tests; not an authentication boundary. */
|
||||
export class MockIdentityProvider implements IdentityProvider {
|
||||
readonly scopes: readonly string[] = []
|
||||
|
||||
constructor(
|
||||
readonly id: string,
|
||||
private readonly personas: readonly MockIdentityPersona[],
|
||||
) {
|
||||
if (id === '') throw new Error('mock identity provider id must not be empty')
|
||||
if (personas.length === 0) throw new Error('mock identity provider requires at least one persona')
|
||||
}
|
||||
|
||||
/** Redirect back to the Relay callback with the selected fixed persona code. */
|
||||
authorizationUrl(request: IdentityAuthorizationRequest): URL {
|
||||
const selected = request.loginHint ?? this.personas[0]?.id
|
||||
if (selected === undefined) throw new Error('mock identity provider has no selectable persona')
|
||||
const url = new URL(request.redirectUri)
|
||||
url.searchParams.set('code', selected)
|
||||
url.searchParams.set('state', request.state)
|
||||
return url
|
||||
}
|
||||
|
||||
/** Resolve a fixed persona code into a provider-neutral actor. */
|
||||
exchange(request: IdentityExchangeRequest): Promise<IdentityActor> {
|
||||
const persona = this.personas.find(candidate => candidate.id === request.code)
|
||||
if (persona === undefined) return Promise.reject(new Error('mock identity callback code is unknown'))
|
||||
const actor = normalizeIdentity({
|
||||
providerId: this.id,
|
||||
subjectId: persona.id,
|
||||
tenantId: persona.tenantId ?? 'mock',
|
||||
displayName: persona.displayName ?? persona.id,
|
||||
...(persona.avatarUrl === undefined ? {} : { avatarUrl: persona.avatarUrl }),
|
||||
}, 'mock')
|
||||
if (actor === undefined) return Promise.reject(new Error('mock identity persona id must not be empty'))
|
||||
return Promise.resolve(actor)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/** Provider, tenant, and subject triple that identifies one person across providers. */
|
||||
export interface IdentityTriple {
|
||||
/** Identity provider that owns the subject. */
|
||||
readonly providerId: string
|
||||
/** Provider tenant that contains the subject. */
|
||||
readonly tenantId: string
|
||||
/** Provider-scoped subject id. */
|
||||
readonly subjectId: string
|
||||
}
|
||||
|
||||
/** Provider-neutral viewer identity resolved by a Relay. */
|
||||
export interface IdentityActor extends IdentityTriple {
|
||||
readonly displayName: string
|
||||
/**
|
||||
* Provider-issued avatar URL, when the provider publishes one. Presentation only: it carries no
|
||||
* credential, and a provider that issues none leaves it absent rather than inventing a value.
|
||||
*/
|
||||
readonly avatarUrl?: string
|
||||
}
|
||||
|
||||
/** Request facts needed to build one provider authorization redirect. */
|
||||
export interface IdentityAuthorizationRequest {
|
||||
readonly state: string
|
||||
readonly redirectUri: string
|
||||
readonly scopes: readonly string[]
|
||||
readonly loginHint?: string
|
||||
}
|
||||
|
||||
/** Request facts needed to exchange a provider callback code. */
|
||||
export interface IdentityExchangeRequest {
|
||||
readonly code: string
|
||||
readonly redirectUri: string
|
||||
}
|
||||
|
||||
/** Generic browser OAuth contract a deployment's identity adapter implements; the protocol's mock implements it for local runs. */
|
||||
export interface IdentityProvider {
|
||||
readonly id: string
|
||||
readonly scopes: readonly string[]
|
||||
authorizationUrl(request: IdentityAuthorizationRequest): URL
|
||||
exchange(request: IdentityExchangeRequest): Promise<IdentityActor>
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Liveshare wire protocol and identity contract shared by the owner bundle and the Relay.
|
||||
* @module @deepseek-ai/dsh-experimental-liveshare-protocol
|
||||
*/
|
||||
|
||||
export * from './tunnel-protocol.ts'
|
||||
export * from './identity/index.ts'
|
||||
export * from './viewer-carrier.ts'
|
||||
@@ -0,0 +1,615 @@
|
||||
/** IPC frames between the owner host plugin and its one tunnel worker, plus the Relay wire frames. */
|
||||
|
||||
import type { Branded } from '@deepseek-ai/dsh-brand'
|
||||
|
||||
export * from './viewer-states.ts'
|
||||
|
||||
/** Worker-issued identity for one request; never reused across sockets or worker processes. */
|
||||
export type TunnelRequestToken = Branded<'TunnelRequestToken'>
|
||||
|
||||
/** Supervisor-issued UUID for one logical add; retained on process restart, invalidated by removal. Never sent to the Relay. */
|
||||
export type TunnelRegistrationToken = Branded<'TunnelRegistrationToken'>
|
||||
|
||||
/** Relay wire version; Host/worker IPC ships together and is not negotiated by this number. */
|
||||
export const LIVESHARE_PROTOCOL_VERSION = 1
|
||||
|
||||
/**
|
||||
* Optional behaviors this build offers the Relay, beyond the frames themselves.
|
||||
*
|
||||
* A peer that declares none is a build older than this one. Each name states behavior the peer can
|
||||
* observe on the wire, so a Relay relies only on what it has been told rather than on the release it
|
||||
* happens to run beside.
|
||||
*/
|
||||
export const LIVESHARE_CAPABILITIES = [
|
||||
'session-mode',
|
||||
'fork',
|
||||
'acl-subjects',
|
||||
'expiry',
|
||||
'owner-credential',
|
||||
'scoped-rpc-response',
|
||||
'unsupported-frame-refusal',
|
||||
'share-access-state',
|
||||
'file-upload',
|
||||
'actor-credential',
|
||||
'direct-connection',
|
||||
] as const
|
||||
|
||||
/** One optional behavior this build offers the Relay; a peer compiles against the names it knows. */
|
||||
export type LiveshareCapability = typeof LIVESHARE_CAPABILITIES[number]
|
||||
|
||||
/**
|
||||
* The permission facts a share publishes.
|
||||
*
|
||||
* The owner asks for them in {@link TunnelShareSpec}; the Relay commits them in
|
||||
* {@link ShareAccessStateFrame}. The committed frame is the authority: a reader follows it, not the
|
||||
* request that produced it. `allowsFileUpload` is optional here because a request may omit the switch,
|
||||
* while a committed frame always states it.
|
||||
*/
|
||||
export interface SharePermissions {
|
||||
readonly accessMode: 'open' | 'selected'
|
||||
readonly allowedSubjectIds: readonly string[]
|
||||
readonly sessionMode?: 'view' | 'write'
|
||||
readonly allowsFork?: boolean
|
||||
readonly allowsFileUpload?: boolean
|
||||
readonly expiresAt?: string
|
||||
}
|
||||
|
||||
/** One share the owner host asks its gateway worker to carry to the Relay. */
|
||||
export interface TunnelShareSpec extends SharePermissions {
|
||||
/** How a viewer reaches the owner; absent reads as `{ mode: 'relay' }`, today's only shape. */
|
||||
readonly connection?: ShareConnection
|
||||
readonly shareId: string
|
||||
readonly sessionId: string
|
||||
/** Display-only share title; the host refreshes it with `reconcileShareTitles()` when renamed. */
|
||||
readonly sessionTitle: string
|
||||
readonly accessMode: 'open' | 'selected'
|
||||
readonly relay: string
|
||||
readonly gatewayToken: string
|
||||
readonly ownerProviderId?: string
|
||||
readonly ownerTenantId?: string
|
||||
readonly ownerDisplayName: string
|
||||
/** Display-only: the owner's DSH version shown on the Relay share picker. */
|
||||
readonly dshVersion?: string
|
||||
/**
|
||||
* Stable id of the owner DSH instance that published this share. Not display-only: the Relay groups
|
||||
* shares of the same owner instance by it.
|
||||
*/
|
||||
readonly ownerInstanceId?: string
|
||||
/**
|
||||
* Whether this share lets an admitted viewer fork it.
|
||||
*
|
||||
* Its own switch, independent of {@link TunnelShareSpec.sessionMode}: a view-tier share may allow
|
||||
* forking and a writable one may refuse it. Absent means no forking.
|
||||
*/
|
||||
readonly allowsFork?: boolean
|
||||
/**
|
||||
* Tier this share was created with.
|
||||
*
|
||||
* `view` reads the shared Session and drives its loop inside the granted workspace without writing it;
|
||||
* `write` also modifies the files inside that workspace. Absent reads as `view`.
|
||||
*/
|
||||
readonly sessionMode?: 'view' | 'write'
|
||||
/**
|
||||
* Whether an admitted viewer may attach uploaded files in this share's Session and its own forks.
|
||||
*
|
||||
* Independent of the tier and of {@link TunnelShareSpec.allowsFork}; absent means no file uploads.
|
||||
*/
|
||||
readonly allowsFileUpload?: boolean
|
||||
/**
|
||||
* Relay-issued owner credential proving which logged-in subject publishes this share. The Relay
|
||||
* refuses a new share without it and ignores self-reported identity fields when it is present.
|
||||
*/
|
||||
readonly ownerCredential?: string
|
||||
readonly allowedSubjectIds: readonly string[]
|
||||
/** ISO time after which the Relay denies viewers; absent means the share never expires. */
|
||||
readonly expiresAt?: string
|
||||
}
|
||||
|
||||
/** Commands sent from the owner host plugin to its tunnel worker. */
|
||||
export type TunnelWorkerCommand =
|
||||
| { readonly type: 'add-share'; readonly registrationToken: TunnelRegistrationToken; readonly share: TunnelShareSpec }
|
||||
| { readonly type: 'remove-share'; readonly shareId: string }
|
||||
| {
|
||||
readonly type: 'share-rpc-response'
|
||||
readonly registrationToken: TunnelRegistrationToken
|
||||
/** Echo the request's token; Relay ids alone do not identify an IPC request. */
|
||||
readonly token: TunnelRequestToken
|
||||
readonly id: number
|
||||
readonly shareId: string
|
||||
readonly status: number
|
||||
readonly body?: unknown
|
||||
}
|
||||
| { readonly type: 'shutdown' }
|
||||
|
||||
interface TunnelRegistrationIdentity {
|
||||
readonly registrationToken: TunnelRegistrationToken
|
||||
readonly shareId: string
|
||||
}
|
||||
|
||||
/** Lifecycle and request events echo their add's registration token; neither IPC token enters Relay frames. */
|
||||
export type TunnelWorkerEvent =
|
||||
| { readonly type: 'ready' }
|
||||
| {
|
||||
readonly type: 'share-rpc-request'
|
||||
readonly registrationToken: TunnelRegistrationToken
|
||||
readonly token: TunnelRequestToken
|
||||
readonly id: number
|
||||
readonly shareId: string
|
||||
/** Opaque viewer request the Relay forwarded; the owner host is its only reader. */
|
||||
readonly body: unknown
|
||||
/** Viewer identity the Relay authenticated, which the owner host reads instead of the body. */
|
||||
readonly actor: ShareRpcActor
|
||||
}
|
||||
| {
|
||||
readonly type: 'share-rpc-cancel'
|
||||
readonly registrationToken: TunnelRegistrationToken
|
||||
readonly token: TunnelRequestToken
|
||||
readonly id: number
|
||||
readonly shareId: string
|
||||
}
|
||||
| (ShareAccessStateFrame & TunnelRegistrationIdentity)
|
||||
| ({ readonly type: 'share-connected' } & TunnelRegistrationIdentity)
|
||||
| ({ readonly type: 'share-error'; readonly message: string } & TunnelRegistrationIdentity)
|
||||
| ({ readonly type: 'share-closed' } & TunnelRegistrationIdentity)
|
||||
|
||||
/** One opaque viewer request the Relay routes to the owner gateway. */
|
||||
export interface ShareRpcFrame {
|
||||
readonly type: 'share-rpc'
|
||||
readonly id: number
|
||||
/** Viewer request the Relay forwards without reading it. */
|
||||
readonly body: unknown
|
||||
/**
|
||||
* Viewer identity the Relay authenticated for this request.
|
||||
*
|
||||
* This is the only viewer identity an owner may act on: the Relay holds the session and asserts it,
|
||||
* the browser never does, and it travels outside the opaque body so the owner learns who is asking
|
||||
* without interpreting the request itself.
|
||||
*/
|
||||
readonly actor: ShareRpcActor
|
||||
}
|
||||
|
||||
/** Authenticated viewer identity the Relay asserts for one forwarded request. */
|
||||
export interface ShareRpcActor {
|
||||
readonly providerId: string
|
||||
/** Provider tenant; the Relay asserts the normalized, non-empty tenant its adapters store. */
|
||||
readonly tenantId: string
|
||||
readonly subjectId: string
|
||||
/**
|
||||
* Owner-verifiable credential asserting this identity, when the deployment's data path has no
|
||||
* in-band authority to assert it (a viewer reaching the owner directly). Absent today: the Relay
|
||||
* asserts the triple itself. The owner verifies it before trusting the identity; the protocol does
|
||||
* not verify it.
|
||||
*/
|
||||
readonly credential?: string
|
||||
}
|
||||
|
||||
/** How a viewer reaches the owner that published this share. */
|
||||
export interface ShareConnection {
|
||||
/**
|
||||
* `relay` reaches the owner through the Relay that carried this registration. `direct` is reserved
|
||||
* for a deployment where viewers reach the owner itself; its transport parameters are added when
|
||||
* that path is implemented.
|
||||
*/
|
||||
readonly mode: 'relay' | 'direct'
|
||||
}
|
||||
|
||||
/**
|
||||
* Routing fields an opaque viewer request carries, for logging only.
|
||||
*
|
||||
* The Relay and the owner worker both forward the same request body without reading it, and both
|
||||
* need the same two fields to correlate one read across hops; every other field stays opaque.
|
||||
* @param body Request body as forwarded.
|
||||
* @returns The operation name and stream id, or placeholders when the body carries neither.
|
||||
*/
|
||||
export function viewerRequestFields(body: unknown): { readonly op: string; readonly streamId: string } {
|
||||
if (typeof body !== 'object' || body === null) return { op: 'unknown', streamId: '-' }
|
||||
const value = body as { readonly op?: unknown; readonly id?: unknown }
|
||||
return {
|
||||
op: typeof value.op === 'string' ? value.op : 'unknown',
|
||||
streamId: typeof value.id === 'number' ? String(value.id) : '-',
|
||||
}
|
||||
}
|
||||
|
||||
/** The owner gateway's opaque answer to one routed viewer request. */
|
||||
export interface ShareRpcResFrame {
|
||||
readonly type: 'share-rpc-res'
|
||||
readonly id: number
|
||||
readonly status: number
|
||||
readonly body?: unknown
|
||||
}
|
||||
|
||||
/** Cancel one in-flight viewer request after its viewer went away. */
|
||||
export interface ShareRpcCancelFrame {
|
||||
readonly type: 'share-rpc-cancel'
|
||||
readonly id: number
|
||||
}
|
||||
|
||||
/** Committed Relay authority for one share, scoped to the socket carrying it. */
|
||||
export interface ShareAccessStateFrame extends SharePermissions {
|
||||
readonly type: 'share-access-state'
|
||||
/** Monotonic durable Relay store revision. */
|
||||
readonly version: number
|
||||
readonly accessMode: 'open' | 'selected'
|
||||
readonly allowedSubjectIds: readonly string[]
|
||||
/**
|
||||
* Tier the share carries.
|
||||
*
|
||||
* The current tiers are `view` and `write`; any other value is rejected.
|
||||
*/
|
||||
readonly sessionMode: 'view' | 'write'
|
||||
/**
|
||||
* Whether this share lets an admitted viewer fork it.
|
||||
*
|
||||
* Absent means no forking.
|
||||
*/
|
||||
readonly allowsFork?: boolean
|
||||
/** Whether this share permits viewer file uploads; always present after parsing, absent means false. */
|
||||
readonly allowsFileUpload: boolean
|
||||
readonly expiresAt?: string
|
||||
}
|
||||
|
||||
/** Every frame exchanged between the Relay and one owner gateway. */
|
||||
export type Frame = ShareRpcFrame | ShareRpcResFrame | ShareRpcCancelFrame | ShareAccessStateFrame
|
||||
|
||||
/** The part of a socket `sendFrame` needs, satisfied by a `ws` WebSocket. */
|
||||
export interface FrameSocket {
|
||||
readonly readyState: number
|
||||
send(data: string): void
|
||||
}
|
||||
|
||||
/** `WebSocket.OPEN`, restated so the shared protocol package carries no socket dependency. */
|
||||
const SOCKET_OPEN = 1
|
||||
|
||||
/**
|
||||
* Send one frame when the socket is open.
|
||||
* @param socket Owner gateway or viewer socket.
|
||||
* @param frame Wire frame.
|
||||
*/
|
||||
export function sendFrame(socket: FrameSocket, frame: Frame): void {
|
||||
if (socket.readyState === SOCKET_OPEN) socket.send(JSON.stringify(frame))
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode one WebSocket data frame without relying on its representation.
|
||||
* @param data Message bytes supplied by ws.
|
||||
* @returns UTF-8 text for one complete message.
|
||||
*/
|
||||
export function rawText(data: Buffer | ArrayBuffer | Buffer[]): string {
|
||||
if (Array.isArray(data)) return Buffer.concat(data).toString('utf8')
|
||||
if (data instanceof ArrayBuffer) return Buffer.from(data).toString('utf8')
|
||||
return Buffer.from(data).toString('utf8')
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the envelope every accepted frame carries from an already-decoded value.
|
||||
*
|
||||
* Both directions state the same envelope, so one decoder owns it — a frame's id is what correlates an
|
||||
* answer with its request, and a second copy of these rules is a second place for that to drift.
|
||||
* @param value - Decoded JSON value.
|
||||
* @returns The value with its id, or undefined when the value is not an accepted envelope.
|
||||
*/
|
||||
function frameEnvelope(value: unknown): { readonly value: Record<string, unknown>; readonly id: number } | undefined {
|
||||
if (!isRecord(value) || !Number.isSafeInteger(value.id) || Number(value.id) <= 0) return undefined
|
||||
return { value, id: Number(value.id) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode one raw frame's envelope: the JSON value and the request id every accepted frame carries.
|
||||
* @param text - Raw socket text.
|
||||
* @returns The decoded value with its id, or undefined when the text is not an accepted envelope.
|
||||
*/
|
||||
function decodeFrameEnvelope(text: string): { readonly value: Record<string, unknown>; readonly id: number } | undefined {
|
||||
let value: unknown
|
||||
try {
|
||||
value = JSON.parse(text)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
return frameEnvelope(value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse one gateway-to-Relay frame; unknown or malformed frames are dropped.
|
||||
* @param text Raw socket text.
|
||||
* @returns Parsed frame, or undefined when the frame is not accepted.
|
||||
*/
|
||||
export function parseGatewayFrame(text: string): Frame | undefined {
|
||||
const envelope = decodeFrameEnvelope(text)
|
||||
if (envelope === undefined) return undefined
|
||||
const { value, id } = envelope
|
||||
if (value.type === 'share-rpc-res') {
|
||||
if (!Number.isSafeInteger(value.status) || Number(value.status) < 100 || Number(value.status) > 599) {
|
||||
return undefined
|
||||
}
|
||||
return {
|
||||
type: 'share-rpc-res',
|
||||
id,
|
||||
status: Number(value.status),
|
||||
...(value.body === undefined ? {} : { body: value.body }),
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse one already-decoded Relay-to-gateway value; unknown or malformed frames are dropped.
|
||||
* @param value Decoded JSON value.
|
||||
* @returns Parsed frame, or undefined when the frame is not accepted.
|
||||
*/
|
||||
function parseRelayValue(value: unknown): Frame | undefined {
|
||||
const state = parseShareAccessState(value)
|
||||
if (state !== undefined) return state
|
||||
const envelope = frameEnvelope(value)
|
||||
if (envelope === undefined) return undefined
|
||||
const { value: frame, id } = envelope
|
||||
if (frame.type === 'share-rpc') {
|
||||
if (frame.body === undefined) return undefined
|
||||
// A frame without the Relay's asserted actor is refused, so an owner never sees a request whose
|
||||
// caller it cannot attribute.
|
||||
if (!isShareRpcActor(frame.actor)) return undefined
|
||||
return { type: 'share-rpc', id, body: frame.body, actor: frame.actor }
|
||||
}
|
||||
if (frame.type === 'share-rpc-cancel') return { type: 'share-rpc-cancel', id }
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse one Relay-to-gateway frame; unknown or malformed frames are dropped.
|
||||
* @param text Raw socket text.
|
||||
* @returns Parsed frame, or undefined when the frame is not accepted.
|
||||
*/
|
||||
export function parseRelayFrame(text: string): Frame | undefined {
|
||||
let value: unknown
|
||||
try {
|
||||
value = JSON.parse(text)
|
||||
} catch (_error) {
|
||||
// Invalid wire JSON carries neither a lifecycle state nor an RPC.
|
||||
return undefined
|
||||
}
|
||||
return parseRelayValue(value)
|
||||
}
|
||||
|
||||
/**
|
||||
* The refusal this build answers with when it reads a frame it cannot serve.
|
||||
*
|
||||
* A frame whose type this build does not know, or a known request whose fields it refuses, otherwise
|
||||
* leaves the peer waiting for an answer that will never come: the read holds until the peer's own
|
||||
* budget expires, and a version mismatch reaches the reader as a timeout rather than as a fact.
|
||||
* Answering states the one thing the peer can act on — this build cannot serve that frame — while a
|
||||
* frame with no usable envelope states no request id to correlate an answer with, and a frame that
|
||||
* answers or cancels something is not a request to answer at all.
|
||||
* @param text Raw socket text the Relay sent.
|
||||
* @returns The refusal to send, or undefined when this frame is not one to answer.
|
||||
*/
|
||||
export function unsupportedFrameRefusal(text: string): ShareRpcResFrame | undefined {
|
||||
let value: unknown
|
||||
try {
|
||||
value = JSON.parse(text)
|
||||
} catch (_error) {
|
||||
// Text that is not JSON states no frame to answer.
|
||||
return undefined
|
||||
}
|
||||
// A frame this build serves is not one to refuse, so the answer holds whoever calls this.
|
||||
if (parseRelayValue(value) !== undefined) return undefined
|
||||
const envelope = frameEnvelope(value)
|
||||
if (envelope === undefined) return undefined
|
||||
const type = envelope.value.type
|
||||
if (type === 'share-rpc') {
|
||||
// The Relay's own request frame, carrying fields the gateway refuses: the peer sent something
|
||||
// this build reads and rejects, so the answer names that rather than an unknown frame.
|
||||
return {
|
||||
type: 'share-rpc-res',
|
||||
id: envelope.id,
|
||||
status: 400,
|
||||
body: { error: 'invalid-request' },
|
||||
}
|
||||
}
|
||||
if (type === 'share-rpc-res' || type === 'share-rpc-cancel') return undefined
|
||||
if (typeof type !== 'string' || type === '') return undefined
|
||||
// A frame type this build does not know: the peer is newer, and saying so is what lets the Relay
|
||||
// report a version mismatch instead of holding the read.
|
||||
return {
|
||||
type: 'share-rpc-res',
|
||||
id: envelope.id,
|
||||
status: 501,
|
||||
body: { error: 'unsupported-frame' },
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The share one rejected IPC command names, so its host learns the command was refused.
|
||||
*
|
||||
* A command this build does not accept is otherwise dropped in silence: an interactive share then
|
||||
* fails after its own wait, and a share restored at startup stays offline with nothing said.
|
||||
* @param value Raw IPC message payload the worker refused.
|
||||
* @returns The share the command named, or undefined when the payload names none.
|
||||
*/
|
||||
export function rejectedCommandShareId(value: unknown): string | undefined {
|
||||
if (!isRecord(value)) return undefined
|
||||
if (typeof value.shareId === 'string' && value.shareId !== '') return value.shareId
|
||||
const share = value.share
|
||||
if (isRecord(share) && typeof share.shareId === 'string' && share.shareId !== '') return share.shareId
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse one host-to-worker IPC command; unknown or malformed commands are dropped.
|
||||
*
|
||||
* The worker and its host run in separate processes, so the message crosses a process boundary and
|
||||
* every field the worker reads is checked here rather than asserted.
|
||||
* @param value Raw IPC message payload.
|
||||
* @returns Parsed command, or undefined when the payload is not an accepted command.
|
||||
*/
|
||||
export function parseTunnelWorkerCommand(value: unknown): TunnelWorkerCommand | undefined {
|
||||
if (!isRecord(value)) return undefined
|
||||
switch (value.type) {
|
||||
case 'shutdown':
|
||||
return { type: 'shutdown' }
|
||||
case 'remove-share':
|
||||
return typeof value.shareId === 'string' && value.shareId !== ''
|
||||
? { type: 'remove-share', shareId: value.shareId }
|
||||
: undefined
|
||||
case 'add-share':
|
||||
return isRegistrationToken(value.registrationToken) && isTunnelShareSpec(value.share)
|
||||
? {
|
||||
type: 'add-share',
|
||||
registrationToken: value.registrationToken,
|
||||
share: { ...value.share, connection: value.share.connection ?? { mode: 'relay' } },
|
||||
} : undefined
|
||||
case 'share-rpc-response': {
|
||||
if (!isTunnelRequestIdentity(value) || !Number.isSafeInteger(value.status)
|
||||
|| Number(value.status) < 100 || Number(value.status) > 599) return undefined
|
||||
return {
|
||||
type: 'share-rpc-response',
|
||||
registrationToken: value.registrationToken,
|
||||
token: value.token,
|
||||
id: value.id,
|
||||
shareId: value.shareId,
|
||||
status: Number(value.status),
|
||||
...(value.body === undefined ? {} : { body: value.body }),
|
||||
}
|
||||
}
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse one worker-to-host IPC event; unknown or malformed events are dropped.
|
||||
* @param value Raw IPC message payload.
|
||||
* @returns Parsed event, or undefined when the payload is not an accepted event.
|
||||
*/
|
||||
export function parseTunnelWorkerEvent(value: unknown): TunnelWorkerEvent | undefined {
|
||||
if (!isRecord(value)) return undefined
|
||||
switch (value.type) {
|
||||
case 'ready':
|
||||
return { type: 'ready' }
|
||||
case 'share-connected':
|
||||
case 'share-closed': {
|
||||
const type = value.type
|
||||
return isTunnelRegistrationIdentity(value)
|
||||
? { type, registrationToken: value.registrationToken, shareId: value.shareId }
|
||||
: undefined
|
||||
}
|
||||
case 'share-access-state': {
|
||||
const state = parseShareAccessState(value)
|
||||
return state !== undefined && isTunnelRegistrationIdentity(value)
|
||||
? { ...state, registrationToken: value.registrationToken, shareId: value.shareId } : undefined
|
||||
}
|
||||
case 'share-error':
|
||||
return isTunnelRegistrationIdentity(value) && typeof value.message === 'string'
|
||||
? { type: 'share-error', registrationToken: value.registrationToken, shareId: value.shareId, message: value.message }
|
||||
: undefined
|
||||
case 'share-rpc-cancel':
|
||||
return isTunnelRequestIdentity(value)
|
||||
? { type: 'share-rpc-cancel', registrationToken: value.registrationToken, token: value.token, id: value.id, shareId: value.shareId }
|
||||
: undefined
|
||||
case 'share-rpc-request':
|
||||
return isTunnelRequestIdentity(value) && value.body !== undefined && isShareRpcActor(value.actor)
|
||||
? {
|
||||
type: 'share-rpc-request', registrationToken: value.registrationToken, token: value.token, id: value.id,
|
||||
shareId: value.shareId, body: value.body, actor: value.actor,
|
||||
}
|
||||
: undefined
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate one share spec the owner host asked its worker to carry.
|
||||
*
|
||||
* Optional fields are checked against the same rules the frame parsers apply; an expiry must be a
|
||||
* parseable ISO time, so a registration cannot carry a deadline no reader can enforce.
|
||||
* @param value Candidate spec.
|
||||
* @returns True when every required field is present with the declared type.
|
||||
*/
|
||||
function isTunnelShareSpec(value: unknown): value is TunnelShareSpec {
|
||||
if (!isRecord(value)) return false
|
||||
const mode = value.sessionMode
|
||||
return typeof value.shareId === 'string' && value.shareId !== ''
|
||||
&& typeof value.sessionId === 'string'
|
||||
&& typeof value.sessionTitle === 'string'
|
||||
&& (value.accessMode === 'open' || value.accessMode === 'selected')
|
||||
&& typeof value.relay === 'string'
|
||||
&& typeof value.gatewayToken === 'string'
|
||||
&& typeof value.ownerDisplayName === 'string'
|
||||
&& (value.ownerProviderId === undefined || typeof value.ownerProviderId === 'string')
|
||||
&& (value.ownerTenantId === undefined || typeof value.ownerTenantId === 'string')
|
||||
&& (value.dshVersion === undefined || typeof value.dshVersion === 'string')
|
||||
&& (value.ownerInstanceId === undefined || typeof value.ownerInstanceId === 'string')
|
||||
&& (value.allowsFork === undefined || typeof value.allowsFork === 'boolean')
|
||||
&& (mode === undefined || mode === 'view' || mode === 'write')
|
||||
&& (value.allowsFileUpload === undefined || typeof value.allowsFileUpload === 'boolean')
|
||||
&& (value.connection === undefined
|
||||
|| (isRecord(value.connection) && (value.connection.mode === 'relay' || value.connection.mode === 'direct')))
|
||||
&& (value.ownerCredential === undefined || typeof value.ownerCredential === 'string')
|
||||
&& Array.isArray(value.allowedSubjectIds)
|
||||
&& value.allowedSubjectIds.every(subject => typeof subject === 'string' && subject !== '')
|
||||
&& (value.expiresAt === undefined
|
||||
|| (typeof value.expiresAt === 'string' && Number.isFinite(Date.parse(value.expiresAt))))
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the actor the Relay asserts on one forwarded request.
|
||||
* @param value Candidate actor.
|
||||
* @returns True when it carries a non-empty provider, tenant, and subject.
|
||||
*/
|
||||
function isShareRpcActor(value: unknown): value is ShareRpcActor {
|
||||
if (typeof value !== 'object' || value === null) return false
|
||||
const actor = value as Record<string, unknown>
|
||||
return typeof actor.providerId === 'string' && actor.providerId !== ''
|
||||
&& typeof actor.tenantId === 'string' && actor.tenantId !== ''
|
||||
&& typeof actor.subjectId === 'string' && actor.subjectId !== ''
|
||||
&& (actor.credential === undefined || typeof actor.credential === 'string')
|
||||
}
|
||||
|
||||
function isRegistrationToken(value: unknown): value is TunnelRegistrationToken {
|
||||
return typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)
|
||||
}
|
||||
|
||||
function isTunnelRegistrationIdentity(value: Record<string, unknown>): value is Record<string, unknown> & TunnelRegistrationIdentity {
|
||||
return isRegistrationToken(value.registrationToken) && typeof value.shareId === 'string' && value.shareId !== ''
|
||||
}
|
||||
|
||||
/** Validate request correlation fields at the IPC parser. */
|
||||
function isTunnelRequestIdentity(value: Record<string, unknown>): value is Record<string, unknown> & {
|
||||
readonly registrationToken: TunnelRegistrationToken
|
||||
readonly token: TunnelRequestToken
|
||||
readonly id: number
|
||||
readonly shareId: string
|
||||
} {
|
||||
return isTunnelRegistrationIdentity(value) && typeof value.token === 'string' && value.token !== ''
|
||||
&& Number.isSafeInteger(value.id) && Number(value.id) > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a committed Relay authority snapshot at wire, IPC, or authenticated HTTP ingress.
|
||||
* @param value - Untrusted snapshot fields.
|
||||
* @returns Owned snapshot fields, or undefined when any authority field is invalid.
|
||||
*/
|
||||
export function parseShareAccessState(value: unknown): ShareAccessStateFrame | undefined {
|
||||
if (!isRecord(value) || value.type !== 'share-access-state'
|
||||
|| !Number.isSafeInteger(value.version) || Number(value.version) < 0
|
||||
|| (value.accessMode !== 'open' && value.accessMode !== 'selected')
|
||||
|| !isSubjectIds(value.allowedSubjectIds)
|
||||
|| (value.sessionMode !== 'view' && value.sessionMode !== 'write')
|
||||
|| (value.allowsFork !== undefined && typeof value.allowsFork !== 'boolean')
|
||||
|| (value.allowsFileUpload !== undefined && typeof value.allowsFileUpload !== 'boolean')
|
||||
|| (value.expiresAt !== undefined && (typeof value.expiresAt !== 'string' || !Number.isFinite(Date.parse(value.expiresAt))))) {
|
||||
return undefined
|
||||
}
|
||||
return { type: 'share-access-state', version: Number(value.version), accessMode: value.accessMode,
|
||||
allowedSubjectIds: [...value.allowedSubjectIds], sessionMode: value.sessionMode,
|
||||
allowsFileUpload: value.allowsFileUpload === true,
|
||||
...(value.allowsFork === undefined ? {} : { allowsFork: value.allowsFork }),
|
||||
...(value.expiresAt === undefined ? {} : { expiresAt: value.expiresAt }) }
|
||||
}
|
||||
|
||||
function isSubjectIds(value: unknown): value is string[] {
|
||||
return Array.isArray(value) && value.every(id => typeof id === 'string' && id !== '')
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
/**
|
||||
* Viewer page carrier: the script the Relay places at the top of the owner's served index document.
|
||||
*
|
||||
* It installs the page's Connection transport over the Relay read channel and names the share the
|
||||
* page presents. It performs no Liveshare business: grants, page status, and refusal handling belong
|
||||
* to the Liveshare client plugin, which reads them through ordinary reads. The carrier only converts
|
||||
* Connection calls into `call` requests, Gateway streams into `stream-open`/`stream-next`/
|
||||
* `stream-cancel` polls, and marks each failure as a retryable carrier loss or a terminal refusal.
|
||||
*
|
||||
* It also forwards the page-origin owner routes the Relay cannot answer, so app code that calls `fetch`
|
||||
* directly reaches the owner instead of the Relay's tail. That set is explicit and read-only; every
|
||||
* other request keeps the page's own `fetch`.
|
||||
*
|
||||
* {@link installViewerCarrier} runs in the browser from its own source text, so it must reference no
|
||||
* module binding: every constant and helper it needs is declared inside its body.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-experimental-liveshare-protocol
|
||||
*/
|
||||
|
||||
/** Page global naming the share one viewer page presents; the Liveshare client plugin reads it. */
|
||||
export const LIVESHARE_VIEWER_GLOBAL = '__DSH_LIVESHARE_VIEWER__'
|
||||
|
||||
/** Share one served viewer page presents. */
|
||||
export interface ViewerPageTarget {
|
||||
/** Public Relay base path every read is posted under; empty at the Relay root. */
|
||||
readonly basePath: string
|
||||
readonly shareId: string
|
||||
/** Session the share presents; the page opens it once the session list carries it. */
|
||||
readonly sessionId: string
|
||||
}
|
||||
|
||||
/** Carrier inputs: the page target plus the page's own read budget. */
|
||||
export interface ViewerCarrierOptions extends ViewerPageTarget {
|
||||
/** Longest wait for one Relay answer before the read counts as lost. */
|
||||
readonly readTimeoutMs: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Install the viewer globals in the current page. Runs before the shell entry so the Connection
|
||||
* plugin finds `__DSH_TRANSPORT__` when it installs.
|
||||
* @param options - Page target and read budget.
|
||||
*/
|
||||
export function installViewerCarrier(options: ViewerCarrierOptions): void {
|
||||
// Statuses whose definition says the read may be tried again.
|
||||
const carrierStatus = new Set([408, 429, 502, 503, 504])
|
||||
// The only owner codes meaning the logical stream was lost rather than refused. Every other code — an
|
||||
// owner refusal such as `remote-access/denied`, whose `details.reason` carries the policy's own
|
||||
// `liveshare/read-only` — is terminal, so the consumer reports it once instead of re-opening.
|
||||
const carrierCodes = new Set(['stream-not-found', 'gateway/cancelled'])
|
||||
const codeShaped = /^[a-z][a-z0-9-]*(?:\/[a-z0-9-]+)*$/u
|
||||
const target = options.shareId === ''
|
||||
? `${options.basePath}/__share/rpc`
|
||||
: `${options.basePath}/__share/rpc?shareId=${encodeURIComponent(options.shareId)}`
|
||||
// Each page numbers its streams in its own far-apart window, so two pages reading one share never
|
||||
// replace each other's streams.
|
||||
let nextStreamId = (crypto.getRandomValues(new Uint32Array(1))[0] ?? 0) % 0x7fff_ff00 + 1
|
||||
|
||||
type Answer = { readonly status: number; readonly body: unknown }
|
||||
type Marked = Error & { dshRemoteStreamFailure?: object }
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
const carrier = (message: string): Error => {
|
||||
const error: Marked = new Error(message)
|
||||
error.dshRemoteStreamFailure = { kind: 'carrier' }
|
||||
return error
|
||||
}
|
||||
const refusal = (answer: Answer): { readonly code?: string; readonly message?: string } => {
|
||||
if (!isRecord(answer.body)) return {}
|
||||
const value = answer.body.error
|
||||
const nested = isRecord(value)
|
||||
const code = nested ? value.code : value
|
||||
const message = nested ? value.message : answer.body.message
|
||||
return {
|
||||
...(typeof code === 'string' && codeShaped.test(code) ? { code } : {}),
|
||||
...(typeof message === 'string' ? { message } : {}),
|
||||
}
|
||||
}
|
||||
const remote = (answer: Answer, subject: string): Error => {
|
||||
const { code = 'liveshare/read-refused', message = `${subject} refused (HTTP ${String(answer.status)})` } = refusal(answer)
|
||||
const error: Marked = new Error(message)
|
||||
error.name = code
|
||||
error.dshRemoteStreamFailure = { kind: 'remote', code, details: { status: answer.status } }
|
||||
return error
|
||||
}
|
||||
const post = async (request: object, subject: string, signal?: AbortSignal): Promise<Answer> => {
|
||||
const timeout = AbortSignal.timeout(options.readTimeoutMs)
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(target, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
signal: signal === undefined ? timeout : AbortSignal.any([signal, timeout]),
|
||||
})
|
||||
} catch (error) {
|
||||
// A read the browser could not send never reached the peer; the caller's own cancellation is
|
||||
// not a loss.
|
||||
if (signal?.aborted === true) throw error
|
||||
throw carrier(`${subject}: Relay unreachable`)
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => undefined)
|
||||
return { status: response.status, body }
|
||||
}
|
||||
const readable = (answer: Answer, subject: string): Record<string, unknown> => {
|
||||
if (answer.status === 200) {
|
||||
if (isRecord(answer.body)) return answer.body
|
||||
throw carrier(`${subject}: Relay answered without a body`)
|
||||
}
|
||||
const code = refusal(answer).code
|
||||
if (answer.status !== 401 && answer.status !== 403
|
||||
&& (carrierStatus.has(answer.status) || (code !== undefined && carrierCodes.has(code)))) {
|
||||
throw carrier(`${subject}: ${code ?? `HTTP ${String(answer.status)}`}`)
|
||||
}
|
||||
throw remote(answer, subject)
|
||||
}
|
||||
const failure = (frame: Record<string, unknown>, subject: string): Error | undefined => {
|
||||
const value = frame.failure
|
||||
if (!isRecord(value)) return undefined
|
||||
const code = typeof value.code === 'string' ? value.code : 'liveshare/read-refused'
|
||||
const message = typeof value.message === 'string' ? value.message : subject
|
||||
if (carrierCodes.has(code)) return carrier(message)
|
||||
const error: Marked = new Error(message)
|
||||
error.name = code
|
||||
error.dshRemoteStreamFailure = { kind: 'remote', code, details: isRecord(value.details) ? value.details : {} }
|
||||
return error
|
||||
}
|
||||
|
||||
/**
|
||||
* Page-origin owner routes the Relay serves no answer for, forwarded instead of left to the Relay.
|
||||
*
|
||||
* Each is a read the shell makes for itself and the Relay cannot serve: the owner route exists on the
|
||||
* owner's own server, so a direct `fetch` from this page would leave the Relay origin and 404 at its
|
||||
* tail. Only read-only routes belong here: a route that acts on the owner's machine stays out.
|
||||
*/
|
||||
const forwardedRoutes = ['/open-in-app/apps', '/api/present.host']
|
||||
/**
|
||||
* Offset at which `route` starts a path segment run, ignoring a Relay base path in front of it.
|
||||
* @param pathname - Resolved request pathname.
|
||||
* @param route - Owner route to find.
|
||||
* @returns The offset, or undefined when the route appears only inside a longer segment.
|
||||
*/
|
||||
const segmentOffset = (pathname: string, route: string): number | undefined => {
|
||||
let from = 0
|
||||
for (;;) {
|
||||
const at = pathname.indexOf(route, from)
|
||||
if (at === -1) return undefined
|
||||
// The route starts with '/', so its own slash is the segment boundary; only the tail decides
|
||||
// whether a longer segment (e.g. `/api/present.hostile`) merely shares the prefix.
|
||||
const next = pathname[at + route.length]
|
||||
if (next === undefined || next === '/') return at
|
||||
from = at + 1
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Owner path one page request forwards, matched at path-segment boundaries because the page URL carries
|
||||
* the Relay's own base path in front of it. Prefix-neighbouring paths such as `/api/present.hostile` or
|
||||
* `/x/open-in-app/apps-foo` are not this route.
|
||||
* @param pathname - Resolved request pathname (query and hash already excluded).
|
||||
* @param method - Request method, already upper-cased.
|
||||
* @returns The owner path to post, or undefined when this request is not one of the forwarded routes.
|
||||
*/
|
||||
const forwardedRoute = (pathname: string, method: string): string | undefined => {
|
||||
if (method !== 'GET') return undefined
|
||||
for (const route of forwardedRoutes) {
|
||||
const at = segmentOffset(pathname, route)
|
||||
if (at !== undefined) return pathname.slice(at)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
/**
|
||||
* Read one forwarded owner route and rebuild its answer as an ordinary HTTP response.
|
||||
* @param path - Owner path to post.
|
||||
* @param init - The page request's own init, for its signal.
|
||||
* @returns The owner's status and body, JSON-encoded.
|
||||
*/
|
||||
const forwardRoute = async (path: string, init: RequestInit | undefined): Promise<Response> => {
|
||||
const body: unknown = typeof init?.body === 'string' ? JSON.parse(init.body) : {}
|
||||
const answer = await post({ op: 'call', path, body }, path, init?.signal ?? undefined)
|
||||
return new Response(JSON.stringify(answer.body ?? null), {
|
||||
status: answer.status,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
// Installed over the page's own fetch so app code that does not go through `__DSH_TRANSPORT__` still
|
||||
// reaches the owner. Every request outside the forwarded set is handed to the fetch this replaced.
|
||||
const pageFetch = globalThis.fetch
|
||||
const carrierFetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
|
||||
let pathname: string | undefined
|
||||
let method = 'GET'
|
||||
try {
|
||||
const page = globalThis as {
|
||||
readonly document?: { readonly baseURI: string }
|
||||
readonly location?: { readonly origin: string }
|
||||
}
|
||||
const pageOrigin = page.location?.origin
|
||||
const target = new URL(input instanceof Request ? input.url : String(input), page.document?.baseURI)
|
||||
// A request outside the page's own origin belongs to that origin: its path naming an owner
|
||||
// route must not divert it from the fetch the page replaced.
|
||||
pathname = pageOrigin !== undefined && target.origin === pageOrigin ? target.pathname : undefined
|
||||
method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase()
|
||||
} catch {
|
||||
// A target this page base cannot resolve is not one of the forwarded routes.
|
||||
pathname = undefined
|
||||
}
|
||||
const path = pathname === undefined ? undefined : forwardedRoute(pathname, method)
|
||||
return path === undefined ? await pageFetch.call(globalThis, input, init) : await forwardRoute(path, init)
|
||||
}
|
||||
globalThis.fetch = carrierFetch
|
||||
|
||||
const fetchCall = async (input: RequestInfo | URL, init: RequestInit): Promise<Response> => {
|
||||
// The Connection caller posts the document-relative route; the owner reads the `/api/...` path.
|
||||
const pageBase = (globalThis as { document?: { readonly baseURI: string } }).document?.baseURI
|
||||
const pathname = new URL(input instanceof Request ? input.url : input, pageBase).pathname
|
||||
const marker = pathname.lastIndexOf('/api/')
|
||||
const path = marker === -1 ? pathname : pathname.slice(marker)
|
||||
const body: unknown = typeof init.body === 'string' ? JSON.parse(init.body) : undefined
|
||||
const answer = await post({ op: 'call', path, body }, path, init.signal ?? undefined)
|
||||
if (answer.status === 200 && isRecord(answer.body)) return Response.json(answer.body)
|
||||
// A refusal is the owner's answer, not a transport failure: the caller receives the Connection
|
||||
// failure result the owner's code names.
|
||||
const rpcId = isRecord(body) && typeof body.rpcId === 'string' ? body.rpcId : ''
|
||||
const { code = 'liveshare/relay-error', message = `Relay answered HTTP ${String(answer.status)}` } = refusal(answer)
|
||||
return Response.json({
|
||||
type: 'server-response',
|
||||
rpcId,
|
||||
result: { ok: false, error: { code, message, details: { status: answer.status } } },
|
||||
})
|
||||
}
|
||||
|
||||
const openStream = (endpoint: string, payload: unknown, signal: AbortSignal): AsyncIterable<unknown> => ({
|
||||
async *[Symbol.asyncIterator]() {
|
||||
const id = nextStreamId++
|
||||
signal.throwIfAborted()
|
||||
// Each path below sends this at most once: the abort listener only runs on abort, the final
|
||||
// block only without one, and an open that ends the stream cancels here before either is armed.
|
||||
const cancel = (): void => {
|
||||
void post({ op: 'stream-cancel', id }, endpoint).catch(() => undefined)
|
||||
}
|
||||
let opened: Answer
|
||||
try {
|
||||
opened = await post({ op: 'stream-open', id, endpoint, payload }, endpoint, signal)
|
||||
} catch (error) {
|
||||
// An open the page abandoned may still have reached the owner, which would hold the stream.
|
||||
if (signal.aborted) cancel()
|
||||
throw error
|
||||
}
|
||||
if (signal.aborted) {
|
||||
cancel()
|
||||
signal.throwIfAborted()
|
||||
}
|
||||
// A refused open is answered as a 200 failure frame rather than a status, and the owner registers
|
||||
// no stream for it: polling that id would only read `stream-not-found`, which looks like a lost
|
||||
// logical stream and would be re-opened forever. The frame's own code decides instead — an owner
|
||||
// refusal such as `remote-access/denied` is terminal, while a lost stream stays re-openable.
|
||||
let openedBody: Record<string, unknown>
|
||||
try {
|
||||
openedBody = readable(opened, endpoint)
|
||||
} catch (error) {
|
||||
// A 200 answer the page cannot read reached the owner, which may already hold this stream id.
|
||||
if (opened.status === 200) cancel()
|
||||
throw error
|
||||
}
|
||||
const refusedOpen = failure(openedBody, endpoint)
|
||||
if (refusedOpen !== undefined) throw refusedOpen
|
||||
signal.addEventListener('abort', cancel, { once: true })
|
||||
try {
|
||||
while (!signal.aborted) {
|
||||
const frame = readable(await post({ op: 'stream-next', id }, endpoint, signal), endpoint)
|
||||
signal.throwIfAborted()
|
||||
const failed = failure(frame, endpoint)
|
||||
if (failed !== undefined) throw failed
|
||||
if (frame.end === true) return
|
||||
if (frame.pending === true) continue
|
||||
if (Array.isArray(frame.values)) {
|
||||
for (const value of frame.values) {
|
||||
signal.throwIfAborted()
|
||||
yield value
|
||||
}
|
||||
continue
|
||||
}
|
||||
yield frame.value
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener('abort', cancel)
|
||||
if (!signal.aborted) cancel()
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const page = globalThis as Record<string, unknown>
|
||||
page.__DSH_LIVESHARE_VIEWER__ = { basePath: options.basePath, shareId: options.shareId, sessionId: options.sessionId }
|
||||
page.__DSH_TRANSPORT__ = { fetch: fetchCall, openStream }
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the classic inline script the Relay places first in the served viewer document.
|
||||
* @param options - Page target and read budget.
|
||||
* @returns Script text: {@link installViewerCarrier}'s own source applied to `options`.
|
||||
*/
|
||||
export function viewerCarrierScript(options: ViewerCarrierOptions): string {
|
||||
// `<` is escaped so no option value can close the surrounding script element.
|
||||
const argument = JSON.stringify(options).replace(/</g, '\\u003c')
|
||||
return `(${installViewerCarrier.toString()})(${argument});`
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* The conditions one viewer read can end in, and the answer that carries each.
|
||||
*
|
||||
* A page that cannot name why a read failed states one failure for every cause: a link that never
|
||||
* named a share, a share the owner stopped, an owner whose machine is asleep, and a sign-in that
|
||||
* expired all reach a reader as the same silence. These are the conditions the Relay may answer a
|
||||
* viewer with, each paired with the answer that means it and nothing else, so a page, a test, and an
|
||||
* operator all read the same name for what happened.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-experimental-liveshare-protocol
|
||||
*/
|
||||
|
||||
/** One condition a viewer read can end in. */
|
||||
export type ViewerState =
|
||||
/** The link names no share: it was never valid, or the owner deleted it. */
|
||||
| 'share-not-found'
|
||||
/** The owner stopped the share, which ends every viewer's access to it. */
|
||||
| 'share-stopped'
|
||||
/** The share's own deadline passed, which denies like a stop but states its own reason. */
|
||||
| 'share-expired'
|
||||
/** No live owner gateway holds the share's route, or one stopped answering a held read. */
|
||||
| 'owner-offline'
|
||||
/** The reader's sign-in expired, so the Relay cannot say who is asking. */
|
||||
| 'sign-in-expired'
|
||||
/** The reader is signed in and admitted to the deployment, but this share does not admit it. */
|
||||
| 'access-denied'
|
||||
/** The viewer page could not reach the Relay at all: the request never arrived. */
|
||||
| 'relay-unreachable'
|
||||
|
||||
/** Whether the page may ask again, or the answer is the peer's verdict. */
|
||||
export type ViewerStateReach = 'retryable' | 'terminal'
|
||||
|
||||
/**
|
||||
* Whether the page may ask again, or the answer is the peer's verdict, for every condition.
|
||||
*
|
||||
* This is the whole vocabulary the protocol layer publishes: HTTP statuses and error codes belong to
|
||||
* the Relay, and copy keys belong to the client. A page, a test, and an operator read one name per
|
||||
* condition from here and get the retry decision with it.
|
||||
*/
|
||||
export const VIEWER_STATE_REACH: Readonly<Record<ViewerState, ViewerStateReach>> = {
|
||||
'share-not-found': 'terminal',
|
||||
'share-stopped': 'terminal',
|
||||
'share-expired': 'terminal',
|
||||
'owner-offline': 'retryable',
|
||||
'sign-in-expired': 'terminal',
|
||||
'access-denied': 'terminal',
|
||||
'relay-unreachable': 'retryable',
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/** The package's single public entry carries the whole shared contract. */
|
||||
|
||||
import { expect, it } from 'vitest'
|
||||
import * as root from '@deepseek-ai/dsh-experimental-liveshare-protocol'
|
||||
import { MockIdentityProvider } from '../src/identity/mock.ts'
|
||||
|
||||
it('publishes the wire, identity, carrier, and viewer-state contracts from the package root', () => {
|
||||
expect(root.LIVESHARE_PROTOCOL_VERSION).toBeTypeOf('number')
|
||||
expect(root.parseShareAccessState).toBeTypeOf('function')
|
||||
expect(root.parseTunnelWorkerCommand).toBeTypeOf('function')
|
||||
expect(root.identityKeyOf({ providerId: 'p', tenantId: 't', subjectId: 's' })).toBe('p:t:s')
|
||||
expect(root.identityFromKey('p:t:s')).toEqual({ providerId: 'p', tenantId: 't', subjectId: 's' })
|
||||
expect(root.identityFromKey('p:t')).toBeUndefined()
|
||||
expect(root.identityFromKey('p::s')).toBeUndefined()
|
||||
expect(root.viewerCarrierScript).toBeTypeOf('function')
|
||||
expect(root.VIEWER_STATE_REACH).toBeTypeOf('object')
|
||||
})
|
||||
|
||||
it('keeps the mock identity provider out of the published surface', () => {
|
||||
// Tests import the mock from its source module; no package entry exposes it.
|
||||
expect('MockIdentityProvider' in root).toBe(false)
|
||||
expect(MockIdentityProvider).toBeTypeOf('function')
|
||||
})
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"dir": "gateway->relay",
|
||||
"note": "an answer whose status is outside the HTTP range the frame accepts",
|
||||
"frame": { "type": "share-rpc-res", "id": 7, "status": 700 }
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"dir": "host->worker",
|
||||
"note": "a command this worker does not know: it must be refused rather than acted on",
|
||||
"frame": { "type": "set-share-mode", "shareId": "share-one", "mode": "view" }
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"dir": "host->worker",
|
||||
"note": "a share whose access mode is outside the closed enum fails the whole command instead of widening it",
|
||||
"frame": {
|
||||
"type": "add-share",
|
||||
"registrationToken": "11111111-1111-4111-8111-111111111111",
|
||||
"share": {
|
||||
"shareId": "share-three",
|
||||
"sessionId": "session-three",
|
||||
"sessionTitle": "Third",
|
||||
"accessMode": "future",
|
||||
"relay": "wss://relay.example",
|
||||
"gatewayToken": "token-three",
|
||||
"ownerDisplayName": "Owner",
|
||||
"allowedSubjectIds": []
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"dir": "relay->gateway",
|
||||
"note": "a frame type this build does not know: an old gateway must refuse it instead of throwing",
|
||||
"frame": {
|
||||
"type": "share-stream-delta",
|
||||
"id": 11,
|
||||
"body": {
|
||||
"op": "stream-next"
|
||||
}
|
||||
},
|
||||
"refusal": {
|
||||
"status": 501,
|
||||
"body": {
|
||||
"error": "unsupported-frame"
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"dir": "relay->gateway",
|
||||
"note": "an envelope whose id cannot correlate an answer with its request",
|
||||
"frame": {
|
||||
"type": "share-rpc",
|
||||
"id": 0,
|
||||
"body": {
|
||||
"op": "call",
|
||||
"path": "/__share/context",
|
||||
"body": {}
|
||||
},
|
||||
"actor": {
|
||||
"providerId": "example",
|
||||
"tenantId": "tenant-a",
|
||||
"subjectId": "user_viewer"
|
||||
}
|
||||
},
|
||||
"refusal": null
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"dir": "relay->gateway",
|
||||
"note": "a request whose caller the Relay did not assert: the owner may never act on an unattributable request",
|
||||
"frame": {
|
||||
"type": "share-rpc",
|
||||
"id": 12,
|
||||
"body": {
|
||||
"op": "call",
|
||||
"path": "/__share/context",
|
||||
"body": {}
|
||||
}
|
||||
},
|
||||
"refusal": {
|
||||
"status": 400,
|
||||
"body": {
|
||||
"error": "invalid-request"
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"dir": "worker->host",
|
||||
"note": "an event this host does not know: it must be ignored rather than misread as a known event",
|
||||
"frame": { "type": "share-progress", "shareId": "share-one", "percent": 50 }
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"dir": "gateway->relay",
|
||||
"note": "the owner's opaque answer to one routed request",
|
||||
"frame": { "type": "share-rpc-res", "id": 7, "status": 200, "body": { "ok": true } },
|
||||
"optional": ["body"]
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"dir": "host->worker",
|
||||
"note": "a share with only the required spec fields and the parser's default relay connection: no sessionMode, no allowsFork, no deadline",
|
||||
"frame": {
|
||||
"type": "add-share",
|
||||
"registrationToken": "11111111-1111-4111-8111-111111111111",
|
||||
"share": {
|
||||
"shareId": "share-two",
|
||||
"sessionId": "session-two",
|
||||
"sessionTitle": "Second",
|
||||
"accessMode": "open",
|
||||
"relay": "wss://relay.example",
|
||||
"gatewayToken": "token-two",
|
||||
"ownerDisplayName": "Owner",
|
||||
"allowedSubjectIds": [],
|
||||
"connection": { "mode": "relay" }
|
||||
}
|
||||
},
|
||||
"optional": []
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"dir": "host->worker",
|
||||
"note": "the owner host publishes one share to its gateway worker, every optional spec field present",
|
||||
"frame": {
|
||||
"type": "add-share",
|
||||
"registrationToken": "11111111-1111-4111-8111-111111111111",
|
||||
"share": {
|
||||
"shareId": "share-one",
|
||||
"sessionId": "session-one",
|
||||
"sessionTitle": "Review the migration",
|
||||
"accessMode": "selected",
|
||||
"relay": "wss://relay.example",
|
||||
"gatewayToken": "token-one",
|
||||
"ownerDisplayName": "Owner",
|
||||
"allowedSubjectIds": [
|
||||
"user_viewer",
|
||||
"example:tenant-a:user-other"
|
||||
],
|
||||
"sessionMode": "write",
|
||||
"allowsFork": true,
|
||||
"allowsFileUpload": true,
|
||||
"dshVersion": "0.2.0-rc.2",
|
||||
"ownerInstanceId": "instance-one",
|
||||
"expiresAt": "2026-10-03T00:00:00.000Z",
|
||||
"connection": {
|
||||
"mode": "relay"
|
||||
}
|
||||
}
|
||||
},
|
||||
"optional": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"dir": "host->worker",
|
||||
"note": "the owner host withdraws one share",
|
||||
"frame": { "type": "remove-share", "shareId": "share-one" },
|
||||
"optional": []
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"dir": "host->worker",
|
||||
"note": "the owner host hands its answer back for one in-flight request, naming the share it came through",
|
||||
"frame": {
|
||||
"type": "share-rpc-response",
|
||||
"registrationToken": "11111111-1111-4111-8111-111111111111",
|
||||
"token": "request-token",
|
||||
"id": 7,
|
||||
"status": 200,
|
||||
"body": {
|
||||
"ok": true
|
||||
},
|
||||
"shareId": "share-one"
|
||||
},
|
||||
"optional": ["body"]
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"dir": "relay->gateway",
|
||||
"note": "the reader left, so the Relay cancels one in-flight request",
|
||||
"frame": { "type": "share-rpc-cancel", "id": 8 },
|
||||
"optional": []
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"dir": "relay->gateway",
|
||||
"note": "one viewer request the Relay routed, carrying the identity it asserted",
|
||||
"frame": {
|
||||
"type": "share-rpc",
|
||||
"id": 7,
|
||||
"body": {
|
||||
"op": "call",
|
||||
"path": "/__share/context",
|
||||
"body": {}
|
||||
},
|
||||
"actor": {
|
||||
"providerId": "example",
|
||||
"tenantId": "tenant-a",
|
||||
"subjectId": "user_viewer",
|
||||
"credential": "signed-owner-verified-token"
|
||||
}
|
||||
},
|
||||
"optional": []
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"dir": "worker->host",
|
||||
"note": "the gateway worker is up",
|
||||
"frame": { "type": "ready" },
|
||||
"optional": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"dir": "worker->host",
|
||||
"note": "one share is registered on the Relay and reachable",
|
||||
"frame": { "type": "share-connected", "registrationToken": "11111111-1111-4111-8111-111111111111", "shareId": "share-one" },
|
||||
"optional": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"dir": "worker->host",
|
||||
"note": "one share could not be carried, with the reason the worker read",
|
||||
"frame": { "type": "share-error", "registrationToken": "11111111-1111-4111-8111-111111111111", "shareId": "share-one", "message": "relay refused registration status=401" },
|
||||
"optional": []
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"dir": "worker->host",
|
||||
"note": "the gateway worker reports one routed request, with the identity the Relay asserted",
|
||||
"frame": {
|
||||
"type": "share-rpc-request",
|
||||
"registrationToken": "11111111-1111-4111-8111-111111111111",
|
||||
"token": "request-token",
|
||||
"id": 7,
|
||||
"shareId": "share-one",
|
||||
"body": { "op": "stream-open", "id": 1, "endpoint": "trajectory", "payload": {} },
|
||||
"actor": { "providerId": "example", "tenantId": "tenant-a", "subjectId": "user_viewer" }
|
||||
},
|
||||
"optional": []
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/** The deterministic identity provider tests and loopback demos stand on. */
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
MockIdentityProvider,
|
||||
type MockIdentityPersona,
|
||||
} from '../src/identity/mock.ts'
|
||||
|
||||
/** The personas one provider is built from; the array stays writable so a test can empty it. */
|
||||
function personas(): MockIdentityPersona[] {
|
||||
return [
|
||||
{ id: 'alice', tenantId: 'tenant-a', displayName: 'Alice', avatarUrl: 'https://avatar.example/alice.png' },
|
||||
{ id: 'bob' },
|
||||
]
|
||||
}
|
||||
|
||||
describe('mock identity provider', () => {
|
||||
it('refuses a provider that names no id or carries no persona', () => {
|
||||
expect(() => new MockIdentityProvider('', personas())).toThrow('mock identity provider id must not be empty')
|
||||
expect(() => new MockIdentityProvider('mock', [])).toThrow('mock identity provider requires at least one persona')
|
||||
expect(new MockIdentityProvider('mock', personas()).scopes).toEqual([])
|
||||
})
|
||||
|
||||
it('redirects to the callback with the selected persona code and the caller state', () => {
|
||||
const provider = new MockIdentityProvider('mock', personas())
|
||||
const url = provider.authorizationUrl({
|
||||
redirectUri: 'https://relay.example/__liveshare/auth/callback?existing=1',
|
||||
state: 'state-7',
|
||||
scopes: [],
|
||||
loginHint: 'bob',
|
||||
})
|
||||
expect(url.origin + url.pathname).toBe('https://relay.example/__liveshare/auth/callback')
|
||||
expect(Object.fromEntries(url.searchParams)).toEqual({ existing: '1', code: 'bob', state: 'state-7' })
|
||||
expect(provider.authorizationUrl({
|
||||
redirectUri: 'https://relay.example/callback', state: 'state-8', scopes: [],
|
||||
}).searchParams.get('code')).toBe('alice')
|
||||
})
|
||||
|
||||
it('refuses a redirect when no persona is selectable', () => {
|
||||
const list = personas()
|
||||
const provider = new MockIdentityProvider('mock', list)
|
||||
list.length = 0
|
||||
expect(() => provider.authorizationUrl({ redirectUri: 'https://relay.example/callback', state: 's', scopes: [] }))
|
||||
.toThrow('mock identity provider has no selectable persona')
|
||||
})
|
||||
|
||||
it('resolves a persona into a normalized actor, keeping what the provider issued', async () => {
|
||||
const provider = new MockIdentityProvider('mock', personas())
|
||||
await expect(provider.exchange({ code: 'alice', redirectUri: 'https://relay.example/callback' })).resolves.toEqual({
|
||||
providerId: 'mock',
|
||||
tenantId: 'tenant-a',
|
||||
subjectId: 'alice',
|
||||
displayName: 'Alice',
|
||||
avatarUrl: 'https://avatar.example/alice.png',
|
||||
})
|
||||
// A persona with no tenant, no display name, and no avatar receives the documented defaults.
|
||||
await expect(provider.exchange({ code: 'bob', redirectUri: 'https://relay.example/callback' })).resolves.toEqual({
|
||||
providerId: 'mock', tenantId: 'mock', subjectId: 'bob', displayName: 'bob',
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects an unknown callback code and an empty persona id', async () => {
|
||||
const provider = new MockIdentityProvider('mock', personas())
|
||||
await expect(provider.exchange({ code: 'nobody', redirectUri: 'https://relay.example/callback' })).rejects.toThrow('mock identity callback code is unknown')
|
||||
const empty = new MockIdentityProvider('mock', [{ id: '' }])
|
||||
await expect(empty.exchange({ code: '', redirectUri: 'https://relay.example/callback' })).rejects.toThrow('mock identity persona id must not be empty')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
IDENTITY_TENANT_PLACEHOLDER,
|
||||
identityFromKey,
|
||||
identityKeyOf,
|
||||
normalizeIdentity,
|
||||
requireIdentityTenant,
|
||||
type IdentityActor,
|
||||
} from '@deepseek-ai/dsh-experimental-liveshare-protocol'
|
||||
|
||||
const actor: IdentityActor = {
|
||||
providerId: 'example',
|
||||
tenantId: 'tenant/a',
|
||||
subjectId: 'user:one',
|
||||
displayName: 'Alice',
|
||||
}
|
||||
|
||||
describe('identity keys', () => {
|
||||
it('derives one stable, encoded identity key from the provider triple', () => {
|
||||
expect(identityKeyOf(actor)).toBe('example:tenant%2Fa:user%3Aone')
|
||||
expect(identityKeyOf(actor)).toBe(identityKeyOf({
|
||||
providerId: actor.providerId,
|
||||
tenantId: actor.tenantId,
|
||||
subjectId: actor.subjectId,
|
||||
}))
|
||||
expect(identityFromKey(identityKeyOf(actor))).toEqual({
|
||||
providerId: actor.providerId,
|
||||
tenantId: actor.tenantId,
|
||||
subjectId: actor.subjectId,
|
||||
})
|
||||
expect(identityFromKey('example:only-two')).toBeUndefined()
|
||||
expect(identityFromKey('example:%E0%A4%A:user')).toBeUndefined()
|
||||
// The key codec reads the triple it is given: a caller that skips normalization can build a key
|
||||
// whose empty tenant segment its own parser refuses.
|
||||
expect(identityKeyOf({ providerId: 'example', tenantId: '', subjectId: 'user' })).toBe('example::user')
|
||||
expect(identityFromKey('example::user')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('fills the placeholder tenant only for a provider that issues none', () => {
|
||||
expect(normalizeIdentity({ providerId: 'example', tenantId: '', subjectId: 'user' }))
|
||||
.toEqual({ providerId: 'example', tenantId: IDENTITY_TENANT_PLACEHOLDER, subjectId: 'user' })
|
||||
expect(normalizeIdentity({ providerId: 'example', tenantId: 'tenant-a', subjectId: 'user' }))
|
||||
.toEqual({ providerId: 'example', tenantId: 'tenant-a', subjectId: 'user' })
|
||||
expect(normalizeIdentity({ providerId: '', tenantId: '', subjectId: 'user' })).toBeUndefined()
|
||||
expect(normalizeIdentity({ providerId: 'example', tenantId: '', subjectId: '' })).toBeUndefined()
|
||||
expect(normalizeIdentity({ providerId: 'example', tenantId: '', subjectId: 'user' }, ''))
|
||||
.toBeUndefined()
|
||||
expect(normalizeIdentity({ providerId: 'example', tenantId: '', subjectId: 'user' }, 'tenant-b'))
|
||||
.toEqual({ providerId: 'example', tenantId: 'tenant-b', subjectId: 'user' })
|
||||
})
|
||||
|
||||
it('rejects any triple whose provider must issue a tenant but left it empty', () => {
|
||||
expect(requireIdentityTenant({ providerId: 'example', tenantId: 'tenant-a', subjectId: 'user' }))
|
||||
.toEqual({ providerId: 'example', tenantId: 'tenant-a', subjectId: 'user' })
|
||||
expect(requireIdentityTenant({ providerId: 'example', tenantId: '', subjectId: 'user' })).toBeUndefined()
|
||||
expect(requireIdentityTenant({ providerId: '', tenantId: 'tenant-a', subjectId: 'user' })).toBeUndefined()
|
||||
expect(requireIdentityTenant({ providerId: 'example', tenantId: 'tenant-a', subjectId: '' })).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,78 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseTunnelWorkerCommand, parseTunnelWorkerEvent } from '../src/tunnel-protocol.ts'
|
||||
|
||||
const registrationToken = '12345678-1234-4123-8123-123456789abc'
|
||||
const identity = { registrationToken, token: 'worker-unique-request', shareId: 'share', id: 1 }
|
||||
const frames = [
|
||||
{ type: 'share-rpc-response', ...identity, status: 200, body: { answer: true } },
|
||||
{ type: 'share-rpc-request', ...identity, body: { op: 'stream-read' }, actor: { providerId: 'mock', tenantId: 'mock', subjectId: 'alice' } },
|
||||
{ type: 'share-rpc-cancel', ...identity },
|
||||
]
|
||||
const parse = (frame: Record<string, unknown>) => frame.type === 'share-rpc-response'
|
||||
? parseTunnelWorkerCommand(frame)
|
||||
: parseTunnelWorkerEvent(frame)
|
||||
|
||||
describe('Host/worker request tokens', () => {
|
||||
it.each(frames)('accepts $type with complete request identity', (frame) => {
|
||||
expect(parse(frame)).toEqual(frame)
|
||||
})
|
||||
|
||||
it.each(frames)('refuses $type without any correlation field', (frame) => {
|
||||
for (const field of ['registrationToken', 'token', 'id', 'shareId']) {
|
||||
expect(parse(Object.fromEntries(Object.entries(frame).filter(([key]) => key !== field)))).toBeUndefined()
|
||||
}
|
||||
for (const token of ['', null, 1]) expect(parse({ ...frame, token })).toBeUndefined()
|
||||
for (const id of [0, -1, 1.5, '1']) expect(parse({ ...frame, id })).toBeUndefined()
|
||||
expect(parse({ ...frame, shareId: '' })).toBeUndefined()
|
||||
})
|
||||
|
||||
it('requires response status and request actor and body', () => {
|
||||
for (const status of [99, 600, 200.5]) expect(parse({ ...frames[0], status })).toBeUndefined()
|
||||
expect(parse({ ...frames[1], actor: undefined })).toBeUndefined()
|
||||
expect(parse({ ...frames[1], actor: { providerId: 'mock', tenantId: '', subjectId: 'alice' } })).toBeUndefined()
|
||||
expect(parse({ ...frames[1], body: undefined })).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
const share = { shareId: 'share', sessionId: 'session', sessionTitle: 'Session', accessMode: 'open',
|
||||
relay: 'http://relay.invalid', gatewayToken: 'gateway', ownerDisplayName: 'Owner', allowedSubjectIds: [],
|
||||
connection: { mode: 'relay' } }
|
||||
const registrationFrames = [
|
||||
{ type: 'add-share', registrationToken, share },
|
||||
{ type: 'share-connected', registrationToken, shareId: 'share' },
|
||||
{ type: 'share-closed', registrationToken, shareId: 'share' },
|
||||
{ type: 'share-error', registrationToken, shareId: 'share', message: 'offline' },
|
||||
{ type: 'share-access-state', registrationToken, shareId: 'share', version: 1, accessMode: 'open',
|
||||
allowedSubjectIds: [], sessionMode: 'view', allowsFileUpload: false },
|
||||
]
|
||||
|
||||
describe('Host/worker registration identity', () => {
|
||||
it('rejects an empty subject in a share registration without rejecting an empty ACL', () => {
|
||||
expect(parseTunnelWorkerCommand({ type: 'add-share', registrationToken, share })).toBeDefined()
|
||||
expect(parseTunnelWorkerCommand({ type: 'add-share', registrationToken,
|
||||
share: { ...share, allowedSubjectIds: [''] } })).toBeUndefined()
|
||||
})
|
||||
const decode = (frame: Record<string, unknown>) => (frame.type === 'add-share' || frame.type === 'share-rpc-response')
|
||||
? parseTunnelWorkerCommand(frame) : parseTunnelWorkerEvent(frame)
|
||||
it.each(registrationFrames)('accepts $type with its original registration UUID', (frame) => {
|
||||
expect(decode(frame)).toEqual(frame)
|
||||
})
|
||||
it.each([...registrationFrames, ...frames])('rejects $type without a valid registration UUID', (frame) => {
|
||||
for (const token of [undefined, '', 'not-a-uuid', 1, null,
|
||||
'12345678-1234-1123-8123-123456789abc', '12345678-1234-4123-0123-123456789abc']) {
|
||||
expect(decode({ ...frame, registrationToken: token })).toBeUndefined()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('unknown tier at the IPC boundary', () => {
|
||||
it('rejects a tier the current vocabulary does not name', () => {
|
||||
const share = {
|
||||
shareId: 'share', sessionId: 'session', sessionTitle: 'Source', accessMode: 'selected' as const,
|
||||
relay: 'https://relay.test', gatewayToken: 'token', ownerDisplayName: 'Owner',
|
||||
sessionMode: 'future', allowsFork: true, allowedSubjectIds: [],
|
||||
}
|
||||
expect(parseTunnelWorkerCommand({ type: 'add-share', registrationToken: randomUUID(), share })).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,204 @@
|
||||
/** Relay wire version 1; same-package Host/worker IPC requires request tokens. */
|
||||
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
LIVESHARE_PROTOCOL_VERSION,
|
||||
parseGatewayFrame,
|
||||
parseRelayFrame,
|
||||
parseTunnelWorkerCommand,
|
||||
parseTunnelWorkerEvent,
|
||||
rejectedCommandShareId,
|
||||
unsupportedFrameRefusal,
|
||||
} from '@deepseek-ai/dsh-experimental-liveshare-protocol'
|
||||
|
||||
/** Which two endpoints exchanged a recorded frame, which also names the codec that reads it. */
|
||||
type Direction = 'relay->gateway' | 'gateway->relay' | 'host->worker' | 'worker->host'
|
||||
|
||||
/** One frame the current build exchanges, with the fields it may omit. */
|
||||
interface RecordedFrame {
|
||||
readonly dir: Direction
|
||||
readonly note: string
|
||||
readonly frame: Record<string, unknown>
|
||||
/** Raw socket text, when the recording pins bytes rather than the frame's fields. */
|
||||
readonly text?: string
|
||||
/** Top-level fields this build sends only when it has something to say. */
|
||||
readonly optional?: readonly string[]
|
||||
}
|
||||
|
||||
/** One frame this build must refuse: a later build's addition, or a value the vocabulary rejects. */
|
||||
interface RefusedFrame {
|
||||
readonly dir: Direction
|
||||
readonly note: string
|
||||
readonly frame: Record<string, unknown>
|
||||
readonly text?: string
|
||||
/**
|
||||
* The refusal this build answers with, or null when the frame states nothing to answer: an
|
||||
* unreadable envelope, or a frame that answers another rather than asking for one.
|
||||
*/
|
||||
readonly refusal?: { readonly status: number; readonly body: { readonly error: string } } | null
|
||||
}
|
||||
|
||||
const FRAMES_DIR = join(import.meta.dirname, 'frames')
|
||||
|
||||
/**
|
||||
* Read every recorded frame in one directory.
|
||||
* @param directory - Directory under `frames/`.
|
||||
* @returns Recordings in file-name order.
|
||||
*/
|
||||
function readFrames<T>(directory: string): T[] {
|
||||
return readdirSync(join(FRAMES_DIR, directory))
|
||||
.filter(name => name.endsWith('.json'))
|
||||
.sort()
|
||||
.map(name => JSON.parse(readFileSync(join(FRAMES_DIR, directory, name), 'utf8')) as T)
|
||||
}
|
||||
|
||||
/**
|
||||
* The socket text a recording stands for.
|
||||
* @param recorded - Recording holding either raw text or the frame it carried.
|
||||
* @returns The recorded text.
|
||||
*/
|
||||
function wireText(recorded: { readonly frame: Record<string, unknown>; readonly text?: string }): string {
|
||||
return recorded.text ?? JSON.stringify(recorded.frame)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read one recorded frame through the codec its direction names.
|
||||
* @param direction - Endpoints that exchanged the frame.
|
||||
* @param text - Raw socket text the recording carries.
|
||||
* @returns The parsed frame, or undefined when this build refuses it.
|
||||
*/
|
||||
function parseFrame(direction: Direction, text: string): unknown {
|
||||
switch (direction) {
|
||||
case 'relay->gateway':
|
||||
return parseRelayFrame(text)
|
||||
case 'gateway->relay':
|
||||
return parseGatewayFrame(text)
|
||||
// The worker's two directions cross a process boundary as values, not socket text, so the
|
||||
// codecs read the decoded value and the envelope is the caller's JSON parse.
|
||||
case 'host->worker':
|
||||
return parseTunnelWorkerCommand(JSON.parse(text))
|
||||
case 'worker->host':
|
||||
return parseTunnelWorkerEvent(JSON.parse(text))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One recorded frame without one top-level field.
|
||||
* @param frame - Recorded frame.
|
||||
* @param field - Field to remove.
|
||||
* @returns A copy without that field.
|
||||
*/
|
||||
function withoutField(frame: Record<string, unknown>, field: string): Record<string, unknown> {
|
||||
return Object.fromEntries(Object.entries(frame).filter(([key]) => key !== field))
|
||||
}
|
||||
|
||||
describe('recorded frames', () => {
|
||||
it('round-trips every current frame through the codec its direction names', () => {
|
||||
for (const recorded of readFrames<RecordedFrame>('v1')) {
|
||||
expect(parseFrame(recorded.dir, wireText(recorded)), recorded.note).toEqual(recorded.frame)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps every recorded optional field optional', () => {
|
||||
for (const recorded of readFrames<RecordedFrame>('v1')) {
|
||||
if (parseFrame(recorded.dir, wireText(recorded)) === undefined) continue
|
||||
for (const field of recorded.optional ?? []) {
|
||||
const withoutOptional = { ...recorded, frame: withoutField(recorded.frame, field) }
|
||||
expect(parseFrame(recorded.dir, wireText(withoutOptional)), `${recorded.note} (without ${field})`)
|
||||
.toEqual(withoutField(recorded.frame, field))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('refuses a frame this build does not know instead of throwing', () => {
|
||||
for (const recorded of readFrames<RefusedFrame>('unknown')) {
|
||||
expect(() => parseFrame(recorded.dir, wireText(recorded)), recorded.note).not.toThrow()
|
||||
expect(parseFrame(recorded.dir, wireText(recorded)), recorded.note).toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the fields that carry a request identity required', () => {
|
||||
// `id` correlates an answer with its request and `actor` is the caller the owner may act on:
|
||||
// widening either one moves authority rather than convenience, so both stay required without
|
||||
// being recorded as optional elsewhere.
|
||||
const request = readFrames<RecordedFrame>('v1')
|
||||
.find(recorded => recorded.dir === 'relay->gateway' && recorded.frame.type === 'share-rpc')
|
||||
if (request === undefined) throw new Error('the relay->gateway share-rpc recording is missing')
|
||||
for (const field of ['id', 'actor']) {
|
||||
expect(parseFrame(request.dir, wireText({ ...request, frame: withoutField(request.frame, field) })), field)
|
||||
.toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('answers a frame it cannot serve instead of leaving the peer to wait', () => {
|
||||
for (const recorded of readFrames<RefusedFrame>('unknown')) {
|
||||
if (recorded.dir !== 'relay->gateway') continue
|
||||
const refusal = unsupportedFrameRefusal(wireText(recorded))
|
||||
if (recorded.refusal === null || recorded.refusal === undefined) {
|
||||
expect(refusal, recorded.note).toBeUndefined()
|
||||
continue
|
||||
}
|
||||
expect(refusal, recorded.note).toMatchObject({ type: 'share-rpc-res', ...recorded.refusal })
|
||||
}
|
||||
})
|
||||
|
||||
it('answers nothing for a frame it does serve', () => {
|
||||
for (const recorded of readFrames<RecordedFrame>('v1')) {
|
||||
if (recorded.dir !== 'relay->gateway') continue
|
||||
expect(unsupportedFrameRefusal(wireText(recorded)), recorded.note).toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('names the share a refused owner command was about', () => {
|
||||
expect(rejectedCommandShareId({ type: 'set-share-mode', shareId: 'share-one' })).toBe('share-one')
|
||||
expect(rejectedCommandShareId({ type: 'add-share', share: { shareId: 'share-two' } })).toBe('share-two')
|
||||
expect(rejectedCommandShareId({ type: 'set-share-mode' })).toBeUndefined()
|
||||
expect(rejectedCommandShareId({ type: 'remove-share', shareId: '' })).toBeUndefined()
|
||||
expect(rejectedCommandShareId({ type: 'add-share', share: { sessionId: 'session-one' } })).toBeUndefined()
|
||||
expect(rejectedCommandShareId(null)).toBeUndefined()
|
||||
expect(rejectedCommandShareId('share-one')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('refuses malformed text without throwing', () => {
|
||||
const malformed = ['', '{', 'null', '[]', '"share-rpc"', '{"type":"share-rpc"}', '{"id":1}', '{"type":"share-rpc","id":"7"}']
|
||||
for (const text of malformed) {
|
||||
expect(() => parseRelayFrame(text), text).not.toThrow()
|
||||
expect(parseRelayFrame(text), text).toBeUndefined()
|
||||
expect(() => parseGatewayFrame(text), text).not.toThrow()
|
||||
expect(parseGatewayFrame(text), text).toBeUndefined()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('wire protocol version', () => {
|
||||
it('states the initial wire protocol version', () => {
|
||||
expect(LIVESHARE_PROTOCOL_VERSION).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('additive wire fields reject invalid values', () => {
|
||||
const actor = { providerId: 'example', tenantId: 'tenant-a', subjectId: 'user-one' }
|
||||
const request = (overrides: Record<string, unknown>) => {
|
||||
const text = JSON.stringify({ type: 'share-rpc', id: 1, body: {}, actor: { ...actor, ...overrides } })
|
||||
return parseGatewayFrame(text) ?? parseRelayFrame(text)
|
||||
}
|
||||
|
||||
it('accepts an absent actor credential and refuses a non-string one', () => {
|
||||
expect(request({})).toMatchObject({ actor })
|
||||
expect(request({ credential: 123 })).toBeUndefined()
|
||||
})
|
||||
|
||||
it('refuses an unknown connection mode and defaults an absent one to relay', () => {
|
||||
const share = {
|
||||
shareId: 'share', sessionId: 'session', sessionTitle: 'Source', accessMode: 'selected',
|
||||
relay: 'wss://relay.test', gatewayToken: 'token', ownerDisplayName: 'Owner', allowedSubjectIds: [],
|
||||
}
|
||||
const token = '12345678-1234-4123-8123-123456789abc'
|
||||
expect(parseTunnelWorkerCommand({ type: 'add-share', registrationToken: token,
|
||||
share: { ...share, connection: { mode: 'bogus' } } })).toBeUndefined()
|
||||
expect(parseTunnelWorkerCommand({ type: 'add-share', registrationToken: token, share }))
|
||||
.toMatchObject({ share: { connection: { mode: 'relay' } } })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,303 @@
|
||||
/** Every wire helper and additive-field parser branch, exercised without a recorded frame. */
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
parseRelayFrame,
|
||||
parseShareAccessState,
|
||||
parseTunnelWorkerCommand,
|
||||
parseTunnelWorkerEvent,
|
||||
rawText,
|
||||
rejectedCommandShareId,
|
||||
sendFrame,
|
||||
unsupportedFrameRefusal,
|
||||
viewerRequestFields,
|
||||
} from '@deepseek-ai/dsh-experimental-liveshare-protocol'
|
||||
|
||||
/** One registration token; the parsers accept only this UUID-v4 shape. */
|
||||
const REGISTRATION = '11111111-1111-4111-8111-111111111111'
|
||||
/** One request token the IPC parsers require to be non-empty. */
|
||||
const TOKEN = 'request-token'
|
||||
|
||||
/**
|
||||
* A share spec the worker accepts as written.
|
||||
* @returns Every required field, with no optional field present.
|
||||
*/
|
||||
function spec(): Record<string, unknown> {
|
||||
return {
|
||||
shareId: 'share-one',
|
||||
sessionId: 'session-one',
|
||||
sessionTitle: 'Title',
|
||||
accessMode: 'selected',
|
||||
relay: 'wss://relay.example',
|
||||
gatewayToken: 'token-one',
|
||||
ownerDisplayName: 'Owner',
|
||||
allowedSubjectIds: ['viewer'],
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap one share spec as the add-share command the host sends its worker.
|
||||
* @param share - Share spec to carry.
|
||||
* @returns The IPC command.
|
||||
*/
|
||||
function addShare(share: unknown): Record<string, unknown> {
|
||||
return { type: 'add-share', registrationToken: REGISTRATION, share }
|
||||
}
|
||||
|
||||
/**
|
||||
* A committed authority snapshot the parser accepts.
|
||||
* @returns Every required field, with the optional additions left out.
|
||||
*/
|
||||
function state(): Record<string, unknown> {
|
||||
return {
|
||||
type: 'share-access-state',
|
||||
version: 3,
|
||||
accessMode: 'selected',
|
||||
allowedSubjectIds: ['viewer'],
|
||||
sessionMode: 'view',
|
||||
}
|
||||
}
|
||||
|
||||
describe('wire helpers', () => {
|
||||
it('summarizes one opaque viewer request for logging', () => {
|
||||
expect(viewerRequestFields({ op: 'call', id: 7 })).toEqual({ op: 'call', streamId: '7' })
|
||||
expect(viewerRequestFields({ op: 4, id: 'seven' })).toEqual({ op: 'unknown', streamId: '-' })
|
||||
expect(viewerRequestFields({})).toEqual({ op: 'unknown', streamId: '-' })
|
||||
for (const body of [null, 'text', 3, undefined]) {
|
||||
expect(viewerRequestFields(body)).toEqual({ op: 'unknown', streamId: '-' })
|
||||
}
|
||||
})
|
||||
|
||||
it('sends one frame only on an open socket', () => {
|
||||
const sent: string[] = []
|
||||
sendFrame({ readyState: 1, send: (data: string) => { sent.push(data) } }, { type: 'share-rpc-cancel', id: 1 })
|
||||
sendFrame({ readyState: 3, send: (data: string) => { sent.push(data) } }, { type: 'share-rpc-cancel', id: 1 })
|
||||
expect(sent).toHaveLength(1)
|
||||
expect(JSON.parse(sent[0] ?? '')).toEqual({ type: 'share-rpc-cancel', id: 1 })
|
||||
})
|
||||
|
||||
it('decodes every representation ws hands the gateways', () => {
|
||||
expect(rawText(Buffer.from('a'))).toBe('a')
|
||||
expect(rawText(new TextEncoder().encode('bc').buffer)).toBe('bc')
|
||||
expect(rawText([Buffer.from('de'), Buffer.from('f')])).toBe('def')
|
||||
})
|
||||
|
||||
it('reads the share a rejected command names', () => {
|
||||
expect(rejectedCommandShareId({ shareId: 'direct' })).toBe('direct')
|
||||
expect(rejectedCommandShareId({ share: { shareId: 'nested' } })).toBe('nested')
|
||||
expect(rejectedCommandShareId({ share: { shareId: '' } })).toBeUndefined()
|
||||
expect(rejectedCommandShareId({ share: 'not-an-object' })).toBeUndefined()
|
||||
expect(rejectedCommandShareId({})).toBeUndefined()
|
||||
expect(rejectedCommandShareId(null)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Relay frame parsing', () => {
|
||||
it('parses the frames a gateway may receive', () => {
|
||||
expect(parseRelayFrame(JSON.stringify(state()))).toMatchObject({ type: 'share-access-state', version: 3 })
|
||||
expect(parseRelayFrame(JSON.stringify({
|
||||
type: 'share-rpc', id: 4, body: { op: 'call' }, actor: { providerId: 'p', tenantId: 't', subjectId: 's' },
|
||||
}))).toEqual({
|
||||
type: 'share-rpc', id: 4, body: { op: 'call' },
|
||||
actor: { providerId: 'p', tenantId: 't', subjectId: 's' },
|
||||
})
|
||||
expect(parseRelayFrame(JSON.stringify({
|
||||
type: 'share-rpc', id: 4, body: null,
|
||||
actor: { providerId: 'p', tenantId: 't', subjectId: 's', credential: 'signed' },
|
||||
}))).toMatchObject({ actor: { credential: 'signed' } })
|
||||
expect(parseRelayFrame(JSON.stringify({ type: 'share-rpc-cancel', id: 5 }))).toEqual({ type: 'share-rpc-cancel', id: 5 })
|
||||
})
|
||||
|
||||
it('drops frames that carry no serveable request', () => {
|
||||
expect(parseRelayFrame('not json')).toBeUndefined()
|
||||
expect(parseRelayFrame('null')).toBeUndefined()
|
||||
expect(parseRelayFrame('[]')).toBeUndefined()
|
||||
expect(parseRelayFrame(JSON.stringify({ type: 'share-rpc', body: {} }))).toBeUndefined()
|
||||
expect(parseRelayFrame(JSON.stringify({ type: 'share-rpc', id: 1, actor: { providerId: 'p', tenantId: 't', subjectId: 's' } })))
|
||||
.toBeUndefined()
|
||||
const valid = { type: 'share-rpc', id: 1, body: {} }
|
||||
for (const actor of [
|
||||
undefined,
|
||||
'actor',
|
||||
{ providerId: '', tenantId: 't', subjectId: 's' },
|
||||
{ providerId: 'p', tenantId: '', subjectId: 's' },
|
||||
{ providerId: 'p', tenantId: 't', subjectId: '' },
|
||||
{ providerId: 'p', tenantId: 't', subjectId: 's', credential: 3 },
|
||||
]) {
|
||||
expect(parseRelayFrame(JSON.stringify({ ...valid, actor }))).toBeUndefined()
|
||||
}
|
||||
expect(parseRelayFrame(JSON.stringify({ type: 'share-rpc-res', id: 1 }))).toBeUndefined()
|
||||
expect(parseRelayFrame(JSON.stringify({ type: 'future', id: 1 }))).toBeUndefined()
|
||||
})
|
||||
|
||||
it('answers only a request it could not serve', () => {
|
||||
expect(unsupportedFrameRefusal(JSON.stringify({ type: 'share-rpc-cancel', id: 1 }))).toBeUndefined()
|
||||
expect(unsupportedFrameRefusal(JSON.stringify(state()))).toBeUndefined()
|
||||
expect(unsupportedFrameRefusal('not json')).toBeUndefined()
|
||||
expect(unsupportedFrameRefusal(JSON.stringify({ type: 'share-rpc', body: {} }))).toBeUndefined()
|
||||
expect(unsupportedFrameRefusal(JSON.stringify({ type: 'share-rpc', id: 1 }))).toEqual({
|
||||
type: 'share-rpc-res', id: 1, status: 400, body: { error: 'invalid-request' },
|
||||
})
|
||||
expect(unsupportedFrameRefusal(JSON.stringify({ type: 'share-rpc-res', id: 1 }))).toBeUndefined()
|
||||
expect(unsupportedFrameRefusal(JSON.stringify({ type: 'share-rpc-cancel', id: 1 }))).toBeUndefined()
|
||||
expect(unsupportedFrameRefusal(JSON.stringify({ type: 'future-frame', id: 2 }))).toEqual({
|
||||
type: 'share-rpc-res', id: 2, status: 501, body: { error: 'unsupported-frame' },
|
||||
})
|
||||
expect(unsupportedFrameRefusal(JSON.stringify({ type: '', id: 3 }))).toBeUndefined()
|
||||
expect(unsupportedFrameRefusal(JSON.stringify({ type: 4, id: 5 }))).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('tunnel worker commands', () => {
|
||||
it('parses the commands a worker serves', () => {
|
||||
expect(parseTunnelWorkerCommand({ type: 'shutdown' })).toEqual({ type: 'shutdown' })
|
||||
expect(parseTunnelWorkerCommand({ type: 'remove-share', shareId: 'share-one' })).toEqual({
|
||||
type: 'remove-share', shareId: 'share-one',
|
||||
})
|
||||
expect(parseTunnelWorkerCommand({ type: 'remove-share', shareId: '' })).toBeUndefined()
|
||||
expect(parseTunnelWorkerCommand(addShare(spec()))).toMatchObject({
|
||||
type: 'add-share',
|
||||
share: { shareId: 'share-one', connection: { mode: 'relay' } },
|
||||
})
|
||||
expect(parseTunnelWorkerCommand(addShare({ ...spec(), connection: { mode: 'direct' } }))).toMatchObject({
|
||||
share: { connection: { mode: 'direct' } },
|
||||
})
|
||||
expect(parseTunnelWorkerCommand(addShare({ ...spec(), connection: { mode: 'carrier' } }))).toBeUndefined()
|
||||
expect(parseTunnelWorkerCommand(addShare({ ...spec(), connection: 'relay' }))).toBeUndefined()
|
||||
expect(parseTunnelWorkerCommand({ type: 'add-share', registrationToken: 'not-a-token', share: spec() })).toBeUndefined()
|
||||
expect(parseTunnelWorkerCommand({
|
||||
type: 'share-rpc-response', registrationToken: REGISTRATION, token: TOKEN, id: 1,
|
||||
shareId: 'share-one', status: 200, body: { ok: true },
|
||||
})).toMatchObject({ type: 'share-rpc-response', status: 200, body: { ok: true } })
|
||||
expect(parseTunnelWorkerCommand({
|
||||
type: 'share-rpc-response', registrationToken: REGISTRATION, token: TOKEN, id: 1,
|
||||
shareId: 'share-one', status: 200,
|
||||
})).not.toHaveProperty('body')
|
||||
for (const status of [99, 600, '200', 2_147_483_648]) {
|
||||
expect(parseTunnelWorkerCommand({
|
||||
type: 'share-rpc-response', registrationToken: REGISTRATION, token: TOKEN, id: 1,
|
||||
shareId: 'share-one', status,
|
||||
})).toBeUndefined()
|
||||
}
|
||||
expect(parseTunnelWorkerCommand({ type: 'future-command' })).toBeUndefined()
|
||||
expect(parseTunnelWorkerCommand(null)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('refuses every malformed field of a share spec', () => {
|
||||
const invalid: ReadonlyArray<Record<string, unknown>> = [
|
||||
{},
|
||||
{ ...spec(), shareId: '' },
|
||||
{ ...spec(), shareId: 4 },
|
||||
{ ...spec(), sessionId: 4 },
|
||||
{ ...spec(), sessionTitle: 4 },
|
||||
{ ...spec(), accessMode: 'approval' },
|
||||
{ ...spec(), relay: 4 },
|
||||
{ ...spec(), gatewayToken: 4 },
|
||||
{ ...spec(), ownerDisplayName: 4 },
|
||||
{ ...spec(), ownerProviderId: 4 },
|
||||
{ ...spec(), ownerTenantId: 4 },
|
||||
{ ...spec(), dshVersion: 4 },
|
||||
{ ...spec(), ownerInstanceId: 4 },
|
||||
{ ...spec(), ownerCredential: 4 },
|
||||
{ ...spec(), expiresAt: 4 },
|
||||
{ ...spec(), expiresAt: 'banana' },
|
||||
{ ...spec(), allowsFork: 'yes' },
|
||||
{ ...spec(), sessionMode: 'fork-readonly' },
|
||||
{ ...spec(), allowsFileUpload: 'yes' },
|
||||
{ ...spec(), allowedSubjectIds: 'viewer' },
|
||||
{ ...spec(), allowedSubjectIds: ['viewer', ''] },
|
||||
{ ...spec(), allowedSubjectIds: ['viewer', 4] },
|
||||
]
|
||||
for (const share of invalid) expect(parseTunnelWorkerCommand(addShare(share)), JSON.stringify(share)).toBeUndefined()
|
||||
for (const share of [null, 'share-one', []] as const) {
|
||||
expect(parseTunnelWorkerCommand(addShare(share))).toBeUndefined()
|
||||
}
|
||||
|
||||
const allOptional = {
|
||||
...spec(),
|
||||
ownerProviderId: 'p', ownerTenantId: 't', dshVersion: '1.0.0', ownerInstanceId: 'i',
|
||||
ownerCredential: 'credential', expiresAt: '2026-10-03T00:00:00.000Z',
|
||||
allowsFork: true, sessionMode: 'write', allowsFileUpload: false,
|
||||
}
|
||||
expect(parseTunnelWorkerCommand(addShare(allOptional))).toBeDefined()
|
||||
expect(parseTunnelWorkerCommand(addShare({ ...spec(), accessMode: 'open' }))).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('tunnel worker events', () => {
|
||||
it('parses the lifecycle events a host receives', () => {
|
||||
expect(parseTunnelWorkerEvent({ type: 'ready' })).toEqual({ type: 'ready' })
|
||||
for (const type of ['share-connected', 'share-closed'] as const) {
|
||||
expect(parseTunnelWorkerEvent({ type, registrationToken: REGISTRATION, shareId: 'share-one' }))
|
||||
.toEqual({ type, registrationToken: REGISTRATION, shareId: 'share-one' })
|
||||
expect(parseTunnelWorkerEvent({ type, registrationToken: 'bad', shareId: 'share-one' })).toBeUndefined()
|
||||
expect(parseTunnelWorkerEvent({ type, registrationToken: REGISTRATION, shareId: '' })).toBeUndefined()
|
||||
}
|
||||
expect(parseTunnelWorkerEvent({
|
||||
...state(), registrationToken: REGISTRATION, shareId: 'share-one',
|
||||
})).toMatchObject({ type: 'share-access-state', registrationToken: REGISTRATION, shareId: 'share-one' })
|
||||
expect(parseTunnelWorkerEvent({
|
||||
...state(), registrationToken: 'bad', shareId: 'share-one',
|
||||
})).toBeUndefined()
|
||||
expect(parseTunnelWorkerEvent({
|
||||
type: 'share-error', registrationToken: REGISTRATION, shareId: 'share-one', message: 'nope',
|
||||
})).toEqual({ type: 'share-error', registrationToken: REGISTRATION, shareId: 'share-one', message: 'nope' })
|
||||
expect(parseTunnelWorkerEvent({
|
||||
type: 'share-error', registrationToken: REGISTRATION, shareId: 'share-one',
|
||||
})).toBeUndefined()
|
||||
expect(parseTunnelWorkerEvent({
|
||||
type: 'share-rpc-cancel', registrationToken: REGISTRATION, token: TOKEN, id: 2, shareId: 'share-one',
|
||||
})).toEqual({ type: 'share-rpc-cancel', registrationToken: REGISTRATION, token: TOKEN, id: 2, shareId: 'share-one' })
|
||||
const actor = { providerId: 'p', tenantId: 't', subjectId: 's' }
|
||||
expect(parseTunnelWorkerEvent({
|
||||
type: 'share-rpc-request', registrationToken: REGISTRATION, token: TOKEN, id: 3,
|
||||
shareId: 'share-one', body: { op: 'call' }, actor,
|
||||
})).toMatchObject({ type: 'share-rpc-request', id: 3, actor })
|
||||
for (const malformed of [
|
||||
{ type: 'share-rpc-request', registrationToken: REGISTRATION, token: TOKEN, id: 3, shareId: 'share-one', actor },
|
||||
{ type: 'share-rpc-request', registrationToken: REGISTRATION, token: TOKEN, id: 3, shareId: 'share-one', body: {}, actor: 'actor' },
|
||||
{ type: 'share-rpc-request', registrationToken: REGISTRATION, token: '', id: 3, shareId: 'share-one', body: {}, actor },
|
||||
{ type: 'share-rpc-request', registrationToken: REGISTRATION, token: TOKEN, id: 0, shareId: 'share-one', body: {}, actor },
|
||||
{ type: 'future-event' },
|
||||
]) {
|
||||
expect(parseTunnelWorkerEvent(malformed)).toBeUndefined()
|
||||
}
|
||||
expect(parseTunnelWorkerEvent(null)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('committed authority parsing', () => {
|
||||
it('owns the snapshot fields a reader follows', () => {
|
||||
expect(parseShareAccessState(state())).toEqual({
|
||||
type: 'share-access-state', version: 3, accessMode: 'selected',
|
||||
allowedSubjectIds: ['viewer'], sessionMode: 'view', allowsFileUpload: false,
|
||||
})
|
||||
expect(parseShareAccessState({
|
||||
...state(), version: 0, accessMode: 'open', sessionMode: 'write', allowsFork: true,
|
||||
allowsFileUpload: true, allowedSubjectIds: [], expiresAt: '2026-10-03T00:00:00.000Z',
|
||||
})).toEqual({
|
||||
type: 'share-access-state', version: 0, accessMode: 'open', allowedSubjectIds: [],
|
||||
sessionMode: 'write', allowsFork: true, allowsFileUpload: true,
|
||||
expiresAt: '2026-10-03T00:00:00.000Z',
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses a snapshot field this build cannot trust', () => {
|
||||
const invalid: ReadonlyArray<unknown> = [
|
||||
null,
|
||||
{ ...state(), type: 'share-rpc' },
|
||||
{ ...state(), version: -1 },
|
||||
{ ...state(), version: 1.5 },
|
||||
{ ...state(), accessMode: 'approval' },
|
||||
{ ...state(), allowedSubjectIds: 'viewer' },
|
||||
{ ...state(), allowedSubjectIds: [''] },
|
||||
{ ...state(), allowedSubjectIds: [4] },
|
||||
{ ...state(), sessionMode: 'fork-readonly' },
|
||||
{ ...state(), allowsFork: 'yes' },
|
||||
{ ...state(), allowsFileUpload: 'yes' },
|
||||
{ ...state(), expiresAt: 4 },
|
||||
{ ...state(), expiresAt: 'not-a-date' },
|
||||
]
|
||||
for (const value of invalid) expect(parseShareAccessState(value), JSON.stringify(value)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
/** Lifecycle authority frames are id-less and validated independently from RPC envelopes. */
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseGatewayFrame, parseRelayFrame, parseTunnelWorkerEvent, LIVESHARE_CAPABILITIES } from '../src/tunnel-protocol.ts'
|
||||
|
||||
const registrationToken = '12345678-1234-4123-8123-123456789abc'
|
||||
const state = { type: 'share-access-state', version: 12, accessMode: 'selected',
|
||||
allowedSubjectIds: ['identity-key'], sessionMode: 'write', allowsFileUpload: false,
|
||||
expiresAt: '2026-10-09T00:00:00Z' }
|
||||
|
||||
describe('Relay authority snapshot frame', () => {
|
||||
it('accepts lifecycle wire and IPC snapshots without an RPC id', () => {
|
||||
expect(parseRelayFrame(JSON.stringify(state))).toEqual(state)
|
||||
expect(parseTunnelWorkerEvent({ ...state, registrationToken, shareId: 'share' })).toEqual({ ...state, registrationToken, shareId: 'share' })
|
||||
expect(parseGatewayFrame(JSON.stringify(state))).toBeUndefined()
|
||||
expect(LIVESHARE_CAPABILITIES).toContain('share-access-state')
|
||||
})
|
||||
it.each([
|
||||
{ version: -1 }, { version: 0.5 }, { accessMode: 'future' }, { sessionMode: 'future' },
|
||||
{ allowedSubjectIds: [1] }, { allowedSubjectIds: [''] }, { expiresAt: 'not-a-time' },
|
||||
])('refuses malformed authority fields %j', (fields) => {
|
||||
expect(parseRelayFrame(JSON.stringify({ ...state, ...fields }))).toBeUndefined()
|
||||
expect(parseTunnelWorkerEvent({ ...state, registrationToken, shareId: 'share', ...fields })).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('share access-state file uploads', () => {
|
||||
it('defaults uploads off when the frame omits the field', () => {
|
||||
const { allowsFileUpload: _ignored, ...legacy } = state
|
||||
expect(parseRelayFrame(JSON.stringify(legacy))).toMatchObject({ allowsFileUpload: false })
|
||||
})
|
||||
|
||||
it('carries an explicit upload permission through', () => {
|
||||
expect(parseRelayFrame(JSON.stringify({ ...state, allowsFileUpload: true })))
|
||||
.toMatchObject({ allowsFileUpload: true })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,670 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* The viewer page carrier: where it posts each read, how it numbers streams, and how it classifies what
|
||||
* went wrong as a retryable carrier loss or the peer's terminal refusal.
|
||||
*/
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { installViewerCarrier, viewerCarrierScript, type ViewerCarrierOptions } from '../src/viewer-carrier.ts'
|
||||
|
||||
/** Page globals the carrier installs. */
|
||||
interface CarrierGlobals {
|
||||
__DSH_LIVESHARE_VIEWER__?: { readonly basePath: string; readonly shareId: string; readonly sessionId: string }
|
||||
__DSH_TRANSPORT__?: {
|
||||
fetch(input: RequestInfo | URL, init: RequestInit): Promise<Response>
|
||||
openStream(endpoint: string, payload: unknown, signal: AbortSignal): AsyncIterable<unknown>
|
||||
}
|
||||
}
|
||||
|
||||
interface MarkedFailure {
|
||||
readonly dshRemoteStreamFailure?: { readonly kind: 'carrier' | 'remote'; readonly code?: string; readonly details?: object }
|
||||
}
|
||||
|
||||
/** One request the carrier posted. */
|
||||
interface Posted {
|
||||
readonly url: string
|
||||
readonly op: string
|
||||
readonly id?: number
|
||||
readonly endpoint?: string
|
||||
readonly payload?: unknown
|
||||
readonly path?: string
|
||||
readonly body?: unknown
|
||||
}
|
||||
|
||||
const OPTIONS: ViewerCarrierOptions = { basePath: '', shareId: 'share-1', sessionId: 'fx-alpha', readTimeoutMs: 30_000 }
|
||||
const page = globalThis as CarrierGlobals
|
||||
const pristineFetch = globalThis.fetch
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
// The carrier replaces `globalThis.fetch` directly, so a test that installed it without a stub
|
||||
// would otherwise leave its wrapper on every later test.
|
||||
globalThis.fetch = pristineFetch
|
||||
delete page.__DSH_LIVESHARE_VIEWER__
|
||||
delete page.__DSH_TRANSPORT__
|
||||
})
|
||||
|
||||
/**
|
||||
* Install the carrier over a stubbed Relay.
|
||||
* @param answer - Answers one posted request; a rejection is a read the browser could not send.
|
||||
* @param options - Carrier options.
|
||||
* @returns The installed transport and every posted request.
|
||||
*/
|
||||
function carrier(
|
||||
answer: (request: Posted, index: number, init: RequestInit) => Promise<Response> | Response,
|
||||
options: ViewerCarrierOptions = OPTIONS,
|
||||
) {
|
||||
const posted: Posted[] = []
|
||||
vi.stubGlobal('fetch', vi.fn(async (input: unknown, init?: RequestInit) => {
|
||||
if (typeof init?.body !== 'string') throw new Error('carrier posted a non-string body')
|
||||
const request = { url: String(input), ...JSON.parse(init.body) as Omit<Posted, 'url'> }
|
||||
posted.push(request)
|
||||
return await answer(request, posted.length - 1, init)
|
||||
}))
|
||||
installViewerCarrier(options)
|
||||
const transport = page.__DSH_TRANSPORT__
|
||||
if (transport === undefined) throw new Error('carrier installed no transport')
|
||||
return { transport, posted }
|
||||
}
|
||||
|
||||
/** A JSON Relay answer. */
|
||||
function json(body: unknown, status = 200): Response {
|
||||
return new Response(body === undefined ? '' : JSON.stringify(body), {
|
||||
status, headers: { 'content-type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Open one stream against Relay answers given in order; the last one repeats.
|
||||
* @param answers - Answers, in order.
|
||||
* @returns Values the consumer saw, the error it saw, and every posted request.
|
||||
*/
|
||||
async function readStream(answers: readonly { readonly status: number; readonly body: unknown }[]) {
|
||||
const { transport, posted } = carrier((_request, index) => {
|
||||
const answer = answers[Math.min(index, answers.length - 1)] ?? { status: 200, body: { end: true } }
|
||||
return json(answer.body, answer.status)
|
||||
})
|
||||
const values: unknown[] = []
|
||||
try {
|
||||
for await (const value of transport.openStream('session/follow', { address: 'x' }, new AbortController().signal)) {
|
||||
values.push(value)
|
||||
}
|
||||
return { values, error: undefined, posted }
|
||||
} catch (error) {
|
||||
return { values, error, posted }
|
||||
}
|
||||
}
|
||||
|
||||
function markerOf(error: unknown): MarkedFailure['dshRemoteStreamFailure'] {
|
||||
return (error as MarkedFailure | undefined)?.dshRemoteStreamFailure
|
||||
}
|
||||
|
||||
const OPENED = { status: 200, body: { opened: true } }
|
||||
|
||||
describe('viewer carrier installation', () => {
|
||||
it('names the share the page presents and posts every read to that share', async () => {
|
||||
const { posted } = carrier(() => json({ end: true }), { ...OPTIONS, basePath: '/relay', shareId: 'share 1/x' })
|
||||
expect(page.__DSH_LIVESHARE_VIEWER__).toEqual({ basePath: '/relay', shareId: 'share 1/x', sessionId: 'fx-alpha' })
|
||||
for await (const value of page.__DSH_TRANSPORT__!.openStream('session/follow', {}, new AbortController().signal)) void value
|
||||
expect(posted[0]?.url).toBe('/relay/__share/rpc?shareId=share%201%2Fx')
|
||||
})
|
||||
|
||||
it('posts to the bare read channel when the page names no share', async () => {
|
||||
const { transport, posted } = carrier(() => json({ end: true }), { ...OPTIONS, shareId: '' })
|
||||
for await (const value of transport.openStream('session/follow', {}, new AbortController().signal)) void value
|
||||
expect(posted[0]?.url).toBe('/__share/rpc')
|
||||
})
|
||||
|
||||
it('installs both globals from its own script text and escapes markup in option values', () => {
|
||||
const script = viewerCarrierScript({ ...OPTIONS, shareId: '</script><b>' })
|
||||
expect(script).not.toContain('</script>')
|
||||
expect(script).toContain('\\u003c/script>')
|
||||
;(0, eval)(script)
|
||||
expect(page.__DSH_LIVESHARE_VIEWER__).toEqual({ basePath: '', shareId: '</script><b>', sessionId: 'fx-alpha' })
|
||||
expect(typeof page.__DSH_TRANSPORT__?.fetch).toBe('function')
|
||||
expect(typeof page.__DSH_TRANSPORT__?.openStream).toBe('function')
|
||||
})
|
||||
})
|
||||
|
||||
describe('viewer carrier stream ids', () => {
|
||||
/**
|
||||
* Open `count` streams on one page and report the ids they opened under.
|
||||
* @param random - What the page's id seed draw writes, or undefined for the environment's own.
|
||||
* @param count - Streams to open.
|
||||
* @returns The `stream-open` ids in order.
|
||||
*/
|
||||
async function pageStreamIds(random: ((array: Uint32Array) => unknown) | undefined, count: number): Promise<number[]> {
|
||||
if (random !== undefined) vi.stubGlobal('crypto', { getRandomValues: random })
|
||||
const { transport, posted } = carrier(() => json({ end: true }))
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
for await (const value of transport.openStream('session/follow', {}, new AbortController().signal)) void value
|
||||
}
|
||||
return posted.filter(request => request.op === 'stream-open').map(request => request.id ?? -1)
|
||||
}
|
||||
const seeded = (seed: number) => (array: Uint32Array): Uint32Array => {
|
||||
array[0] = seed
|
||||
return array
|
||||
}
|
||||
|
||||
it('numbers a page from its own seeded id, not from one', async () => {
|
||||
expect(await pageStreamIds(seeded(0x1000_0000), 2)).toEqual([0x1000_0001, 0x1000_0002])
|
||||
})
|
||||
|
||||
it('gives two pages of one share disjoint id windows', async () => {
|
||||
const first = await pageStreamIds(seeded(0x1000_0000), 3)
|
||||
const second = await pageStreamIds(seeded(0x2000_0000), 3)
|
||||
expect(second.filter(id => first.includes(id))).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps every id inside the positive window', async () => {
|
||||
expect(await pageStreamIds(seeded(0xffff_ffff), 1)).toEqual([0xffff_ffff % 0x7fff_ff00 + 1])
|
||||
expect(await pageStreamIds(() => [], 1)).toEqual([1])
|
||||
})
|
||||
|
||||
it('seeds the id space from the page environment', async () => {
|
||||
const ids = await pageStreamIds(undefined, 2)
|
||||
expect(ids[0]).toBeGreaterThanOrEqual(1)
|
||||
expect(ids[1]).toBe((ids[0] ?? 0) + 1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('viewer carrier streams', () => {
|
||||
it('opens, polls through pending answers, yields batches and single values, and stops at the end', async () => {
|
||||
const { values, error, posted } = await readStream([
|
||||
OPENED,
|
||||
{ status: 200, body: { pending: true } },
|
||||
{ status: 200, body: { values: [1, 2] } },
|
||||
{ status: 200, body: { value: 3 } },
|
||||
{ status: 200, body: { end: true } },
|
||||
])
|
||||
expect(error).toBeUndefined()
|
||||
expect(values).toEqual([1, 2, 3])
|
||||
expect(posted.map(request => request.op)).toEqual([
|
||||
'stream-open', 'stream-next', 'stream-next', 'stream-next', 'stream-next', 'stream-cancel',
|
||||
])
|
||||
expect(posted[0]).toMatchObject({ endpoint: 'session/follow', payload: { address: 'x' } })
|
||||
})
|
||||
|
||||
it('reports a released stream as re-openable and stops asking for its id', async () => {
|
||||
const { error, posted } = await readStream([OPENED, { status: 404, body: { error: 'stream-not-found' } }])
|
||||
expect(markerOf(error)).toEqual({ kind: 'carrier' })
|
||||
expect(posted.map(request => request.op)).toEqual(['stream-open', 'stream-next', 'stream-cancel'])
|
||||
})
|
||||
|
||||
it('reports a stream the shared vocabulary cancelled as re-openable', async () => {
|
||||
const { error } = await readStream([
|
||||
OPENED, { status: 200, body: { failure: { code: 'gateway/cancelled', message: 'owner gateway replaced' } } },
|
||||
])
|
||||
expect(markerOf(error)).toEqual({ kind: 'carrier' })
|
||||
expect((error as Error).message).toBe('owner gateway replaced')
|
||||
})
|
||||
|
||||
it('reports a Relay that cannot answer or is failing as re-openable', async () => {
|
||||
for (const status of [408, 429, 502, 503, 504]) {
|
||||
const answer = await readStream([{ status, body: { error: 'gateway unavailable' } }])
|
||||
expect([status, markerOf(answer.error)]).toEqual([status, { kind: 'carrier' }])
|
||||
}
|
||||
const silent = await readStream([OPENED, { status: 503, body: undefined }])
|
||||
expect(markerOf(silent.error)).toEqual({ kind: 'carrier' })
|
||||
})
|
||||
|
||||
it('does not assume a plain server error is transient', async () => {
|
||||
const failed = await readStream([{ status: 500, body: { error: 'gateway/internal' } }])
|
||||
expect(markerOf(failed.error)).toEqual({ kind: 'remote', code: 'gateway/internal', details: { status: 500 } })
|
||||
const unshaped = await readStream([{ status: 500, body: { error: 'Internal failure.' } }])
|
||||
expect(markerOf(unshaped.error)).toEqual({ kind: 'remote', code: 'liveshare/read-refused', details: { status: 500 } })
|
||||
expect((unshaped.error as Error).message).toBe('session/follow refused (HTTP 500)')
|
||||
})
|
||||
|
||||
it('never yields an event a peer never answered', async () => {
|
||||
const { transport, posted } = carrier((_request, index) => new Response(index === 0 ? '{"opened":true}' : 'not json'))
|
||||
const values: unknown[] = []
|
||||
let error: unknown
|
||||
try {
|
||||
for await (const value of transport.openStream('session/follow', {}, new AbortController().signal)) values.push(value)
|
||||
} catch (caught) {
|
||||
error = caught
|
||||
}
|
||||
expect(values).toEqual([])
|
||||
expect(markerOf(error)).toEqual({ kind: 'carrier' })
|
||||
expect(posted.map(request => request.op)).toEqual(['stream-open', 'stream-next', 'stream-cancel'])
|
||||
const empty = await readStream([{ status: 200, body: [] }])
|
||||
expect(markerOf(empty.error)).toEqual({ kind: 'carrier' })
|
||||
// The 200 open reached the owner, so a body the page cannot read still releases the stream id.
|
||||
expect(empty.posted.map(request => request.op)).toEqual(['stream-open', 'stream-cancel'])
|
||||
})
|
||||
|
||||
it('keeps an authentication refusal terminal whatever code its body carries', async () => {
|
||||
for (const status of [401, 403]) {
|
||||
for (const code of ['stream-not-found', 'gateway/cancelled']) {
|
||||
const refused = await readStream([{ status, body: { error: code } }])
|
||||
expect([status, code, markerOf(refused.error)]).toEqual([status, code, { kind: 'remote', code, details: { status } }])
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('states a refusal as terminal, in either body shape, so the page cannot reconnect around it', async () => {
|
||||
const denied = await readStream([{ status: 403, body: { error: 'share-not-found' } }])
|
||||
expect(markerOf(denied.error)).toEqual({ kind: 'remote', code: 'share-not-found', details: { status: 403 } })
|
||||
expect((denied.error as Error).name).toBe('share-not-found')
|
||||
const nested = await readStream([{ status: 403, body: { error: { code: 'share-stopped', message: 'stopped' } } }])
|
||||
expect(markerOf(nested.error)).toEqual({ kind: 'remote', code: 'share-stopped', details: { status: 403 } })
|
||||
expect((nested.error as Error).message).toBe('stopped')
|
||||
const unauthorized = await readStream([{ status: 401, body: { error: 'authentication required' } }])
|
||||
expect(markerOf(unauthorized.error)).toEqual({ kind: 'remote', code: 'liveshare/read-refused', details: { status: 401 } })
|
||||
const bare = await readStream([{ status: 401, body: 'denied' }])
|
||||
expect(markerOf(bare.error)).toEqual({ kind: 'remote', code: 'liveshare/read-refused', details: { status: 401 } })
|
||||
})
|
||||
|
||||
it('keeps the code and details a refused stream frame names, and names a refusal that names none', async () => {
|
||||
const refused = await readStream([
|
||||
OPENED, { status: 200, body: { failure: { code: 'gateway/forbidden', message: 'not authorized', details: { a: 1 } } } },
|
||||
])
|
||||
expect(markerOf(refused.error)).toEqual({ kind: 'remote', code: 'gateway/forbidden', details: { a: 1 } })
|
||||
expect((refused.error as Error).name).toBe('gateway/forbidden')
|
||||
const unnamed = await readStream([OPENED, { status: 200, body: { failure: {} } }])
|
||||
expect(markerOf(unnamed.error)).toEqual({ kind: 'remote', code: 'liveshare/read-refused', details: {} })
|
||||
expect((unnamed.error as Error).message).toBe('session/follow')
|
||||
})
|
||||
|
||||
it('reports a refused stream open once, classified by the owner code rather than as a lost stream', async () => {
|
||||
// The owner answers a refused open as a 200 failure frame and registers no stream for that id, so the
|
||||
// carrier must surface the refusal instead of polling an id that would read `stream-not-found`.
|
||||
const refused = () => json({ failure: {
|
||||
code: 'remote-access/denied',
|
||||
message: 'remote access: job/list: access denied (liveshare/read-only)',
|
||||
details: { action: 'job/list', reason: 'liveshare/read-only' },
|
||||
} })
|
||||
const { transport, posted } = carrier(refused)
|
||||
let error: unknown
|
||||
try {
|
||||
for await (const value of transport.openStream('job/list', {}, new AbortController().signal)) void value
|
||||
} catch (caught) {
|
||||
error = caught
|
||||
}
|
||||
expect(markerOf(error)).toEqual({
|
||||
kind: 'remote',
|
||||
code: 'remote-access/denied',
|
||||
details: { action: 'job/list', reason: 'liveshare/read-only' },
|
||||
})
|
||||
// One attempt: no `stream-next` poll, and no re-open a supervisor could drive from a carrier marker.
|
||||
expect(posted.map(request => request.op)).toEqual(['stream-open'])
|
||||
})
|
||||
|
||||
it('classifies an open-time failure frame by its exact owner code', async () => {
|
||||
/**
|
||||
* Open one stream whose open is refused with one code.
|
||||
* @param code - owner code the failure frame carries.
|
||||
* @returns the failure marker the consumer saw and the ops the carrier posted.
|
||||
*/
|
||||
const refusedWith = async (code: string) => {
|
||||
const { transport, posted } = carrier(() => json({ failure: { code, message: code } }))
|
||||
try {
|
||||
for await (const value of transport.openStream('job/list', {}, new AbortController().signal)) void value
|
||||
return { marker: undefined, ops: posted.map(request => request.op) }
|
||||
} catch (error) {
|
||||
return { marker: markerOf(error), ops: posted.map(request => request.op) }
|
||||
}
|
||||
}
|
||||
// Lost-stream codes keep the supervisor's reopen rule; every other code is an owner refusal, so the
|
||||
// carrier posts nothing after the open and the failure is reported once.
|
||||
expect((await refusedWith('stream-not-found')).marker).toEqual({ kind: 'carrier' })
|
||||
expect((await refusedWith('gateway/cancelled')).marker).toEqual({ kind: 'carrier' })
|
||||
expect(await refusedWith('remote-access/denied')).toEqual({
|
||||
marker: { kind: 'remote', code: 'remote-access/denied', details: {} },
|
||||
ops: ['stream-open'],
|
||||
})
|
||||
expect(await refusedWith('liveshare/read-only')).toEqual({
|
||||
marker: { kind: 'remote', code: 'liveshare/read-only', details: {} },
|
||||
ops: ['stream-open'],
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps a refused, revoked, or expired read terminal', async () => {
|
||||
for (const [status, code] of [
|
||||
[401, 'viewer-not-authorized'], [403, 'share-stopped'], [403, 'share-revoked'], [403, 'share-expired'],
|
||||
] as const) {
|
||||
const refused = await readStream([{ status, body: { error: code } }])
|
||||
expect([status, code, markerOf(refused.error)]).toEqual([status, code, { kind: 'remote', code, details: { status } }])
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('viewer carrier read losses and cancellation', () => {
|
||||
it('reports a read the browser could not send, or its own expired budget, as re-openable', async () => {
|
||||
for (const failure of [
|
||||
new TypeError('Failed to fetch'),
|
||||
new DOMException('The operation was aborted due to timeout', 'TimeoutError'),
|
||||
]) {
|
||||
const { transport, posted } = carrier(() => Promise.reject(failure))
|
||||
let error: unknown
|
||||
try {
|
||||
for await (const value of transport.openStream('session/follow', {}, new AbortController().signal)) void value
|
||||
} catch (caught) {
|
||||
error = caught
|
||||
}
|
||||
expect(markerOf(error)).toEqual({ kind: 'carrier' })
|
||||
expect(posted.map(request => request.op)).toEqual(['stream-open'])
|
||||
}
|
||||
})
|
||||
|
||||
it('reports a read the network dropped after the stream opened as re-openable, and swallows its cancel', async () => {
|
||||
const { transport, posted } = carrier((_request, index) => index === 0
|
||||
? json({ opened: true })
|
||||
: Promise.reject(new TypeError('NetworkError when attempting to fetch resource.')))
|
||||
let error: unknown
|
||||
try {
|
||||
for await (const value of transport.openStream('session/follow', {}, new AbortController().signal)) void value
|
||||
} catch (caught) {
|
||||
error = caught
|
||||
}
|
||||
expect(markerOf(error)).toEqual({ kind: 'carrier' })
|
||||
await vi.waitFor(() => {
|
||||
expect(posted.map(request => request.op)).toEqual(['stream-open', 'stream-next', 'stream-cancel'])
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses to open a stream whose consumer already left', async () => {
|
||||
const { transport, posted } = carrier(() => json({ opened: true }))
|
||||
const left = new AbortController()
|
||||
left.abort(new Error('left'))
|
||||
await expect(transport.openStream('session/follow', {}, left.signal)[Symbol.asyncIterator]().next())
|
||||
.rejects.toThrow('left')
|
||||
expect(posted).toEqual([])
|
||||
})
|
||||
|
||||
it.each(['stream-open', 'stream-next'] as const)('ignores a late %s answer after cancellation and cancels once', async (pendingOp) => {
|
||||
const requested = Promise.withResolvers<undefined>()
|
||||
const answer = Promise.withResolvers<Response>()
|
||||
const { transport, posted } = carrier((request) => {
|
||||
if (request.op === pendingOp) {
|
||||
requested.resolve(undefined)
|
||||
return answer.promise
|
||||
}
|
||||
return json({ opened: true })
|
||||
})
|
||||
const leaving = new AbortController()
|
||||
const reading = transport.openStream('session/control', {}, leaving.signal)[Symbol.asyncIterator]().next()
|
||||
await requested.promise
|
||||
const failure = new Error('viewer left the page')
|
||||
leaving.abort(failure)
|
||||
answer.resolve(json(pendingOp === 'stream-open' ? { opened: true } : { value: 'late' }))
|
||||
await expect(reading).rejects.toBe(failure)
|
||||
await vi.waitFor(() => { expect(posted.filter(request => request.op === 'stream-cancel')).toHaveLength(1) })
|
||||
})
|
||||
|
||||
it('stops a received batch at the consumer\u2019s cancellation', async () => {
|
||||
const { transport } = carrier(request => json(request.op === 'stream-next' ? { values: ['a', 'b'] } : { opened: true }))
|
||||
const leaving = new AbortController()
|
||||
const iterator = transport.openStream('session/control', {}, leaving.signal)[Symbol.asyncIterator]()
|
||||
expect(await iterator.next()).toEqual({ done: false, value: 'a' })
|
||||
const failure = new Error('viewer switched Session')
|
||||
leaving.abort(failure)
|
||||
await expect(iterator.next()).rejects.toBe(failure)
|
||||
})
|
||||
|
||||
it('cancels the stream when its consumer stops reading early', async () => {
|
||||
const { transport, posted } = carrier(request => json(request.op === 'stream-next' ? { value: 'a' } : { opened: true }))
|
||||
for await (const value of transport.openStream('session/control', {}, new AbortController().signal)) {
|
||||
expect(value).toBe('a')
|
||||
break
|
||||
}
|
||||
expect(posted.map(request => request.op)).toEqual(['stream-open', 'stream-next', 'stream-cancel'])
|
||||
})
|
||||
|
||||
it('keeps the caller\u2019s own cancellation out of the reconnect path and releases the abandoned open', async () => {
|
||||
const { transport, posted } = carrier((_request, _index, init) => new Promise<Response>((_resolve, reject) => {
|
||||
init.signal?.addEventListener('abort', () => { reject(new Error('aborted by the caller')) }, { once: true })
|
||||
}))
|
||||
const leaving = new AbortController()
|
||||
const reading = (async (): Promise<unknown> => {
|
||||
try {
|
||||
for await (const value of transport.openStream('session/follow', {}, leaving.signal)) void value
|
||||
return undefined
|
||||
} catch (error) {
|
||||
return error
|
||||
}
|
||||
})()
|
||||
await Promise.resolve()
|
||||
leaving.abort(new Error('viewer left the page'))
|
||||
const error = await reading
|
||||
expect(error).toBeInstanceOf(Error)
|
||||
expect(markerOf(error)).toBeUndefined()
|
||||
// The open may already have reached the owner, so the page releases that stream id.
|
||||
expect(posted.map(request => request.op)).toEqual(['stream-open', 'stream-cancel'])
|
||||
expect(posted[1]?.id).toBe(posted[0]?.id)
|
||||
})
|
||||
})
|
||||
|
||||
describe('viewer carrier unary calls', () => {
|
||||
/**
|
||||
* Post one Connection call through the carrier.
|
||||
* @param answer - The Relay's answer.
|
||||
* @param input - Route the Connection caller posts.
|
||||
* @param body - Request body; `null` posts none.
|
||||
* @returns The envelope the caller parses, and the request the carrier posted.
|
||||
*/
|
||||
async function call(answer: Response, input: string | URL | Request = 'api/session/prompt', body: unknown = {
|
||||
type: 'client-request', rpcId: 'rpc-1', method: 'session/prompt', payload: { args: {} },
|
||||
}) {
|
||||
const { transport, posted } = carrier(() => answer)
|
||||
const response = await transport.fetch(input, {
|
||||
method: 'POST', ...(body === null ? {} : { body: JSON.stringify(body) }),
|
||||
})
|
||||
return { envelope: await response.json() as Record<string, unknown>, posted }
|
||||
}
|
||||
|
||||
it('posts the owner\u2019s /api path and returns the owner\u2019s answer unchanged', async () => {
|
||||
const { envelope, posted } = await call(json({ type: 'server-response', rpcId: 'rpc-1', result: { ok: true } }),
|
||||
'https://relay.example/share/x/api/session/list')
|
||||
expect(envelope).toEqual({ type: 'server-response', rpcId: 'rpc-1', result: { ok: true } })
|
||||
expect(posted[0]).toMatchObject({ op: 'call', path: '/api/session/list', body: { rpcId: 'rpc-1' } })
|
||||
const relative = await call(json({ ok: true }))
|
||||
expect(relative.posted[0]?.path).toBe('/api/session/prompt')
|
||||
const request = await call(json({ ok: true }), new Request('https://relay.example/share/x/api/session/page'))
|
||||
expect(request.posted[0]?.path).toBe('/api/session/page')
|
||||
const unmarked = await call(json({ ok: true }), 'https://relay.example/health', null)
|
||||
expect(unmarked.posted[0]).toEqual({ url: '/__share/rpc?shareId=share-1', op: 'call', path: '/health' })
|
||||
})
|
||||
|
||||
it('rebuilds a refused call as the Connection failure the peer\u2019s code names', async () => {
|
||||
for (const code of ['share-not-writable', 'source-write-unavailable']) {
|
||||
for (const body of [{ error: code, message: 'refused by the host' }, { error: { code, message: 'refused by the host' } }]) {
|
||||
const { envelope } = await call(json(body, 403))
|
||||
expect(envelope).toEqual({
|
||||
type: 'server-response',
|
||||
rpcId: 'rpc-1',
|
||||
result: { ok: false, error: { code, message: 'refused by the host', details: { status: 403 } } },
|
||||
})
|
||||
}
|
||||
}
|
||||
const unnamed = await call(json({ message: 'refused' }, 403))
|
||||
expect(unnamed.envelope.result).toEqual({
|
||||
ok: false, error: { code: 'liveshare/relay-error', message: 'refused', details: { status: 403 } },
|
||||
})
|
||||
const sentence = await call(json({ error: 'the owner said no', message: 'refused' }, 403))
|
||||
expect(sentence.envelope.result).toMatchObject({ error: { code: 'liveshare/relay-error', message: 'refused' } })
|
||||
const silent = await call(json(undefined, 502), 'api/session/list', [])
|
||||
expect(silent.envelope).toEqual({
|
||||
type: 'server-response',
|
||||
rpcId: '',
|
||||
result: { ok: false, error: { code: 'liveshare/relay-error', message: 'Relay answered HTTP 502', details: { status: 502 } } },
|
||||
})
|
||||
const unreadable = await call(json(['not', 'a', 'record']))
|
||||
expect(unreadable.envelope.result).toMatchObject({ ok: false, error: { details: { status: 200 } } })
|
||||
})
|
||||
|
||||
it('reports a call the browser could not send as re-openable, and the caller\u2019s cancellation as itself', async () => {
|
||||
const { transport } = carrier(() => Promise.reject(new TypeError('Failed to fetch')))
|
||||
await expect(transport.fetch('api/session/list', { method: 'POST', body: '{}' })).rejects.toSatisfy(
|
||||
(error: unknown) => markerOf(error)?.kind === 'carrier',
|
||||
)
|
||||
const aborted = new AbortController()
|
||||
aborted.abort()
|
||||
const reason = new Error('caller left')
|
||||
const cancelled = carrier(() => Promise.reject(reason))
|
||||
await expect(cancelled.transport.fetch('api/session/list', { method: 'POST', body: '{}', signal: aborted.signal }))
|
||||
.rejects.toBe(reason)
|
||||
})
|
||||
})
|
||||
|
||||
describe('viewer carrier forwarded page routes', () => {
|
||||
/**
|
||||
* Install the carrier over a page fetch that answers everything itself.
|
||||
* @returns The Fetch replacement the carrier captured, and every request it received.
|
||||
*/
|
||||
function directFetch() {
|
||||
const direct = vi.fn(async (input: unknown) => new Response(`direct:${String(input)}`))
|
||||
vi.stubGlobal('fetch', direct)
|
||||
installViewerCarrier(OPTIONS)
|
||||
return direct
|
||||
}
|
||||
|
||||
it('forwards a page-origin owner route the Relay serves no answer for', async () => {
|
||||
const { posted } = carrier(() => json({ apps: ['finder'] }))
|
||||
const response = await globalThis.fetch('open-in-app/apps')
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.json()).toEqual({ apps: ['finder'] })
|
||||
expect(posted[0]).toMatchObject({ op: 'call', path: '/open-in-app/apps', body: {} })
|
||||
})
|
||||
|
||||
it('forwards the /api owner route a direct fetch never sends through the Connection transport', async () => {
|
||||
const { posted } = carrier(() => json({ name: 'owner-host', available: true, fileManager: 'finder' }))
|
||||
expect(await (await globalThis.fetch('/api/present.host')).json()).toMatchObject({ name: 'owner-host' })
|
||||
expect(posted[0]).toMatchObject({ op: 'call', path: '/api/present.host' })
|
||||
})
|
||||
|
||||
it('reads the owner path under the Relay\u2019s own base path and keeps the owner\u2019s refusal status', async () => {
|
||||
const { posted } = carrier(() => json({ error: 'route-unavailable' }, 403))
|
||||
const response = await globalThis.fetch('/relay/s/abc/open-in-app/apps')
|
||||
expect(response.status).toBe(403)
|
||||
expect(await response.json()).toEqual({ error: 'route-unavailable' })
|
||||
expect(posted[0]).toMatchObject({ op: 'call', path: '/open-in-app/apps' })
|
||||
})
|
||||
|
||||
it('forwards a route only when it starts a path segment', async () => {
|
||||
const below = carrier(() => json({ apps: ['finder'] }))
|
||||
expect(await (await globalThis.fetch('/relay/s/abc/open-in-app/apps/foo')).json()).toEqual({ apps: ['finder'] })
|
||||
expect(below.posted[0]).toMatchObject({ op: 'call', path: '/open-in-app/apps/foo' })
|
||||
const exact = carrier(() => json({ name: 'owner-host' }))
|
||||
expect(await (await globalThis.fetch('/relay/s/abc/api/present.host')).json()).toEqual({ name: 'owner-host' })
|
||||
expect(exact.posted[0]).toMatchObject({ op: 'call', path: '/api/present.host' })
|
||||
})
|
||||
|
||||
it('does not forward a prefix neighbour of a forwarded route', async () => {
|
||||
const direct = directFetch()
|
||||
expect(await (await globalThis.fetch('/api/present.hostile')).text()).toBe('direct:/api/present.hostile')
|
||||
expect(await (await globalThis.fetch('/x/open-in-app/apps-foo')).text()).toBe('direct:/x/open-in-app/apps-foo')
|
||||
expect(await (await globalThis.fetch('/api/present.hostile?x=1')).text()).toBe('direct:/api/present.hostile?x=1')
|
||||
expect(direct).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('leaves a cross-origin request that names a forwarded route to the page fetch', async () => {
|
||||
const direct = directFetch()
|
||||
expect(await (await globalThis.fetch('https://cdn.example/api/present.host')).text())
|
||||
.toBe('direct:https://cdn.example/api/present.host')
|
||||
expect(await (await globalThis.fetch('https://cdn.example/x/open-in-app/apps')).text())
|
||||
.toBe('direct:https://cdn.example/x/open-in-app/apps')
|
||||
expect(direct).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('forwards an absolute request the page makes to its own origin', async () => {
|
||||
const { posted } = carrier(() => json({ name: 'owner-host' }))
|
||||
const origin = new URL(document.baseURI).origin
|
||||
expect(await (await globalThis.fetch(`${origin}/relay/s/abc/api/present.host`)).json())
|
||||
.toMatchObject({ name: 'owner-host' })
|
||||
expect(posted[0]).toMatchObject({ op: 'call', path: '/api/present.host' })
|
||||
})
|
||||
|
||||
it('leaves a relative route to the page fetch once the page base names another origin', async () => {
|
||||
const direct = directFetch()
|
||||
const base = document.createElement('base')
|
||||
base.href = 'https://cdn.example/'
|
||||
document.head.append(base)
|
||||
try {
|
||||
expect(await (await globalThis.fetch('api/present.host')).text()).toBe('direct:api/present.host')
|
||||
expect(direct).toHaveBeenCalledTimes(1)
|
||||
} finally {
|
||||
base.remove()
|
||||
}
|
||||
})
|
||||
|
||||
it('forwards a hit whose page URL carries a query without passing it to the owner', async () => {
|
||||
const { posted } = carrier(() => json({ name: 'owner-host', available: true, fileManager: 'finder' }))
|
||||
expect(await (await globalThis.fetch('/relay/s/abc/api/present.host?x=1#frag')).json()).toMatchObject({ name: 'owner-host' })
|
||||
expect(posted[0]).toMatchObject({ op: 'call', path: '/api/present.host' })
|
||||
})
|
||||
|
||||
it('leaves every other request to the page\u2019s own fetch', async () => {
|
||||
const direct = directFetch()
|
||||
expect(await (await globalThis.fetch('health')).text()).toBe('direct:health')
|
||||
expect(direct).toHaveBeenCalledExactlyOnceWith('health', undefined)
|
||||
})
|
||||
|
||||
it('keeps the receiver of the page fetch it replaced', async () => {
|
||||
const receivers: unknown[] = []
|
||||
const direct = vi.fn(function (this: unknown, input: unknown) {
|
||||
receivers.push(this)
|
||||
return Promise.resolve(new Response(`direct:${String(input)}`))
|
||||
})
|
||||
vi.stubGlobal('fetch', direct)
|
||||
installViewerCarrier(OPTIONS)
|
||||
await globalThis.fetch('health')
|
||||
expect(receivers).toEqual([globalThis])
|
||||
})
|
||||
|
||||
it('does not forward a route that acts on the owner\u2019s machine', async () => {
|
||||
const direct = directFetch()
|
||||
expect(await (await globalThis.fetch('open-in-app/open', { method: 'POST', body: '{"app":"finder"}' })).text())
|
||||
.toBe('direct:open-in-app/open')
|
||||
expect(direct).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('carries a forwarded request body and its abort signal to the owner', async () => {
|
||||
const { posted } = carrier(() => json({ name: 'owner-host' }))
|
||||
const controller = new AbortController()
|
||||
const response = await globalThis.fetch('/api/present.host', {
|
||||
body: '{"app":"finder"}',
|
||||
signal: controller.signal,
|
||||
})
|
||||
expect(await response.json()).toEqual({ name: 'owner-host' })
|
||||
expect(posted[0]).toMatchObject({ op: 'call', path: '/api/present.host', body: { app: 'finder' } })
|
||||
})
|
||||
|
||||
it('forwards a GET whose init states no body or signal', async () => {
|
||||
const { posted } = carrier(() => json({ name: 'owner-host' }))
|
||||
expect(await (await globalThis.fetch('/api/present.host', { method: 'GET' })).json())
|
||||
.toEqual({ name: 'owner-host' })
|
||||
expect(posted[0]).toMatchObject({ op: 'call', path: '/api/present.host', body: {} })
|
||||
})
|
||||
|
||||
it('treats a null page signal as no signal', async () => {
|
||||
const { posted } = carrier(() => json({ name: 'owner-host' }))
|
||||
// A page handler may pass `signal: null`; the carrier states it as no signal rather than as one.
|
||||
expect(await (await globalThis.fetch('/api/present.host', { signal: null })).json())
|
||||
.toEqual({ name: 'owner-host' })
|
||||
expect(posted[0]).toMatchObject({ op: 'call', path: '/api/present.host' })
|
||||
})
|
||||
|
||||
it('answers a forwarded route whose owner reply carries no body', async () => {
|
||||
const { posted } = carrier(() => new Response('', { status: 200 }))
|
||||
const response = await globalThis.fetch('/api/present.host')
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.text()).toBe('null')
|
||||
expect(posted).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('reads the target and method from a Request object', async () => {
|
||||
const { posted } = carrier(() => json({ apps: ['finder'] }))
|
||||
const response = await globalThis.fetch(new Request(new URL('open-in-app/apps', document.baseURI)))
|
||||
expect(await response.json()).toEqual({ apps: ['finder'] })
|
||||
expect(posted[0]).toMatchObject({ op: 'call', path: '/open-in-app/apps' })
|
||||
})
|
||||
|
||||
it('leaves a target the page base cannot resolve to the page fetch', async () => {
|
||||
const direct = directFetch()
|
||||
// `new URL` rejects this target, so it cannot name a forwarded route.
|
||||
expect(await (await globalThis.fetch('http://[invalid')).text()).toBe('direct:http://[invalid')
|
||||
expect(direct).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.base.client.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types",
|
||||
"tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo"
|
||||
},
|
||||
"files": [
|
||||
"src/viewer-carrier.ts",
|
||||
"src/viewer-states.ts",
|
||||
"src/identity/types.ts"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types",
|
||||
"tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo"
|
||||
},
|
||||
"files": [
|
||||
"src/index.ts",
|
||||
"src/tunnel-protocol.ts",
|
||||
"src/viewer-carrier.ts",
|
||||
"src/viewer-states.ts",
|
||||
"src/identity/index.ts",
|
||||
"src/identity/keys.ts",
|
||||
"src/identity/mock.ts",
|
||||
"src/identity/types.ts"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "../../util/brand"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.host.json" },
|
||||
{ "path": "./tsconfig.client.json" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { UserConfig } from 'tsdown'
|
||||
import { defineConfig } from 'tsdown'
|
||||
|
||||
/**
|
||||
* Dependency-free code shared by the owner bundle and the Relay. The package carries two compiler
|
||||
* faces — a Host leaf for the wire codecs and identity contract, and a browser leaf for the viewer
|
||||
* carrier — but only the Host face publishes runtime modules; the carrier reaches a browser as
|
||||
* generated source text, so it needs no client bundle.
|
||||
*/
|
||||
export default defineConfig(({ env }) => {
|
||||
if (env?.DSH_BUILD_FACE === 'client') return { entry: '' } satisfies UserConfig
|
||||
return {
|
||||
entry: [
|
||||
'lib/types/index.js',
|
||||
],
|
||||
outDir: 'lib',
|
||||
format: ['esm'],
|
||||
platform: 'node',
|
||||
target: 'es2024',
|
||||
fixedExtension: false,
|
||||
dts: false,
|
||||
clean: false,
|
||||
} satisfies UserConfig
|
||||
})
|
||||
@@ -57,8 +57,8 @@
|
||||
en: 843f9f4319ca2ae3
|
||||
zh: 218bf355816d4ff6
|
||||
/deepseek-ai-dsh-subagent/understand-the-implementation/ownership-and-invariants:
|
||||
en: 6b8d5667426731cf
|
||||
zh: da16e81e87e7fdf0
|
||||
en: ab5d2c41f06b8fea
|
||||
zh: 13a9ca3685fa799b
|
||||
/deepseek-ai-dsh-subagent/further-exploration:
|
||||
en: 5b0f408dd901d90a
|
||||
zh: e11866d5fd878327
|
||||
|
||||
@@ -136,7 +136,7 @@ Targets without a saved preset use the host composition and retain their histori
|
||||
- **Registration is effect-scoped** — removing a provider blocks new starts but never revokes accepted runs.
|
||||
- **Agent-message authority follows the tree** — the exact live sender and target must belong to one root. Cold delivery verifies the target descriptor and creation catalogs before restoring only the target. Final inbox admission rechecks the sender and subagent tree root; failed restoration releases the new instance.
|
||||
- **The descriptor is log-only** — a session event absent from model history and retained across compaction; the writer records the resolved child provider, model, and reasoning effort for cold resume. Historical one-shot descriptors remain readable.
|
||||
- **This runtime answers archive admission for children** ([seam](../../workspace/workspace/README.md)) — activity queries, parent-cause cancellation, and pre-step rejection use managed creation ancestors even after an intermediate creator goes offline. Agents without a published Activation use live header ancestry; ordinary forks remain independent. Labels come from a live Session observation when Session query is composed, otherwise only ids are reported. Each cancellation failure is contained. The Agent registry owns the parent’s turn, job providers own jobs, and the API Session Controller checks archived Sessions and available header ancestry.
|
||||
- **This runtime answers archive admission for children** ([seam](../../workspace/workspace/README.md)) — activity queries, parent-cause cancellation, and pre-step rejection use managed creation ancestors even after an intermediate creator goes offline. Agents without a published Activation use live header ancestry; ordinary forks remain independent. Labels use the current identity projection's latest descriptor only when it belongs to the child's own log; missing, invalid, inherited, or unlabelled identities report only the id. Reporting requires no Session query service and starts after identity projection registration. Each cancellation failure is contained. The Agent registry owns the parent’s turn, job providers own jobs, and the API Session Controller checks archived Sessions and available header ancestry.
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -136,7 +136,7 @@ kind: "package-reference"
|
||||
- **注册受 effect 作用域约束**——移除提供方会阻止新启动,但绝不撤销已接受的运行。
|
||||
- **Agent 消息权限由树决定**——确切在线发送者和目标必须属于同一个根。冷投递验证目标描述符和创建目录后仅恢复目标。最终收件箱准入重新检查发送者与 subagent 树根;恢复失败释放新建实例。
|
||||
- **描述符仅进日志**——它是会话事件,不进入模型历史,并跨压缩(compaction)保留;写入器记录解析后的子级提供方、模型与推理强度,用于冷恢复。历史 one-shot 描述符仍可读取。
|
||||
- **本 runtime 为子代理回答归档准入**([接缝](../../workspace/workspace/README.zh.md))——活动查询、以父级原因取消和步骤执行前的拒绝都使用托管实例的创建祖先,即使中间创建者已离线。尚无已发布 Activation 的 Agent 使用在线 header 血缘;普通 fork 保持独立。组合了 Session query 时通过在线 Session observation 读取名称,否则只报告 id。每次取消的失败都单独收敛。Agent 注册表拥有父级回合,job 提供方拥有任务,API Session Controller 检查已归档 Session 和可用的 header 血缘。
|
||||
- **本 runtime 为子代理回答归档准入**([接缝](../../workspace/workspace/README.zh.md))——活动查询、以父级原因取消和步骤执行前的拒绝都使用托管实例的创建祖先,即使中间创建者已离线。尚无已发布 Activation 的 Agent 使用在线 header 血缘;普通 fork 保持独立。名称取自当前身份投影中的最新 descriptor,且该 descriptor 必须属于孩子自身的日志;身份缺失、无效、来自继承或没有名称时只报告 id。报告不依赖 Session query 服务,并在身份投影注册完成后启用。每次取消的失败都单独收敛。Agent 注册表拥有父级回合,job 提供方拥有任务,API Session Controller 检查已归档 Session 和可用的 header 血缘。
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -9,22 +9,23 @@
|
||||
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type {} from '@deepseek-ai/dsh-session-query'
|
||||
import type { Session, SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionActivity, SessionActivityItem } from '@deepseek-ai/dsh-workspace'
|
||||
import { foldSubagentDescriptor } from './descriptor.ts'
|
||||
import type { SubagentIdentityProjection } from './projection-types.ts'
|
||||
|
||||
/**
|
||||
* Answer `workspace/session-activity` with the running subagent descendants of
|
||||
* the asked Session, and `workspace/session-stop` by cancelling each of them
|
||||
* as their parent would. Reject subsequent steps beneath archived ancestors.
|
||||
* All listeners live as long as `ctx`'s fiber.
|
||||
* @param ctx - context carrying the Agent registry; the Session query service is optional and only supplies labels.
|
||||
* @param ctx - context carrying the Agent registry.
|
||||
* @param residentAncestors - verified creation ancestors for an exact managed Agent, absent before publication or for unmanaged Agents.
|
||||
* @param identityOf - ready service-owned descriptor identity reader; absent or invalid descriptors yield no identity.
|
||||
*/
|
||||
export function installSubagentArchiveAdmission(
|
||||
ctx: Context,
|
||||
residentAncestors: (agent: Agent) => readonly SessionId[] | undefined,
|
||||
identityOf: (session: Session) => SubagentIdentityProjection | undefined,
|
||||
): void {
|
||||
const ancestorsOf = (agent: Agent): readonly SessionId[] => residentAncestors(agent) ?? headerAncestors(ctx, agent)
|
||||
const runningDescendants = (sessionId: SessionId): Agent[] => ctx.agents.list()
|
||||
@@ -33,7 +34,7 @@ export function installSubagentArchiveAdmission(
|
||||
const running = runningDescendants(sessionId)
|
||||
const rest = await next()
|
||||
if (running.length === 0) return rest
|
||||
const own: SessionActivity = { kind: 'subagent', items: await Promise.all(running.map(child => describe(ctx, child))) }
|
||||
const own: SessionActivity = { kind: 'subagent', items: running.map(child => describe(child, identityOf(child.session))) }
|
||||
return [own, ...rest]
|
||||
})
|
||||
ctx.on('workspace/session-stop', ({ sessionId }) => {
|
||||
@@ -74,20 +75,10 @@ function headerAncestors(ctx: Context, agent: Agent): readonly SessionId[] {
|
||||
}
|
||||
|
||||
/**
|
||||
* The child's activity item: its id, plus the durable creation label its
|
||||
* descriptor carries, read through a live Session observation. Without the
|
||||
* Session query service, or with a descriptor that is absent or unreadable,
|
||||
* the item names the child by id alone.
|
||||
* Report the child's current projected label only when its descriptor belongs
|
||||
* to the child's own log; inherited, absent, or invalid identities yield the id alone.
|
||||
*/
|
||||
async function describe(ctx: Context, child: Agent): Promise<SessionActivityItem> {
|
||||
const query = ctx.get('sessionQuery')
|
||||
if (query === undefined) return { id: child.id }
|
||||
try {
|
||||
using observation = await query.observeSession(child.id, { projectionMode: 'none' })
|
||||
const label = foldSubagentDescriptor(observation.events.slice(observation.inheritedEventCount))?.label
|
||||
return label === undefined ? { id: child.id } : { id: child.id, label }
|
||||
} catch {
|
||||
// A damaged descriptor is data damage in the child; the report still names the child.
|
||||
return { id: child.id }
|
||||
}
|
||||
function describe(child: Agent, identity: SubagentIdentityProjection | undefined): SessionActivityItem {
|
||||
const label = identity !== undefined && child.session.isOwnSeq(identity.seq) ? identity.label : undefined
|
||||
return label === undefined ? { id: child.id } : { id: child.id, label }
|
||||
}
|
||||
@@ -39,7 +39,6 @@ import { assertObjectJsonSchema } from '@deepseek-ai/dsh-tools'
|
||||
import type { ContentBlock, MessageId } from '@deepseek-ai/dsh-llm'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
|
||||
import { canonicalClientTimeZone } from '@deepseek-ai/dsh-util-time'
|
||||
import { Remote, RemoteError, TypertRemoteService, principalOf, type Principal } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import {
|
||||
@@ -70,7 +69,6 @@ import SubagentManager from './manager.ts'
|
||||
import { listDescendants as listSubagentDescendants } from './list-children.ts'
|
||||
import type { SubagentDescendantListEntry } from './list-children.ts'
|
||||
import { subagentIdentityProjectionDefinition, subagentTimingProjectionDefinition } from './projection.ts'
|
||||
import type { IdentityState } from './projection.ts'
|
||||
import { subagentCatalogProjectionDefinition } from './catalog.ts'
|
||||
|
||||
export type {} from './catalog.ts'
|
||||
@@ -196,7 +194,6 @@ export class SubagentRuntime extends TypertRemoteService {
|
||||
static inject = ['workingDirectory', 'sessionProjections']
|
||||
private providers = new Map<string, SubagentProvider>()
|
||||
private manager: SubagentManager | undefined
|
||||
private identityProjectionHandle!: ProjectionHandle<IdentityState>
|
||||
/**
|
||||
* The contained lifecycle-edge publisher. Built here because scoped dispatch
|
||||
* keys its carrier by this exact service instance, whose own context filter
|
||||
@@ -207,9 +204,17 @@ export class SubagentRuntime extends TypertRemoteService {
|
||||
constructor(ctx: Context, private config: Config) {
|
||||
super(ctx, 'subagents')
|
||||
this.emitLifecycle = createLifecycleEmitter(this.ctx, parent => scopeTarget(this, parent))
|
||||
}
|
||||
|
||||
protected async [Service.init](): Promise<void> {
|
||||
const ctx = this.ctx
|
||||
await ctx.sessionProjections.register(subagentCatalogProjectionDefinition)
|
||||
await ctx.sessionProjections.register(subagentTimingProjectionDefinition)
|
||||
const identityProjection = await ctx.sessionProjections.register(subagentIdentityProjectionDefinition)
|
||||
if (ctx.fiber.uid === null) return
|
||||
ctx.inject(['agents'], (childCtx: Context) => {
|
||||
const manager = new SubagentManager(childCtx, {
|
||||
identityOf: session => this.identityProjectionHandle.stateOf(session).identity,
|
||||
identityOf: session => identityProjection.stateOf(session).identity,
|
||||
emitLifecycle: this.emitLifecycle,
|
||||
}, () => this.config.maxActiveSubagents.get())
|
||||
this.manager = manager
|
||||
@@ -220,13 +225,6 @@ export class SubagentRuntime extends TypertRemoteService {
|
||||
})
|
||||
}
|
||||
|
||||
protected async [Service.init](): Promise<void> {
|
||||
const { sessionProjections } = this.ctx
|
||||
await sessionProjections.register(subagentCatalogProjectionDefinition)
|
||||
await sessionProjections.register(subagentTimingProjectionDefinition)
|
||||
this.identityProjectionHandle = await sessionProjections.register(subagentIdentityProjectionDefinition)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a delegation tool's depth policy against the current user setting.
|
||||
* @param configured - Explicit tool limit, or provider-managed for external delegation.
|
||||
|
||||
@@ -162,7 +162,7 @@ export class SubagentManager {
|
||||
installSubagentArchiveAdmission(ctx, (agent) => {
|
||||
const activation = this.resident.get(agent.id)
|
||||
return activation !== undefined && activationAgent(activation) === agent ? activation.ancestors : undefined
|
||||
})
|
||||
}, session => host.identityOf(session))
|
||||
ctx.on('agent/disposed', ({ agent }) => {
|
||||
this.closingRoots.delete(agent)
|
||||
})
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Context } from '@deepseek-ai/cordis'
|
||||
import AgentRegistry from '@deepseek-ai/dsh-agent'
|
||||
import type { Agent, AgentCancelCause, AgentStatus, CancelOptions } from '@deepseek-ai/dsh-agent'
|
||||
import { unsupportedModel, unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit'
|
||||
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import SessionStore, { SessionId, SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session'
|
||||
import type { Session } from '@deepseek-ai/dsh-session'
|
||||
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
|
||||
import type { SessionActivity } from '@deepseek-ai/dsh-workspace'
|
||||
@@ -16,7 +16,7 @@ type CancelCall = [AgentCancelCause, CancelOptions | undefined]
|
||||
/** A registered Agent double whose status the test flips and whose cancels it records. */
|
||||
type LiveAgent = Agent & { cancels: CancelCall[]; setStatus(status: AgentStatus): void }
|
||||
|
||||
async function harness(options: { sessionQuery?: boolean } = {}): Promise<Context> {
|
||||
async function harness(options: { sessionQuery?: boolean; runtime?: boolean } = {}): Promise<Context> {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
await ctx.plugin(SessionStore)
|
||||
@@ -24,7 +24,7 @@ async function harness(options: { sessionQuery?: boolean } = {}): Promise<Contex
|
||||
await ctx.plugin(AgentRegistry)
|
||||
if (options.sessionQuery !== false) await ctx.plugin(TestSessionQuery)
|
||||
await mountWorkingDirectoryFixture(ctx)
|
||||
await ctx.plugin(SubagentRuntime)
|
||||
if (options.runtime !== false) await ctx.plugin(SubagentRuntime)
|
||||
return ctx
|
||||
}
|
||||
|
||||
@@ -102,13 +102,15 @@ describe('Subagent archive admission: reporting', () => {
|
||||
expect(await ask(ctx, SessionId('cold-or-unknown'))).toEqual([{ kind: 'probe' }])
|
||||
})
|
||||
|
||||
it('names a child by id alone without the Session query service or with a damaged descriptor', async () => {
|
||||
it('reports a child label without the Session query service', async () => {
|
||||
const queryless = await harness({ sessionQuery: false })
|
||||
const parent = queryless.sessions.create(SessionId('parent'))
|
||||
await liveAgent(queryless, parent, 'idle')
|
||||
await liveAgent(queryless, childOf(queryless, 'child', parent.id, 'reviewer'), 'running')
|
||||
expect(await ask(queryless, parent.id)).toEqual([{ kind: 'subagent', items: [{ id: 'child' }] }])
|
||||
expect(await ask(queryless, parent.id)).toEqual([{ kind: 'subagent', items: [{ id: 'child', label: 'reviewer' }] }])
|
||||
})
|
||||
|
||||
it('names a child by id alone with a damaged descriptor', async () => {
|
||||
const ctx = await harness()
|
||||
const damagedParent = ctx.sessions.create(SessionId('damaged-parent'))
|
||||
await liveAgent(ctx, damagedParent, 'idle')
|
||||
@@ -119,6 +121,36 @@ describe('Subagent archive admission: reporting', () => {
|
||||
expect(await ask(ctx, damagedParent.id)).toEqual([{ kind: 'subagent', items: [{ id: 'damaged-child' }] }])
|
||||
})
|
||||
|
||||
it('uses only the latest own descriptor identity without observing history', async () => {
|
||||
const ctx = await harness()
|
||||
const parent = ctx.sessions.create(SessionId('seed-parent'))
|
||||
await liveAgent(ctx, parent, 'idle')
|
||||
const child = ctx.sessions.create(SessionId('seed-child'), {
|
||||
meta: { parentSession: parent.id, origin: 'subagent', isSeeded: true },
|
||||
seed: [{
|
||||
type: 'subagent/descriptor', seq: SessionSeq(0), time: 1,
|
||||
data: { version: SUBAGENT_DESCRIPTOR_VERSION, mode: 'continuable', provider: 'fork', label: 'ancestor' },
|
||||
}],
|
||||
inheritedEventCount: SessionLogOffset(1),
|
||||
})
|
||||
await liveAgent(ctx, child, 'running')
|
||||
const observe = vi.spyOn(ctx.sessionQuery, 'observeSession')
|
||||
onTestFinished(() => { observe.mockRestore() })
|
||||
|
||||
expect(await ask(ctx, parent.id)).toEqual([{ kind: 'subagent', items: [{ id: child.id }] }])
|
||||
for (const label of ['reviewer', 'latest reviewer']) {
|
||||
child.append('subagent/descriptor', { version: SUBAGENT_DESCRIPTOR_VERSION, mode: 'continuable', provider: 'fork', label })
|
||||
expect(await ask(ctx, parent.id)).toEqual([{ kind: 'subagent', items: [{ id: child.id, label }] }])
|
||||
}
|
||||
child.append('subagent/descriptor', { version: SUBAGENT_DESCRIPTOR_VERSION, mode: 'continuable', provider: 'fork', label: 7 } as never)
|
||||
expect(await ask(ctx, parent.id)).toEqual([{ kind: 'subagent', items: [{ id: child.id }] }])
|
||||
child.append('subagent/descriptor', { version: SUBAGENT_DESCRIPTOR_VERSION + 1, mode: 'continuable', provider: 'fork', label: 'unknown' })
|
||||
expect(await ask(ctx, parent.id)).toEqual([{ kind: 'subagent', items: [{ id: child.id }] }])
|
||||
child.append('subagent/descriptor', { version: SUBAGENT_DESCRIPTOR_VERSION, mode: 'one-shot', provider: 'fork' })
|
||||
expect(await ask(ctx, parent.id)).toEqual([{ kind: 'subagent', items: [{ id: child.id }] }])
|
||||
expect(observe).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('visits a damaged lineage that loops only once', async () => {
|
||||
const ctx = await harness()
|
||||
// Two headers naming each other as subagent parents cannot be created by
|
||||
@@ -168,6 +200,46 @@ describe('Subagent archive admission: stopping', () => {
|
||||
})
|
||||
|
||||
describe('Subagent archive admission: lifetime', () => {
|
||||
it.each(['ready', 'failed', 'disposed'] as const)('installs reporting only after identity registration is %s', async (outcome) => {
|
||||
const ctx = await harness({ runtime: false })
|
||||
const entered = Promise.withResolvers<undefined>()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
onTestFinished(() => { release.resolve(undefined) })
|
||||
const register = ctx.sessionProjections.register.bind(ctx.sessionProjections)
|
||||
const registration = vi.spyOn(ctx.sessionProjections, 'register').mockImplementation(async (definition) => {
|
||||
const handle = await register(definition)
|
||||
if (definition.key === 'subagent') {
|
||||
entered.resolve(undefined)
|
||||
await release.promise
|
||||
}
|
||||
return handle
|
||||
})
|
||||
onTestFinished(() => { registration.mockRestore() })
|
||||
const error = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {})
|
||||
onTestFinished(() => { error.mockRestore() })
|
||||
const parent = ctx.sessions.create(SessionId('initializing-parent'))
|
||||
await liveAgent(ctx, parent, 'idle')
|
||||
await liveAgent(ctx, childOf(ctx, 'initializing-child', parent.id, 'reviewer'), 'running')
|
||||
const fiber = ctx.plugin(SubagentRuntime)
|
||||
await entered.promise
|
||||
expect(await ask(ctx, parent.id)).toEqual([])
|
||||
|
||||
if (outcome === 'failed') {
|
||||
const failure = expect(Promise.resolve(fiber)).rejects.toThrow('identity registration failed')
|
||||
release.reject(new Error('identity registration failed'))
|
||||
await failure
|
||||
expect(error).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message: 'identity registration failed' }))
|
||||
} else {
|
||||
const disposal = outcome === 'disposed' ? fiber.dispose() : undefined
|
||||
release.resolve(undefined)
|
||||
await (disposal ?? fiber)
|
||||
expect(error).not.toHaveBeenCalled()
|
||||
}
|
||||
expect(await ask(ctx, parent.id)).toEqual(outcome === 'ready'
|
||||
? [{ kind: 'subagent', items: [{ id: 'initializing-child', label: 'reviewer' }] }]
|
||||
: [])
|
||||
})
|
||||
|
||||
it('checks header ancestry for unmanaged Agents and permits independent forks', async () => {
|
||||
const ctx = await harness()
|
||||
const parentId = SessionId('offline-parent')
|
||||
@@ -181,8 +253,9 @@ describe('Subagent archive admission: lifetime', () => {
|
||||
expect(await proposed(ctx, child)).toEqual({ kind: 'enter', messages: [] })
|
||||
})
|
||||
|
||||
it('stops answering once the runtime fiber is disposed', async () => {
|
||||
it('removes archive listeners on disposal and restores them on replacement', async () => {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
await ctx.plugin(AgentRegistry)
|
||||
@@ -190,15 +263,20 @@ describe('Subagent archive admission: lifetime', () => {
|
||||
const fiber = await ctx.plugin(SubagentRuntime)
|
||||
const parent = ctx.sessions.create(SessionId('watched'))
|
||||
await liveAgent(ctx, parent, 'idle')
|
||||
const child = await liveAgent(ctx, childOf(ctx, 'watched-child', parent.id), 'running')
|
||||
const child = await liveAgent(ctx, childOf(ctx, 'watched-child', parent.id, 'reviewer'), 'running')
|
||||
ctx.provide('workspaceRegistry', { archivedSessionIds: [parent.id] } as never)
|
||||
expect(await proposed(ctx, child)).toEqual({ kind: 'reject' })
|
||||
expect(await ask(ctx, parent.id)).toEqual([{ kind: 'subagent', items: [{ id: 'watched-child' }] }])
|
||||
expect(await ask(ctx, parent.id)).toEqual([{ kind: 'subagent', items: [{ id: 'watched-child', label: 'reviewer' }] }])
|
||||
await fiber.dispose()
|
||||
expect(await ask(ctx, parent.id)).toEqual([])
|
||||
await stop(ctx, parent.id)
|
||||
expect(child.cancels).toEqual([])
|
||||
expect(await proposed(ctx, child)).toEqual({ kind: 'enter', messages: [] })
|
||||
await ctx.plugin(SubagentRuntime)
|
||||
expect(await ask(ctx, parent.id)).toEqual([{ kind: 'subagent', items: [{ id: 'watched-child', label: 'reviewer' }] }])
|
||||
expect(await proposed(ctx, child)).toEqual({ kind: 'reject' })
|
||||
await stop(ctx, parent.id)
|
||||
expect(child.cancels).toEqual([[{ kind: 'parent' }, undefined]])
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
en: f486d856fd8e392c
|
||||
zh: 6ddbc59dd08d3c49
|
||||
/deepseek-ai-dsh-tool-subagent-control/use-this-package/minimal-configuration:
|
||||
en: 8ea91b799a8b4e74
|
||||
zh: a22a840c6458d10d
|
||||
en: d224de77b41ed4e4
|
||||
zh: f1e94f9cc9e04384
|
||||
/deepseek-ai-dsh-tool-subagent-control/use-this-package/send-message:
|
||||
en: 849b9b3e576aed01
|
||||
zh: d52239ca40d3a168
|
||||
|
||||
@@ -40,7 +40,7 @@ With the required services available, load the subagent service, a backend, the
|
||||
- name: '@deepseek-ai/dsh-tool-subagent-control'
|
||||
```
|
||||
|
||||
Set `config.interrupt: false` to omit `interrupt_agent` and its guidance in `list_agents`. The default is `true`. The other three tools and `ctx.subagents.interrupt()` remain available. See the generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-tool-subagent-control).
|
||||
Set `config.interrupt: false` to omit `interrupt_agent`. The default is `true`. The other three tools and `ctx.subagents.interrupt()` remain available. See the generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-tool-subagent-control).
|
||||
|
||||
### send_message
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ kind: "package-reference"
|
||||
- name: '@deepseek-ai/dsh-tool-subagent-control'
|
||||
```
|
||||
|
||||
设置 `config.interrupt: false` 可省略 `interrupt_agent` 及其在 `list_agents` 中的指引。默认值为 `true`。其余三个工具和 `ctx.subagents.interrupt()` 仍然可用。参见生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-tool-subagent-control)。
|
||||
设置 `config.interrupt: false` 可省略 `interrupt_agent`。默认值为 `true`。其余三个工具和 `ctx.subagents.interrupt()` 仍然可用。参见生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-tool-subagent-control)。
|
||||
|
||||
### send_message
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ export const inject = ['tools', 'subagents', 'agents', 'systemPrompt']
|
||||
|
||||
/** Optional subagent control tools. */
|
||||
export interface Config {
|
||||
/** Register `interrupt_agent` and its discovery guidance. Defaults to true; false leaves the service API available. */
|
||||
/** Register `interrupt_agent`. Defaults to true; false leaves the service API available. */
|
||||
interrupt?: boolean
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ export const Config: z<Config> = z.object({
|
||||
*/
|
||||
export function apply(ctx: Context, config: Config = {}): void {
|
||||
const interrupt = config.interrupt !== false
|
||||
registerListAgents(ctx, interrupt)
|
||||
registerListAgents(ctx)
|
||||
registerWaitAgent(ctx)
|
||||
const sendMessage = defineTool({
|
||||
name: 'send_message',
|
||||
|
||||
@@ -58,16 +58,14 @@ function project(
|
||||
/**
|
||||
* Register the `list_agents` tool.
|
||||
* @param ctx - context carrying the tool registry, subagent service, and live Agent registry.
|
||||
* @param interrupt - whether the control plugin exposes interruption.
|
||||
*/
|
||||
export function registerListAgents(ctx: Context, interrupt: boolean): void {
|
||||
export function registerListAgents(ctx: Context): void {
|
||||
ctx.tools.register(defineTool({
|
||||
name: 'list_agents',
|
||||
description:
|
||||
'List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. '
|
||||
+ 'Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. '
|
||||
+ 'You can message any other agent in the subagent tree listed as running or inactive. '
|
||||
+ (interrupt ? 'You can interrupt only your own descendants. ' : '')
|
||||
+ 'running means it is working; inactive means it is not currently working. '
|
||||
+ 'While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. '
|
||||
+ 'Use send_message to continue the conversation.',
|
||||
|
||||
@@ -146,7 +146,6 @@ describe('list_agents', () => {
|
||||
expect(Object.keys(parameters.properties ?? {})).toEqual([])
|
||||
expect(parameters.required ?? []).toEqual([])
|
||||
expect(schemas[0]?.description).toContain('You can message any other agent in the subagent tree')
|
||||
expect(schemas[0]?.description).toContain('You can interrupt only your own descendants')
|
||||
})
|
||||
|
||||
it('renders the Lead when the tree has no children', async () => {
|
||||
|
||||
@@ -408,9 +408,9 @@ describe('dsh-tool-subagent-control', () => {
|
||||
const names = ['send_message', 'list_agents', 'wait_agent']
|
||||
if (config.interrupt !== false) names.push('interrupt_agent')
|
||||
for (const name of names) expect(ctx.tools.schemas().filter(schema => schema.name === name)).toHaveLength(1)
|
||||
expect(ctx.tools.get('list_agents')?.description).not.toContain('interrupt')
|
||||
if (config.interrupt === false) {
|
||||
expect(ctx.tools.get('interrupt_agent')).toBeUndefined()
|
||||
expect(ctx.tools.get('list_agents')?.description).not.toContain('interrupt')
|
||||
expect(typeof ctx.subagents.interrupt).toBe('function')
|
||||
}
|
||||
expect(ctx.tools.get('list_subagent_models')).toBeUndefined()
|
||||
|
||||
Generated
+10
@@ -9797,6 +9797,16 @@ importers:
|
||||
specifier: ^4.3.2
|
||||
version: 4.3.2
|
||||
|
||||
packages/experimental/liveshare-protocol:
|
||||
dependencies:
|
||||
'@deepseek-ai/dsh-brand':
|
||||
specifier: workspace:*
|
||||
version: link:../../util/brand
|
||||
devDependencies:
|
||||
'@deepseek-ai/cordis':
|
||||
specifier: workspace:~
|
||||
version: link:../../../vendor/cordis
|
||||
|
||||
packages/experimental/personalized-recommendations:
|
||||
dependencies:
|
||||
'@deepseek-ai/dsh-action-cards':
|
||||
|
||||
@@ -68,6 +68,7 @@ const PACKAGE_LIBRARIES: Readonly<Record<string, string>> = {
|
||||
'packages/experimental/webworker-packer': 'Build-time VFS image packer and command library.',
|
||||
'packages/experimental/webworker-runtime': 'Browser worker runtime library with explicit host entry points.',
|
||||
'packages/experimental/hook-protocol': 'Shared wire-protocol library between the hook bridges.',
|
||||
'packages/experimental/liveshare-protocol': 'Shared wire frames and identity contract; plain module exports with no plugin entry.',
|
||||
'packages/identity/anonymous-user-id': 'Harness-home identity helper with no plugin registration.',
|
||||
'packages/sandbox/sandbox-windows-acl': 'Windows ACL sandbox library consumed by sandbox-local.',
|
||||
'packages/sdk/client': 'Client-process library; the spawned runtime owns plugin behavior.',
|
||||
|
||||
@@ -79,6 +79,7 @@ describe('release families', () => {
|
||||
'@deepseek-ai/dsh-hooks-codex',
|
||||
'@deepseek-ai/dsh-experimental-inspector-profile',
|
||||
'@deepseek-ai/dsh-experimental-inspector',
|
||||
'@deepseek-ai/dsh-experimental-liveshare-protocol',
|
||||
'@deepseek-ai/dsh-personalized-recommendations',
|
||||
'@deepseek-ai/dsh-experimental-plugin-market-bundle',
|
||||
'@deepseek-ai/dsh-plugin-recommendations',
|
||||
|
||||
@@ -873,6 +873,7 @@ function docSyncLeafGates(options: {
|
||||
'website/tests/mermaid-viewer.spec.ts',
|
||||
'website/tests/image-viewer.spec.ts',
|
||||
'website/tests/code-groups.spec.ts',
|
||||
'website/tests/table-filter.spec.ts',
|
||||
'website/tests/page-markdown-actions.spec.ts', 'website/tests/raw-markdown.spec.ts',
|
||||
], {
|
||||
label: 'documentation site checks',
|
||||
|
||||
@@ -32,6 +32,7 @@ interface SentenceContract {
|
||||
const NO_MODEL_EXPERIENCE_SECTION: Readonly<Record<string, string>> = {
|
||||
'packages/util/file-drag': 'The package resolves export names and declares native file operations; it does not construct model input.',
|
||||
'packages/core/scope': 'The package is a model-agnostic registration and lifecycle primitive; model-facing consumers own any context selection.',
|
||||
'packages/experimental/liveshare-protocol': 'The package only defines wire frames and identity values that its consumers exchange; it registers nothing model-facing.',
|
||||
'packages/util/brand': 'The package only constructs plain string values and registers nothing model-facing.',
|
||||
'packages/util/home-paths': 'The package only resolves harness-owned host paths; model-facing consumers own any rendered use.',
|
||||
'packages/util/launch-environment': 'The package only resolves host environment values; model-facing consumers own any rendered use.',
|
||||
|
||||
@@ -292,7 +292,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -292,7 +292,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -150,7 +150,7 @@ interface ToolArgsMap {
|
||||
/** Max wait in milliseconds with wait: true. Defaults to and is capped by configuration. */
|
||||
timeout_ms?: number;
|
||||
} & Record<string, JsonValue>;
|
||||
/** List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation. */
|
||||
/** List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation. */
|
||||
list_agents: Record<string, JsonValue>;
|
||||
/** Declare existing files as final deliverables for the user. Hosts may show presented files only after your turn ends, so call it once the files are final. If the user needs to review files earlier, such as before a tool call that waits for their answer, link them in your message instead. Use it when the user needs a separate file, especially Office documents, spreadsheets, and slide decks; prefer your final response when that suffices. The user opens the current files; their contents are not copied. */
|
||||
present: {
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -163,7 +163,7 @@ interface ToolArgsMap {
|
||||
/** Max wait in milliseconds with wait: true. Defaults to and is capped by configuration. */
|
||||
timeout_ms?: number;
|
||||
} & Record<string, JsonValue>;
|
||||
/** List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation. */
|
||||
/** List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation. */
|
||||
list_agents: Record<string, JsonValue>;
|
||||
/** Read a UTF-8 text file and return line-numbered content. */
|
||||
read: {
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -176,7 +176,7 @@ interface ToolArgsMap {
|
||||
/** Max wait in milliseconds with wait: true. Defaults to and is capped by configuration. */
|
||||
timeout_ms?: number;
|
||||
} & Record<string, JsonValue>;
|
||||
/** List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation. */
|
||||
/** List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation. */
|
||||
list_agents: Record<string, JsonValue>;
|
||||
/** Read a UTF-8 text file and return line-numbered content. */
|
||||
read: {
|
||||
|
||||
@@ -270,7 +270,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
@@ -971,7 +971,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
@@ -850,7 +850,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -130,7 +130,7 @@ interface ToolArgsMap {
|
||||
/** Max wait in milliseconds with wait: true. Defaults to and is capped by configuration. */
|
||||
timeout_ms?: number;
|
||||
} & Record<string, JsonValue>;
|
||||
/** List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation. */
|
||||
/** List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation. */
|
||||
list_agents: Record<string, JsonValue>;
|
||||
/** Read a UTF-8 text file and return line-numbered content. */
|
||||
read: {
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_agents",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. You can interrupt only your own descendants. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means it is not currently working. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
Loaded 100 of 170 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user