From 4488e61c6ef89b385479bd45a0d79b99f6ee8a18 Mon Sep 17 00:00:00 2001 From: gengruilin Date: Fri, 20 Nov 2026 01:22:39 +0800 Subject: [PATCH 1/8] feat(feishu): download lark-cli in the account check when it is missing The plugin failed at load when the lark-cli executable was absent, which is the normal state of a source or `link:` install: pnpm denies the @larksuite/cli install script there. The plugin now loads without the executable and starts one account check. A check first runs the vendor install script through ctx.subprocess, shows a cancellable downloading step, and reports a download that does not finish as not installed with a Retry button. The entry skill and the CLI path are offered only once the executable is in place. --- docs/config-catalog.md | 9 +- docs/config-catalog.zh.md | 9 +- docs/module-graph.md | 3 +- docs/module-graph.zh.md | 3 +- packages/connector/feishu/README.i18n.yaml | 55 +++--- packages/connector/feishu/README.md | 41 +++-- packages/connector/feishu/README.zh.md | 41 +++-- packages/connector/feishu/package.json | 3 +- packages/connector/feishu/src/account.ts | 68 +++++--- packages/connector/feishu/src/cli.ts | 106 +++++++++-- packages/connector/feishu/src/index.ts | 50 ++++-- packages/connector/feishu/src/locales.ts | 16 ++ packages/connector/feishu/src/presentation.ts | 23 ++- packages/connector/feishu/src/skills.ts | 10 +- packages/connector/feishu/src/types.ts | 9 +- packages/connector/feishu/tests/cli.spec.ts | 118 +++++++++++-- .../connector/feishu/tests/download.spec.ts | 164 ++++++++++++++++++ packages/connector/feishu/tests/harness.ts | 30 +++- .../feishu/tests/presentation.spec.ts | 24 +++ .../connector/feishu/tests/skills.spec.ts | 14 +- packages/connector/feishu/tsconfig.json | 3 + 21 files changed, 649 insertions(+), 150 deletions(-) create mode 100644 packages/connector/feishu/tests/download.spec.ts diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 9b46ade20d..e9c81301c2 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1750,13 +1750,16 @@ export interface Config { ## `@deepseek-ai/dsh-feishu` -- `inject`: `cliAccounts` · `skills` -- `source`: [`packages/connector/feishu/src/index.ts:30`](../packages/connector/feishu/src/index.ts) +- `inject`: `cliAccounts` · `skills` · `subprocess` +- `source`: [`packages/connector/feishu/src/index.ts:33`](../packages/connector/feishu/src/index.ts) ```ts config-catalog /** Where lark-cli is. */ export interface Config { - /** Absolute directory holding the `lark-cli` executable; defaults to the installed `@larksuite/cli` package. */ + /** + * Absolute directory holding the `lark-cli` executable, which the plugin then never downloads. Defaults to the + * installed `@larksuite/cli` package. + */ binDir?: string } ``` diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 5a60ec42e6..d639558d66 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1752,13 +1752,16 @@ export interface Config { ## `@deepseek-ai/dsh-feishu` -- `inject`: `cliAccounts` · `skills` -- `source`: [`packages/connector/feishu/src/index.ts:30`](../packages/connector/feishu/src/index.ts) +- `inject`: `cliAccounts` · `skills` · `subprocess` +- `source`: [`packages/connector/feishu/src/index.ts:33`](../packages/connector/feishu/src/index.ts) ```ts config-catalog /** Where lark-cli is. */ export interface Config { - /** Absolute directory holding the `lark-cli` executable; defaults to the installed `@larksuite/cli` package. */ + /** + * Absolute directory holding the `lark-cli` executable, which the plugin then never downloads. Defaults to the + * installed `@larksuite/cli` package. + */ binDir?: string } ``` diff --git a/docs/module-graph.md b/docs/module-graph.md index 6964096fb9..3b80456891 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -758,6 +758,7 @@ flowchart TD pkg_dingtalk --> pkg_skill pkg_feishu --> pkg_cli_account pkg_feishu --> pkg_skill + pkg_feishu --> pkg_subprocess pkg_tencent_meeting --> pkg_cli_account pkg_tencent_meeting --> pkg_upstream_skills pkg_wecom --> pkg_cli_account @@ -1891,7 +1892,7 @@ flowchart TD | [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-auth`](../packages/account/deepseek-auth), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-auth`](../packages/account/deepseek-auth), [`launch-environment`](../packages/util/launch-environment), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`dingtalk`](../packages/connector/dingtalk) | `connector` | [`cli-account`](../packages/connector/cli-account), [`skill`](../packages/skill/skill) | -| [`feishu`](../packages/connector/feishu) | `connector` | [`cli-account`](../packages/connector/cli-account), [`skill`](../packages/skill/skill) | +| [`feishu`](../packages/connector/feishu) | `connector` | [`cli-account`](../packages/connector/cli-account), [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) | | [`tencent-meeting`](../packages/connector/tencent-meeting) | `connector` | [`cli-account`](../packages/connector/cli-account), [`upstream-skills`](../packages/connector/upstream-skills) | | [`wecom`](../packages/connector/wecom) | `connector` | [`cli-account`](../packages/connector/cli-account), [`upstream-skills`](../packages/connector/upstream-skills) | | [`file-reference`](../packages/context/file-reference) | `context` | [`agent`](../packages/core/agent) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 7d88c3c3e1..0c908b83d7 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -760,6 +760,7 @@ flowchart TD pkg_dingtalk --> pkg_skill pkg_feishu --> pkg_cli_account pkg_feishu --> pkg_skill + pkg_feishu --> pkg_subprocess pkg_tencent_meeting --> pkg_cli_account pkg_tencent_meeting --> pkg_upstream_skills pkg_wecom --> pkg_cli_account @@ -1893,7 +1894,7 @@ flowchart TD | [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-auth`](../packages/account/deepseek-auth), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-auth`](../packages/account/deepseek-auth), [`launch-environment`](../packages/util/launch-environment), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`dingtalk`](../packages/connector/dingtalk) | `connector` | [`cli-account`](../packages/connector/cli-account), [`skill`](../packages/skill/skill) | -| [`feishu`](../packages/connector/feishu) | `connector` | [`cli-account`](../packages/connector/cli-account), [`skill`](../packages/skill/skill) | +| [`feishu`](../packages/connector/feishu) | `connector` | [`cli-account`](../packages/connector/cli-account), [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) | | [`tencent-meeting`](../packages/connector/tencent-meeting) | `connector` | [`cli-account`](../packages/connector/cli-account), [`upstream-skills`](../packages/connector/upstream-skills) | | [`wecom`](../packages/connector/wecom) | `connector` | [`cli-account`](../packages/connector/cli-account), [`upstream-skills`](../packages/connector/upstream-skills) | | [`file-reference`](../packages/context/file-reference) | `context` | [`agent`](../packages/core/agent) | diff --git a/packages/connector/feishu/README.i18n.yaml b/packages/connector/feishu/README.i18n.yaml index 55ff46ab77..9991ff3933 100644 --- a/packages/connector/feishu/README.i18n.yaml +++ b/packages/connector/feishu/README.i18n.yaml @@ -9,8 +9,8 @@ en: 5b26d6ad2128b454 zh: 6d3ccfcdb716ef8d /deepseek-ai-dsh-feishu/summary: - en: a07d30fd633d14b8 - zh: d78e326c5edcde47 + en: b74aed7ca4215ed4 + zh: 8e2a9c8b4af28a1b /deepseek-ai-dsh-feishu/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb @@ -18,20 +18,23 @@ en: bbff250eba0f1b89 zh: 0a618f05cc88ee2b /deepseek-ai-dsh-feishu/use-this-package/install-into-a-profile: - en: 756d8e3c33815f24 - zh: 7f6a3fcfef92c6b8 + en: 10bdd68f45f9dfe9 + zh: 9ea8d884ae12690a +/deepseek-ai-dsh-feishu/use-this-package/download-of-a-missing-cli: + en: f2a40b09d50c60b6 + zh: b91f83986c37eb4d /deepseek-ai-dsh-feishu/use-this-package/what-you-get: - en: 55d9fdc4ef0be522 - zh: 8063b8baa6c42776 + en: 841b50c329791ac8 + zh: 0ed710e724673e44 /deepseek-ai-dsh-feishu/use-this-package/account-operations: - en: 4b5f07c32cac8141 - zh: 473a23f50efa5947 + en: 01d9b58b9bfcde43 + zh: c1ca8d5ee256306b /deepseek-ai-dsh-feishu/use-this-package/configure: - en: 7791974428fc09cb - zh: 62bb720d2b4842be + en: 960f5688f8585fa2 + zh: e54ad80f078936c5 /deepseek-ai-dsh-feishu/understand-the-implementation: - en: f8f0f9cb9eb55960 - zh: 05f09e2198565082 + en: 4d4d894cdaf549cc + zh: ea1b40fafc8feec6 /deepseek-ai-dsh-feishu/further-exploration: en: b25e4caa8c5b7116 zh: 4976eddc4b3e5ec4 @@ -42,17 +45,17 @@ en: a861712b6b65f49a zh: 3447e587c56a25d6 /deepseek-ai-dsh-feishu/model-experience/skill-catalog-entry/what-the-model-sees: - en: 0a73c38722f334ac - zh: 56d0060443414c9a + en: ee4b4d90f5c598ba + zh: 41ac55fd0428f642 /deepseek-ai-dsh-feishu/model-experience/skill-catalog-entry/what-the-model-sees/catalog-description: en: 8ff7f9b51a85c5b5 zh: 55e58973015e27f7 /deepseek-ai-dsh-feishu/model-experience/skill-catalog-entry/token-effect: - en: 7bd1792c4c56e682 - zh: 94be77d208dddc69 + en: 1da22c82cb1a2086 + zh: 9939ba273214f65f /deepseek-ai-dsh-feishu/model-experience/skill-catalog-entry/kv-cache-effect: - en: 09346f854e96f385 - zh: c2fa26fbcd1cd6f1 + en: 088068538282cd4e + zh: 33d475d2f59e4e25 /deepseek-ai-dsh-feishu/model-experience/loaded-skill-body: en: 8955ac196848e69f zh: 54aa7db097eafd3c @@ -69,8 +72,8 @@ en: b5fed52af6c0d771 zh: 25b7aa5297583030 /deepseek-ai-dsh-feishu/model-experience/cli-path/what-the-model-sees: - en: fb721433c0dec520 - zh: 7b17e45979e2fdca + en: 30a329a50e111315 + zh: dea504b45ffd80b3 /deepseek-ai-dsh-feishu/model-experience/cli-path/what-the-model-sees/runtime-context-entry: en: c91314832f78f460 zh: aac156ea0b5b816a @@ -81,11 +84,11 @@ en: 2952585b710ffd05 zh: 6e93e58b6256d534 /deepseek-ai-dsh-feishu/model-experience/cli-path/kv-cache-effect: - en: 67398dd4e4b02db9 - zh: a873eacd006fa656 + en: e6d8593416cb392e + zh: eadd5d656866b7eb /deepseek-ai-dsh-feishu/known-limitations-and-deferred-work: - en: 95d813f5fe6e7cb2 - zh: c65fcf992ac18b69 + en: 710294c637b2ef1b + zh: d95d925173f060df /deepseek-ai-dsh-feishu/known-limitations-and-deferred-work/dev-note: - en: be15f75bf32de641 - zh: 85de42dc5e1d934b + en: 84119ac4f878e897 + zh: 1a9c4f3f96cc9663 diff --git a/packages/connector/feishu/README.md b/packages/connector/feishu/README.md index 6da72a2d2c..9e35b0e585 100644 --- a/packages/connector/feishu/README.md +++ b/packages/connector/feishu/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -The Feishu plugin lets conversations use Feishu through the official `lark-cli`. It installs a pinned `@larksuite/cli`, gives the model the absolute path of its `lark-cli` executable in runtime context, and registers one `feishu` skill that indexes the guides embedded in that CLI. It registers the account with the [connector account registry](../../client/ui-connector-account/README.md), whose Plugins page section checks the default account, links an app and signs in through the CLI's browser flows, signs out, and cancels. The CLI keeps credentials in its default configuration, which the user's own terminal shares. Only macOS and Windows x64 are supported. +The Feishu plugin lets conversations use Feishu through the official `lark-cli`. It installs a pinned `@larksuite/cli`, downloads a missing `lark-cli` executable, gives the model that executable's absolute path in runtime context, and registers one `feishu` skill that indexes the guides embedded in that CLI. It registers the account with the [connector account registry](../../client/ui-connector-account/README.md), whose Plugins page section checks the default account, links an app and signs in through the CLI's browser flows, signs out, and cancels. The CLI keeps credentials in its default configuration, which the user's own terminal shares. Only macOS and Windows x64 are supported. ## Table of Contents @@ -34,34 +34,39 @@ dsh plugin --profile web add @deepseek-ai/dsh-feishu dsh plugin --profile web remove @deepseek-ai/dsh-feishu ``` -pnpm blocks the `@larksuite/cli` install script, which downloads and verifies the official native binary; approve it through the Plugins page's **Allow these scripts and retry** or the other paths that [Plugin Manager](../../boot/plugin-manager/README.md) documents. Until the executable exists, the `feishu` row fails to load with an error that names the missing path. +pnpm blocks the `@larksuite/cli` install script, which downloads and verifies the official native binary; approve it through the Plugins page's **Allow these scripts and retry** or the other paths that [Plugin Manager](../../boot/plugin-manager/README.md) documents. An installation that did not run the script, such as a source checkout or a `link:` install, has no executable; the `feishu` row then loads without it and [downloads it](#cli-download). + + +### Download of a missing CLI + +When the `feishu` row loads without `binDir` and the `@larksuite/cli` package holds no executable `lark-cli`, the row starts one check, which first runs that package's install script with the Node that runs DSH. The script fetches the release archive for the computer's platform with `curl`, from GitHub and then from npm mirrors, for at most 120 seconds each, verifies its SHA-256 against the package's `checksums.txt`, and copies the binary into the package's `bin` directory. The runtime context gives no `lark-cli` path, and the catalog has no `feishu` skill, until the executable is in place. The download needs no browser; the Plugins page shows it as a step of the check, with **Cancel**. A download that does not finish leaves the account `not-installed`: the page says that the CLI could not be downloaded and offers **Retry**, and unless it was cancelled, the Host log has one warning with the script's exit code and error output. The next check downloads again. ### What you get -After the plugin loads, one `feishu` skill joins the skill catalog. The agent loads it with the `skill` tool, opens the guide it needs, such as `lark-doc` or `lark-shared`, with `lark-cli skills read`, and runs `lark-cli` by that path through the ordinary Shell tools under the current sandbox and approval policy. When a command reports a missing app configuration or sign-in, the agent asks the user to connect Feishu on the plugin page; it runs the CLI's own setup and sign-in flow only when the user asks to finish it in the conversation. Commands that save sign-in state ask for single-command approval because they write outside the workspace. +Once `lark-cli` is in place, one `feishu` skill joins the skill catalog. The agent loads it with the `skill` tool, opens the guide it needs, such as `lark-doc` or `lark-shared`, with `lark-cli skills read`, and runs `lark-cli` by that path through the ordinary Shell tools under the current sandbox and approval policy. When a command reports a missing app configuration or sign-in, the agent asks the user to connect Feishu on the plugin page; it runs the CLI's own setup and sign-in flow only when the user asks to finish it in the conversation. Commands that save sign-in state ask for single-command approval because they write outside the workspace. -Turning the plugin off in Plugin Manager withdraws the `feishu` skill, the path from runtime context, and the account section. The CLI configuration and sign-in stay in place. +Turning the plugin off in Plugin Manager withdraws the `feishu` skill, the path from runtime context, and the account section. The CLI configuration, the sign-in, and a downloaded executable stay in place. ### Account operations -The Plugins page drives these operations through the connector account registry, which the Web app loads; a headless profile loads the plugin without it. The Host runs at most one account operation at a time and owns it, so leaving the page does not cancel it. Linking an app and signing in are separate operations, so the page starts each one from its own click. +The Plugins page drives these operations through the connector account registry, which the Web app loads; a headless profile loads the plugin without it. The Host runs at most one account operation at a time and owns it, so leaving the page does not cancel it. Linking an app and signing in are separate operations, so the page starts each one from its own click. Loading the row starts one check only while `lark-cli` is missing. | Operation | Effect | |---|---| -| `check` | Checks the account again; each browser that opens the Web app starts one when no operation runs | +| `check` | Downloads `lark-cli` while it is missing, then checks the account again; each browser that opens the Web app starts one when no operation runs | | `link-app` | Runs `config init --new`, which replaces the CLI's default configuration, including its sign-ins and any other app, with the app the user creates or chooses; it does not sign in. Replacing a linked app asks first | | `sign-in` | Runs `auth login --json` for the linked app and checks that the same user is signed in | | `sign-out` | After the user confirms, runs `auth logout --json`, which also signs out the user's own terminal, then checks again | -| Cancel | Cancels the operation during app setup or sign-in and waits for its command to exit; other steps are ignored | +| Cancel | Cancels the operation during the download, app setup, or sign-in and waits for its command to exit; other steps are ignored | -A check runs `auth status --verify --json`. The account reads `connected` only when the CLI reports an available user that its server verified, `signed-out` when the user is missing, not configured, or needs a refresh, `unconfigured` when no app exists, and `unverified` otherwise, for example when verification cannot reach the server. Every state except `unconfigured` carries the configured `appId`. Each link that `config init` prints and each device-authorization link that `auth login` reports is offered only when it is an HTTPS address on `feishu.cn` or `larksuite.com`. A sign-in that leaves requested permissions ungranted (`auth login` exits with code 3 and lists them as missing) still succeeds; a command that later needs a missing permission reports it. Results report succeeded, cancelled, or failed. Failures show the command and observed exit code on the page and in the Host log; native messages, paths, and authorization data are omitted. A successful Feishu webpage does not confirm that local credentials were saved. The process running DSH needs access to the CLI configuration and system credential storage; `DSH_HOME` does not relocate either. +A check runs `auth status --verify --json`. The account reads `connected` only when the CLI reports an available user that its server verified, `signed-out` when the user is missing, not configured, or needs a refresh, `unconfigured` when no app exists, and `unverified` otherwise, for example when verification cannot reach the server. `connected`, `signed-out`, and `unverified` carry the configured `appId`. Each link that `config init` prints and each device-authorization link that `auth login` reports is offered only when it is an HTTPS address on `feishu.cn` or `larksuite.com`. A sign-in that leaves requested permissions ungranted (`auth login` exits with code 3 and lists them as missing) still succeeds; a command that later needs a missing permission reports it. Results report succeeded, cancelled, or failed. A failed command shows its name and observed exit code on the page and in the Host log; native messages, paths, and authorization data are omitted. A successful Feishu webpage does not confirm that local credentials were saved. The process running DSH needs access to the CLI configuration and system credential storage; `DSH_HOME` does not relocate either. ### Configure | Field | Default | Meaning | |---|---|---| -| `binDir` | the installed `@larksuite/cli` package's `bin` | Absolute directory containing an executable `lark-cli`, `lark-cli.exe` on Windows | +| `binDir` | the installed `@larksuite/cli` package's `bin` | Absolute directory containing an executable `lark-cli`, `lark-cli.exe` on Windows; when set, the executable is not downloaded, and the row fails to load with an error that names the path when it is missing | An account check or sign-out gets the `commandTimeoutMs` of the [`cli-account` row](../cli-account/README.md#use-this-package), 30 seconds by default. App setup and sign-in wait up to 10 minutes for the user in the browser, and each command keeps at most 1 MiB of stdout; the CLI account Service fixes both limits. @@ -75,9 +80,9 @@ The generated [config catalog](../../../docs/config-catalog.md#deepseek-aidsh-fe
Implementation internals — click to expand -[`cordis.patch.yml`](cordis.patch.yml) inserts this package as the `feishu` row after the profile's other layers, and the Plugins page keys the account section by this package name. [`src/index.ts`](src/index.ts) is a function plugin. It checks that `binDir/lark-cli` (`lark-cli.exe` on Windows) is executable, registers that path and the account with `ctx.cliAccounts`, and registers the skill provider. [`src/cli.ts`](src/cli.ts) locates `lark-cli` and parses the JSON output of its account commands. The [CLI account Service](../cli-account/README.md) gives the model that path in runtime context, runs each command by the same path, runs one account operation at a time, and reports a failed command by its exit code. [`src/account.ts`](src/account.ts) carries out each operation with the Feishu commands and reads setup and sign-in links from their output lines. [`src/presentation.ts`](src/presentation.ts) maps each view to the section the registry serves, in the text of [`src/locales.ts`](src/locales.ts). Disposal cancels the active operation, aborts running commands, and settles after their processes exit. +[`cordis.patch.yml`](cordis.patch.yml) inserts this package as the `feishu` row after the profile's other layers, and the Plugins page keys the account section by this package name. [`src/index.ts`](src/index.ts) is a function plugin. It registers the path of `lark-cli` and the account with `ctx.cliAccounts`, registers the skill provider, and, while `lark-cli` is missing, starts one check so that a session without a browser also gets the CLI and the skill; with `binDir`, it requires an executable `lark-cli` (`lark-cli.exe` on Windows) there at load. [`src/cli.ts`](src/cli.ts) locates `lark-cli`, downloads a missing one by running the `@larksuite/cli` install script through `ctx.subprocess`, and parses the JSON output of the account commands. A download succeeded when the executable is in place after the script exits, whatever its exit code, because another process running the same script may have put it there. The [CLI account Service](../cli-account/README.md) gives the model that path in runtime context while `lark-cli` is installed, runs each command by the same path, runs one account operation at a time, and reports a failed command by its exit code. [`src/account.ts`](src/account.ts) carries out each operation with the Feishu commands, downloads a missing `lark-cli` before a check's first command, and reads setup and sign-in links from their output lines. [`src/presentation.ts`](src/presentation.ts) maps each view to the section the registry serves, in the text of [`src/locales.ts`](src/locales.ts). Disposal cancels the active operation, aborts running commands and the download, and settles after their processes exit. -[`skills/feishu/SKILL.md`](skills/feishu/SKILL.md) is the only skill this package carries: the DSH guidance, an index of the 28 guides that `lark-cli` 1.0.97 embeds, and how to open them. [`src/skills.ts`](src/skills.ts) reads the entry once when the plugin loads and lists it as the `feishu` provider's one skill with an opaque resource base, so the catalog lists the entry and a load returns the file without running the CLI. The guides stay in the binary, and the agent reads them with `lark-cli skills read`. +[`skills/feishu/SKILL.md`](skills/feishu/SKILL.md) is the only skill this package carries: the DSH guidance, an index of the 28 guides that `lark-cli` 1.0.97 embeds, and how to open them. [`src/skills.ts`](src/skills.ts) reads the entry once when the plugin loads and lists it as the `feishu` provider's one skill with an opaque resource base, so the catalog lists the entry and a load returns the file without running the CLI. It lists the entry only while `lark-cli` is installed, and the plugin invalidates the catalog when a download finishes, because the catalog may already have been listed without the entry. The guides stay in the binary, and the agent reads them with `lark-cli skills read`.
@@ -101,7 +106,7 @@ The generated [config catalog](../../../docs/config-catalog.md#deepseek-aidsh-fe #### What the model sees -One `feishu` entry appears in the skill catalog with the description below. +While `lark-cli` is installed, one `feishu` entry appears in the skill catalog with the description below. ##### Catalog description @@ -111,11 +116,11 @@ Feishu (飞书) and Lark through the bundled lark-cli: documents and wiki, Base, #### Token effect -The entry stays in context while the plugin is loaded, at about 350 characters. +The entry stays in context while the plugin is loaded and `lark-cli` is installed, at about 350 characters. #### KV Cache effect -The entry is fixed. Loading or unloading the plugin changes the catalog, which is republished as a new message and leaves earlier context in place. +The entry is fixed. Loading or unloading the plugin, or a download finishing after the catalog was listed, changes the catalog, which is republished as a new message and leaves earlier context in place. ### Loaded skill body @@ -135,7 +140,7 @@ Loading appends a tool result and does not rewrite earlier context. #### What the model sees -While the row is loaded, the [CLI account Service](../cli-account/README.md#model-experience) adds one required runtime-context entry with the path of `lark-cli` in `binDir`, which defaults to the installed `@larksuite/cli` package's `bin` directory. +While the row is loaded and `lark-cli` is installed, the [CLI account Service](../cli-account/README.md#model-experience) adds one required runtime-context entry with the path of `lark-cli` in `binDir`, which defaults to the installed `@larksuite/cli` package's `bin` directory. ##### Runtime-context entry @@ -155,7 +160,7 @@ One line of about 110 characters plus the path in each runtime-context snapshot. #### KV Cache effect -The system prompt does not change; loading or unloading the row, or a changed path, appends one runtime-context snapshot. +The system prompt does not change; finishing the download, loading or unloading the row, or a changed path appends one runtime-context snapshot. ## Known Limitations and Deferred Work @@ -167,6 +172,8 @@ The system prompt does not change; loading or unloading the row, or a changed pa - Sign-in reads the device-authorization link and the completion from `lark-cli auth login --json` events; a CLI version that changes those events fails the connection with a retryable result. - The entry's guide index follows `lark-cli` 1.0.97; pinning another `@larksuite/cli` version means checking the index against that version's `lark-cli skills list`. - Under a file sandbox, a token refresh during an ordinary command can be denied and then needs single-command approval. +- An installation that did not run the `@larksuite/cli` install script needs `curl`, `tar` (PowerShell on Windows), and network access to GitHub or an npm mirror at its first check, and the `feishu` skill and the CLI path are absent until that download succeeds. The page shows no progress. A process that exits during the download, such as a one-shot headless run, stops it, and the next process starts it again. A download stopped that way or cancelled leaves the script's `lark-cli-*` directory, with any partial archive, in the system temporary directory. +- The install script copies the binary into the package's `bin` directory without a rename. A process stopped during that copy can leave an incomplete file that counts as installed; deleting that `bin` directory makes the next check download again. ### Dev Note @@ -174,6 +181,6 @@ The system prompt does not change; loading or unloading the row, or a changed pa
Working context for maintainers — click to expand -Repository installs deny the `@larksuite/cli` install script in the root `pnpm-workspace.yaml`, so a checkout has no native binary. To run the plugin from source against the real CLI, run `node packages/connector/feishu/node_modules/@larksuite/cli/scripts/install.js` once. Specs and the `feishu-skills` session snapshot use stand-in executables through `binDir`. +Repository installs deny the `@larksuite/cli` install script in the root `pnpm-workspace.yaml`, so a checkout has no native binary until the plugin first loads without `binDir` and downloads it into `packages/connector/feishu/node_modules/@larksuite/cli/bin`. Specs and the `feishu-skills` session snapshot use stand-in executables through `binDir`; the download specs replace the executable check and the subprocess runtime, so they neither run the script nor write into the package.
diff --git a/packages/connector/feishu/README.zh.md b/packages/connector/feishu/README.zh.md index b773af156a..1e966a2c2f 100644 --- a/packages/connector/feishu/README.zh.md +++ b/packages/connector/feishu/README.zh.md @@ -9,7 +9,7 @@ kind: "package-bundle" ## 概述 -飞书插件让对话通过官方 `lark-cli` 使用飞书。它安装固定版本的 `@larksuite/cli`,在运行时上下文中把其 `lark-cli` 可执行文件的绝对路径告诉模型,并注册一个 `feishu` skill,为该 CLI 内嵌的子指南提供索引。它把账号注册到 [连接器账号注册表](../../client/ui-connector-account/README.zh.md),其插件页区块负责检查默认账号、通过 CLI 的浏览器流程关联应用并登录、退出登录以及取消操作。CLI 把凭据保存在默认配置中,用户自己的终端也共用这份配置。仅支持 macOS 和 Windows x64。 +飞书插件让对话通过官方 `lark-cli` 使用飞书。它安装固定版本的 `@larksuite/cli`,下载缺失的 `lark-cli` 可执行文件,在运行时上下文中把这个可执行文件的绝对路径告诉模型,并注册一个 `feishu` skill,为该 CLI 内嵌的子指南提供索引。它把账号注册到 [连接器账号注册表](../../client/ui-connector-account/README.zh.md),其插件页区块负责检查默认账号、通过 CLI 的浏览器流程关联应用并登录、退出登录以及取消操作。CLI 把凭据保存在默认配置中,用户自己的终端也共用这份配置。仅支持 macOS 和 Windows x64。 ## 目录 @@ -34,34 +34,39 @@ dsh plugin --profile web add @deepseek-ai/dsh-feishu dsh plugin --profile web remove @deepseek-ai/dsh-feishu ``` -pnpm 会拦截 `@larksuite/cli` 的安装脚本,该脚本负责下载并校验官方原生程序;请通过插件页的**允许这些脚本并重试**,或 [Plugin Manager](../../boot/plugin-manager/README.zh.md) 记录的其他方式批准。可执行文件存在之前,`feishu` 行会加载失败,并给出缺失的路径。 +pnpm 会拦截 `@larksuite/cli` 的安装脚本,该脚本负责下载并校验官方原生程序;请通过插件页的**允许这些脚本并重试**,或 [Plugin Manager](../../boot/plugin-manager/README.zh.md) 记录的其他方式批准。没有运行该脚本的安装(例如源码检出或 `link:` 安装)没有可执行文件;这时 `feishu` 行照常加载,并[自行下载](#cli-download)。 + + +### 下载缺失的 CLI + +`feishu` 行加载时没有设置 `binDir`、且 `@larksuite/cli` 包中没有可执行的 `lark-cli` 时,该行会发起一次检查,检查先用运行 DSH 的 Node 运行该包的安装脚本。脚本用 `curl` 获取本机平台的发布压缩包,先从 GitHub、再从 npm 镜像,每个来源最多 120 秒,按包内 `checksums.txt` 校验 SHA-256,并把二进制复制到该包的 `bin` 目录。可执行文件就位之前,运行时上下文不给出 `lark-cli` 路径,目录中也没有 `feishu` skill。下载不需要浏览器;插件页把它显示为检查的一个步骤,并提供**取消**。没有完成的下载使账号处于 `not-installed`:页面提示没能下载 CLI 并提供**重试**;除非是被取消,Host 日志中有一条警告,带脚本的退出码和错误输出。下一次检查会重新下载。 ### 获得的能力 -插件加载后,一个 `feishu` skill 进入 skill 目录。agent 用 `skill` 工具加载它,用 `lark-cli skills read` 打开所需的子指南(例如 `lark-doc` 或 `lark-shared`),并在当前沙箱与审批策略下通过普通 Shell 工具按这个路径运行 `lark-cli`。命令报告缺少应用配置或登录时,agent 会请用户到插件页连接飞书;只有用户要求在对话中完成时,才按 CLI 自带的流程配置和登录。保存登录状态的命令会在工作区之外写入,因此会申请单条命令审批。 +`lark-cli` 就位后,一个 `feishu` skill 进入 skill 目录。agent 用 `skill` 工具加载它,用 `lark-cli skills read` 打开所需的子指南(例如 `lark-doc` 或 `lark-shared`),并在当前沙箱与审批策略下通过普通 Shell 工具按这个路径运行 `lark-cli`。命令报告缺少应用配置或登录时,agent 会请用户到插件页连接飞书;只有用户要求在对话中完成时,才按 CLI 自带的流程配置和登录。保存登录状态的命令会在工作区之外写入,因此会申请单条命令审批。 -在 Plugin Manager 中关闭插件会撤下 `feishu` skill、运行时上下文中的路径和账号区块,CLI 配置与登录保持不变。 +在 Plugin Manager 中关闭插件会撤下 `feishu` skill、运行时上下文中的路径和账号区块,CLI 配置、登录和已下载的可执行文件保持不变。 ### 账号操作 -插件页通过 连接器账号注册表发起这些操作,注册表由 Web 应用加载;headless profile 加载插件时没有它。Host 同一时间最多运行一个账号操作并持有它,因此离开页面不会取消操作。关联应用和登录是两个独立操作,页面分别由各自的一次点击发起。 +插件页通过 连接器账号注册表发起这些操作,注册表由 Web 应用加载;headless profile 加载插件时没有它。Host 同一时间最多运行一个账号操作并持有它,因此离开页面不会取消操作。关联应用和登录是两个独立操作,页面分别由各自的一次点击发起。只有 `lark-cli` 缺失时,加载该行才会发起一次检查。 | 操作 | 作用 | |---|---| -| `check` | 重新检查账号;没有操作运行时,每个打开 Web 应用的浏览器会触发一次 | +| `check` | `lark-cli` 缺失时先下载,然后重新检查账号;没有操作运行时,每个打开 Web 应用的浏览器会触发一次 | | `link-app` | 运行 `config init --new`,用用户新建或选择的应用替换 CLI 的默认配置,其中的登录和其他应用一并替换;不会登录。更换已关联的应用前会先询问 | | `sign-in` | 为已关联的应用运行 `auth login --json`,并确认登录的是同一个用户 | | `sign-out` | 用户确认后运行 `auth logout --json`,同时退出用户自己终端里的登录,然后重新检查 | -| 取消 | 在应用配置或登录期间取消操作并等待其命令退出;其他步骤会被忽略 | +| 取消 | 在下载、应用配置或登录期间取消操作并等待其命令退出;其他步骤会被忽略 | -检查运行 `auth status --verify --json`。只有 CLI 报告用户可用且已被服务端核实时,账号才是 `connected`;用户缺失、未配置或需要刷新时为 `signed-out`;没有应用时为 `unconfigured`;其他情况为 `unverified`,例如核实时无法连到服务端。除 `unconfigured` 外,每种状态都带有已配置的 `appId`。`config init` 打印的链接和 `auth login` 报告的设备授权链接,只有是 `feishu.cn` 或 `larksuite.com` 上的 HTTPS 地址时才会提供。登录后仍有申请的权限未被授予时(`auth login` 以退出码 3 结束并把它们列为缺失),登录仍算成功;之后需要这些权限的命令会报告缺少哪些。结果分为成功、已取消和失败。失败时,页面和 Host 日志显示命令和观察到的退出码;原生消息、路径和授权数据均不保留。飞书网页显示成功不代表本地凭据已保存。运行 DSH 的进程需要能访问 CLI 配置和系统凭据存储;`DSH_HOME` 不会迁移这两者。 +检查运行 `auth status --verify --json`。只有 CLI 报告用户可用且已被服务端核实时,账号才是 `connected`;用户缺失、未配置或需要刷新时为 `signed-out`;没有应用时为 `unconfigured`;其他情况为 `unverified`,例如核实时无法连到服务端。`connected`、`signed-out` 和 `unverified` 带有已配置的 `appId`。`config init` 打印的链接和 `auth login` 报告的设备授权链接,只有是 `feishu.cn` 或 `larksuite.com` 上的 HTTPS 地址时才会提供。登录后仍有申请的权限未被授予时(`auth login` 以退出码 3 结束并把它们列为缺失),登录仍算成功;之后需要这些权限的命令会报告缺少哪些。结果分为成功、已取消和失败。命令失败时,页面和 Host 日志显示命令名和观察到的退出码;原生消息、路径和授权数据均不保留。飞书网页显示成功不代表本地凭据已保存。运行 DSH 的进程需要能访问 CLI 配置和系统凭据存储;`DSH_HOME` 不会迁移这两者。 ### 配置 | 字段 | 默认值 | 含义 | |---|---|---| -| `binDir` | 已安装 `@larksuite/cli` 包的 `bin` | 包含可执行 `lark-cli`(Windows 上为 `lark-cli.exe`)的绝对目录 | +| `binDir` | 已安装 `@larksuite/cli` 包的 `bin` | 包含可执行 `lark-cli`(Windows 上为 `lark-cli.exe`)的绝对目录;设置后不再下载可执行文件,目录中没有它时该行加载失败,并给出缺失的路径 | 账号检查和退出登录使用 [`cli-account` 行](../cli-account/README.zh.md#use-this-package)的 `commandTimeoutMs`,默认 30 秒。应用配置和登录最多等待用户在浏览器中操作 10 分钟,每条命令最多保留 1 MiB 的 stdout;这两个上限由 CLI 账号 Service 固定。 @@ -75,9 +80,9 @@ pnpm 会拦截 `@larksuite/cli` 的安装脚本,该脚本负责下载并校验
实现内部机制——点击展开 -[`cordis.patch.yml`](cordis.patch.yml) 在 profile 其他层之后把本包作为 `feishu` 行插入,插件页以本包名作为账号区块的 key。[`src/index.ts`](src/index.ts) 是一个函数插件。它检查 `binDir/lark-cli`(Windows 上为 `lark-cli.exe`)是否可执行,把这个路径和账号注册到 `ctx.cliAccounts`,并注册 skill 提供方。[`src/cli.ts`](src/cli.ts) 定位 `lark-cli` 并解析账号命令的 JSON 输出。[CLI 账号 Service](../cli-account/README.zh.md) 在运行时上下文中把这个路径告诉模型,按同一路径运行每条命令,一次执行一个账号操作,并以退出码报告失败的命令。[`src/account.ts`](src/account.ts) 用飞书的命令完成每个操作,并从命令输出行中读取配置与登录链接。[`src/presentation.ts`](src/presentation.ts) 用 [`src/locales.ts`](src/locales.ts) 中的文案,把每个视图映射为注册表提供的区块。释放时取消进行中的操作,中止正在运行的命令,并在这些进程退出后完成。 +[`cordis.patch.yml`](cordis.patch.yml) 在 profile 其他层之后把本包作为 `feishu` 行插入,插件页以本包名作为账号区块的 key。[`src/index.ts`](src/index.ts) 是一个函数插件。它把 `lark-cli` 的路径和账号注册到 `ctx.cliAccounts`,注册 skill 提供方,并在 `lark-cli` 缺失时发起一次检查,使没有浏览器的会话也能得到 CLI 和 skill;设置了 `binDir` 时,它要求加载时那里有可执行的 `lark-cli`(Windows 上为 `lark-cli.exe`)。[`src/cli.ts`](src/cli.ts) 定位 `lark-cli`,通过 `ctx.subprocess` 运行 `@larksuite/cli` 的安装脚本来下载缺失的可执行文件,并解析账号命令的 JSON 输出。脚本退出后可执行文件就位即为下载成功,与退出码无关,因为运行同一脚本的另一个进程可能已经把它放好。[CLI 账号 Service](../cli-account/README.zh.md) 在 `lark-cli` 已安装期间于运行时上下文中把这个路径告诉模型,按同一路径运行每条命令,一次执行一个账号操作,并以退出码报告失败的命令。[`src/account.ts`](src/account.ts) 用飞书的命令完成每个操作,在检查的第一条命令之前下载缺失的 `lark-cli`,并从命令输出行中读取配置与登录链接。[`src/presentation.ts`](src/presentation.ts) 用 [`src/locales.ts`](src/locales.ts) 中的文案,把每个视图映射为注册表提供的区块。释放时取消进行中的操作,中止正在运行的命令和下载,并在这些进程退出后完成。 -[`skills/feishu/SKILL.md`](skills/feishu/SKILL.md) 是本包携带的唯一 skill:DSH 指引、`lark-cli` 1.0.97 内嵌的 28 个子指南的索引,以及打开它们的方法。[`src/skills.ts`](src/skills.ts) 在插件加载时读取一次入口,并把它作为 `feishu` 提供方的唯一 skill 列出,资源基址为 opaque 类型,因此目录列出入口、加载返回该文件时都不运行 CLI。子指南留在二进制中,agent 用 `lark-cli skills read` 读取。 +[`skills/feishu/SKILL.md`](skills/feishu/SKILL.md) 是本包携带的唯一 skill:DSH 指引、`lark-cli` 1.0.97 内嵌的 28 个子指南的索引,以及打开它们的方法。[`src/skills.ts`](src/skills.ts) 在插件加载时读取一次入口,并把它作为 `feishu` 提供方的唯一 skill 列出,资源基址为 opaque 类型,因此目录列出入口、加载返回该文件时都不运行 CLI。它只在 `lark-cli` 已安装期间列出入口;下载完成时插件会使目录失效,因为目录可能已经在没有该入口时列出过。子指南留在二进制中,agent 用 `lark-cli skills read` 读取。
@@ -101,7 +106,7 @@ pnpm 会拦截 `@larksuite/cli` 的安装脚本,该脚本负责下载并校验 #### 模型看到什么 -skill 目录中出现一个 `feishu` 条目,描述见下方。 +`lark-cli` 已安装期间,skill 目录中出现一个 `feishu` 条目,描述见下方。 ##### 目录描述 @@ -111,11 +116,11 @@ Feishu (飞书) and Lark through the bundled lark-cli: documents and wiki, Base, #### Token 影响 -插件加载期间该条目一直留在上下文中,约 350 个字符。 +插件已加载且 `lark-cli` 已安装期间,该条目一直留在上下文中,约 350 个字符。 #### KV Cache 影响 -该条目固定不变。加载或卸载插件会改变目录,目录作为新消息重新发布,不改动更早的上下文。 +该条目固定不变。加载或卸载插件、或目录列出之后下载完成,都会改变目录,目录作为新消息重新发布,不改动更早的上下文。 ### 已加载的 skill 正文 @@ -135,7 +140,7 @@ Feishu (飞书) and Lark through the bundled lark-cli: documents and wiki, Base, #### 模型看到什么 -该行加载期间,[CLI 账号 Service](../cli-account/README.zh.md#model-experience) 添加一条必需的运行时上下文,给出 `binDir` 中 `lark-cli` 的路径;`binDir` 默认是已安装的 `@larksuite/cli` 包的 `bin` 目录。 +该行已加载且 `lark-cli` 已安装期间,[CLI 账号 Service](../cli-account/README.zh.md#model-experience) 添加一条必需的运行时上下文,给出 `binDir` 中 `lark-cli` 的路径;`binDir` 默认是已安装的 `@larksuite/cli` 包的 `bin` 目录。 ##### 运行时上下文条目 @@ -155,7 +160,7 @@ Feishu CLI: run `lark-cli` by its absolute path with the call operator, & ' ### 开发备注 @@ -174,6 +181,6 @@ Feishu CLI: run `lark-cli` by its absolute path with the call operator, & ' 维护者工作上下文——点击展开 -仓库安装在根目录 `pnpm-workspace.yaml` 中拒绝 `@larksuite/cli` 的安装脚本,因此检出的仓库没有原生二进制。要在源码中用真实 CLI 运行插件,请执行一次 `node packages/connector/feishu/node_modules/@larksuite/cli/scripts/install.js`。单测与 `feishu-skills` 会话快照通过 `binDir` 使用替身可执行文件。 +仓库安装在根目录 `pnpm-workspace.yaml` 中拒绝 `@larksuite/cli` 的安装脚本,因此检出的仓库没有原生二进制,直到插件第一次在没有 `binDir` 的情况下加载,并把它下载到 `packages/connector/feishu/node_modules/@larksuite/cli/bin`。单测与 `feishu-skills` 会话快照通过 `binDir` 使用替身可执行文件;下载的单测替换了可执行文件检查和子进程运行时,因此既不运行脚本,也不向该包写入。 diff --git a/packages/connector/feishu/package.json b/packages/connector/feishu/package.json index af202f1fc4..73182171aa 100644 --- a/packages/connector/feishu/package.json +++ b/packages/connector/feishu/package.json @@ -53,7 +53,8 @@ "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-cli-account": "workspace:*", - "@deepseek-ai/dsh-skill": "workspace:*" + "@deepseek-ai/dsh-skill": "workspace:*", + "@deepseek-ai/dsh-subprocess": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", diff --git a/packages/connector/feishu/src/account.ts b/packages/connector/feishu/src/account.ts index abc6437673..429b520fa4 100644 --- a/packages/connector/feishu/src/account.ts +++ b/packages/connector/feishu/src/account.ts @@ -1,10 +1,13 @@ -/** Check, connection, and sign-out of the CLI's default Feishu account, as the operations `ctx.cliAccounts` runs. */ +/** + * Check, connection, and sign-out of the CLI's default Feishu account, as the operations `ctx.cliAccounts` runs; a + * check downloads a missing lark-cli first. + */ import { brandString } from '@deepseek-ai/dsh-brand' import z from 'zod' import type { CliOperationControl } from '@deepseek-ai/dsh-cli-account/types' import { assertNever } from '@deepseek-ai/dsh-util-values' -import { parseJson } from './cli.ts' +import { parseJson, type LarkCli } from './cli.ts' import type { FeishuAccountState, FeishuAppId, FeishuCommand, FeishuOperationKind, FeishuPhase } from './types.ts' const NotConfigured = z.object({ ok: z.literal(false), error: z.object({ subtype: z.literal('not_configured') }) }) @@ -25,34 +28,51 @@ type Control = CliOperationControl + /** - * Carry out one account operation with lark-cli and publish the account each check observes. - * @param kind - the requested operation. - * @param control - phase changes, link offers, command runs, and account updates for this operation. - * @param signal - aborts on cancellation and when the plugin unloads. - * @returns after the operation finishes. - * @throws when a command fails, its output is not the expected JSON, or the account it leaves is not the one the - * operation set out to reach. + * Bind the Feishu account operations to the lark-cli installation. + * @param cli - the managed lark-cli. + * @returns the function that carries out one account operation with lark-cli and publishes the account each check + * observes; it throws when the download or a command fails, a command's output is not the expected JSON, or the + * account it leaves is not the one the operation set out to reach. */ -export async function perform(kind: FeishuOperationKind, control: Control, signal: AbortSignal): Promise { - switch (kind) { - case 'check': - await check(control, signal) - return - case 'link-app': return linkApp(control, signal) - case 'sign-in': return signIn(control, signal) - case 'sign-out': { - control.stage('signing-out') - const result = await control.run('auth-logout', ['auth', 'logout', '--json'], signal) - if (result.exitCode !== 0) throw new Error('feishu: auth logout failed') - await check(control, signal) - return +export function performWith(cli: Cli): (kind: FeishuOperationKind, control: Control, signal: AbortSignal) => Promise { + return async (kind, control, signal) => { + switch (kind) { + case 'check': + await download(cli, control, signal) + await check(control, signal) + return + case 'link-app': return linkApp(control, signal) + case 'sign-in': return signIn(control, signal) + case 'sign-out': { + control.stage('signing-out') + const result = await control.run('auth-logout', ['auth', 'logout', '--json'], signal) + if (result.exitCode !== 0) throw new Error('feishu: auth logout failed') + await check(control, signal) + return + } + /* v8 ignore next -- closed operation kind union */ + default: return assertNever(kind) } - /* v8 ignore next -- closed operation kind union */ - default: return assertNever(kind) } } +/** Download lark-cli while it is missing, a step the page may cancel; a download that does not finish publishes `not-installed`. */ +async function download(cli: Cli, control: Control, signal: AbortSignal): Promise { + if (cli.installed()) return + control.stage('downloading') + try { + await cli.install(signal) + } catch (error) { + control.publish({ state: 'not-installed' }) + throw error + } + control.stage('checking') +} + /** * Link an app through the CLI's setup page; sign-in is a separate operation. An existing configuration, * including its sign-ins and any other app, is replaced by the app the user creates or chooses. diff --git a/packages/connector/feishu/src/cli.ts b/packages/connector/feishu/src/cli.ts index 8028c8da97..1469299a19 100644 --- a/packages/connector/feishu/src/cli.ts +++ b/packages/connector/feishu/src/cli.ts @@ -1,12 +1,19 @@ -/** Managed lark-cli location and the JSON output of its commands. */ +/** Managed lark-cli: its location, the download of a missing one, and the JSON output of its commands. */ import { accessSync, constants } from 'node:fs' +import { homedir } from 'node:os' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' +import type { Context } from '@deepseek-ai/cordis' +import type { SubprocessOutputReader, SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' /** The name lark-cli's guides run it by. */ export const PROGRAM = 'lark-cli' +/** How much of each output stream of the install script is kept; a failed download logs the error stream. */ +const SCRIPT_OUTPUT_BYTES = 8192 +const TERMINATE_GRACE_MS = 2_000 + /** * Name the executable file as `@larksuite/cli` installs it. * @param platform - the Host platform. @@ -17,19 +24,94 @@ export function executableFileName(platform: NodeJS.Platform): string { } /** - * Locate the managed executable. - * @param binDir - absolute override; defaults to the installed `@larksuite/cli` package. - * @returns the absolute path of the executable `lark-cli`, `lark-cli.exe` on Windows. - * @throws when the executable is missing. + * The managed executable. Without `binDir` it is the one in the installed `@larksuite/cli` package, which only that + * package's install script puts there: an installation that did not run the script has none until {@link install} + * runs it. */ -export function resolveCliExecutable(binDir: string | undefined): string { - const program = join(binDir ?? join(dirname(fileURLToPath(import.meta.resolve('@larksuite/cli/package.json'))), 'bin'), executableFileName(process.platform)) - try { - accessSync(program, constants.X_OK) - } catch (error) { - throw new Error(`feishu: ${program} is not executable; approve the @larksuite/cli install script or set binDir`, { cause: error }) +export class LarkCli { + /** Absolute path of `lark-cli`, `lark-cli.exe` on Windows; the file is there while {@link installed} returns true. */ + readonly executable: string + /** The `@larksuite/cli` install script; absent when `binDir` names the directory. */ + private readonly installer: string | undefined + + /** + * @param binDir - absolute directory override; defaults to the `bin` directory of the installed `@larksuite/cli` package. + * @param subprocess - runs the install script. + * @param logger - receives the warning of a failed download. + * @throws when `binDir` holds no executable `lark-cli`. + */ + constructor( + binDir: string | undefined, + private readonly subprocess: SubprocessRuntime, + private readonly logger: Context['logger'], + ) { + if (binDir === undefined) { + const root = dirname(fileURLToPath(import.meta.resolve('@larksuite/cli/package.json'))) + this.executable = join(root, 'bin', executableFileName(process.platform)) + this.installer = join(root, 'scripts', 'install.js') + } else { + this.executable = join(binDir, executableFileName(process.platform)) + if (!this.installed()) throw this.notExecutable() + } + } + + /** + * Check whether the executable is in place. + * @returns whether {@link executable} is an executable file. + */ + installed(): boolean { + try { accessSync(this.executable, constants.X_OK) } catch (_notExecutable) { return false } + return true + } + + /** + * Download the executable by running the `@larksuite/cli` install script with this process's Node. The script + * fetches the release archive for this platform from GitHub or an npm mirror, at most 120 seconds per source, + * verifies its SHA-256 digest, and copies the binary into the package's `bin` directory. A failure other than an + * abort is logged as a warning with the script's exit and error output before it is thrown, because the account + * operation that runs the download discards what it throws. + * @param signal - aborts the script and the commands it runs. + * @returns after the script's process has exited and the executable is in place. + * @throws when `binDir` lost its executable, the script cannot start, or it leaves no executable; with the abort + * reason after an abort. + */ + async install(signal: AbortSignal): Promise { + try { + await this.download(signal) + } catch (error) { + if (!signal.aborted) this.logger.warn('feishu: could not download lark-cli', error) + throw error + } + } + + private async download(signal: AbortSignal): Promise { + const { installer } = this + if (installer === undefined) throw this.notExecutable() + const handle = this.subprocess.spawn({ + argv: [process.execPath, installer], cwd: homedir(), + // Under `pnpm exec` the script downloads only with this set, as the package's own launcher sets it. + env: { LARK_CLI_RUN: 'true' }, + stdio: { stdin: 'ignore', stdout: { maxBytes: SCRIPT_OUTPUT_BYTES }, stderr: { maxBytes: SCRIPT_OUTPUT_BYTES } }, + graceMs: TERMINATE_GRACE_MS, signal, + }) + try { + const outcome = await handle.done + signal.throwIfAborted() + // The file decides, not the exit code: another process running the same script may have put the executable in place. + if (!this.installed()) { + const exit = String(outcome.exitCode ?? outcome.signal) + const output = (handle.collected.stderr as SubprocessOutputReader).readFrom(0).text + throw new Error(`feishu: ${installer} exited with ${exit} and left no executable ${this.executable}\n${output}`.trimEnd()) + } + } finally { + handle.terminate() + await handle.waitForExit() + } + } + + private notExecutable(): Error { + return new Error(`feishu: ${this.executable} is not executable; set binDir to a directory containing an executable ${executableFileName(process.platform)}`) } - return program } /** diff --git a/packages/connector/feishu/src/index.ts b/packages/connector/feishu/src/index.ts index 5d2b507a68..42a644fd11 100644 --- a/packages/connector/feishu/src/index.ts +++ b/packages/connector/feishu/src/index.ts @@ -1,7 +1,9 @@ /** * Feishu plugin: registers the managed lark-cli and its account with `ctx.cliAccounts`, which tells the model the CLI's - * absolute path and shows the account on the Plugins page, and lists the packaged `feishu` skill that indexes the - * guides embedded in that CLI. The CLI's default account is shared with the user's own terminal. + * absolute path once the CLI is installed and shows the account on the Plugins page, and lists the packaged `feishu` + * skill that indexes the guides embedded in that CLI. An installation whose `@larksuite/cli` install script did not run + * has no lark-cli: the plugin then downloads it after loading. The CLI's default account is shared with the user's own + * terminal. * @module @deepseek-ai/dsh-feishu */ @@ -10,8 +12,9 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-cli-account' import type {} from '@deepseek-ai/dsh-skill' -import { perform } from './account.ts' -import { PROGRAM, resolveCliExecutable } from './cli.ts' +import type {} from '@deepseek-ai/dsh-subprocess' +import { performWith } from './account.ts' +import { LarkCli, PROGRAM } from './cli.ts' import { dictionaries, type FeishuTextKey } from './locales.ts' import { copy, FEISHU_PACKAGE, operations, presentAccount } from './presentation.ts' import { FeishuSkillProvider } from './skills.ts' @@ -20,15 +23,18 @@ import type { FeishuAccountState, FeishuCommand, FeishuOperationKind, FeishuPhas /** Plugin name. */ export const name = 'feishu' -/** Services the CLI's account and its skill register with. */ -export const inject = ['cliAccounts', 'skills'] +/** Services the CLI's account and its skill register with, and the one that runs the CLI's install script. */ +export const inject = ['cliAccounts', 'skills', 'subprocess'] /** The packaged entry skill; the guides it indexes stay in the CLI. */ const ENTRY = fileURLToPath(new URL('../skills/feishu/SKILL.md', import.meta.url)) /** Where lark-cli is. */ export interface Config { - /** Absolute directory holding the `lark-cli` executable; defaults to the installed `@larksuite/cli` package. */ + /** + * Absolute directory holding the `lark-cli` executable, which the plugin then never downloads. Defaults to the + * installed `@larksuite/cli` package. + */ binDir?: string } @@ -38,25 +44,39 @@ export const Config: z = z.object({ }) /** - * Register the CLI with its account, and the skill. - * @param ctx - Context carrying the CLI account Service and the skill registry. + * Register the CLI with its account, and the skill, and start downloading a missing CLI. + * @param ctx - Context carrying the CLI account Service, the skill registry, and the subprocess runtime. * @param config - CLI location. - * @throws when `lark-cli` is not executable, or the packaged entry skill has no name or description. + * @throws when `binDir` holds no executable `lark-cli`, or the packaged entry skill has no name or description. */ export function apply(ctx: Context, config: Config): void { - ctx.cliAccounts.register({ + const cli = new LarkCli(config.binDir, ctx.subprocess, ctx.logger) + let listSkill: () => void + ctx.skills.registerProvider((control) => { + listSkill = control.invalidate + return new FeishuSkillProvider(ENTRY, () => cli.installed()) + }) + const account = ctx.cliAccounts.register({ name, packageName: FEISHU_PACKAGE, - cli: { product: 'Feishu', program: PROGRAM, executable: resolveCliExecutable(config.binDir) }, + cli: { product: 'Feishu', program: PROGRAM, executable: cli.executable, ready: () => cli.installed() }, account: { state: 'unchecked' }, check: 'check', - cancellable: ['configuring', 'authorizing'], + cancellable: ['downloading', 'configuring', 'authorizing'], authorizationHosts: ['feishu.cn', 'larksuite.com'], - perform, + perform: performWith({ + installed: () => cli.installed(), + install: async (signal) => { + await cli.install(signal) + // The skill catalog listed before the download has no `feishu` skill. + listSkill() + }, + }), dictionaries, operations, copy, present: presentAccount, }) - ctx.skills.registerProvider(() => new FeishuSkillProvider(ENTRY)) + // Download a missing lark-cli without waiting for the Plugins page, so a session without a browser gets it. + if (!cli.installed()) account.refresh() } diff --git a/packages/connector/feishu/src/locales.ts b/packages/connector/feishu/src/locales.ts index 3d8f3fbd0b..e522d4ca4b 100644 --- a/packages/connector/feishu/src/locales.ts +++ b/packages/connector/feishu/src/locales.ts @@ -7,6 +7,7 @@ export const zh = { 'status.disconnected': '未连接', 'status.unavailable': '暂时无法确认登录状态', 'status.connected': '已连接', + 'step.downloading': '正在下载飞书 CLI', 'step.configuring': '第 1 步:关联飞书应用', 'step.authorizing': '第 2 步:登录飞书账号', 'step.connecting': '正在连接', @@ -14,6 +15,7 @@ export const zh = { 'detail.no-app': '先关联一个飞书应用(可以新建,也可以选择已有应用),再登录飞书账号。连接后,可以在对话中使用飞书文档、消息及其他你授权的功能。', 'detail.signed-out': '已关联飞书应用。登录飞书账号后,就可以在对话中使用飞书。', 'detail.unavailable': '已保留现有配置和登录,可以稍后重试。', + 'detail.missing': '没能下载飞书 CLI,请检查网络或代理后重试。', 'detail.connected': '可以在对话中直接请 Agent 使用飞书。', 'detail.connectedAs': '已登录为 {name}。可以在对话中直接请 Agent 使用飞书。', 'detail.configuring': '在打开的飞书页面中新建或选择应用,完成后回到这里登录。页面没有打开时,点击“打开飞书页面”。', @@ -55,6 +57,7 @@ export const en: Record = { 'status.disconnected': 'Not connected', 'status.unavailable': 'Cannot confirm sign-in right now', 'status.connected': 'Connected', + 'step.downloading': 'Downloading the Feishu CLI', 'step.configuring': 'Step 1: Link a Feishu app', 'step.authorizing': 'Step 2: Sign in to Feishu', 'step.connecting': 'Connecting', @@ -62,6 +65,7 @@ export const en: Record = { 'detail.no-app': 'Link a Feishu app first, either a new one or one you already have, then sign in to Feishu. After that, you can use Feishu docs, messages, and other features you authorize in conversations.', 'detail.signed-out': 'A Feishu app is linked. Sign in to Feishu to use it in conversations.', 'detail.unavailable': 'The existing setup and sign-in are kept. Try again later.', + 'detail.missing': 'The Feishu CLI could not be downloaded. Check the network or proxy, then retry.', 'detail.connected': 'Ask the agent to use Feishu directly in a conversation.', 'detail.connectedAs': 'Signed in as {name}. Ask the agent to use Feishu directly in a conversation.', 'detail.configuring': 'Create or choose an app on the Feishu page, then come back here to sign in. If the page did not open, select Open Feishu page.', @@ -100,6 +104,7 @@ export const ja: Record = { 'status.disconnected': '未接続', 'status.unavailable': '現在サインイン状態を確認できません', 'status.connected': '接続済み', + 'step.downloading': 'Feishu CLI をダウンロード中', 'step.configuring': 'ステップ 1:Feishu アプリを関連付ける', 'step.authorizing': 'ステップ 2:Feishu にサインイン', 'step.connecting': '接続中', @@ -107,6 +112,7 @@ export const ja: Record = { 'detail.no-app': 'まず Feishu アプリを関連付け(新規作成または既存のアプリを選択)、次に Feishu にサインインしてください。その後、会話の中で Feishu のドキュメント、メッセージ、その他の承認した機能を使用できます。', 'detail.signed-out': 'Feishu アプリは関連付け済みです。Feishu にサインインすると、会話の中で使用できます。', 'detail.unavailable': '現在の設定とサインイン状態は保持されています。しばらくしてから再試行してください。', + 'detail.missing': 'Feishu CLI をダウンロードできませんでした。ネットワークまたはプロキシを確認してから再試行してください。', 'detail.connected': '会話の中でエージェントに Feishu の使用を直接依頼できます。', 'detail.connectedAs': '{name} としてサインインしています。会話の中でエージェントに Feishu の使用を直接依頼できます。', 'detail.configuring': '開いた Feishu ページでアプリを作成または選択し、完了したらここに戻ってサインインしてください。ページが開かない場合は、「Feishu ページを開く」を選択してください。', @@ -145,6 +151,7 @@ export const es: Record = { 'status.disconnected': 'No conectado', 'status.unavailable': 'No se puede confirmar el inicio de sesión en este momento', 'status.connected': 'Conectado', + 'step.downloading': 'Descargando la CLI de Feishu', 'step.configuring': 'Paso 1: vincule una aplicación de Feishu', 'step.authorizing': 'Paso 2: inicie sesión en Feishu', 'step.connecting': 'Conectando', @@ -152,6 +159,7 @@ export const es: Record = { 'detail.no-app': 'Primero vincule una aplicación de Feishu, ya sea nueva o una que ya tenga, y luego inicie sesión en Feishu. Después, podrá usar en las conversaciones los documentos, los mensajes y otras funciones de Feishu que autorice.', 'detail.signed-out': 'Hay una aplicación de Feishu vinculada. Inicie sesión en Feishu para usarlo en las conversaciones.', 'detail.unavailable': 'Se conservan la configuración y el inicio de sesión actuales. Inténtelo de nuevo más tarde.', + 'detail.missing': 'No se pudo descargar la CLI de Feishu. Compruebe la red o el proxy y vuelva a intentarlo.', 'detail.connected': 'Pida al agente que use Feishu directamente en una conversación.', 'detail.connectedAs': 'Sesión iniciada como {name}. Pida al agente que use Feishu directamente en una conversación.', 'detail.configuring': 'Cree o elija una aplicación en la página de Feishu y luego vuelva aquí para iniciar sesión. Si la página no se abrió, seleccione “Abrir página de Feishu”.', @@ -190,6 +198,7 @@ export const fr: Record = { 'status.disconnected': 'Non connecté', 'status.unavailable': 'Impossible de confirmer la connexion pour le moment', 'status.connected': 'Connecté', + 'step.downloading': 'Téléchargement de la CLI Feishu', 'step.configuring': 'Étape 1 : associez une application Feishu', 'step.authorizing': 'Étape 2 : connectez-vous à Feishu', 'step.connecting': 'Connexion en cours', @@ -197,6 +206,7 @@ export const fr: Record = { 'detail.no-app': 'Associez d’abord une application Feishu, nouvelle ou existante, puis connectez-vous à Feishu. Vous pourrez ensuite utiliser dans les conversations les documents, les messages et les autres fonctionnalités de Feishu que vous autorisez.', 'detail.signed-out': 'Une application Feishu est associée. Connectez-vous à Feishu pour l’utiliser dans les conversations.', 'detail.unavailable': 'La configuration et la connexion existantes sont conservées. Réessayez plus tard.', + 'detail.missing': 'Impossible de télécharger la CLI Feishu. Vérifiez le réseau ou le proxy, puis réessayez.', 'detail.connected': 'Demandez à l’agent d’utiliser Feishu directement dans une conversation.', 'detail.connectedAs': 'Connecté en tant que {name}. Demandez à l’agent d’utiliser Feishu directement dans une conversation.', 'detail.configuring': 'Créez ou choisissez une application sur la page Feishu, puis revenez ici pour vous connecter. Si la page ne s’est pas ouverte, sélectionnez « Ouvrir la page Feishu ».', @@ -235,6 +245,7 @@ export const de: Record = { 'status.disconnected': 'Nicht verbunden', 'status.unavailable': 'Anmeldung kann gerade nicht bestätigt werden', 'status.connected': 'Verbunden', + 'step.downloading': 'Feishu-CLI wird heruntergeladen', 'step.configuring': 'Schritt 1: Feishu-App verknüpfen', 'step.authorizing': 'Schritt 2: Bei Feishu anmelden', 'step.connecting': 'Wird verbunden', @@ -242,6 +253,7 @@ export const de: Record = { 'detail.no-app': 'Verknüpfen Sie zuerst eine Feishu-App, entweder eine neue oder eine vorhandene, und melden Sie sich dann bei Feishu an. Danach können Sie Dokumente, Nachrichten und weitere von Ihnen autorisierte Funktionen von Feishu in Unterhaltungen verwenden.', 'detail.signed-out': 'Eine Feishu-App ist verknüpft. Melden Sie sich bei Feishu an, um es in Unterhaltungen zu verwenden.', 'detail.unavailable': 'Die bestehende Einrichtung und Anmeldung bleiben erhalten. Versuchen Sie es später erneut.', + 'detail.missing': 'Die Feishu-CLI konnte nicht heruntergeladen werden. Prüfen Sie das Netzwerk oder den Proxy und versuchen Sie es dann erneut.', 'detail.connected': 'Bitten Sie den Agenten, Feishu direkt in einer Unterhaltung zu verwenden.', 'detail.connectedAs': 'Angemeldet als {name}. Bitten Sie den Agenten, Feishu direkt in einer Unterhaltung zu verwenden.', 'detail.configuring': 'Erstellen oder wählen Sie auf der Feishu-Seite eine App und kehren Sie dann hierher zurück, um sich anzumelden. Falls sich die Seite nicht geöffnet hat, wählen Sie „Feishu-Seite öffnen“.', @@ -280,6 +292,7 @@ export const ru: Record = { 'status.disconnected': 'Не подключено', 'status.unavailable': 'Сейчас не удаётся подтвердить вход', 'status.connected': 'Подключено', + 'step.downloading': 'Загрузка Feishu CLI', 'step.configuring': 'Шаг 1. Привяжите приложение Feishu', 'step.authorizing': 'Шаг 2. Войдите в Feishu', 'step.connecting': 'Подключение', @@ -287,6 +300,7 @@ export const ru: Record = { 'detail.no-app': 'Сначала привяжите приложение Feishu — новое или уже существующее, — затем войдите в Feishu. После этого в беседах можно будет использовать документы, сообщения и другие разрешённые вами функции Feishu.', 'detail.signed-out': 'Приложение Feishu привязано. Войдите в Feishu, чтобы использовать его в беседах.', 'detail.unavailable': 'Текущие настройки и вход сохранены. Повторите попытку позже.', + 'detail.missing': 'Не удалось загрузить Feishu CLI. Проверьте сеть или прокси, затем повторите попытку.', 'detail.connected': 'Попросите агента использовать Feishu прямо в беседе.', 'detail.connectedAs': 'Выполнен вход как {name}. Попросите агента использовать Feishu прямо в беседе.', 'detail.configuring': 'Создайте или выберите приложение на странице Feishu, затем вернитесь сюда, чтобы войти. Если страница не открылась, нажмите «Открыть страницу Feishu».', @@ -325,6 +339,7 @@ export const pt: Record = { 'status.disconnected': 'Não conectado', 'status.unavailable': 'Não é possível confirmar o login no momento', 'status.connected': 'Conectado', + 'step.downloading': 'Baixando a CLI do Feishu', 'step.configuring': 'Etapa 1: vincule um app do Feishu', 'step.authorizing': 'Etapa 2: entre no Feishu', 'step.connecting': 'Conectando', @@ -332,6 +347,7 @@ export const pt: Record = { 'detail.no-app': 'Primeiro vincule um app do Feishu, novo ou já existente, e depois entre no Feishu. Em seguida, você poderá usar nas conversas os documentos, as mensagens e outros recursos do Feishu que autorizar.', 'detail.signed-out': 'Há um app do Feishu vinculado. Entre no Feishu para usá-lo nas conversas.', 'detail.unavailable': 'A configuração e o login atuais foram mantidos. Tente novamente mais tarde.', + 'detail.missing': 'Não foi possível baixar a CLI do Feishu. Verifique a rede ou o proxy e tente novamente.', 'detail.connected': 'Peça ao agente que use o Feishu diretamente em uma conversa.', 'detail.connectedAs': 'Conectado como {name}. Peça ao agente que use o Feishu diretamente em uma conversa.', 'detail.configuring': 'Crie ou escolha um app na página do Feishu e depois volte aqui para entrar. Se a página não abriu, selecione “Abrir página do Feishu”.', diff --git a/packages/connector/feishu/src/presentation.ts b/packages/connector/feishu/src/presentation.ts index 74fad4b129..af068c59fb 100644 --- a/packages/connector/feishu/src/presentation.ts +++ b/packages/connector/feishu/src/presentation.ts @@ -48,11 +48,12 @@ const SIGN_OUT = { kind: 'start', operation: 'sign-out' } as const /* jscpd:ignore-end */ type Operation = NonNullable -type Step = 'step.configuring' | 'step.authorizing' | 'step.connecting' | 'step.signing-out' +type Step = 'step.downloading' | 'step.configuring' | 'step.authorizing' | 'step.connecting' | 'step.signing-out' function step(operation: Operation): Step { if (operation.kind === 'sign-out') return 'step.signing-out' switch (operation.phase) { + case 'downloading': return 'step.downloading' case 'configuring': return 'step.configuring' case 'authorizing': return 'step.authorizing' case 'signing-out': return 'step.signing-out' @@ -64,12 +65,16 @@ function step(operation: Operation): Step { } } +function cancelButton(text: Text): ConnectorAccountButton { + return { label: text('action.cancel'), command: { kind: 'cancel' }, variant: 'ghost' } +} + /** The section while an operation runs: its step, the Feishu page and its guidance while waiting there, and cancel. */ function presentOperation(operation: Operation, text: Text): ConnectorAccountDisplay { const current = step(operation) const buttons: ConnectorAccountButton[] = [] if (operation.authorizationUrl !== undefined) buttons.push({ label: text('action.open'), command: { kind: 'open' }, variant: 'primary' }) - if (operation.cancellable) buttons.push({ label: text('action.cancel'), command: { kind: 'cancel' }, variant: 'ghost' }) + if (operation.cancellable) buttons.push(cancelButton(text)) const guidance = operation.authorizationUrl === undefined ? undefined : current === 'step.configuring' ? text('detail.configuring') : current === 'step.authorizing' ? text('detail.authorizing') : undefined @@ -104,11 +109,23 @@ function failureOf(result: FeishuState['result'], text: Text): { failure?: Conne */ export function presentAccount(view: FeishuState, text: Text): ConnectorAccountDisplay { const { account, operation } = view - if (operation?.kind === 'check') return { phase: 'checking', status: text('status.checking'), buttons: [], notes: [] } + /* jscpd:ignore-start -- CLI app plugins that download their CLI show a running check alike, each with its own text. */ + if (operation?.kind === 'check') { + return { + phase: 'checking', status: text(operation.phase === 'downloading' ? 'step.downloading' : 'status.checking'), + buttons: operation.cancellable ? [cancelButton(text)] : [], notes: [], + } + } + /* jscpd:ignore-end */ if (operation !== undefined) return presentOperation(operation, text) const failure = failureOf(view.result, text) switch (account.state) { case 'unchecked': return { phase: 'checking', status: text('status.checking'), buttons: [], notes: [] } + case 'not-installed': + return { + phase: 'unavailable', status: text('status.unavailable'), badge: text('badge.unavailable'), + buttons: [{ label: text('action.retry'), command: CHECK }], detail: text('detail.missing'), notes: [], ...failure, + } case 'unconfigured': return { phase: 'disconnected', status: text('status.disconnected'), badge: text('badge.disconnected'), diff --git a/packages/connector/feishu/src/skills.ts b/packages/connector/feishu/src/skills.ts index e708c9e687..362b27dc1c 100644 --- a/packages/connector/feishu/src/skills.ts +++ b/packages/connector/feishu/src/skills.ts @@ -11,7 +11,10 @@ const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u /** The guides are not files: the loaded entry tells the model to open them through lark-cli. */ const RESOURCES = 'Embedded lark-cli guides; open them with the skills read command given in the loaded skill.' -/** Lists the packaged entry without running lark-cli; the entry is read once, when the plugin loads. */ +/** + * Lists the packaged entry while lark-cli is installed, without running it; the entry is read once, when the plugin + * loads. The catalog caches a listing, so the plugin invalidates it when a download installs lark-cli. + */ export class FeishuSkillProvider implements SkillProvider { readonly name = 'feishu' private readonly candidate: SkillCandidate @@ -19,9 +22,10 @@ export class FeishuSkillProvider implements SkillProvider { /** * @param entry - absolute path of the packaged `SKILL.md`, whose frontmatter gives the skill's name and description. + * @param installed - whether lark-cli, which serves the guides the entry indexes, is in place. * @throws when the entry has no YAML frontmatter, or its frontmatter has no skill name or no description. */ - constructor(entry: string) { + constructor(entry: string, private readonly installed: () => boolean) { const raw = readFileSync(entry, 'utf8') const match = FRONTMATTER.exec(raw) const block = match?.[1] @@ -41,7 +45,7 @@ export class FeishuSkillProvider implements SkillProvider { } list(): Promise { - return Promise.resolve([this.candidate]) + return Promise.resolve(this.installed() ? [this.candidate] : []) } get(): Promise { diff --git a/packages/connector/feishu/src/types.ts b/packages/connector/feishu/src/types.ts index 4dde98d734..4982df423b 100644 --- a/packages/connector/feishu/src/types.ts +++ b/packages/connector/feishu/src/types.ts @@ -6,9 +6,12 @@ import type { CliAccountView } from '@deepseek-ai/dsh-cli-account/types' /** The Feishu app the CLI's default configuration uses, as `auth status` reports it. */ export type FeishuAppId = Branded<'FeishuAppId'> -/** The CLI's default account as the latest check observed it. */ +/** + * The CLI's default account as the latest check observed it. `not-installed` means lark-cli was missing and the + * download that check started did not finish. + */ export type FeishuAccountState = - | { readonly state: 'unchecked' | 'unconfigured' } + | { readonly state: 'unchecked' | 'not-installed' | 'unconfigured' } | { readonly state: 'signed-out' | 'unverified'; readonly appId: FeishuAppId } | { readonly state: 'connected'; readonly appId: FeishuAppId; readonly userName?: string } @@ -16,7 +19,7 @@ export type FeishuAccountState = export type FeishuOperationKind = 'check' | 'link-app' | 'sign-in' | 'sign-out' /** Feishu steps of an operation, besides the Service's `checking` and `cancelling`. */ -export type FeishuPhase = 'configuring' | 'authorizing' | 'verifying' | 'signing-out' +export type FeishuPhase = 'downloading' | 'configuring' | 'authorizing' | 'verifying' | 'signing-out' /** The lark-cli commands an operation runs; a failed operation reports its last one with that command's exit code. */ export type FeishuCommand = 'config-init' | 'auth-status' | 'auth-login' | 'auth-logout' diff --git a/packages/connector/feishu/tests/cli.spec.ts b/packages/connector/feishu/tests/cli.spec.ts index ecf9fe7bbf..96d95a927e 100644 --- a/packages/connector/feishu/tests/cli.spec.ts +++ b/packages/connector/feishu/tests/cli.spec.ts @@ -1,34 +1,128 @@ +/** The managed lark-cli: where it is, whether it is in place, and the install script that downloads a missing one. */ import { constants } from 'node:fs' +import { homedir } from 'node:os' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' -import { beforeEach, expect, it, vi } from 'vitest' -import { executableFileName, parseJson, resolveCliExecutable } from '../src/cli.ts' +import { Context } from '@deepseek-ai/cordis' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { executableFileName, LarkCli, parseJson } from '../src/cli.ts' +import { ScriptedSubprocess, type CliReply } from './harness.ts' const fs = vi.hoisted(() => ({ accessSync: vi.fn() })) vi.mock('node:fs', async importOriginal => ({ ...await importOriginal(), accessSync: fs.accessSync })) -const PACKAGE_BIN = join(dirname(fileURLToPath(import.meta.resolve('@larksuite/cli/package.json'))), 'bin') +const PACKAGE = dirname(fileURLToPath(import.meta.resolve('@larksuite/cli/package.json'))) const FILE = process.platform === 'win32' ? 'lark-cli.exe' : 'lark-cli' +const EXECUTABLE = join(PACKAGE, 'bin', FILE) +const INSTALLER = join(PACKAGE, 'scripts', 'install.js') +const CONFIGURED = join('/opt/lark/bin', FILE) -beforeEach(() => { +let ctx: Context +let subprocess: ScriptedSubprocess +/** Whether the executable is in place. */ +let present: boolean + +beforeEach(async () => { + present = false fs.accessSync.mockReset() + fs.accessSync.mockImplementation(() => { if (!present) throw new Error('ENOENT') }) + ctx = new Context() + await ctx.plugin(ScriptedSubprocess) + subprocess = ctx.subprocess as ScriptedSubprocess }) +afterEach(async () => { + await ctx.fiber.dispose() +}) + +const warnings = (): unknown[] => ctx.logger.buffer.filter(message => message.type === 'warn').map((message): unknown => message.args) +/** Answer the install script with `reply`; `installs` says whether it left the executable in place. */ +const script = (reply: CliReply, installs: boolean): void => { + subprocess.respond = (process) => { + present = installs + process.reply(reply) + } +} + it('names the executable file with the .exe extension on Windows only', () => { expect(executableFileName('win32')).toBe('lark-cli.exe') expect(executableFileName('darwin')).toBe('lark-cli') }) -it('defaults to the executable in the installed @larksuite/cli bin directory', () => { - expect(resolveCliExecutable(undefined)).toBe(join(PACKAGE_BIN, FILE)) - expect(fs.accessSync).toHaveBeenCalledWith(join(PACKAGE_BIN, FILE), constants.X_OK) +it('locates the executable in the installed @larksuite/cli package, whether or not it is there yet', () => { + const cli = new LarkCli(undefined, subprocess, ctx.logger) + expect(cli.executable).toBe(EXECUTABLE) + expect(cli.installed()).toBe(false) + expect(fs.accessSync).toHaveBeenCalledWith(EXECUTABLE, constants.X_OK) + present = true + expect(cli.installed()).toBe(true) }) -it('accepts a configured directory and names the missing executable with the install remedy', () => { - expect(resolveCliExecutable('/opt/lark/bin')).toBe(join('/opt/lark/bin', FILE)) - fs.accessSync.mockImplementation(() => { throw new Error('EACCES') }) - expect(() => resolveCliExecutable(PACKAGE_BIN)) - .toThrow(`feishu: ${join(PACKAGE_BIN, FILE)} is not executable; approve the @larksuite/cli install script or set binDir`) +it('requires the executable in a configured directory and names the missing one', () => { + present = true + expect(new LarkCli('/opt/lark/bin', subprocess, ctx.logger).executable).toBe(CONFIGURED) + present = false + expect(() => new LarkCli('/opt/lark/bin', subprocess, ctx.logger)) + .toThrow(`feishu: ${CONFIGURED} is not executable; set binDir to a directory containing an executable ${FILE}`) +}) + +it('downloads a missing executable by running the package\'s install script with this Node', async () => { + script({}, true) + const { signal } = new AbortController() + + await new LarkCli(undefined, subprocess, ctx.logger).install(signal) + + expect(subprocess.processes.map(process => process.spec)).toEqual([{ + argv: [process.execPath, INSTALLER], cwd: homedir(), env: { LARK_CLI_RUN: 'true' }, + stdio: { stdin: 'ignore', stdout: { maxBytes: 8192 }, stderr: { maxBytes: 8192 } }, + graceMs: 2_000, signal, + }]) + expect(subprocess.processes[0]?.terminated).toBe(true) + expect(warnings()).toEqual([]) +}) + +it('accepts an executable that is in place although the script failed', async () => { + script({ exitCode: 1, stderr: 'Failed to install lark-cli: EEXIST\n' }, true) + await new LarkCli(undefined, subprocess, ctx.logger).install(new AbortController().signal) + expect(warnings()).toEqual([]) +}) + +it.each<[string, CliReply, string, string]>([ + ['fails', { exitCode: 1, stderr: 'Failed to install lark-cli: timeout\n\n' }, '1', '\nFailed to install lark-cli: timeout'], + ['exits without downloading', {}, '0', ''], + ['is killed', { exitCode: null, signal: 'SIGKILL' }, 'SIGKILL', ''], +])('rejects and logs one warning with the exit and error output when the script %s', async (_name, reply, exit, output) => { + script(reply, false) + const message = `feishu: ${INSTALLER} exited with ${exit} and left no executable ${EXECUTABLE}${output}` + + await expect(new LarkCli(undefined, subprocess, ctx.logger).install(new AbortController().signal)).rejects.toThrow(new Error(message)) + + expect(warnings()).toEqual([['feishu: could not download lark-cli', new Error(message)]]) + expect(subprocess.processes[0]?.terminated).toBe(true) +}) + +it('stops the script on abort and rejects with the abort reason, without a warning', async () => { + subprocess.respond = () => {} + const controller = new AbortController() + const reason = new Error('cancelled') + + const installing = new LarkCli(undefined, subprocess, ctx.logger).install(controller.signal) + controller.abort(reason) + + await expect(installing).rejects.toBe(reason) + expect(subprocess.processes[0]?.terminated).toBe(true) + expect(warnings()).toEqual([]) +}) + +it('never downloads into a configured directory that lost its executable', async () => { + present = true + const cli = new LarkCli('/opt/lark/bin', subprocess, ctx.logger) + present = false + + await expect(cli.install(new AbortController().signal)).rejects.toThrow(`feishu: ${CONFIGURED} is not executable`) + + expect(subprocess.processes).toEqual([]) + expect(warnings()).toHaveLength(1) }) it('parses a command\'s JSON output and names the command whose output is not JSON', () => { diff --git a/packages/connector/feishu/tests/download.spec.ts b/packages/connector/feishu/tests/download.spec.ts new file mode 100644 index 0000000000..2fa301b20c --- /dev/null +++ b/packages/connector/feishu/tests/download.spec.ts @@ -0,0 +1,164 @@ +/** A Feishu plugin loaded without lark-cli downloads it by itself, shows the step, and leaves a retry when the download does not finish. */ +import { rm } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { Context } from '@deepseek-ai/cordis' +import { cliPathContextText } from '@deepseek-ai/dsh-cli-account/src/context.ts' +import { renderContextSections } from '@deepseek-ai/dsh-system-prompt' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { executableFileName } from '../src/cli.ts' +import * as Feishu from '../src/index.ts' +import { en, zh, type FeishuTextKey } from '../src/locales.ts' +import type { FeishuAppId, FeishuState } from '../src/types.ts' +import { createHost, type CliReply, type FeishuHost, type FeishuPage, type ScriptedProcess } from './harness.ts' + +const fs = vi.hoisted(() => ({ accessSync: vi.fn() })) +vi.mock('node:fs', async importOriginal => ({ ...await importOriginal(), accessSync: fs.accessSync })) + +const PACKAGE = dirname(fileURLToPath(import.meta.resolve('@larksuite/cli/package.json'))) +const EXECUTABLE = join(PACKAGE, 'bin', executableFileName(process.platform)) +const INSTALLER = join(PACKAGE, 'scripts', 'install.js') +const STATUS = 'auth status --verify --json' +const APP = 'cli_a' as FeishuAppId +const SIGNED_OUT: CliReply = { stdout: JSON.stringify({ appId: APP, identities: { user: { status: 'missing', available: false } } }) } +const CHECK = { kind: 'start', operation: 'check' } as const + +/** The key's text as the Chinese and English browsers resolve it. */ +const say = (key: FeishuTextKey): Partial> => ({ zh: zh[key], en: en[key] }) + +let host: FeishuHost +let ctx: Context +/** Whether lark-cli is in the `@larksuite/cli` package; the specs never write there. */ +let present: boolean +/** How the install script and `auth status` answer. */ +let install: (process: ScriptedProcess) => void +let status: (process: ScriptedProcess) => void + +beforeEach(async () => { + present = false + fs.accessSync.mockReset() + fs.accessSync.mockImplementation(() => { if (!present) throw new Error('ENOENT') }) + host = await createHost() + ;({ ctx } = host) + status = (process) => { process.reply(SIGNED_OUT) } + host.subprocess.respond = (process) => { + if (process.spec.argv[1] === INSTALLER) install(process) + else status(process) + } +}) + +afterEach(async () => { + await ctx.fiber.dispose() + await rm(host.binDir, { recursive: true, force: true }) +}) + +/** Load the plugin without `binDir`, so it manages the executable of the `@larksuite/cli` package. */ +const load = async (): Promise => { + await ctx.plugin(Feishu, {}) + return host.pages[0]! +} +const commands = () => host.subprocess.processes.map(process => process.spec.argv.slice(1).join(' ')) +const warnings = (): unknown[] => ctx.logger.buffer.filter(message => message.type === 'warn').map((message): unknown => message.args) +const runtimeContext = async () => renderContextSections(await ctx.systemPrompt.assemble()) +const skills = async () => (await ctx.skills.list()).map(skill => skill.name) +const settled = async (account: FeishuPage['source']): Promise => { + await vi.waitFor(() => { expect(account.snapshot().result).toBeDefined() }) + return account.snapshot() +} + +it('downloads a missing lark-cli after loading, then checks the account and offers the CLI path and the skill', async () => { + const downloading = Promise.withResolvers() + const checking = Promise.withResolvers() + install = (process) => { downloading.resolve(process) } + status = (process) => { checking.resolve(process) } + + const page = await load() + const account = page.source + const id = account.snapshot().operation?.id + expect(account.snapshot()).toEqual({ account: { state: 'unchecked' }, operation: { id, kind: 'check', phase: 'downloading', cancellable: true } }) + expect(page.present(account.snapshot())).toMatchObject({ + phase: 'checking', status: say('step.downloading'), buttons: [{ label: say('action.cancel'), command: { kind: 'cancel' } }], + }) + expect(await runtimeContext()).toEqual([]) + expect(await skills()).toEqual([]) + + present = true + ;(await downloading.promise).reply({}) + const check = await checking.promise + expect(account.snapshot().operation).toEqual({ id, kind: 'check', phase: 'checking', cancellable: false }) + check.reply(SIGNED_OUT) + + expect(await settled(account)).toEqual({ account: { state: 'signed-out', appId: APP }, result: { id, kind: 'check', outcome: 'succeeded' } }) + expect(commands()).toEqual([INSTALLER, STATUS]) + expect(await runtimeContext()).toEqual([{ + name: 'feishu:cli', + text: cliPathContextText({ product: 'Feishu', program: 'lark-cli', executable: EXECUTABLE }, process.platform), + }]) + expect(await skills()).toEqual(['feishu']) + expect(warnings()).toEqual([]) +}) + +it('reports a failed download with a retry, logs the script\'s error output, and downloads again on retry', async () => { + install = (process) => { process.reply({ exitCode: 1, stderr: 'Failed to install lark-cli: timeout\n' }) } + + const page = await load() + const account = page.source + const failed = await settled(account) + expect(failed).toMatchObject({ account: { state: 'not-installed' }, result: { kind: 'check', outcome: 'failed' } }) + expect(failed.result).not.toHaveProperty('failure') + expect(page.present(failed)).toMatchObject({ + phase: 'unavailable', status: say('status.unavailable'), detail: say('detail.missing'), failure: { text: say('failed') }, + buttons: [{ label: say('action.retry'), command: CHECK }], + }) + expect(warnings()).toEqual([[ + 'feishu: could not download lark-cli', + new Error(`feishu: ${INSTALLER} exited with 1 and left no executable ${EXECUTABLE}\nFailed to install lark-cli: timeout`), + ]]) + expect(await skills()).toEqual([]) + + install = (process) => { + present = true + process.reply({}) + } + const retry = await account.start('check') + await vi.waitFor(() => { expect(account.snapshot().result).toEqual({ id: retry, kind: 'check', outcome: 'succeeded' }) }) + expect(account.snapshot().account).toEqual({ state: 'signed-out', appId: APP }) + expect(commands()).toEqual([INSTALLER, INSTALLER, STATUS]) + expect(warnings()).toHaveLength(1) + expect(await skills()).toEqual(['feishu']) +}) + +it('cancels the download from the page without a warning and leaves the retry', async () => { + install = () => {} + const page = await load() + const account = page.source + const id = account.snapshot().operation!.id + + await account.cancel(id) + + expect(account.snapshot()).toEqual({ account: { state: 'not-installed' }, result: { id, kind: 'check', outcome: 'cancelled' } }) + expect(page.present(account.snapshot()).buttons).toMatchObject([{ label: say('action.retry'), command: CHECK }]) + expect(host.subprocess.processes[0]?.terminated).toBe(true) + expect(commands()).toEqual([INSTALLER]) + expect(warnings()).toEqual([]) +}) + +it('stops the download when the plugin unloads', async () => { + install = () => {} + const fiber = await ctx.plugin(Feishu, {}) + expect(commands()).toEqual([INSTALLER]) + + await fiber.dispose() + + expect(host.subprocess.processes[0]?.terminated).toBe(true) + expect(warnings()).toEqual([]) +}) + +it('starts nothing at load when the package\'s install script already put lark-cli in place', async () => { + present = true + const page = await load() + + expect(page.source.snapshot()).toEqual({ account: { state: 'unchecked' } }) + expect(host.subprocess.processes).toEqual([]) + expect(await skills()).toEqual(['feishu']) +}) diff --git a/packages/connector/feishu/tests/harness.ts b/packages/connector/feishu/tests/harness.ts index 0bfb87d673..8a473ec57c 100644 --- a/packages/connector/feishu/tests/harness.ts +++ b/packages/connector/feishu/tests/harness.ts @@ -1,4 +1,4 @@ -/** A Host for Feishu plugin specs: scripted lark-cli processes, a temporary bin directory, and a recording Plugins page registry. */ +/** A Host for Feishu plugin specs: scripted processes, a temporary bin directory, and a recording Plugins page registry. */ import { chmod, mkdtemp, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' @@ -13,6 +13,7 @@ import type { SubprocessCollectedOutputs, SubprocessHandle, SubprocessOutcome, + SubprocessOutputReader, SubprocessSpawnSpec, SubprocessTerminalEnvironment, } from '@deepseek-ai/dsh-subprocess' @@ -29,32 +30,49 @@ export interface CliReply { signal?: NodeJS.Signals | null } -/** A piped process whose managed range exits on termination. */ +type Stream = 'stdout' | 'stderr' + +/** A process whose managed range exits on termination; a stream the spec collects is read through `collected`. */ export class ScriptedProcess implements SubprocessHandle { readonly stdin = undefined readonly stdout = new PassThrough() readonly stderr = new PassThrough() readonly control = undefined - readonly collected: SubprocessCollectedOutputs = {} + readonly collected: SubprocessCollectedOutputs readonly done: Promise terminated = false + private readonly written: Record = { stdout: '', stderr: '' } private readonly outcome = Promise.withResolvers() private readonly exit = Promise.withResolvers() constructor(readonly spec: SubprocessSpawnSpec) { this.done = this.outcome.promise + this.collected = { + ...typeof spec.stdio.stdout === 'object' ? { stdout: this.reader('stdout') } : {}, + ...typeof spec.stdio.stderr === 'object' ? { stderr: this.reader('stderr') } : {}, + } spec.signal?.addEventListener('abort', () => { this.terminate() }, { once: true }) } /** Write output while the command keeps running. */ - write(stream: 'stdout' | 'stderr', text: string): void { + write(stream: Stream, text: string): void { + this.written[stream] += text this[stream].write(text) } + private reader(stream: Stream): SubprocessOutputReader { + return { + readFrom: (fromByte) => { + const bytes = Buffer.from(this.written[stream]) + return { text: bytes.subarray(fromByte).toString(), nextOffset: bytes.length, lossy: false } + }, + } + } + /** Finish the command with the given output; the managed range stays alive until termination. */ reply(reply: CliReply): void { - if (reply.stdout !== undefined) this.stdout.write(reply.stdout) - if (reply.stderr !== undefined) this.stderr.write(reply.stderr) + if (reply.stdout !== undefined) this.write('stdout', reply.stdout) + if (reply.stderr !== undefined) this.write('stderr', reply.stderr) this.close() this.outcome.resolve({ exitCode: reply.exitCode === undefined ? 0 : reply.exitCode, signal: reply.signal ?? null }) } diff --git a/packages/connector/feishu/tests/presentation.spec.ts b/packages/connector/feishu/tests/presentation.spec.ts index 61fd722166..90216a628a 100644 --- a/packages/connector/feishu/tests/presentation.spec.ts +++ b/packages/connector/feishu/tests/presentation.spec.ts @@ -92,6 +92,30 @@ it('retries an unconfirmed sign-in by checking again', () => { expect(shown.buttons).toMatchObject([{ label: say('action.retry'), command: CHECK }]) }) +it('shows the download of a missing CLI with its cancel, and a retry after one that did not finish', () => { + const UNCHECKED: FeishuState = { account: { state: 'unchecked' } } + let shown = presentAccount({ ...UNCHECKED, operation: { id: OP, kind: 'check', phase: 'downloading', cancellable: true } }) + expect(shown).toMatchObject({ phase: 'checking', status: say('step.downloading'), notes: [] }) + expect(shown.buttons).toMatchObject([{ label: say('action.cancel'), command: { kind: 'cancel' }, variant: 'ghost' }]) + expect(shown.badge).toBeUndefined() + shown = presentAccount({ ...UNCHECKED, operation: { id: OP, kind: 'check', phase: 'cancelling', cancellable: false } }) + expect(shown).toMatchObject({ phase: 'checking', status: say('status.checking'), buttons: [] }) + shown = presentAccount({ ...UNCHECKED, operation: { id: OP, kind: 'link-app', phase: 'downloading', cancellable: true } }) + expect(shown).toMatchObject({ phase: 'connecting', status: say('step.downloading') }) + + const MISSING: FeishuState = { account: { state: 'not-installed' } } + shown = presentAccount({ ...MISSING, result: { id: OP, kind: 'check', outcome: 'failed' } }) + expect(shown).toMatchObject({ + phase: 'unavailable', status: say('status.unavailable'), badge: say('badge.unavailable'), detail: say('detail.missing'), + notes: [], failure: { text: say('failed') }, + }) + expect(shown.buttons).toMatchObject([{ label: say('action.retry'), command: CHECK }]) + shown = presentAccount({ ...MISSING, result: { id: OP, kind: 'check', outcome: 'cancelled' } }) + expect(shown).toMatchObject({ phase: 'unavailable', detail: say('detail.missing') }) + expect(labels(shown)).toEqual([zh['action.retry']]) + expect(shown.failure).toBeUndefined() +}) + it('reports app-link recovery with the command and exit code', () => { let shown = presentAccount({ ...UNCONFIGURED, diff --git a/packages/connector/feishu/tests/skills.spec.ts b/packages/connector/feishu/tests/skills.spec.ts index 8e9cbd38ad..266b29e824 100644 --- a/packages/connector/feishu/tests/skills.spec.ts +++ b/packages/connector/feishu/tests/skills.spec.ts @@ -48,7 +48,7 @@ it('indexes every guide of the pinned lark-cli exactly once', () => { it('lists the entry with an opaque resource base and returns its body without the catalog-only fields', async () => { const file = join(entry, 'SKILL.md') - const provider = new FeishuSkillProvider(file) + const provider = new FeishuSkillProvider(file, () => true) expect(await provider.list()).toMatchObject([{ name: 'feishu', provider: 'feishu', source: 'bundled', locator: file, resourceBase: { kind: 'opaque' } }]) const definition = await provider.get() expect(definition).not.toHaveProperty('rank') @@ -56,14 +56,22 @@ it('lists the entry with an opaque resource base and returns its body without th expect(definition.content).toBe(body().trim()) }) +it('lists the entry only while lark-cli, which serves its guides, is installed', async () => { + let installed = false + const provider = new FeishuSkillProvider(join(entry, 'SKILL.md'), () => installed) + expect(await provider.list()).toEqual([]) + installed = true + expect(await provider.list()).toMatchObject([{ name: 'feishu' }]) +}) + it('refuses an entry without YAML frontmatter or without a skill name and description', async () => { const dir = await mkdtemp(join(tmpdir(), 'dsh-feishu-entry-')) try { const file = join(dir, 'SKILL.md') await writeFile(file, '# No frontmatter\n') - expect(() => new FeishuSkillProvider(file)).toThrow('has no YAML frontmatter') + expect(() => new FeishuSkillProvider(file, () => true)).toThrow('has no YAML frontmatter') await writeFile(file, '---\nname: Not A Skill\n---\n\nbody\n') - expect(() => new FeishuSkillProvider(file)).toThrow('needs a skill name and a description') + expect(() => new FeishuSkillProvider(file, () => true)).toThrow('needs a skill name and a description') } finally { await rm(dir, { recursive: true, force: true }) } diff --git a/packages/connector/feishu/tsconfig.json b/packages/connector/feishu/tsconfig.json index e907e5373d..8e9912658b 100644 --- a/packages/connector/feishu/tsconfig.json +++ b/packages/connector/feishu/tsconfig.json @@ -23,6 +23,9 @@ { "path": "../../skill/skill" }, + { + "path": "../../subprocess/subprocess" + }, { "path": "../cli-account" }, From 930997545cc13ac4367fff0fb218dc7dd29b440f Mon Sep 17 00:00:00 2001 From: gengruilin Date: Sat, 21 Nov 2026 16:58:36 +0800 Subject: [PATCH 2/8] feat(cli-account): prepare step for CLI and skills downloads ctx.cliAccounts takes an optional `prepare` (phase, unprepared, ready, run). While it is not ready, a check stages the phase and awaits `run` before the plugin's `perform`; a failed or cancelled run publishes `unprepared` and `perform` is not called. - Feishu and DingTalk declare the lark-cli and dws release downloads as their prepare step instead of running them in their own check. - WeCom and Tencent Meeting declare the upstream skills download as theirs, so the account check waits for the skills and the page can cancel and retry it. The skills handle is now `installed()` / `install(signal)`; `state`, `watch()`, and `retry()` are removed. - `CliPathContext.ready` is replaced by `prepare.ready`. - Feishu's skill provider invalidates the catalog once lark-cli is in place after a listing without the entry, including after a cancelled download that already copied the binary and after an installation made outside the plugin's download. Refs #8942 --- docs/subsystems/boot.md | 5 +- docs/subsystems/boot.zh.md | 5 +- docs/subsystems/skills.md | 9 +- docs/subsystems/skills.zh.md | 9 +- .../connector/cli-account/README.i18n.yaml | 15 +- packages/connector/cli-account/README.md | 10 +- packages/connector/cli-account/README.zh.md | 10 +- packages/connector/cli-account/src/context.ts | 7 +- packages/connector/cli-account/src/index.ts | 23 ++- packages/connector/cli-account/src/types.ts | 27 ++++ .../cli-account/tests/context.spec.ts | 8 +- .../cli-account/tests/service.spec.ts | 126 ++++++++++++++- packages/connector/dingtalk/README.i18n.yaml | 4 +- packages/connector/dingtalk/README.md | 4 +- packages/connector/dingtalk/README.zh.md | 4 +- packages/connector/dingtalk/src/account.ts | 28 +--- packages/connector/dingtalk/src/index.ts | 12 +- packages/connector/feishu/README.i18n.yaml | 12 +- packages/connector/feishu/README.md | 8 +- packages/connector/feishu/README.zh.md | 8 +- packages/connector/feishu/src/account.ts | 68 +++----- packages/connector/feishu/src/index.ts | 32 ++-- packages/connector/feishu/src/skills.ts | 24 ++- .../connector/feishu/tests/download.spec.ts | 40 +++++ .../connector/feishu/tests/skills.spec.ts | 26 ++- .../tencent-meeting/README.i18n.yaml | 24 +-- packages/connector/tencent-meeting/README.md | 16 +- .../connector/tencent-meeting/README.zh.md | 16 +- .../connector/tencent-meeting/src/account.ts | 60 +++---- .../connector/tencent-meeting/src/index.ts | 27 ++-- .../connector/tencent-meeting/src/locales.ts | 32 ++-- .../tencent-meeting/src/presentation.ts | 58 ++++--- .../connector/tencent-meeting/src/types.ts | 18 +-- .../tencent-meeting/tests/account.spec.ts | 91 +++++++---- .../tencent-meeting/tests/plugin.spec.ts | 12 +- .../tests/presentation.spec.ts | 26 +-- .../upstream-skills/README.i18n.yaml | 12 +- packages/connector/upstream-skills/README.md | 12 +- .../connector/upstream-skills/README.zh.md | 12 +- .../connector/upstream-skills/src/index.ts | 121 ++++++++------ .../connector/upstream-skills/src/types.ts | 26 +-- .../upstream-skills/tests/service.spec.ts | 153 ++++++++++-------- packages/connector/wecom/README.i18n.yaml | 24 +-- packages/connector/wecom/README.md | 16 +- packages/connector/wecom/README.zh.md | 16 +- packages/connector/wecom/src/account.ts | 45 +++--- packages/connector/wecom/src/index.ts | 27 ++-- packages/connector/wecom/src/locales.ts | 32 ++-- packages/connector/wecom/src/presentation.ts | 49 +++--- packages/connector/wecom/src/types.ts | 14 +- .../connector/wecom/tests/account.spec.ts | 83 +++++++--- packages/connector/wecom/tests/plugin.spec.ts | 12 +- .../wecom/tests/presentation.spec.ts | 30 ++-- .../extensions/tool-cordis/src/api-catalog.ts | 20 +-- 54 files changed, 975 insertions(+), 633 deletions(-) diff --git a/docs/subsystems/boot.md b/docs/subsystems/boot.md index 704ce4467b..9a460428fb 100644 --- a/docs/subsystems/boot.md +++ b/docs/subsystems/boot.md @@ -126,8 +126,9 @@ Holds what CLI app plugins register: for each plugin, the CLI path the model rea /** * Register the calling plugin's CLI and account: add the CLI's absolute path to required runtime context, run the * plugin's account operations one at a time, and show the account on the Plugins page while `connectorAccounts` is - * loaded. The registration belongs to the calling plugin: unloading that plugin withdraws it, after the active - * operation and the CLI processes it started have stopped. + * loaded. With a `prepare` step, the path stays out of runtime context while the step reports that something is + * missing, and each check first runs the step. The registration belongs to the calling plugin: unloading that plugin + * withdraws it, after the active operation and the CLI processes it started have stopped. * @param registration - the plugin's CLI, account operations, and Plugins page text. * @returns the handle for the plugin's own reads and updates of the account. * @throws when the runtime-context name `:cli` is already registered. diff --git a/docs/subsystems/boot.zh.md b/docs/subsystems/boot.zh.md index e441de34b8..7b8d4265f0 100644 --- a/docs/subsystems/boot.zh.md +++ b/docs/subsystems/boot.zh.md @@ -126,8 +126,9 @@ Holds what CLI app plugins register: for each plugin, the CLI path the model rea /** * Register the calling plugin's CLI and account: add the CLI's absolute path to required runtime context, run the * plugin's account operations one at a time, and show the account on the Plugins page while `connectorAccounts` is - * loaded. The registration belongs to the calling plugin: unloading that plugin withdraws it, after the active - * operation and the CLI processes it started have stopped. + * loaded. With a `prepare` step, the path stays out of runtime context while the step reports that something is + * missing, and each check first runs the step. The registration belongs to the calling plugin: unloading that plugin + * withdraws it, after the active operation and the CLI processes it started have stopped. * @param registration - the plugin's CLI, account operations, and Plugins page text. * @returns the handle for the plugin's own reads and updates of the account. * @throws when the runtime-context name `:cli` is already registered. diff --git a/docs/subsystems/skills.md b/docs/subsystems/skills.md index 9c644b2f2b..82fdfa72db 100644 --- a/docs/subsystems/skills.md +++ b/docs/subsystems/skills.md @@ -337,11 +337,12 @@ Holds what CLI app plugins register: for each plugin, the entry skill and the do /** * Register the calling plugin's entry skill and start downloading the upstream files unless they are in place. The * download starts at load so that a session without a client also gets the skill; a failure is logged as a warning - * and waits for `retry()`. In a profile, the files go to that profile's own directory for the plugin, and the - * registration deletes the other pins there once, the first time its own pin is in place. The registration belongs - * to the calling plugin: unloading that plugin aborts the download and removes the entry skill. + * and the files stay missing until a call of `install()` downloads them. In a profile, the files go to that + * profile's own directory for the plugin, and the registration deletes the other pins there once, the first time its + * own pin is in place. The registration belongs to the calling plugin: unloading that plugin aborts the download and + * removes the entry skill. * @param registration - the plugin's provider name, entry, pinned files, and optional skills directory. - * @returns the handle the plugin's view observes and its check retries. + * @returns the handle the plugin reads the files' presence from and waits for the download through. * @throws when the entry has no skill name or description in its frontmatter, `skillsDir` is not a directory, or a * skill provider named `name` is already registered. */ diff --git a/docs/subsystems/skills.zh.md b/docs/subsystems/skills.zh.md index 72defb9e6e..9ecb54a1dd 100644 --- a/docs/subsystems/skills.zh.md +++ b/docs/subsystems/skills.zh.md @@ -337,11 +337,12 @@ Holds what CLI app plugins register: for each plugin, the entry skill and the do /** * Register the calling plugin's entry skill and start downloading the upstream files unless they are in place. The * download starts at load so that a session without a client also gets the skill; a failure is logged as a warning - * and waits for `retry()`. In a profile, the files go to that profile's own directory for the plugin, and the - * registration deletes the other pins there once, the first time its own pin is in place. The registration belongs - * to the calling plugin: unloading that plugin aborts the download and removes the entry skill. + * and the files stay missing until a call of `install()` downloads them. In a profile, the files go to that + * profile's own directory for the plugin, and the registration deletes the other pins there once, the first time its + * own pin is in place. The registration belongs to the calling plugin: unloading that plugin aborts the download and + * removes the entry skill. * @param registration - the plugin's provider name, entry, pinned files, and optional skills directory. - * @returns the handle the plugin's view observes and its check retries. + * @returns the handle the plugin reads the files' presence from and waits for the download through. * @throws when the entry has no skill name or description in its frontmatter, `skillsDir` is not a directory, or a * skill provider named `name` is already registered. */ diff --git a/packages/connector/cli-account/README.i18n.yaml b/packages/connector/cli-account/README.i18n.yaml index c55613959b..dc32284333 100644 --- a/packages/connector/cli-account/README.i18n.yaml +++ b/packages/connector/cli-account/README.i18n.yaml @@ -24,11 +24,14 @@ en: 9e7f25e057b870b0 zh: a8950b9482758801 /deepseek-ai-dsh-cli-account/use-this-package/register-a-cli-and-its-account: - en: 076ef7d8d0d837b1 - zh: 5053287a6410caa2 + en: a1878b0a5129ad53 + zh: bd920a3c5f985d03 +/deepseek-ai-dsh-cli-account/use-this-package/prepare-before-a-check: + en: d872850f76f7cc99 + zh: 4389f3750c92e2db /deepseek-ai-dsh-cli-account/use-this-package/runtime-context: - en: 4f73f126b4ae0afe - zh: ac8123c5f2a72ea2 + en: e9152a589f09b94b + zh: 04d192c2742bc2a8 /deepseek-ai-dsh-cli-account/use-this-package/commands-links-and-failures: en: 626febacb5f8979a zh: ac9abc5cb4f7c909 @@ -45,8 +48,8 @@ en: b5fed52af6c0d771 zh: 25b7aa5297583030 /deepseek-ai-dsh-cli-account/model-experience/cli-path/what-the-model-sees: - en: 7200c4d790046006 - zh: 5d7be6048a27acd3 + en: 487a746ec7b90c83 + zh: 43e0d2cc378fa0ba /deepseek-ai-dsh-cli-account/model-experience/cli-path/what-the-model-sees/runtime-context-entry: en: c91314832f78f460 zh: aac156ea0b5b816a diff --git a/packages/connector/cli-account/README.md b/packages/connector/cli-account/README.md index c22b72cf51..2091d80599 100644 --- a/packages/connector/cli-account/README.md +++ b/packages/connector/cli-account/README.md @@ -95,14 +95,20 @@ export function apply(ctx: Context): void { - `packageName` is the npm package whose Plugins page shows the account. - `cli` names the product, the program, and the absolute path of the executable that the model and the operations both run. - `account` is the account before the first check, and `check` is the operation the page starts for each new subscriber when none runs. +- `prepare` is optional: what the plugin puts in place before its account can be checked, such as a download of the CLI or of its skills. [Prepare before a check](#prepare-before-a-check) describes it. - `perform(kind, control, signal)` carries out one operation: `control.run` runs one command of the CLI, `control.stage` enters a phase of the plugin, `control.offer` offers an authorization link to the page, and `control.publish` replaces the account. - `operations(text)` lists the operations a page button may start, `copy(text)` writes the fixed text of the account section, and `present(view, text)` maps the current view to what the section shows. `text(key, params)` writes one key of `dictionaries` in every language they hold and fills each `{name}` placeholder from `params`; the browser resolves the result in its active language. The returned handle serves the plugin outside an operation: `snapshot()` returns the current `CliAccountView`, `publish(account)` replaces the account, `refresh()` starts a check unless an operation already runs, and `dispose()` withdraws the registration before the plugin unloads. The JSDoc in [`src/types.ts`](src/types.ts) states each member's exact behavior. + +### Prepare before a check + +A plugin whose CLI or skills are downloaded after load registers `prepare: { phase, unprepared, ready, run }`. While `ready()` returns false, each `check` operation enters `phase`, awaits `run(signal)`, enters the Service's `checking` phase, and only then calls `perform`; the other operations call `perform` at once. When `run` throws, the account becomes `unprepared`, `perform` is not called, and the operation fails without a command in its result. The page can cancel `run` when `phase` is listed in `cancellable`: the signal aborts, the account becomes `unprepared`, and the operation ends as cancelled. `run` is not called while `ready()` returns true, and the next check calls it again after a failure, which makes the page's retry button the way to repeat a download. + ### Runtime context -`register` adds one required runtime-context entry, named `:cli`, that tells the model to run `cli.program` by `cli.executable`, the path the operations' commands run. With `cli.scripts`, it also tells the model to put the executable's directory first on PATH only in the commands that run the skill's scripts, and never to run `cli.program` by name. The text follows the shell that shipped compositions give the model on the Host platform. Outside Windows it uses POSIX shell syntax: the prefix is `PATH=":$PATH"`, which changes PATH for that command only, and the text also forbids exporting PATH. On Windows, where the model runs PowerShell, it names the executable with the call operator, `& ''`, and gives the prefix as `$env:PATH = ';' + $env:PATH`, which lasts only for that call because each PowerShell call runs in a fresh process. With `cli.ready`, the entry contributes nothing while `ready()` returns false. The text is never interpolated. [Model Experience](#model-experience) shows the text. +`register` adds one required runtime-context entry, named `:cli`, that tells the model to run `cli.program` by `cli.executable`, the path the operations' commands run. With `cli.scripts`, it also tells the model to put the executable's directory first on PATH only in the commands that run the skill's scripts, and never to run `cli.program` by name. The text follows the shell that shipped compositions give the model on the Host platform. Outside Windows it uses POSIX shell syntax: the prefix is `PATH=":$PATH"`, which changes PATH for that command only, and the text also forbids exporting PATH. On Windows, where the model runs PowerShell, it names the executable with the call operator, `& ''`, and gives the prefix as `$env:PATH = ';' + $env:PATH`, which lasts only for that call because each PowerShell call runs in a fresh process. With `prepare`, the entry contributes nothing while `prepare.ready()` returns false. The text is never interpolated. [Model Experience](#model-experience) shows the text. ### Commands, links, and failures @@ -153,7 +159,7 @@ The Service owns each registration's lifetime and the plugin owns the meaning of #### What the model sees -One required runtime-context entry, at context order 220, for each plugin registered with `ctx.cliAccounts` whose `cli.ready` is absent or returns true; it stays when optional runtime context is off. The second line appears only with `cli.scripts`. The placeholders come from the registration's `cli`. Outside Windows the quoted values are JSON strings; on Windows they are PowerShell single-quoted strings, in which a single quote is doubled. While no plugin is registered, the Service adds nothing to a model request. +One required runtime-context entry, at context order 220, for each plugin registered with `ctx.cliAccounts` whose `prepare` is absent or whose `prepare.ready()` returns true; it stays when optional runtime context is off. The second line appears only with `cli.scripts`. The placeholders come from the registration's `cli`. Outside Windows the quoted values are JSON strings; on Windows they are PowerShell single-quoted strings, in which a single quote is doubled. While no plugin is registered, the Service adds nothing to a model request. ##### Runtime-context entry diff --git a/packages/connector/cli-account/README.zh.md b/packages/connector/cli-account/README.zh.md index 044559cb7f..8976e2be5d 100644 --- a/packages/connector/cli-account/README.zh.md +++ b/packages/connector/cli-account/README.zh.md @@ -95,14 +95,20 @@ export function apply(ctx: Context): void { - `packageName` 是 npm 包名,账号显示在这个包的插件页上。 - `cli` 给出产品名、程序名,以及模型和账号操作共同运行的可执行文件的绝对路径。 - `account` 是首次检查之前的账号,`check` 是没有操作运行时插件页为每个新订阅者启动的操作。 +- `prepare` 可选:插件在账号可以检查之前要准备好的内容,例如下载 CLI 或它的 skills,见[检查之前的准备](#prepare-before-a-check)。 - `perform(kind, control, signal)` 执行一个操作:`control.run` 运行 CLI 的一条命令,`control.stage` 进入插件的一个阶段,`control.offer` 向插件页提供授权链接,`control.publish` 替换账号。 - `operations(text)` 列出插件页按钮可以启动的操作,`copy(text)` 写出账号区域的固定文案,`present(view, text)` 把当前视图映射为该区域显示的内容。`text(key, params)` 用 `dictionaries` 中的每种语言写出一个键,并用 `params` 填充每个 `{name}` 占位符;浏览器按其当前语言解析结果。 返回的句柄供插件在操作之外使用:`snapshot()` 返回当前的 `CliAccountView`,`publish(account)` 替换账号,`refresh()` 在没有操作运行时启动一次检查,`dispose()` 在插件卸载之前撤回注册。每个成员的确切行为见 [`src/types.ts`](src/types.ts) 中的 JSDoc。 + +### 检查之前的准备 + +CLI 或 skills 在加载之后才下载的插件注册 `prepare: { phase, unprepared, ready, run }`。`ready()` 返回 false 期间,每次 `check` 操作先进入 `phase`,等待 `run(signal)`,再进入 Service 的 `checking` 阶段,然后才调用 `perform`;其他操作直接调用 `perform`。`run` 抛出异常时,账号变为 `unprepared`,`perform` 不被调用,操作失败,结果中没有命令。`phase` 列在 `cancellable` 中时,插件页可以取消 `run`:signal 中止,账号变为 `unprepared`,操作以取消结束。`ready()` 返回 true 时不调用 `run`;失败之后的下一次检查会再次调用它,所以插件页的重试按钮就是重新下载的方式。 + ### 运行时上下文 -`register` 添加一条必需的运行时上下文条目,名为 `:cli`,让模型按 `cli.executable` 运行 `cli.program`,这正是账号操作的命令运行的路径。设置 `cli.scripts` 时,它还让模型只在运行 skill 脚本的命令中把可执行文件所在目录放到 PATH 最前面,并且不要按名称运行 `cli.program`。文本采用内置组合在 Host 平台上提供给模型的 shell 写法。在 Windows 以外的平台上使用 POSIX shell 语法:前缀是 `PATH="<可执行文件所在目录>:$PATH"`,只改变这一条命令的 PATH,文本还要求不要导出 PATH。在 Windows 上模型使用 PowerShell,文本用调用运算符写出可执行文件 `& '<可执行文件>'`,前缀写作 `$env:PATH = '<可执行文件所在目录>;' + $env:PATH`;PowerShell 每次调用都在新进程中运行,所以这个修改只在本次调用内有效。设置 `cli.ready` 时,`ready()` 返回 false 期间这条上下文不贡献任何内容。文本从不做变量插值。文本见[模型体验](#model-experience)。 +`register` 添加一条必需的运行时上下文条目,名为 `:cli`,让模型按 `cli.executable` 运行 `cli.program`,这正是账号操作的命令运行的路径。设置 `cli.scripts` 时,它还让模型只在运行 skill 脚本的命令中把可执行文件所在目录放到 PATH 最前面,并且不要按名称运行 `cli.program`。文本采用内置组合在 Host 平台上提供给模型的 shell 写法。在 Windows 以外的平台上使用 POSIX shell 语法:前缀是 `PATH="<可执行文件所在目录>:$PATH"`,只改变这一条命令的 PATH,文本还要求不要导出 PATH。在 Windows 上模型使用 PowerShell,文本用调用运算符写出可执行文件 `& '<可执行文件>'`,前缀写作 `$env:PATH = '<可执行文件所在目录>;' + $env:PATH`;PowerShell 每次调用都在新进程中运行,所以这个修改只在本次调用内有效。设置 `prepare` 时,`prepare.ready()` 返回 false 期间这条上下文不贡献任何内容。文本从不做变量插值。文本见[模型体验](#model-experience)。 ### 命令、链接与失败 @@ -153,7 +159,7 @@ Service 负责每个注册的生命周期,插件负责每条命令的含义。 #### 模型看到什么 -每个通过 `ctx.cliAccounts` 注册、且 `cli.ready` 未设置或返回 true 的插件,在上下文顺序 220 处有一条必需的运行时上下文条目;关闭可选运行时上下文时它仍然保留。第二行只在设置 `cli.scripts` 时出现。占位符取自注册的 `cli`。在 Windows 以外的平台上,引号内的值是 JSON 字符串;在 Windows 上是 PowerShell 单引号字符串,其中的单引号写成两个。没有插件注册时,Service 不向模型请求添加任何内容。 +每个通过 `ctx.cliAccounts` 注册、且 `prepare` 未设置或 `prepare.ready()` 返回 true 的插件,在上下文顺序 220 处有一条必需的运行时上下文条目;关闭可选运行时上下文时它仍然保留。第二行只在设置 `cli.scripts` 时出现。占位符取自注册的 `cli`。在 Windows 以外的平台上,引号内的值是 JSON 字符串;在 Windows 上是 PowerShell 单引号字符串,其中的单引号写成两个。没有插件注册时,Service 不向模型请求添加任何内容。 ##### 运行时上下文条目 diff --git a/packages/connector/cli-account/src/context.ts b/packages/connector/cli-account/src/context.ts index 947ade68fa..95fe724c8b 100644 --- a/packages/connector/cli-account/src/context.ts +++ b/packages/connector/cli-account/src/context.ts @@ -14,8 +14,6 @@ export interface CliPathContext { readonly executable: string /** Whether the plugin's skill has scripts that run {@link program} by name; the text then gives their PATH prefix. */ readonly scripts?: boolean - /** Whether the executable is installed; the context contributes nothing while it returns false. Absent means always. */ - readonly ready?: () => boolean } /** @@ -55,11 +53,12 @@ function pwshLiteral(text: string): string { * @param ctx - the registering plugin's context, which reaches `systemPrompt`; disposing it removes the context. * @param name - the runtime-context name, unique across plugins, such as `feishu:cli`. * @param cli - the CLI to describe. + * @param ready - tells whether the CLI and what it needs are in place; the context contributes nothing while it returns + * false. Absent means always. * @returns the registration's effect disposer. */ -export function registerCliPathContext(ctx: Context, name: string, cli: CliPathContext): () => void { +export function registerCliPathContext(ctx: Context, name: string, cli: CliPathContext, ready?: () => boolean): () => void { const text = cliPathContextText(cli, process.platform) - const { ready } = cli return ctx.systemPrompt.context({ name, order: ctx.systemPrompt.getContextOrder('PLUGIN_CLIS'), diff --git a/packages/connector/cli-account/src/index.ts b/packages/connector/cli-account/src/index.ts index 9e198a1b4c..60145d0922 100644 --- a/packages/connector/cli-account/src/index.ts +++ b/packages/connector/cli-account/src/index.ts @@ -53,8 +53,9 @@ export default class CliAccounts extends Service { /** * Register the calling plugin's CLI and account: add the CLI's absolute path to required runtime context, run the * plugin's account operations one at a time, and show the account on the Plugins page while `connectorAccounts` is - * loaded. The registration belongs to the calling plugin: unloading that plugin withdraws it, after the active - * operation and the CLI processes it started have stopped. + * loaded. With a `prepare` step, the path stays out of runtime context while the step reports that something is + * missing, and each check first runs the step. The registration belongs to the calling plugin: unloading that plugin + * withdraws it, after the active operation and the CLI processes it started have stopped. * @param registration - the plugin's CLI, account operations, and Plugins page text. * @returns the handle for the plugin's own reads and updates of the account. * @throws when the runtime-context name `:cli` is already registered. @@ -63,7 +64,7 @@ export default class CliAccounts extends Service { registration: CliAccountRegistration, ): CliAccountHandle { const caller = this.ctx - const { name, packageName, cli } = registration + const { name, packageName, cli, prepare } = registration const text = accountText(registration.dictionaries) const runtime = new CliAccountRuntime({ name, @@ -71,7 +72,19 @@ export default class CliAccounts extends Service { check: registration.check, cancellable: registration.cancellable, authorizationHosts: registration.authorizationHosts, - perform: (kind, control, signal) => registration.perform(kind, control, signal), + perform: async (kind, control, signal) => { + if (kind === registration.check && prepare !== undefined && !prepare.ready()) { + control.stage(prepare.phase) + try { + await prepare.run(signal) + } catch (error) { + control.publish(prepare.unprepared) + throw error + } + control.stage('checking') + } + await registration.perform(kind, control, signal) + }, executor: new CliCommandExecutor(caller.subprocess, { program: cli.program, executable: cli.executable, commandTimeoutMs: this.config.commandTimeoutMs, }), @@ -88,7 +101,7 @@ export default class CliAccounts extends Service { // One effect orders the teardown: the page account goes first, then the operation and its processes stop, and // the path context goes last. const withdraw = caller.effect(function* () { - yield registerCliPathContext(caller, `${name}:cli`, cli) + yield registerCliPathContext(caller, `${name}:cli`, cli, prepare === undefined ? undefined : () => prepare.ready()) yield () => runtime.dispose() const page = caller.inject(['connectorAccounts'], (scope) => { scope.effect( diff --git a/packages/connector/cli-account/src/types.ts b/packages/connector/cli-account/src/types.ts index 98f3e90c7f..2b7ba3c452 100644 --- a/packages/connector/cli-account/src/types.ts +++ b/packages/connector/cli-account/src/types.ts @@ -78,6 +78,31 @@ export interface CliOperationControl { + /** The plugin phase the operation is in while `run` runs; listed in `cancellable` when the page may cancel `run`. */ + readonly phase: Phase + /** The account the view reports after `run` threw or was cancelled. */ + readonly unprepared: Account + /** + * Tell whether everything `run` puts in place is there; called before each `check` operation and each time required + * runtime context is assembled. + * @returns false while something is missing. + */ + ready(): boolean + /** + * Put in place what is missing. Throwing fails the operation, unless the operation was cancelled; what it throws is + * neither logged nor shown. + * @param signal - aborts on cancellation and when the plugin unloads. + * @returns once `ready()` returns true. + */ + run(signal: AbortSignal): Promise +} + /** * One app plugin's CLI, account operations, and Plugins page text. `Account` is the plugin's credential-free account * state, `Kind` its operations, `Phase` its operation phases, `Command` its command identifiers, and `Key` its @@ -95,6 +120,8 @@ export interface CliAccountRegistration< readonly packageName: string /** The CLI the model runs by its absolute path and the operations run commands of. */ readonly cli: CliPathContext + /** What the plugin puts in place before a check; absent when the CLI and what it needs are there from load. */ + readonly prepare?: CliAccountPreparation /** The account before the first check. */ readonly account: Account /** The operation each new Plugins page subscriber starts when none runs. */ diff --git a/packages/connector/cli-account/tests/context.spec.ts b/packages/connector/cli-account/tests/context.spec.ts index 47c664a8e1..132d2347c7 100644 --- a/packages/connector/cli-account/tests/context.spec.ts +++ b/packages/connector/cli-account/tests/context.spec.ts @@ -19,8 +19,8 @@ async function requiredContextOnly(): Promise { } /** Register the context from its own plugin, so disposing that plugin removes it. */ -async function register(ctx: Context, cli: CliPathContext) { - return await ctx.plugin(Object.assign((inner: Context) => { registerCliPathContext(inner, 'fixture:cli', cli) }, { inject: ['systemPrompt'] })) +async function register(ctx: Context, cli: CliPathContext, ready?: () => boolean) { + return await ctx.plugin(Object.assign((inner: Context) => { registerCliPathContext(inner, 'fixture:cli', cli, ready) }, { inject: ['systemPrompt'] })) } async function rendered(ctx: Context) { @@ -66,10 +66,10 @@ describe('registerCliPathContext', () => { expect((await rendered(ctx))[0]?.text).toContain('/opt/{{tools}}/fixture-cli') }) - it('contributes nothing while the executable is not ready', async () => { + it('contributes nothing while the CLI is not ready', async () => { const ctx = await requiredContextOnly() let ready = false - await register(ctx, { ...CLI, scripts: true, ready: () => ready }) + await register(ctx, { ...CLI, scripts: true }, () => ready) expect(await rendered(ctx)).toEqual([]) ready = true diff --git a/packages/connector/cli-account/tests/service.spec.ts b/packages/connector/cli-account/tests/service.spec.ts index 9d9717004e..c8dedd6788 100644 --- a/packages/connector/cli-account/tests/service.spec.ts +++ b/packages/connector/cli-account/tests/service.spec.ts @@ -9,9 +9,9 @@ import { cliPathContextText } from '../src/context.ts' import CliAccounts, { type CliAccountHandle, type CliAccountRegistration } from '../src/index.ts' import { EXECUTABLE, PROGRAM, ScriptedSubprocess, type ScriptedProcess } from './harness.ts' -interface Account { readonly state: 'unchecked' | 'signed-out' | 'signed-in' } +interface Account { readonly state: 'unchecked' | 'not-installed' | 'signed-out' | 'signed-in' } type Kind = 'check' | 'connect' -type Phase = 'authorizing' +type Phase = 'downloading' | 'authorizing' type Command = 'status' | 'login' const DICTIONARIES = { @@ -94,6 +94,26 @@ async function requiredContext(ctx: Context) { return renderContextSections(await ctx.systemPrompt.assemble()) } +/** + * A registration with a prepare step that a test ends: `finish` puts everything in place, `fail` rejects the step, and + * an aborted signal rejects it with the signal's reason. + */ +function preparing() { + const step: PromiseWithResolvers = Promise.withResolvers() + let ready = false + const run = vi.fn(async (signal: AbortSignal) => { + signal.addEventListener('abort', () => { step.reject(signal.reason) }, { once: true }) + await step.promise + ready = true + }) + const registration: Registration = { + ...REGISTRATION, + cancellable: ['downloading', 'authorizing'], + prepare: { phase: 'downloading', unprepared: { state: 'not-installed' }, ready: () => ready, run }, + } + return { registration, run, finish: () => { step.resolve() }, fail: () => { step.reject(new Error('download failed')) } } +} + describe('Config', () => { it('defaults the command deadline to 30 seconds', () => { expect(CliAccounts.Config({})).toEqual({ commandTimeoutMs: 30_000 }) @@ -283,3 +303,105 @@ describe('register', () => { expect(handle.dispose()).toBe(withdrawn) }) }) + +describe('prepare', () => { + it('runs the step in its phase before a check while something is missing, then checks', async () => { + const { ctx, subprocess } = await host() + let status!: ScriptedProcess + subprocess.respond = (process) => { status = process } + const step = preparing() + const { handle } = await app(ctx, step.registration) + + handle.refresh() + + expect(handle.snapshot().operation).toMatchObject({ kind: 'check', phase: 'downloading', cancellable: true }) + expect(subprocess.processes).toEqual([]) + step.finish() + await vi.waitFor(() => { expect(status).toBeDefined() }) + expect(handle.snapshot().operation).toMatchObject({ kind: 'check', phase: 'checking', cancellable: false }) + status.reply({ stdout: 'in\n' }) + await vi.waitFor(() => { expect(handle.snapshot().account).toEqual({ state: 'signed-in' }) }) + + subprocess.respond = (process) => { process.reply({ stdout: 'out\n' }) } + handle.refresh() + await vi.waitFor(() => { expect(handle.snapshot().account).toEqual({ state: 'signed-out' }) }) + expect(step.run).toHaveBeenCalledOnce() + }) + + it('keeps the CLI path out of required runtime context while something is missing', async () => { + const { ctx, subprocess } = await host() + subprocess.respond = (process) => { process.reply({ stdout: 'in\n' }) } + const step = preparing() + const { handle } = await app(ctx, step.registration) + expect(await requiredContext(ctx)).toEqual([]) + + handle.refresh() + step.finish() + + await vi.waitFor(() => { expect(handle.snapshot().account).toEqual({ state: 'signed-in' }) }) + expect(await requiredContext(ctx)).toEqual([CLI_CONTEXT]) + }) + + it('reports the unprepared account and fails the check without performing it when the step throws', async () => { + const { ctx, subprocess } = await host() + const step = preparing() + const { handle } = await app(ctx, step.registration) + const page = follow(ctx) + await vi.waitFor(() => { expect(step.run).toHaveBeenCalledOnce() }) + const id = handle.snapshot().operation?.id + + step.fail() + + await vi.waitFor(() => { expect(handle.snapshot()).toEqual({ account: { state: 'not-installed' }, result: { id, kind: 'check', outcome: 'failed' } }) }) + await vi.waitFor(() => { expect(page()[0]?.display).toEqual({ ...DISCONNECTED, failure: { text: both('failed') } }) }) + expect(subprocess.processes).toEqual([]) + }) + + it('stops the step when the page cancels the check, and reports the unprepared account', async () => { + const { ctx, subprocess } = await host() + const step = preparing() + const { handle } = await app(ctx, step.registration) + const id = await ctx.connectorAccounts.start(PACKAGE, 'check') + + await ctx.connectorAccounts.cancel(PACKAGE, id) + + expect(step.run.mock.calls[0]?.[0].aborted).toBe(true) + expect(handle.snapshot()).toEqual({ account: { state: 'not-installed' }, result: { id, kind: 'check', outcome: 'cancelled' } }) + expect(subprocess.processes).toEqual([]) + }) + + it('starts the other operations without the step', async () => { + const { ctx, subprocess } = await host() + subprocess.respond = (process) => { process.reply({ stdout: 'in\n' }) } + const step = preparing() + const { handle } = await app(ctx, step.registration) + + const id = await ctx.connectorAccounts.start(PACKAGE, 'connect') + + await vi.waitFor(() => { expect(handle.snapshot().result).toEqual({ id, kind: 'connect', outcome: 'succeeded' }) }) + expect(step.run).not.toHaveBeenCalled() + }) + + it('calls ready and run as methods of the step', async () => { + const { ctx, subprocess } = await host() + subprocess.respond = (process) => { process.reply({ stdout: 'in\n' }) } + const prepare: NonNullable & { installed: boolean } = { + phase: 'downloading', + unprepared: { state: 'not-installed' }, + installed: false, + ready() { + return this.installed + }, + run() { + this.installed = true + return Promise.resolve() + }, + } + const { handle } = await app(ctx, { ...REGISTRATION, prepare }) + + handle.refresh() + + await vi.waitFor(() => { expect(handle.snapshot().account).toEqual({ state: 'signed-in' }) }) + expect(await requiredContext(ctx)).toEqual([CLI_CONTEXT]) + }) +}) diff --git a/packages/connector/dingtalk/README.i18n.yaml b/packages/connector/dingtalk/README.i18n.yaml index 98e152e641..449af7e6c2 100644 --- a/packages/connector/dingtalk/README.i18n.yaml +++ b/packages/connector/dingtalk/README.i18n.yaml @@ -30,8 +30,8 @@ en: f97716c608f5d992 zh: 97909644448a4523 /deepseek-ai-dsh-dingtalk/understand-the-implementation: - en: e163577da5bd714e - zh: 4af436cf6e1de313 + en: f8537e0dfd59838e + zh: 5e176fa1f0679757 /deepseek-ai-dsh-dingtalk/further-exploration: en: 6168b422ce45d808 zh: a6cb0e594ca78132 diff --git a/packages/connector/dingtalk/README.md b/packages/connector/dingtalk/README.md index 2a86d718b3..3208d9d985 100644 --- a/packages/connector/dingtalk/README.md +++ b/packages/connector/dingtalk/README.md @@ -79,11 +79,11 @@ The generated [config catalog](../../../docs/config-catalog.md#deepseek-aidsh-di
Implementation internals — click to expand -[`cordis.patch.yml`](cordis.patch.yml) inserts this package as the `dingtalk` row after the profile's other layers, and the Plugins page keys the account section by this package name. [`src/index.ts`](src/index.ts) is a function plugin. It registers the path of `dws` and the account with `ctx.cliAccounts`, mounts a [filesystem skill provider](../../skill/skill-filesystem/README.md) named `dingtalk` over the skill root that `src/release.ts` publishes, and starts one check so that a session without a browser also finds `dws` and the skill. The provider omits the default roots and watches the skill root, because the first download publishes it after the catalog may already have been listed. The npm package `dingtalk-workspace-cli` is not used: its install script copies the official skills into `~/.agents/skills`, which the default skill provider scans, and into other agents' skill directories, so they would outlive the plugin. dws embeds the same skills, but `dws skill setup` writes only into such agent directories. +[`cordis.patch.yml`](cordis.patch.yml) inserts this package as the `dingtalk` row after the profile's other layers, and the Plugins page keys the account section by this package name. [`src/index.ts`](src/index.ts) is a function plugin. It registers the path of `dws` and the account with `ctx.cliAccounts`, declares the installation of the release as the registration's [`prepare` step](../cli-account/README.md#prepare-before-a-check), mounts a [filesystem skill provider](../../skill/skill-filesystem/README.md) named `dingtalk` over the skill root that `src/release.ts` publishes, and starts one check so that a session without a browser also finds `dws` and the skill. The provider omits the default roots and watches the skill root, because the first download publishes it after the catalog may already have been listed. The npm package `dingtalk-workspace-cli` is not used: its install script copies the official skills into `~/.agents/skills`, which the default skill provider scans, and into other agents' skill directories, so they would outlive the plugin. dws embeds the same skills, but `dws skill setup` writes only into such agent directories. [`src/release.ts`](src/release.ts) pins the release version, the archive for each platform, and `dws-skills.zip`, each with the name, size, and SHA-256 from the release's `checksums.txt`. It downloads whichever asset is missing, refuses a response whose `Content-Length` differs before reading the body, and verifies the digest. It extracts a `.tar.gz` platform archive with `tar`, takes only `dws.exe` from the root of the Windows `.zip` archive with `fflate`, and extracts the `multi/` entries and root `LICENSE` and `NOTICE` of the skills archive with `fflate`, into a sibling staging directory, refusing a skills entry whose path has an empty, `.`, or `..` segment or a backslash; it publishes each result by rename, and a directory another process published first is kept. Each source that fails or has not delivered within `releaseTimeoutMs` logs a warning, and cancelling the operation stops the download. An installation that fails for another reason than a cancellation, such as an archive that cannot be extracted or a cache directory that cannot be written, logs a warning with its cause, because the account operation reports only that the download did not finish. The skill root `skill-/` in the cache directory holds a copy of the packaged entry at `dingtalk/SKILL.md` and a `dingtalk/guides` symbolic link to the skills directory, a junction on Windows, which needs no symlink privilege. The digest covers the entry and the link target, so a published root never changes, and the root is published synchronously at load when the skills directory already exists. Only the processes of a profile read its cache directory. The first time the release is in place there, at load or after an installation, `prune` deletes every `dws-…` and `skill-…` entry there that the release does not use, a downloaded dws that a configured `binDir` replaces included; it does so once for each load of the row. It deletes nothing while the release is not installed, logs an entry it cannot delete, such as a `dws.exe` that still runs on Windows, and deletes it at a later load. Because it deletes only once, a process whose release another process of the profile deleted installs it again at its next check and leaves that process's release in place; [Known Limitations](#known-limitations-and-deferred-work) describes that case. A composition that `dsh` did not launch has no profile; its cache directory may be shared by several installations, and nothing is deleted from it. -The [CLI account Service](../cli-account/README.md) gives the model that path in runtime context while `dws` and the skills are installed, runs each command by the same path, runs one account operation at a time, and reports a failed command by its exit code. [`src/account.ts`](src/account.ts) carries out each operation with the dws commands, prepares the release before a check's first command, reads the authorization link from the stderr lines of `auth login`, and parses the `auth status` JSON. [`src/presentation.ts`](src/presentation.ts) maps each view to the section the registry serves, in the text of [`src/locales.ts`](src/locales.ts). It keeps the signed-in account's ids on the Host for sign-out; the Remote view carries only names. Disposal cancels the active operation, aborts running commands and downloads, and settles after their processes exit. +The [CLI account Service](../cli-account/README.md) gives the model that path in runtime context while `dws` and the skills are installed, runs the `prepare` step before a check's first command while either is missing, runs each command by the same path, runs one account operation at a time, and reports a failed command by its exit code. [`src/account.ts`](src/account.ts) carries out each operation with the dws commands, reads the authorization link from the stderr lines of `auth login`, and parses the `auth status` JSON. [`src/presentation.ts`](src/presentation.ts) maps each view to the section the registry serves, in the text of [`src/locales.ts`](src/locales.ts). It keeps the signed-in account's ids on the Host for sign-out; the Remote view carries only names. Disposal cancels the active operation, aborts running commands and downloads, and settles after their processes exit. [`skills/dingtalk/SKILL.md`](skills/dingtalk/SKILL.md) is the only skill: the DSH guidance, an index of the 16 guides, and how to open them. The guides are the `multi/` tree of `dws-skills.zip` in release `v1.0.64`, which the upstream installer uses by default; its `mono/` alternative is one entry that repeats the same content. The filesystem provider discovers only `//SKILL.md`, so the guides are not separate skills. Guides refer to one another by relative paths such as `../dingtalk-shared/SKILL.md`, which resolve because the guides keep their sibling layout, and run their helper scripts from their own `scripts/` directories. Where the DSH guidance and a guide disagree, the entry tells the agent to follow the DSH guidance: it uses the plugin's `dws` instead of installing or upgrading one, does not run `dws skill setup`, and sends sign-in to the plugin page. diff --git a/packages/connector/dingtalk/README.zh.md b/packages/connector/dingtalk/README.zh.md index a5d04da83c..481d7a9efe 100644 --- a/packages/connector/dingtalk/README.zh.md +++ b/packages/connector/dingtalk/README.zh.md @@ -79,11 +79,11 @@ dsh plugin --profile web remove @deepseek-ai/dsh-dingtalk
实现细节 — 点击展开 -[`cordis.patch.yml`](cordis.patch.yml) 在 profile 其他层之后把本包作为 `dingtalk` 行插入,插件页以本包名作为账号区块的 key。[`src/index.ts`](src/index.ts) 是一个函数插件。它把 `dws` 的路径和账号注册到 `ctx.cliAccounts`,在 `src/release.ts` 发布的 skill 根目录上挂载一个名为 `dingtalk` 的[文件系统 skill 提供方](../../skill/skill-filesystem/README.zh.md),并启动一次检查,使没有浏览器的会话也能找到 `dws` 和该 skill。该提供方不包含默认根目录,并监听 skill 根目录,因为第一次下载发布它时,目录可能已经列出过。本包不使用 npm 包 `dingtalk-workspace-cli`:它的安装脚本会把官方技能复制到默认 skill 提供方扫描的 `~/.agents/skills`,以及其他 Agent 的 skill 目录,插件撤下后它们仍会留下。dws 内嵌了同样的技能,但 `dws skill setup` 只写入这类 Agent 目录。 +[`cordis.patch.yml`](cordis.patch.yml) 在 profile 其他层之后把本包作为 `dingtalk` 行插入,插件页以本包名作为账号区块的 key。[`src/index.ts`](src/index.ts) 是一个函数插件。它把 `dws` 的路径和账号注册到 `ctx.cliAccounts`,把安装这个 release 声明为这次注册的 [`prepare` 步骤](../cli-account/README.zh.md#prepare-before-a-check),在 `src/release.ts` 发布的 skill 根目录上挂载一个名为 `dingtalk` 的[文件系统 skill 提供方](../../skill/skill-filesystem/README.zh.md),并启动一次检查,使没有浏览器的会话也能找到 `dws` 和该 skill。该提供方不包含默认根目录,并监听 skill 根目录,因为第一次下载发布它时,目录可能已经列出过。本包不使用 npm 包 `dingtalk-workspace-cli`:它的安装脚本会把官方技能复制到默认 skill 提供方扫描的 `~/.agents/skills`,以及其他 Agent 的 skill 目录,插件撤下后它们仍会留下。dws 内嵌了同样的技能,但 `dws skill setup` 只写入这类 Agent 目录。 [`src/release.ts`](src/release.ts) 固定发布版本、各平台的归档和 `dws-skills.zip`,每项都记录 release 的 `checksums.txt` 中的名称、大小和 SHA-256。它只下载缺少的资产;响应的 `Content-Length` 不符时,在读取正文之前就拒绝,随后校验摘要。它用 `tar` 解压 `.tar.gz` 平台归档,用 `fflate` 只取出 Windows `.zip` 归档根目录下的 `dws.exe`,并用 `fflate` 解压技能归档中 `multi/` 下的条目及根目录的 `LICENSE`、`NOTICE`,都解压到同级的临时目录;技能条目的路径含空段、`.`、`..` 或反斜杠时拒绝。解压结果通过改名发布,另一个进程先发布的目录会被保留。失败或在 `releaseTimeoutMs` 内没有送达的下载源各记录一条警告;取消操作会停止下载。安装因为取消之外的原因失败时,例如归档无法解压或缓存目录无法写入,会记录一条带原因的警告,因为账号操作只报告下载没有完成。缓存目录中的 skill 根目录 `skill-<摘要>/` 包含包内总入口在 `dingtalk/SKILL.md` 的副本,以及指向技能目录的符号链接 `dingtalk/guides`;在 Windows 上它是目录联接(junction),不需要创建符号链接的权限。摘要覆盖总入口和链接目标,因此已发布的根目录不会再变;加载时技能目录已经存在,就同步发布根目录。一个 profile 的缓存目录只由这个 profile 的各个进程读取。release 第一次在其中就位时(加载时已在位,或安装完成后),`prune` 删除其中这个 release 不使用的所有 `dws-…` 和 `skill-…` 条目,包括被配置的 `binDir` 取代的已下载 dws;该行每次加载只删除一次。release 尚未安装时它什么也不删;删不掉的条目(例如 Windows 上仍在运行的 `dws.exe`)记为警告,留到之后的加载时再删。由于只删除一次,某个进程的 release 被同一 profile 的另一个进程删除后,它在下一次检查时重新安装,并保留那个进程的 release;这种情况见[已知限制](#known-limitations-and-deferred-work)。不是由 `dsh` 启动的组合没有 profile;它的缓存目录可能被多个安装共用,其中的内容都不会被删除。 -`dws` 和技能都已安装时,[CLI 账号 Service](../cli-account/README.zh.md) 在运行时上下文中把这个路径告诉模型;它按同一路径运行每条命令,一次执行一个账号操作,并以退出码报告失败的命令。[`src/account.ts`](src/account.ts) 用 dws 的命令完成每个操作,在检查的第一条命令之前准备好版本,从 `auth login` 的 stderr 行中读取授权链接,并解析 `auth status` 的 JSON。[`src/presentation.ts`](src/presentation.ts) 用 [`src/locales.ts`](src/locales.ts) 中的文案,把每个视图映射为注册表提供的区块。它把已登录账号的 id 留在 Host 上供退出登录使用;Remote 视图只包含名字。释放时取消进行中的操作,中止正在运行的命令和下载,并在这些进程退出后完成。 +`dws` 和技能都已安装时,[CLI 账号 Service](../cli-account/README.zh.md) 在运行时上下文中把这个路径告诉模型;任一项缺失时,它在检查的第一条命令之前运行 `prepare` 步骤;它按同一路径运行每条命令,一次执行一个账号操作,并以退出码报告失败的命令。[`src/account.ts`](src/account.ts) 用 dws 的命令完成每个操作,从 `auth login` 的 stderr 行中读取授权链接,并解析 `auth status` 的 JSON。[`src/presentation.ts`](src/presentation.ts) 用 [`src/locales.ts`](src/locales.ts) 中的文案,把每个视图映射为注册表提供的区块。它把已登录账号的 id 留在 Host 上供退出登录使用;Remote 视图只包含名字。释放时取消进行中的操作,中止正在运行的命令和下载,并在这些进程退出后完成。 [`skills/dingtalk/SKILL.md`](skills/dingtalk/SKILL.md) 是唯一的 skill:DSH 指引、16 个子指南的索引,以及打开方式。子指南是 release `v1.0.64` 的 `dws-skills.zip` 中的 `multi/` 目录树,上游安装程序默认使用它;另一种 `mono/` 是重复同样内容的单一入口。文件系统提供方只发现 `//SKILL.md`,因此子指南不是独立的 skill。子指南之间用 `../dingtalk-shared/SKILL.md` 这样的相对路径互相引用,由于子指南保持同级布局,这些路径可以解析;它们的辅助脚本也从各自的 `scripts/` 目录运行。DSH 指引与子指南不一致时,总入口要求 Agent 以 DSH 指引为准:使用插件提供的 `dws`,不另装或升级,不运行 `dws skill setup`,并把登录交给插件页面。 diff --git a/packages/connector/dingtalk/src/account.ts b/packages/connector/dingtalk/src/account.ts index 6eb5790870..e1723a2c6a 100644 --- a/packages/connector/dingtalk/src/account.ts +++ b/packages/connector/dingtalk/src/account.ts @@ -3,7 +3,6 @@ import z from 'zod' import type { CliOperationControl } from '@deepseek-ai/dsh-cli-account/types' import { assertNever } from '@deepseek-ai/dsh-util-values' -import type { DwsRelease } from './release.ts' import type { DingtalkAccountState, DingtalkCommand, DingtalkOperationKind, DingtalkPhase } from './types.ts' /** `auth login --no-browser` prints the authorization link alone on an indented stderr line. */ @@ -43,17 +42,13 @@ function readProfile(status: Status): string | undefined { return `${status.corp_id}:${status.user_id}` } -/** The dws and skill installation each check prepares before its first command. */ -type Release = Pick - /** - * Bind the DingTalk account operations to the dws installation. - * @param release - the dws and skill installation. + * Create the DingTalk account operations of one plugin instance, which share the signed-in account a check found. * @returns the function that carries out one operation with dws and publishes the account each check observes; it - * throws when the installation or a command fails, `auth status` prints an unknown status, a sign-in leaves no - * signed-in account, or a sign-out finds none to sign out. + * throws when a command fails, `auth status` prints an unknown status, a sign-in leaves no signed-in account, or a + * sign-out finds none to sign out. */ -export function performWith(release: Release): (kind: DingtalkOperationKind, control: Control, signal: AbortSignal) => Promise { +export function createPerform(): (kind: DingtalkOperationKind, control: Control, signal: AbortSignal) => Promise { /** The account the latest check found signed in, kept on the Host because the view carries no account ids. */ let profile: string | undefined @@ -81,21 +76,8 @@ export function performWith(release: Release): (kind: DingtalkOperationKind, con await check(control, signal) } - /** - * Install dws and its skills while either is missing, a step the page may cancel, then read the current account, - * publish it, and return it. - */ + /** Read the current account, publish it, and return it. */ async function check(control: Control, signal: AbortSignal): Promise { - if (!release.installed()) { - control.stage('downloading') - try { - await release.install(signal) - } catch (error) { - control.publish({ state: 'not-installed' }) - throw error - } - control.stage('checking') - } const result = await control.run('auth-status', ['auth', 'status', '--format', 'json'], signal) const status = result.exitCode === 0 ? parseStatus(result.stdout) : undefined if (status === undefined) throw new Error(`dingtalk: auth status exited with ${String(result.exitCode)} or printed an unknown status`) diff --git a/packages/connector/dingtalk/src/index.ts b/packages/connector/dingtalk/src/index.ts index 70fc0890de..8ce057ee6c 100644 --- a/packages/connector/dingtalk/src/index.ts +++ b/packages/connector/dingtalk/src/index.ts @@ -17,7 +17,7 @@ import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import type {} from '@deepseek-ai/dsh-app-boot' import type {} from '@deepseek-ai/dsh-cli-account' import type {} from '@deepseek-ai/dsh-skill' -import { performWith } from './account.ts' +import { createPerform } from './account.ts' import { dictionaries, type DingtalkTextKey } from './locales.ts' import { copy, DINGTALK_PACKAGE, operations, presentAccount } from './presentation.ts' import { DwsRelease, executableFileName, PROGRAM } from './release.ts' @@ -74,13 +74,19 @@ export function apply(ctx: Context, config: Config): void { packageName: DINGTALK_PACKAGE, cli: { product: 'DingTalk', program: PROGRAM, executable: join(release.directory, executableFileName(process.platform)), - scripts: true, ready: () => release.installed(), + scripts: true, + }, + prepare: { + phase: 'downloading', + unprepared: { state: 'not-installed' }, + ready: () => release.installed(), + run: signal => release.install(signal), }, account: { state: 'unchecked' }, check: 'check', cancellable: ['downloading', 'authorizing'], authorizationHosts: ['login.dingtalk.com'], - perform: performWith(release), + perform: createPerform(), dictionaries, operations, copy, diff --git a/packages/connector/feishu/README.i18n.yaml b/packages/connector/feishu/README.i18n.yaml index 9991ff3933..895a82932e 100644 --- a/packages/connector/feishu/README.i18n.yaml +++ b/packages/connector/feishu/README.i18n.yaml @@ -33,8 +33,8 @@ en: 960f5688f8585fa2 zh: e54ad80f078936c5 /deepseek-ai-dsh-feishu/understand-the-implementation: - en: 4d4d894cdaf549cc - zh: ea1b40fafc8feec6 + en: fd5411d227a46bcf + zh: 8fb29d0249350698 /deepseek-ai-dsh-feishu/further-exploration: en: b25e4caa8c5b7116 zh: 4976eddc4b3e5ec4 @@ -54,8 +54,8 @@ en: 1da22c82cb1a2086 zh: 9939ba273214f65f /deepseek-ai-dsh-feishu/model-experience/skill-catalog-entry/kv-cache-effect: - en: 088068538282cd4e - zh: 33d475d2f59e4e25 + en: 0649c73c3c77b9b4 + zh: f0e2d248e1bc0dd3 /deepseek-ai-dsh-feishu/model-experience/loaded-skill-body: en: 8955ac196848e69f zh: 54aa7db097eafd3c @@ -87,8 +87,8 @@ en: e6d8593416cb392e zh: eadd5d656866b7eb /deepseek-ai-dsh-feishu/known-limitations-and-deferred-work: - en: 710294c637b2ef1b - zh: d95d925173f060df + en: 049803c1630b278e + zh: c9540e99f1315005 /deepseek-ai-dsh-feishu/known-limitations-and-deferred-work/dev-note: en: 84119ac4f878e897 zh: 1a9c4f3f96cc9663 diff --git a/packages/connector/feishu/README.md b/packages/connector/feishu/README.md index 9e35b0e585..4fc5131c0f 100644 --- a/packages/connector/feishu/README.md +++ b/packages/connector/feishu/README.md @@ -80,9 +80,9 @@ The generated [config catalog](../../../docs/config-catalog.md#deepseek-aidsh-fe
Implementation internals — click to expand -[`cordis.patch.yml`](cordis.patch.yml) inserts this package as the `feishu` row after the profile's other layers, and the Plugins page keys the account section by this package name. [`src/index.ts`](src/index.ts) is a function plugin. It registers the path of `lark-cli` and the account with `ctx.cliAccounts`, registers the skill provider, and, while `lark-cli` is missing, starts one check so that a session without a browser also gets the CLI and the skill; with `binDir`, it requires an executable `lark-cli` (`lark-cli.exe` on Windows) there at load. [`src/cli.ts`](src/cli.ts) locates `lark-cli`, downloads a missing one by running the `@larksuite/cli` install script through `ctx.subprocess`, and parses the JSON output of the account commands. A download succeeded when the executable is in place after the script exits, whatever its exit code, because another process running the same script may have put it there. The [CLI account Service](../cli-account/README.md) gives the model that path in runtime context while `lark-cli` is installed, runs each command by the same path, runs one account operation at a time, and reports a failed command by its exit code. [`src/account.ts`](src/account.ts) carries out each operation with the Feishu commands, downloads a missing `lark-cli` before a check's first command, and reads setup and sign-in links from their output lines. [`src/presentation.ts`](src/presentation.ts) maps each view to the section the registry serves, in the text of [`src/locales.ts`](src/locales.ts). Disposal cancels the active operation, aborts running commands and the download, and settles after their processes exit. +[`cordis.patch.yml`](cordis.patch.yml) inserts this package as the `feishu` row after the profile's other layers, and the Plugins page keys the account section by this package name. [`src/index.ts`](src/index.ts) is a function plugin. It registers the path of `lark-cli` and the account with `ctx.cliAccounts`, declares the download of a missing `lark-cli` as the registration's [`prepare` step](../cli-account/README.md#prepare-before-a-check), registers the skill provider, and, while `lark-cli` is missing, starts one check so that a session without a browser also gets the CLI and the skill; with `binDir`, it requires an executable `lark-cli` (`lark-cli.exe` on Windows) there at load. [`src/cli.ts`](src/cli.ts) locates `lark-cli`, downloads a missing one by running the `@larksuite/cli` install script through `ctx.subprocess`, and parses the JSON output of the account commands. A download succeeded when the executable is in place after the script exits, whatever its exit code, because another process running the same script may have put it there. The [CLI account Service](../cli-account/README.md) gives the model that path in runtime context while `lark-cli` is installed, runs the `prepare` step before a check's first command while it is missing, runs each command by the same path, runs one account operation at a time, and reports a failed command by its exit code. [`src/account.ts`](src/account.ts) carries out each operation with the Feishu commands and reads setup and sign-in links from their output lines. [`src/presentation.ts`](src/presentation.ts) maps each view to the section the registry serves, in the text of [`src/locales.ts`](src/locales.ts). Disposal cancels the active operation, aborts running commands and the download, and settles after their processes exit. -[`skills/feishu/SKILL.md`](skills/feishu/SKILL.md) is the only skill this package carries: the DSH guidance, an index of the 28 guides that `lark-cli` 1.0.97 embeds, and how to open them. [`src/skills.ts`](src/skills.ts) reads the entry once when the plugin loads and lists it as the `feishu` provider's one skill with an opaque resource base, so the catalog lists the entry and a load returns the file without running the CLI. It lists the entry only while `lark-cli` is installed, and the plugin invalidates the catalog when a download finishes, because the catalog may already have been listed without the entry. The guides stay in the binary, and the agent reads them with `lark-cli skills read`. +[`skills/feishu/SKILL.md`](skills/feishu/SKILL.md) is the only skill this package carries: the DSH guidance, an index of the 28 guides that `lark-cli` 1.0.97 embeds, and how to open them. [`src/skills.ts`](src/skills.ts) reads the entry once when the plugin loads and lists it as the `feishu` provider's one skill with an opaque resource base, so the catalog lists the entry and a load returns the file without running the CLI. It lists the entry only while `lark-cli` is installed. The catalog caches a listing, so after one made without the entry the plugin invalidates the catalog once `lark-cli` is in place. It looks for that after each download attempt and before each account operation, because a cancelled or failed install script may already have copied the binary, and the user can run that script outside DSH. The guides stay in the binary, and the agent reads them with `lark-cli skills read`.
@@ -120,7 +120,7 @@ The entry stays in context while the plugin is loaded and `lark-cli` is installe #### KV Cache effect -The entry is fixed. Loading or unloading the plugin, or a download finishing after the catalog was listed, changes the catalog, which is republished as a new message and leaves earlier context in place. +The entry is fixed. Loading or unloading the plugin, or `lark-cli` being installed after the catalog was listed, changes the catalog, which is republished as a new message and leaves earlier context in place. ### Loaded skill body @@ -172,7 +172,7 @@ The system prompt does not change; finishing the download, loading or unloading - Sign-in reads the device-authorization link and the completion from `lark-cli auth login --json` events; a CLI version that changes those events fails the connection with a retryable result. - The entry's guide index follows `lark-cli` 1.0.97; pinning another `@larksuite/cli` version means checking the index against that version's `lark-cli skills list`. - Under a file sandbox, a token refresh during an ordinary command can be denied and then needs single-command approval. -- An installation that did not run the `@larksuite/cli` install script needs `curl`, `tar` (PowerShell on Windows), and network access to GitHub or an npm mirror at its first check, and the `feishu` skill and the CLI path are absent until that download succeeds. The page shows no progress. A process that exits during the download, such as a one-shot headless run, stops it, and the next process starts it again. A download stopped that way or cancelled leaves the script's `lark-cli-*` directory, with any partial archive, in the system temporary directory. +- An installation that did not run the `@larksuite/cli` install script needs `curl`, `tar` (PowerShell on Windows), and network access to GitHub or an npm mirror at its first check, and the `feishu` skill and the CLI path are absent until that download succeeds. When the user installs `lark-cli` outside DSH while the plugin is loaded, runtime context gives its path before the catalog has the `feishu` skill, which joins at the next account operation, such as **Retry** on the Plugins page. The page shows no progress. A process that exits during the download, such as a one-shot headless run, stops it, and the next process starts it again. A download stopped that way or cancelled leaves the script's `lark-cli-*` directory, with any partial archive, in the system temporary directory. - The install script copies the binary into the package's `bin` directory without a rename. A process stopped during that copy can leave an incomplete file that counts as installed; deleting that `bin` directory makes the next check download again. diff --git a/packages/connector/feishu/README.zh.md b/packages/connector/feishu/README.zh.md index 1e966a2c2f..67466a27c2 100644 --- a/packages/connector/feishu/README.zh.md +++ b/packages/connector/feishu/README.zh.md @@ -80,9 +80,9 @@ pnpm 会拦截 `@larksuite/cli` 的安装脚本,该脚本负责下载并校验
实现内部机制——点击展开 -[`cordis.patch.yml`](cordis.patch.yml) 在 profile 其他层之后把本包作为 `feishu` 行插入,插件页以本包名作为账号区块的 key。[`src/index.ts`](src/index.ts) 是一个函数插件。它把 `lark-cli` 的路径和账号注册到 `ctx.cliAccounts`,注册 skill 提供方,并在 `lark-cli` 缺失时发起一次检查,使没有浏览器的会话也能得到 CLI 和 skill;设置了 `binDir` 时,它要求加载时那里有可执行的 `lark-cli`(Windows 上为 `lark-cli.exe`)。[`src/cli.ts`](src/cli.ts) 定位 `lark-cli`,通过 `ctx.subprocess` 运行 `@larksuite/cli` 的安装脚本来下载缺失的可执行文件,并解析账号命令的 JSON 输出。脚本退出后可执行文件就位即为下载成功,与退出码无关,因为运行同一脚本的另一个进程可能已经把它放好。[CLI 账号 Service](../cli-account/README.zh.md) 在 `lark-cli` 已安装期间于运行时上下文中把这个路径告诉模型,按同一路径运行每条命令,一次执行一个账号操作,并以退出码报告失败的命令。[`src/account.ts`](src/account.ts) 用飞书的命令完成每个操作,在检查的第一条命令之前下载缺失的 `lark-cli`,并从命令输出行中读取配置与登录链接。[`src/presentation.ts`](src/presentation.ts) 用 [`src/locales.ts`](src/locales.ts) 中的文案,把每个视图映射为注册表提供的区块。释放时取消进行中的操作,中止正在运行的命令和下载,并在这些进程退出后完成。 +[`cordis.patch.yml`](cordis.patch.yml) 在 profile 其他层之后把本包作为 `feishu` 行插入,插件页以本包名作为账号区块的 key。[`src/index.ts`](src/index.ts) 是一个函数插件。它把 `lark-cli` 的路径和账号注册到 `ctx.cliAccounts`,把下载缺失的 `lark-cli` 声明为这次注册的 [`prepare` 步骤](../cli-account/README.zh.md#prepare-before-a-check),注册 skill 提供方,并在 `lark-cli` 缺失时发起一次检查,使没有浏览器的会话也能得到 CLI 和 skill;设置了 `binDir` 时,它要求加载时那里有可执行的 `lark-cli`(Windows 上为 `lark-cli.exe`)。[`src/cli.ts`](src/cli.ts) 定位 `lark-cli`,通过 `ctx.subprocess` 运行 `@larksuite/cli` 的安装脚本来下载缺失的可执行文件,并解析账号命令的 JSON 输出。脚本退出后可执行文件就位即为下载成功,与退出码无关,因为运行同一脚本的另一个进程可能已经把它放好。[CLI 账号 Service](../cli-account/README.zh.md) 在 `lark-cli` 已安装期间于运行时上下文中把这个路径告诉模型,在它缺失时于检查的第一条命令之前运行 `prepare` 步骤,按同一路径运行每条命令,一次执行一个账号操作,并以退出码报告失败的命令。[`src/account.ts`](src/account.ts) 用飞书的命令完成每个操作,并从命令输出行中读取配置与登录链接。[`src/presentation.ts`](src/presentation.ts) 用 [`src/locales.ts`](src/locales.ts) 中的文案,把每个视图映射为注册表提供的区块。释放时取消进行中的操作,中止正在运行的命令和下载,并在这些进程退出后完成。 -[`skills/feishu/SKILL.md`](skills/feishu/SKILL.md) 是本包携带的唯一 skill:DSH 指引、`lark-cli` 1.0.97 内嵌的 28 个子指南的索引,以及打开它们的方法。[`src/skills.ts`](src/skills.ts) 在插件加载时读取一次入口,并把它作为 `feishu` 提供方的唯一 skill 列出,资源基址为 opaque 类型,因此目录列出入口、加载返回该文件时都不运行 CLI。它只在 `lark-cli` 已安装期间列出入口;下载完成时插件会使目录失效,因为目录可能已经在没有该入口时列出过。子指南留在二进制中,agent 用 `lark-cli skills read` 读取。 +[`skills/feishu/SKILL.md`](skills/feishu/SKILL.md) 是本包携带的唯一 skill:DSH 指引、`lark-cli` 1.0.97 内嵌的 28 个子指南的索引,以及打开它们的方法。[`src/skills.ts`](src/skills.ts) 在插件加载时读取一次入口,并把它作为 `feishu` 提供方的唯一 skill 列出,资源基址为 opaque 类型,因此目录列出入口、加载返回该文件时都不运行 CLI。它只在 `lark-cli` 已安装期间列出入口。目录会缓存列出的结果,因此在没有该入口时列出过之后,插件会在 `lark-cli` 就位后使目录失效一次。插件在每次下载尝试之后和每次账号操作之前检查这一点,因为被取消或失败的安装脚本可能已经复制了二进制,用户也可以在 DSH 之外运行该脚本。子指南留在二进制中,agent 用 `lark-cli skills read` 读取。
@@ -120,7 +120,7 @@ Feishu (飞书) and Lark through the bundled lark-cli: documents and wiki, Base, #### KV Cache 影响 -该条目固定不变。加载或卸载插件、或目录列出之后下载完成,都会改变目录,目录作为新消息重新发布,不改动更早的上下文。 +该条目固定不变。加载或卸载插件、或目录列出之后 `lark-cli` 才安装好,都会改变目录,目录作为新消息重新发布,不改动更早的上下文。 ### 已加载的 skill 正文 @@ -172,7 +172,7 @@ Feishu CLI: run `lark-cli` by its absolute path with the call operator, & ' diff --git a/packages/connector/feishu/src/account.ts b/packages/connector/feishu/src/account.ts index 429b520fa4..abc6437673 100644 --- a/packages/connector/feishu/src/account.ts +++ b/packages/connector/feishu/src/account.ts @@ -1,13 +1,10 @@ -/** - * Check, connection, and sign-out of the CLI's default Feishu account, as the operations `ctx.cliAccounts` runs; a - * check downloads a missing lark-cli first. - */ +/** Check, connection, and sign-out of the CLI's default Feishu account, as the operations `ctx.cliAccounts` runs. */ import { brandString } from '@deepseek-ai/dsh-brand' import z from 'zod' import type { CliOperationControl } from '@deepseek-ai/dsh-cli-account/types' import { assertNever } from '@deepseek-ai/dsh-util-values' -import { parseJson, type LarkCli } from './cli.ts' +import { parseJson } from './cli.ts' import type { FeishuAccountState, FeishuAppId, FeishuCommand, FeishuOperationKind, FeishuPhase } from './types.ts' const NotConfigured = z.object({ ok: z.literal(false), error: z.object({ subtype: z.literal('not_configured') }) }) @@ -28,51 +25,34 @@ type Control = CliOperationControl - /** - * Bind the Feishu account operations to the lark-cli installation. - * @param cli - the managed lark-cli. - * @returns the function that carries out one account operation with lark-cli and publishes the account each check - * observes; it throws when the download or a command fails, a command's output is not the expected JSON, or the - * account it leaves is not the one the operation set out to reach. + * Carry out one account operation with lark-cli and publish the account each check observes. + * @param kind - the requested operation. + * @param control - phase changes, link offers, command runs, and account updates for this operation. + * @param signal - aborts on cancellation and when the plugin unloads. + * @returns after the operation finishes. + * @throws when a command fails, its output is not the expected JSON, or the account it leaves is not the one the + * operation set out to reach. */ -export function performWith(cli: Cli): (kind: FeishuOperationKind, control: Control, signal: AbortSignal) => Promise { - return async (kind, control, signal) => { - switch (kind) { - case 'check': - await download(cli, control, signal) - await check(control, signal) - return - case 'link-app': return linkApp(control, signal) - case 'sign-in': return signIn(control, signal) - case 'sign-out': { - control.stage('signing-out') - const result = await control.run('auth-logout', ['auth', 'logout', '--json'], signal) - if (result.exitCode !== 0) throw new Error('feishu: auth logout failed') - await check(control, signal) - return - } - /* v8 ignore next -- closed operation kind union */ - default: return assertNever(kind) +export async function perform(kind: FeishuOperationKind, control: Control, signal: AbortSignal): Promise { + switch (kind) { + case 'check': + await check(control, signal) + return + case 'link-app': return linkApp(control, signal) + case 'sign-in': return signIn(control, signal) + case 'sign-out': { + control.stage('signing-out') + const result = await control.run('auth-logout', ['auth', 'logout', '--json'], signal) + if (result.exitCode !== 0) throw new Error('feishu: auth logout failed') + await check(control, signal) + return } + /* v8 ignore next -- closed operation kind union */ + default: return assertNever(kind) } } -/** Download lark-cli while it is missing, a step the page may cancel; a download that does not finish publishes `not-installed`. */ -async function download(cli: Cli, control: Control, signal: AbortSignal): Promise { - if (cli.installed()) return - control.stage('downloading') - try { - await cli.install(signal) - } catch (error) { - control.publish({ state: 'not-installed' }) - throw error - } - control.stage('checking') -} - /** * Link an app through the CLI's setup page; sign-in is a separate operation. An existing configuration, * including its sign-ins and any other app, is replaced by the app the user creates or chooses. diff --git a/packages/connector/feishu/src/index.ts b/packages/connector/feishu/src/index.ts index 42a644fd11..b051436b98 100644 --- a/packages/connector/feishu/src/index.ts +++ b/packages/connector/feishu/src/index.ts @@ -13,7 +13,7 @@ import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-cli-account' import type {} from '@deepseek-ai/dsh-skill' import type {} from '@deepseek-ai/dsh-subprocess' -import { performWith } from './account.ts' +import { perform } from './account.ts' import { LarkCli, PROGRAM } from './cli.ts' import { dictionaries, type FeishuTextKey } from './locales.ts' import { copy, FEISHU_PACKAGE, operations, presentAccount } from './presentation.ts' @@ -51,27 +51,33 @@ export const Config: z = z.object({ */ export function apply(ctx: Context, config: Config): void { const cli = new LarkCli(config.binDir, ctx.subprocess, ctx.logger) - let listSkill: () => void + let skill: FeishuSkillProvider ctx.skills.registerProvider((control) => { - listSkill = control.invalidate - return new FeishuSkillProvider(ENTRY, () => cli.installed()) + skill = new FeishuSkillProvider(ENTRY, () => cli.installed(), control.invalidate) + return skill }) const account = ctx.cliAccounts.register({ name, packageName: FEISHU_PACKAGE, - cli: { product: 'Feishu', program: PROGRAM, executable: cli.executable, ready: () => cli.installed() }, + cli: { product: 'Feishu', program: PROGRAM, executable: cli.executable }, + prepare: { + phase: 'downloading', + unprepared: { state: 'not-installed' }, + ready: () => cli.installed(), + run: async (signal) => { + // A cancelled or failed install script may already have put lark-cli in place. + try { await cli.install(signal) } finally { skill.relist() } + }, + }, account: { state: 'unchecked' }, check: 'check', cancellable: ['downloading', 'configuring', 'authorizing'], authorizationHosts: ['feishu.cn', 'larksuite.com'], - perform: performWith({ - installed: () => cli.installed(), - install: async (signal) => { - await cli.install(signal) - // The skill catalog listed before the download has no `feishu` skill. - listSkill() - }, - }), + perform: async (kind, control, signal) => { + // lark-cli may have been installed outside this plugin's download since the catalog was listed. + skill.relist() + await perform(kind, control, signal) + }, dictionaries, operations, copy, diff --git a/packages/connector/feishu/src/skills.ts b/packages/connector/feishu/src/skills.ts index 362b27dc1c..40bd653b13 100644 --- a/packages/connector/feishu/src/skills.ts +++ b/packages/connector/feishu/src/skills.ts @@ -13,19 +13,23 @@ const RESOURCES = 'Embedded lark-cli guides; open them with the skills read comm /** * Lists the packaged entry while lark-cli is installed, without running it; the entry is read once, when the plugin - * loads. The catalog caches a listing, so the plugin invalidates it when a download installs lark-cli. + * loads. The catalog caches a listing, so one made while lark-cli was missing lacks the entry until {@link relist} + * invalidates it. */ export class FeishuSkillProvider implements SkillProvider { readonly name = 'feishu' private readonly candidate: SkillCandidate private readonly content: string + /** Whether the catalog may hold a listing made while lark-cli was missing. */ + private unlisted = false /** * @param entry - absolute path of the packaged `SKILL.md`, whose frontmatter gives the skill's name and description. * @param installed - whether lark-cli, which serves the guides the entry indexes, is in place. + * @param invalidate - makes the catalog list this provider again. * @throws when the entry has no YAML frontmatter, or its frontmatter has no skill name or no description. */ - constructor(entry: string, private readonly installed: () => boolean) { + constructor(entry: string, private readonly installed: () => boolean, private readonly invalidate: () => void) { const raw = readFileSync(entry, 'utf8') const match = FRONTMATTER.exec(raw) const block = match?.[1] @@ -45,7 +49,21 @@ export class FeishuSkillProvider implements SkillProvider { } list(): Promise { - return Promise.resolve(this.installed() ? [this.candidate] : []) + if (this.installed()) return Promise.resolve([this.candidate]) + this.unlisted = true + return Promise.resolve([]) + } + + /** + * Invalidate the catalog once when lark-cli is in place and a listing was made without it. lark-cli can appear + * without a download that this plugin finished: a cancelled or failed install script may already have copied it, and + * the user can run that script in a terminal. The plugin calls this after each download attempt and before each + * account operation. + */ + relist(): void { + if (!this.unlisted || !this.installed()) return + this.unlisted = false + this.invalidate() } get(): Promise { diff --git a/packages/connector/feishu/tests/download.spec.ts b/packages/connector/feishu/tests/download.spec.ts index 2fa301b20c..9d2e0eda45 100644 --- a/packages/connector/feishu/tests/download.spec.ts +++ b/packages/connector/feishu/tests/download.spec.ts @@ -133,6 +133,7 @@ it('cancels the download from the page without a warning and leaves the retry', const page = await load() const account = page.source const id = account.snapshot().operation!.id + expect(await skills()).toEqual([]) await account.cancel(id) @@ -141,6 +142,45 @@ it('cancels the download from the page without a warning and leaves the retry', expect(host.subprocess.processes[0]?.terminated).toBe(true) expect(commands()).toEqual([INSTALLER]) expect(warnings()).toEqual([]) + expect(await skills()).toEqual([]) +}) + +it('offers the skill once a cancelled download has left lark-cli in place, and the retry starts no download', async () => { + install = () => {} + const page = await load() + const account = page.source + const id = account.snapshot().operation!.id + expect(await skills()).toEqual([]) + + // The install script copied the binary and has not exited yet. + present = true + await account.cancel(id) + + expect(account.snapshot()).toEqual({ account: { state: 'not-installed' }, result: { id, kind: 'check', outcome: 'cancelled' } }) + expect(await skills()).toEqual(['feishu']) + + const retry = await account.start('check') + await vi.waitFor(() => { expect(account.snapshot().result).toEqual({ id: retry, kind: 'check', outcome: 'succeeded' }) }) + expect(account.snapshot().account).toEqual({ state: 'signed-out', appId: APP }) + expect(commands()).toEqual([INSTALLER, STATUS]) + expect(await skills()).toEqual(['feishu']) +}) + +it('offers the skill at the retry after lark-cli was installed outside the plugin\'s download, and starts no download', async () => { + install = (process) => { process.reply({ exitCode: 1 }) } + const page = await load() + const account = page.source + await settled(account) + expect(await skills()).toEqual([]) + + // The user ran the install script in a terminal. + present = true + const retry = await account.start('check') + await vi.waitFor(() => { expect(account.snapshot().result).toEqual({ id: retry, kind: 'check', outcome: 'succeeded' }) }) + + expect(account.snapshot().account).toEqual({ state: 'signed-out', appId: APP }) + expect(commands()).toEqual([INSTALLER, STATUS]) + expect(await skills()).toEqual(['feishu']) }) it('stops the download when the plugin unloads', async () => { diff --git a/packages/connector/feishu/tests/skills.spec.ts b/packages/connector/feishu/tests/skills.spec.ts index 266b29e824..39ae7351f8 100644 --- a/packages/connector/feishu/tests/skills.spec.ts +++ b/packages/connector/feishu/tests/skills.spec.ts @@ -5,7 +5,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { renderSkillContent } from '@deepseek-ai/dsh-skill' -import { expect, it } from 'vitest' +import { expect, it, vi } from 'vitest' import { FeishuSkillProvider } from '../src/skills.ts' const skills = fileURLToPath(new URL('../skills/', import.meta.url)) @@ -48,7 +48,7 @@ it('indexes every guide of the pinned lark-cli exactly once', () => { it('lists the entry with an opaque resource base and returns its body without the catalog-only fields', async () => { const file = join(entry, 'SKILL.md') - const provider = new FeishuSkillProvider(file, () => true) + const provider = new FeishuSkillProvider(file, () => true, () => {}) expect(await provider.list()).toMatchObject([{ name: 'feishu', provider: 'feishu', source: 'bundled', locator: file, resourceBase: { kind: 'opaque' } }]) const definition = await provider.get() expect(definition).not.toHaveProperty('rank') @@ -58,20 +58,36 @@ it('lists the entry with an opaque resource base and returns its body without th it('lists the entry only while lark-cli, which serves its guides, is installed', async () => { let installed = false - const provider = new FeishuSkillProvider(join(entry, 'SKILL.md'), () => installed) + const provider = new FeishuSkillProvider(join(entry, 'SKILL.md'), () => installed, () => {}) expect(await provider.list()).toEqual([]) installed = true expect(await provider.list()).toMatchObject([{ name: 'feishu' }]) }) +it('invalidates the catalog once, when lark-cli is in place after a listing without the entry', async () => { + let installed = false + const invalidate = vi.fn() + const provider = new FeishuSkillProvider(join(entry, 'SKILL.md'), () => installed, invalidate) + + provider.relist() + await provider.list() + provider.relist() + expect(invalidate).not.toHaveBeenCalled() + + installed = true + provider.relist() + provider.relist() + expect(invalidate).toHaveBeenCalledTimes(1) +}) + it('refuses an entry without YAML frontmatter or without a skill name and description', async () => { const dir = await mkdtemp(join(tmpdir(), 'dsh-feishu-entry-')) try { const file = join(dir, 'SKILL.md') await writeFile(file, '# No frontmatter\n') - expect(() => new FeishuSkillProvider(file, () => true)).toThrow('has no YAML frontmatter') + expect(() => new FeishuSkillProvider(file, () => true, () => {})).toThrow('has no YAML frontmatter') await writeFile(file, '---\nname: Not A Skill\n---\n\nbody\n') - expect(() => new FeishuSkillProvider(file, () => true)).toThrow('needs a skill name and a description') + expect(() => new FeishuSkillProvider(file, () => true, () => {})).toThrow('needs a skill name and a description') } finally { await rm(dir, { recursive: true, force: true }) } diff --git a/packages/connector/tencent-meeting/README.i18n.yaml b/packages/connector/tencent-meeting/README.i18n.yaml index 2e8f47ff6c..3e75d008c4 100644 --- a/packages/connector/tencent-meeting/README.i18n.yaml +++ b/packages/connector/tencent-meeting/README.i18n.yaml @@ -21,17 +21,17 @@ en: a33500f6c577f008 zh: cedbc1c5cdb8bfc6 /deepseek-ai-dsh-tencent-meeting/use-this-package/what-you-get: - en: 70a1d52b6c0f80af - zh: a3894b2233b5985d + en: 57566f3951ed5a11 + zh: 6d0ea243c0e19e9b /deepseek-ai-dsh-tencent-meeting/use-this-package/account-operations: - en: ad18981ffd47798a - zh: 1f30d2349a2dd447 + en: c282272dc744b8e3 + zh: 028635966af0ad38 /deepseek-ai-dsh-tencent-meeting/use-this-package/configure: en: 1730401daedf703e zh: 5cd9e0bc2699efe8 /deepseek-ai-dsh-tencent-meeting/understand-the-implementation: - en: 8e10bf200eca551e - zh: 1044452f3c12d584 + en: 4a56ecfec4771527 + zh: e7540f3b5a265de4 /deepseek-ai-dsh-tencent-meeting/further-exploration: en: a37fc14df39c8a77 zh: 0f0e795c5f1f9657 @@ -66,8 +66,8 @@ en: b5fed52af6c0d771 zh: 25b7aa5297583030 /deepseek-ai-dsh-tencent-meeting/model-experience/cli-path/what-the-model-sees: - en: 3ffc81ce5500c85c - zh: 28425cf9445d0f8d + en: e0d5d83707857d6b + zh: bfbf46aa4d61843f /deepseek-ai-dsh-tencent-meeting/model-experience/cli-path/what-the-model-sees/runtime-context-entry: en: c91314832f78f460 zh: aac156ea0b5b816a @@ -78,11 +78,11 @@ en: 3fb1f01010d97c7d zh: c0aa6fb57ceadf95 /deepseek-ai-dsh-tencent-meeting/model-experience/cli-path/kv-cache-effect: - en: 67398dd4e4b02db9 - zh: a873eacd006fa656 + en: 549259c52b35d7c7 + zh: f194c6b014b355ca /deepseek-ai-dsh-tencent-meeting/known-limitations-and-deferred-work: - en: ae40715bad4af72b - zh: fc099653415779c3 + en: c641eb15cc0eeb86 + zh: 7a598ca8ac774237 /deepseek-ai-dsh-tencent-meeting/known-limitations-and-deferred-work/dev-note: en: d67cf464f2df6693 zh: ff08f0d56a5ea79d diff --git a/packages/connector/tencent-meeting/README.md b/packages/connector/tencent-meeting/README.md index 3f821c313c..ba13f2d0d2 100644 --- a/packages/connector/tencent-meeting/README.md +++ b/packages/connector/tencent-meeting/README.md @@ -40,7 +40,7 @@ dsh plugin --profile web remove @deepseek-ai/dsh-tencent-meeting After the plugin loads, one `tencent-meeting` skill joins the skill catalog. The agent loads it with the `skill` tool, opens the `tmeet-skill` guide and its references with the file tools, and runs `tmeet` by that path through the ordinary Shell tools under the current sandbox and approval policy. When a command reports a missing or expired sign-in, the agent asks the user to connect Tencent Meeting on the plugin page; it runs `tmeet auth login --no-browser` only when the user asks to finish it in the conversation, and requests `sandbox_permissions` with a `justification` on the first attempt because the command writes outside the workspace. -The guide comes from `skills/tmeet-skill/` of `TencentCloud/tencentmeeting-cli` at tag `v1.0.18` (commit `e631b35`), without `scripts/agent_init.py`. The row downloads that commit's archive when it loads and keeps the verified files in `$DSH_HOME/cache/tencent-meeting/`; until they are in place, the catalog has no `tencent-meeting` skill and the plugin page reports the download. A failed download is retried by the page's check. +The guide comes from `skills/tmeet-skill/` of `TencentCloud/tencentmeeting-cli` at tag `v1.0.18` (commit `e631b35`), without `scripts/agent_init.py`. The row downloads that commit's archive when it loads and keeps the verified files in `$DSH_HOME/cache/tencent-meeting/`; until they are in place, the catalog has no `tencent-meeting` skill, the runtime context gives no `tmeet` path, and the plugin page shows the download instead of the account. The page's check waits for the download and shows it as a step with **Cancel**. A download that does not finish leaves the account at `not-installed`: the page reports that the skill could not be downloaded and offers **Retry**, and the next check downloads again. Turning the plugin off in Plugin Manager withdraws the skill, the path from runtime context, and the account section. The CLI sign-in and the downloaded guide stay in place. @@ -51,12 +51,12 @@ The Plugins page drives these operations through the connector account registry, | Operation | Effect | |---|---| -| `check` | Checks the account again; each browser that opens the Web app starts one when no operation runs | +| `check` | Waits for the guide's download while it is missing, starting one when none runs, then checks the account again; each browser that opens the Web app starts one when no operation runs | | `sign-in` | Runs `auth login --no-browser`, waits for the user to authorize on the Tencent Meeting page, then checks that the server accepts the new sign-in | | `sign-out` | After the user confirms, runs `auth logout`, which also signs out the user's own terminal, then checks again | -| Cancel | Cancels a sign-in while it waits for authorization and waits for its command to exit; other steps are ignored | +| Cancel | Cancels a sign-in while it waits for authorization, or a check while it waits for the guide's download, and waits for the command or download to stop; other steps are ignored | -A check runs `auth status`, which in tmeet 1.0.18 prints plain text and exits with code 0 whether or not a user is signed in. The account reads `signed-out` for `Not logged in.`, for `Session has expired.`, or when `Logged in` comes with an expired refresh token; `connected`, with the user name, when `Logged in` comes with a `UserName:` line, which the CLI prints only after its user-info request to the server succeeds; and `unverified` for any other `Logged in`, for example when that request cannot reach the server. A nonzero exit or other output fails the check and keeps the previous account. The link that `auth login` prints on its `authorize url:` stdout line is offered only when it is an HTTPS address on `meeting.tencent.com`. Results report succeeded, cancelled, or failed. Failures show the command and the observed exit code on the page and in the Host log; the CLI's output, which can carry the one-time authorization code, is omitted. The process running DSH needs access to the CLI configuration in `~/.tmeet`, the encrypted credentials in `~/Library/Application Support/tmeet`, and the macOS Keychain item that holds their key; `DSH_HOME` does not relocate them. +A check runs `auth status`, which in tmeet 1.0.18 prints plain text and exits with code 0 whether or not a user is signed in. The account reads `signed-out` for `Not logged in.`, for `Session has expired.`, or when `Logged in` comes with an expired refresh token; `connected`, with the user name, when `Logged in` comes with a `UserName:` line, which the CLI prints only after its user-info request to the server succeeds; and `unverified` for any other `Logged in`, for example when that request cannot reach the server. A nonzero exit or other output fails the check and keeps the previous account; a download that does not finish leaves `not-installed`. The link that `auth login` prints on its `authorize url:` stdout line is offered only when it is an HTTPS address on `meeting.tencent.com`. Results report succeeded, cancelled, or failed. Failures show the command and the observed exit code on the page and in the Host log; the CLI's output, which can carry the one-time authorization code, is omitted. The process running DSH needs access to the CLI configuration in `~/.tmeet`, the encrypted credentials in `~/Library/Application Support/tmeet`, and the macOS Keychain item that holds their key; `DSH_HOME` does not relocate them. ### Configure @@ -77,7 +77,7 @@ The generated [config catalog](../../../docs/config-catalog.md#deepseek-aidsh-te
Implementation internals — click to expand -[`cordis.patch.yml`](cordis.patch.yml) inserts this package as the `tencent-meeting` row after the profile's other layers, and the Plugins page keys the account section by this package name. [`src/index.ts`](src/index.ts) is a function plugin. It resolves the `tmeet` executable, registers the `tencent-meeting` skill with `ctx.upstreamSkills` under the pin in [`src/skills.ts`](src/skills.ts), and registers that path and the account with `ctx.cliAccounts`. The account view carries the download state, and each check restarts a failed download without waiting for it. `@tencentcloud/tmeet` ships one executable per platform under `dist/`, each named for its platform, and its `bin` is a Node launcher. [`src/directory.ts`](src/directory.ts) therefore picks the executable for `process.platform` and `process.arch` with the same names the launcher uses, and both the runtime context and the plugin's own commands use that path. The [CLI account Service](../cli-account/README.md) gives the model that path in runtime context, runs each command by the same path, runs one operation at a time, and reports a failed command by its exit code. [`src/account.ts`](src/account.ts) carries out each operation with the tmeet commands, reads the authorization link from the output lines of `auth login`, and parses the `auth status` text. [`src/presentation.ts`](src/presentation.ts) maps each view to the section the registry serves, in the text of [`src/locales.ts`](src/locales.ts). Disposal cancels the active operation, aborts running commands, and settles after their processes exit. +[`cordis.patch.yml`](cordis.patch.yml) inserts this package as the `tencent-meeting` row after the profile's other layers, and the Plugins page keys the account section by this package name. [`src/index.ts`](src/index.ts) is a function plugin. It resolves the `tmeet` executable, registers the `tencent-meeting` skill with `ctx.upstreamSkills` under the pin in [`src/skills.ts`](src/skills.ts), and registers that path and the account with `ctx.cliAccounts`. The registration's [`prepare` step](../cli-account/README.md#prepare-before-a-check) is the skill handle's `installed` and `install`, so each check first waits for the guide's download and starts one when none runs. `@tencentcloud/tmeet` ships one executable per platform under `dist/`, each named for its platform, and its `bin` is a Node launcher. [`src/directory.ts`](src/directory.ts) therefore picks the executable for `process.platform` and `process.arch` with the same names the launcher uses, and both the runtime context and the plugin's own commands use that path. The [CLI account Service](../cli-account/README.md) gives the model that path in runtime context while the guide is in place, runs the `prepare` step before a check's first command while it is missing, runs each command by the same path, runs one operation at a time, and reports a failed command by its exit code. [`src/account.ts`](src/account.ts) carries out each operation with the tmeet commands, reads the authorization link from the output lines of `auth login`, and parses the `auth status` text. [`src/presentation.ts`](src/presentation.ts) maps each view to the section the registry serves, in the text of [`src/locales.ts`](src/locales.ts). Disposal cancels the active operation, aborts running commands and the guide's download, and settles after the commands' processes exit. [`skills/tencent-meeting/SKILL.md`](skills/tencent-meeting/SKILL.md) is the only skill this package carries: the DSH guidance, an index of the guide, and how to open it. Upstream publishes the guide only in its repository and not in the npm package, so the [upstream skills Service](../upstream-skills/README.md) downloads it; it is a set of files under the skill's base directory, not a separate skill. The pin excludes `scripts/agent_init.py`, which records the calling agent and model in the CLI configuration for upstream telemetry. Where the DSH guidance and the guide disagree, the entry tells the agent to follow the DSH guidance: it uses the plugin's `tmeet` instead of installing one, skips `agent_init.py`, and sends sign-in to the plugin page. References are ordinary files in the guide's directory. @@ -131,7 +131,7 @@ Loading appends a tool result and does not rewrite earlier context. #### What the model sees -While the row is loaded, the [CLI account Service](../cli-account/README.md#model-experience) adds one required runtime-context entry with the path of the executable: `tmeet` in `binDir`, or by default the installed `@tencentcloud/tmeet` executable for this platform, such as `dist/tmeet-macOS-AppleSilicon`. +While the row is loaded and the guide is in place, the [CLI account Service](../cli-account/README.md#model-experience) adds one required runtime-context entry with the path of the executable: `tmeet` in `binDir`, or by default the installed `@tencentcloud/tmeet` executable for this platform, such as `dist/tmeet-macOS-AppleSilicon`. ##### Runtime-context entry @@ -151,7 +151,7 @@ One line of about 115 characters plus the path in each runtime-context snapshot. #### KV Cache effect -The system prompt does not change; loading or unloading the row, or a changed path, appends one runtime-context snapshot. +The system prompt does not change; finishing the guide's download, loading or unloading the row, or a changed path appends one runtime-context snapshot. ## Known Limitations and Deferred Work @@ -163,7 +163,7 @@ The system prompt does not change; loading or unloading the row, or a changed pa - The plugin uses the CLI's default configuration. Signing in or out from DSH affects the user's own terminal, and there is no DSH-private account or account picker. - The account state comes from the plain-text output of tmeet 1.0.18's `auth status`, and the sign-in link from its `authorize url:` line; a CLI version that changes that text fails the check or the sign-in with a retryable result. An account for which the server returns no user name reads as unconfirmed. - The guide follows upstream tag `v1.0.18`; updating it means a new pin from `scripts/upstream-skills-digest.ts`, after which the entry's index and DSH guidance must be checked against the new guide. -- The first load after a new pin needs access to GitHub or a configured mirror; until a download succeeds, the agent has no `tencent-meeting` skill. +- The first load after a new pin needs access to GitHub or a configured mirror; until a download succeeds, the agent has neither the `tencent-meeting` skill nor the `tmeet` path, and the page offers no sign-in. A computer that reaches neither needs `skillsDir`. A headless profile has no page check, so a download that failed at load is repeated only at the next load. - The downloaded guide stays in `$DSH_HOME/cache/tencent-meeting/` after the plugin is removed or pins another commit. diff --git a/packages/connector/tencent-meeting/README.zh.md b/packages/connector/tencent-meeting/README.zh.md index ffeb37ea54..85b8128d62 100644 --- a/packages/connector/tencent-meeting/README.zh.md +++ b/packages/connector/tencent-meeting/README.zh.md @@ -40,7 +40,7 @@ dsh plugin --profile web remove @deepseek-ai/dsh-tencent-meeting 插件加载后,技能目录中会多一个 `tencent-meeting` skill。Agent 用 `skill` 工具加载它,用文件工具打开 `tmeet-skill` 子指南及其参考文件,并在当前沙箱和审批策略下通过普通 Shell 工具按这个路径运行 `tmeet`。命令报告未登录或登录过期时,Agent 会请用户在插件页面连接腾讯会议;只有用户要求在对话中完成时,它才运行 `tmeet auth login --no-browser`,并且因为该命令会写入工作区之外,第一次尝试就带 `justification` 申请 `sandbox_permissions`。 -子指南来自 `TencentCloud/tencentmeeting-cli` 标签 `v1.0.18`(提交 `e631b35`)中的 `skills/tmeet-skill/`,不含 `scripts/agent_init.py`。该行加载时下载这个提交的归档,并把校验后的文件保存在 `$DSH_HOME/cache/tencent-meeting/`;文件就位之前,skill 目录中没有 `tencent-meeting` skill,插件页会报告下载状态。下载失败时,由插件页的检查重试。 +子指南来自 `TencentCloud/tencentmeeting-cli` 标签 `v1.0.18`(提交 `e631b35`)中的 `skills/tmeet-skill/`,不含 `scripts/agent_init.py`。该行加载时下载这个提交的归档,并把校验后的文件保存在 `$DSH_HOME/cache/tencent-meeting/`;文件就位之前,skill 目录中没有 `tencent-meeting` skill,运行时上下文不给出 `tmeet` 路径,插件页显示的是下载而不是账号。插件页的检查会等待下载,并把它显示为一个带**取消**的步骤。没有完成的下载使账号处于 `not-installed`:页面提示没能下载技能并提供**重试**,下一次检查会重新下载。 在 Plugin Manager 中关闭插件会撤下这个 skill、运行时上下文中的路径和账号区块。CLI 的登录和已下载的子指南会保留。 @@ -51,12 +51,12 @@ dsh plugin --profile web remove @deepseek-ai/dsh-tencent-meeting | 操作 | 效果 | |---|---| -| `check` | 重新检查账号;没有操作运行时,每个打开 Web 应用的浏览器会触发一次 | +| `check` | 子指南缺失时先等待它下载完成(没有下载在运行时发起一次),然后重新检查账号;没有操作运行时,每个打开 Web 应用的浏览器会触发一次 | | `sign-in` | 运行 `auth login --no-browser`,等待用户在腾讯会议页面授权,然后检查服务端是否接受新的登录 | | `sign-out` | 用户确认后运行 `auth logout`,这也会退出用户自己终端里的登录,然后重新检查 | -| 取消 | 在登录等待授权时取消它,并等待其命令退出;其他步骤会被忽略 | +| 取消 | 在登录等待授权期间取消登录,或在检查等待子指南下载期间取消检查,并等待命令或下载停止;其他步骤会被忽略 | -检查运行 `auth status`。在 tmeet 1.0.18 中,它只输出纯文本,无论是否有用户登录,退出码都是 0。输出 `Not logged in.` 或 `Session has expired.`,或 `Logged in` 伴随已过期的 refresh token 时,账号为 `signed-out`;`Logged in` 伴随 `UserName:` 行时为 `connected` 并带用户名,CLI 只有在向服务端请求用户信息成功后才会打印这一行;其他 `Logged in` 为 `unverified`,例如该请求连不上服务端。退出码非零或其他输出会使检查失败,并保留之前的账号状态。`auth login` 在 stdout 的 `authorize url:` 行打印的链接,只有是 `meeting.tencent.com` 上的 HTTPS 地址时才会提供。结果分为成功、已取消和失败。失败时,页面和 Host 日志显示命令和观察到的退出码;CLI 的输出可能带有一次性授权码,因此会被省略。运行 DSH 的进程需要能访问 `~/.tmeet` 中的 CLI 配置、`~/Library/Application Support/tmeet` 中的加密凭据,以及保存其密钥的 macOS 钥匙串项;`DSH_HOME` 不会改变它们的位置。 +检查运行 `auth status`。在 tmeet 1.0.18 中,它只输出纯文本,无论是否有用户登录,退出码都是 0。输出 `Not logged in.` 或 `Session has expired.`,或 `Logged in` 伴随已过期的 refresh token 时,账号为 `signed-out`;`Logged in` 伴随 `UserName:` 行时为 `connected` 并带用户名,CLI 只有在向服务端请求用户信息成功后才会打印这一行;其他 `Logged in` 为 `unverified`,例如该请求连不上服务端。退出码非零或其他输出会使检查失败,并保留之前的账号状态;没有完成的下载使状态成为 `not-installed`。`auth login` 在 stdout 的 `authorize url:` 行打印的链接,只有是 `meeting.tencent.com` 上的 HTTPS 地址时才会提供。结果分为成功、已取消和失败。失败时,页面和 Host 日志显示命令和观察到的退出码;CLI 的输出可能带有一次性授权码,因此会被省略。运行 DSH 的进程需要能访问 `~/.tmeet` 中的 CLI 配置、`~/Library/Application Support/tmeet` 中的加密凭据,以及保存其密钥的 macOS 钥匙串项;`DSH_HOME` 不会改变它们的位置。 ### 配置 @@ -77,7 +77,7 @@ dsh plugin --profile web remove @deepseek-ai/dsh-tencent-meeting
实现细节 — 点击展开 -[`cordis.patch.yml`](cordis.patch.yml) 在 profile 其他层之后把本包作为 `tencent-meeting` 行插入,插件页以本包名作为账号区块的 key。[`src/index.ts`](src/index.ts) 是一个函数插件。它解析 `tmeet` 可执行文件,按 [`src/skills.ts`](src/skills.ts) 中的固定信息把 `tencent-meeting` skill 注册到 `ctx.upstreamSkills`,并把这个路径和账号注册到 `ctx.cliAccounts`。账号视图携带下载状态,每次检查都会在不等待的情况下重新开始失败的下载。`@tencentcloud/tmeet` 在 `dist/` 下为每个平台提供一个按平台命名的可执行文件,其 `bin` 是一个 Node 启动器。因此 [`src/directory.ts`](src/directory.ts) 按 `process.platform` 和 `process.arch`,用与该启动器相同的文件名选出可执行文件,运行时上下文和插件自己的命令都使用这个路径。[CLI 账号 Service](../cli-account/README.zh.md) 在运行时上下文中把这个路径告诉模型,按同一路径运行每条命令,同一时间只运行一个操作,并以退出码报告失败的命令。[`src/account.ts`](src/account.ts) 用 tmeet 命令完成每个操作,从 `auth login` 的输出行读取授权链接,并解析 `auth status` 的文本。[`src/presentation.ts`](src/presentation.ts) 用 [`src/locales.ts`](src/locales.ts) 中的文案,把每个视图映射为注册表提供的区块。释放时会取消进行中的操作、中止正在运行的命令,并在其进程退出后结束。 +[`cordis.patch.yml`](cordis.patch.yml) 在 profile 其他层之后把本包作为 `tencent-meeting` 行插入,插件页以本包名作为账号区块的 key。[`src/index.ts`](src/index.ts) 是一个函数插件。它解析 `tmeet` 可执行文件,按 [`src/skills.ts`](src/skills.ts) 中的固定信息把 `tencent-meeting` skill 注册到 `ctx.upstreamSkills`,并把这个路径和账号注册到 `ctx.cliAccounts`。这次注册的 [`prepare` 步骤](../cli-account/README.zh.md#prepare-before-a-check)就是 skill 句柄的 `installed` 和 `install`,因此每次检查都先等待子指南下载完成,没有下载在运行时发起一次。`@tencentcloud/tmeet` 在 `dist/` 下为每个平台提供一个按平台命名的可执行文件,其 `bin` 是一个 Node 启动器。因此 [`src/directory.ts`](src/directory.ts) 按 `process.platform` 和 `process.arch`,用与该启动器相同的文件名选出可执行文件,运行时上下文和插件自己的命令都使用这个路径。[CLI 账号 Service](../cli-account/README.zh.md) 在子指南就位期间于运行时上下文中把这个路径告诉模型,在它缺失时于检查的第一条命令之前运行 `prepare` 步骤,按同一路径运行每条命令,同一时间只运行一个操作,并以退出码报告失败的命令。[`src/account.ts`](src/account.ts) 用 tmeet 命令完成每个操作,从 `auth login` 的输出行读取授权链接,并解析 `auth status` 的文本。[`src/presentation.ts`](src/presentation.ts) 用 [`src/locales.ts`](src/locales.ts) 中的文案,把每个视图映射为注册表提供的区块。释放时会取消进行中的操作、中止正在运行的命令和子指南的下载,并在这些命令的进程退出后结束。 [`skills/tencent-meeting/SKILL.md`](skills/tencent-meeting/SKILL.md) 是本包携带的唯一 skill:DSH 指引、子指南索引,以及打开子指南的方式。上游只在其仓库中发布这个子指南,npm 包里没有,因此由[上游技能 Service](../upstream-skills/README.zh.md) 下载;它是 skill 基础目录下的一组文件,不是独立的 skill。固定信息排除了 `scripts/agent_init.py`,它用于把调用方 Agent 和模型记录到 CLI 配置中供上游统计。DSH 指引与子指南不一致时,入口要求 Agent 以 DSH 指引为准:使用插件提供的 `tmeet` 而不是自行安装,跳过 `agent_init.py`,并把登录交给插件页面。参考文件是子指南目录中的普通文件。 @@ -131,7 +131,7 @@ dsh plugin --profile web remove @deepseek-ai/dsh-tencent-meeting #### 模型看到的内容 -该行加载期间,[CLI 账号 Service](../cli-account/README.zh.md#model-experience) 添加一条必需的运行时上下文,给出可执行文件的路径:`binDir` 中的 `tmeet`,或者默认使用当前平台已安装的 `@tencentcloud/tmeet` 可执行文件,例如 `dist/tmeet-macOS-AppleSilicon`。 +该行加载且子指南就位期间,[CLI 账号 Service](../cli-account/README.zh.md#model-experience) 添加一条必需的运行时上下文,给出可执行文件的路径:`binDir` 中的 `tmeet`,或者默认使用当前平台已安装的 `@tencentcloud/tmeet` 可执行文件,例如 `dist/tmeet-macOS-AppleSilicon`。 ##### 运行时上下文条目 @@ -151,7 +151,7 @@ Tencent Meeting CLI: run `tmeet` by its absolute path with the call operator, & #### KV Cache 影响 -系统提示词不变;加载或卸载该行、或路径变化时,追加一份运行时上下文快照。 +系统提示词不变;子指南下载完成、加载或卸载该行、或路径变化时,追加一份运行时上下文快照。 ## 已知限制与延期工作 @@ -163,7 +163,7 @@ Tencent Meeting CLI: run `tmeet` by its absolute path with the call operator, & - 插件使用 CLI 的默认配置。在 DSH 中登录或退出登录会影响用户自己的终端,没有 DSH 专用的账号,也没有账号选择。 - 账号状态来自 tmeet 1.0.18 `auth status` 的纯文本输出,登录链接来自它的 `authorize url:` 行;改变这些文本的 CLI 版本会使检查或登录失败,并给出可重试的结果。服务端没有返回用户名的账号会显示为待确认。 - 子指南对应上游标签 `v1.0.18`;更新它要用 `scripts/upstream-skills-digest.ts` 生成新的固定信息,之后对照新的子指南检查入口的索引和 DSH 指引。 -- 换用新的固定提交后,首次加载需要能访问 GitHub 或配置的镜像;下载成功之前,Agent 没有 `tencent-meeting` skill。 +- 换用新的固定提交后,首次加载需要能访问 GitHub 或配置的镜像;下载成功之前,Agent 既没有 `tencent-meeting` skill 也没有 `tmeet` 路径,页面也不提供登录。两者都访问不到的电脑需要设置 `skillsDir`。headless profile 没有页面的检查,因此加载时失败的下载要到下一次加载才会重试。 - 插件卸载或改为固定其他提交后,已下载的子指南仍留在 `$DSH_HOME/cache/tencent-meeting/`。 diff --git a/packages/connector/tencent-meeting/src/account.ts b/packages/connector/tencent-meeting/src/account.ts index 728b709cbe..62b71df9ee 100644 --- a/packages/connector/tencent-meeting/src/account.ts +++ b/packages/connector/tencent-meeting/src/account.ts @@ -4,26 +4,20 @@ */ import type { CliOperationControl } from '@deepseek-ai/dsh-cli-account/types' -import type { UpstreamSkillsHandle } from '@deepseek-ai/dsh-upstream-skills/types' import { assertNever } from '@deepseek-ai/dsh-util-values' -import type { - TencentMeetingAccountState, TencentMeetingCommand, TencentMeetingOperationKind, TencentMeetingPhase, TencentMeetingSignIn, -} from './types.ts' +import type { TencentMeetingAccountState, TencentMeetingCommand, TencentMeetingOperationKind, TencentMeetingPhase } from './types.ts' const LOGIN_LINK = /^authorize url: (https:\/\/\S+)[ \t]*$/u type Control = CliOperationControl -/** The upstream guide whose state the account carries and whose failed download each check restarts. */ -type Guides = Pick - /** * Read the text `auth status` prints; tmeet 1.0.18 has no machine-readable status and exits 0 whether or not a user is * signed in. `Logged in` alone does not show that the server accepts the sign-in: the CLI prints the user name only * after its user-info request succeeds, refreshing the token first when needed. * @returns the account, or undefined for output this version does not print. */ -function readStatus(stdout: string): TencentMeetingSignIn | undefined { +function readStatus(stdout: string): TencentMeetingAccountState | undefined { if (/^[ \t]*(?:Not logged in|Session has expired)\./mu.test(stdout)) return { state: 'signed-out' } if (!/^Logged in$/mu.test(stdout)) return undefined if (/^[ \t]*RefreshToken:[ \t]+expired\b/mu.test(stdout)) return { state: 'signed-out' } @@ -31,30 +25,28 @@ function readStatus(stdout: string): TencentMeetingSignIn | undefined { return userName === undefined ? { state: 'unverified' } : { state: 'connected', userName } } -/* jscpd:ignore-start -- CLI app plugins with downloaded guides bind their operations to the guides alike. */ /** - * Bind the Tencent Meeting account operations to the upstream guide. - * @param guides - the registered upstream guide. - * @returns the function that carries out one operation with tmeet and publishes the account each check observes; it - * throws when a command fails, prints an unknown status, or leaves no verified sign-in after a sign-in. + * Carry out one account operation with tmeet and publish the account each check observes. + * @param kind - the requested operation. + * @param control - phase changes, link offers, command runs, and account updates for this operation. + * @param signal - aborts on cancellation and when the plugin unloads. + * @returns after the operation finishes. + * @throws when a command fails, prints an unknown status, or leaves no verified sign-in after a sign-in. */ -export function performWith(guides: Guides): (kind: TencentMeetingOperationKind, control: Control, signal: AbortSignal) => Promise { - return async (kind, control, signal) => { - switch (kind) { - case 'check': - await check(guides, control, signal) - return - case 'sign-in': return signIn(guides, control, signal) - case 'sign-out': return signOut(guides, control, signal) - /* v8 ignore next -- closed operation kind union */ - default: return assertNever(kind) - } +export async function perform(kind: TencentMeetingOperationKind, control: Control, signal: AbortSignal): Promise { + switch (kind) { + case 'check': + await check(control, signal) + return + case 'sign-in': return signIn(control, signal) + case 'sign-out': return signOut(control, signal) + /* v8 ignore next -- closed operation kind union */ + default: return assertNever(kind) } } -/* jscpd:ignore-end */ /** Sign in through the CLI's authorization page, then confirm that the server accepts the new sign-in. */ -async function signIn(guides: Guides, control: Control, signal: AbortSignal): Promise { +async function signIn(control: Control, signal: AbortSignal): Promise { control.stage('authorizing') const login = await control.run('auth-login', ['auth', 'login', '--no-browser'], signal, { awaitsUser: true, @@ -65,24 +57,22 @@ async function signIn(guides: Guides, control: Control, signal: AbortSignal): Pr }) if (login.exitCode !== 0) throw new Error(`tencent-meeting: auth login exited with ${String(login.exitCode)}`) control.stage('checking') - if ((await check(guides, control, signal)).state !== 'connected') throw new Error('tencent-meeting: auth login left no verified sign-in') + if ((await check(control, signal)).state !== 'connected') throw new Error('tencent-meeting: auth login left no verified sign-in') } /** Clear the default sign-in, which also signs out the user's own terminal, then check again. */ -async function signOut(guides: Guides, control: Control, signal: AbortSignal): Promise { +async function signOut(control: Control, signal: AbortSignal): Promise { control.stage('signing-out') const logout = await control.run('auth-logout', ['auth', 'logout'], signal) if (logout.exitCode !== 0) throw new Error(`tencent-meeting: auth logout exited with ${String(logout.exitCode)}`) - await check(guides, control, signal) + await check(control, signal) } -/** Restart a failed download of the guide without waiting for it, then read the default account, publish it, and return it. */ -async function check(guides: Guides, control: Control, signal: AbortSignal): Promise { - guides.retry() +/** Read the default account, publish it, and return it. */ +async function check(control: Control, signal: AbortSignal): Promise { const result = await control.run('auth-status', ['auth', 'status'], signal) - const signIn = result.exitCode === 0 ? readStatus(result.stdout) : undefined - if (signIn === undefined) throw new Error(`tencent-meeting: auth status exited with ${String(result.exitCode)} or printed an unknown status`) - const account: TencentMeetingAccountState = { ...signIn, skills: guides.state } + const account = result.exitCode === 0 ? readStatus(result.stdout) : undefined + if (account === undefined) throw new Error(`tencent-meeting: auth status exited with ${String(result.exitCode)} or printed an unknown status`) control.publish(account) return account } diff --git a/packages/connector/tencent-meeting/src/index.ts b/packages/connector/tencent-meeting/src/index.ts index 39e3711779..3e3607474c 100644 --- a/packages/connector/tencent-meeting/src/index.ts +++ b/packages/connector/tencent-meeting/src/index.ts @@ -1,8 +1,8 @@ /** - * Tencent Meeting plugin: registers the managed tmeet and its account with `ctx.cliAccounts`, which tells the model the - * CLI's absolute path and shows the account on the Plugins page, and registers the `tencent-meeting` entry skill with - * `ctx.upstreamSkills`, which downloads the upstream guide it indexes. The CLI's default sign-in is shared with the - * user's own terminal. + * Tencent Meeting plugin: registers the `tencent-meeting` entry skill with `ctx.upstreamSkills`, which downloads the + * upstream guide it indexes, and registers the managed tmeet and its account with `ctx.cliAccounts`, which tells the + * model the CLI's absolute path once the guide is in place and shows the account on the Plugins page. The CLI's default + * sign-in is shared with the user's own terminal. * @module @deepseek-ai/dsh-tencent-meeting */ @@ -10,7 +10,7 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-cli-account' import type {} from '@deepseek-ai/dsh-upstream-skills' -import { performWith } from './account.ts' +import { perform } from './account.ts' import { PROGRAM, resolveCliExecutable } from './directory.ts' import { dictionaries, type TencentMeetingTextKey } from './locales.ts' import { copy, operations, presentAccount, TENCENT_MEETING_PACKAGE } from './presentation.ts' @@ -39,7 +39,7 @@ export const Config: z = z.object({ }) /** - * Register the entry skill, and the CLI with its account, whose view follows the guide's download. + * Register the entry skill, and the CLI with its account, whose check first waits for the guide's download. * @param ctx - Context carrying the CLI account Service and the upstream skills Service. * @param config - CLI location and the guide's directory. * @throws when this platform has no packaged `tmeet`, `tmeet` is not executable, or `skillsDir` is not a directory. @@ -47,22 +47,27 @@ export const Config: z = z.object({ export function apply(ctx: Context, config: Config): void { const executable = resolveCliExecutable(config.binDir) const guides = ctx.upstreamSkills.register({ name, entry: ENTRY, set: TMEET_SKILLS, skillsDir: config.skillsDir }) - const account = ctx.cliAccounts.register< + ctx.cliAccounts.register< TencentMeetingAccountState, TencentMeetingOperationKind, TencentMeetingPhase, TencentMeetingCommand, TencentMeetingTextKey >({ name, packageName: TENCENT_MEETING_PACKAGE, cli: { product: 'Tencent Meeting', program: PROGRAM, executable }, - account: { state: 'unchecked', skills: guides.state }, + prepare: { + phase: 'downloading', + unprepared: { state: 'not-installed' }, + ready: () => guides.installed(), + run: signal => guides.install(signal), + }, + account: { state: 'unchecked' }, check: 'check', - cancellable: ['authorizing'], + cancellable: ['downloading', 'authorizing'], authorizationHosts: ['meeting.tencent.com'], - perform: performWith(guides), + perform, dictionaries, operations, copy, present: presentAccount, }) - ctx.effect(() => guides.watch((skills) => { account.publish({ ...account.snapshot().account, skills }) }), 'tencent-meeting: guide') } /* jscpd:ignore-end */ diff --git a/packages/connector/tencent-meeting/src/locales.ts b/packages/connector/tencent-meeting/src/locales.ts index 533ee400de..e0de236872 100644 --- a/packages/connector/tencent-meeting/src/locales.ts +++ b/packages/connector/tencent-meeting/src/locales.ts @@ -7,15 +7,15 @@ export const zh = { 'status.disconnected': '未连接', 'status.unavailable': '暂时无法确认登录状态', 'status.connected': '已连接', + 'step.downloading': '正在下载腾讯会议技能', 'step.authorizing': '等待在腾讯会议页面授权', 'step.connecting': '正在连接', 'step.signing-out': '正在退出登录', 'detail.disconnected': '登录腾讯会议账号后,就可以在对话中使用会议、录制、纪要和会议报告等功能。', 'detail.unavailable': '已保留现有登录,可以稍后重试。', + 'detail.missing': '没能下载腾讯会议技能,请确认这台电脑能访问 GitHub,然后重试。', 'detail.connected': '已登录为 {name}。可以在对话中直接请 Agent 使用腾讯会议。', 'detail.authorizing': '在打开的腾讯会议页面中确认授权,完成后回到这里查看结果。页面没有打开时,点击“打开腾讯会议页面”。', - 'skills.downloading': '正在从 GitHub 下载腾讯会议技能,下载完成后即可在对话中使用。', - 'skills.failed': '腾讯会议技能没能下载,Agent 暂时用不了腾讯会议的子指南。请确认这台电脑能访问 GitHub,然后重试。', hint: '腾讯会议账号与这台电脑终端里的 tmeet 共用;关闭插件不会退出登录。', failed: '操作未完成,请重试', 'action.connect': '连接腾讯会议', @@ -45,15 +45,15 @@ export const en: Record = { 'status.disconnected': 'Not connected', 'status.unavailable': 'Cannot confirm sign-in right now', 'status.connected': 'Connected', + 'step.downloading': 'Downloading the Tencent Meeting skill', 'step.authorizing': 'Waiting for authorization on the Tencent Meeting page', 'step.connecting': 'Connecting', 'step.signing-out': 'Signing out', 'detail.disconnected': 'Sign in to Tencent Meeting to use meetings, recordings, minutes, meeting reports, and other features in conversations.', 'detail.unavailable': 'The existing sign-in is kept. Try again later.', + 'detail.missing': 'The Tencent Meeting skill could not be downloaded. Check that this computer can reach GitHub, then retry.', 'detail.connected': 'Signed in as {name}. Ask the agent to use Tencent Meeting directly in a conversation.', 'detail.authorizing': 'Confirm the authorization on the Tencent Meeting page that opened, then come back here to see the result. If the page did not open, select Open Tencent Meeting page.', - 'skills.downloading': 'Downloading the Tencent Meeting skill from GitHub. It becomes available in conversations when the download finishes.', - 'skills.failed': 'The Tencent Meeting skill could not be downloaded, so the agent cannot use the Tencent Meeting guide yet. Check that this computer can reach GitHub, then retry.', hint: 'The Tencent Meeting account is shared with tmeet in this computer\'s terminal. Turning the plugin off does not sign it out.', failed: 'The action did not finish. Try again.', 'action.connect': 'Connect Tencent Meeting', @@ -80,15 +80,15 @@ export const ja: Record = { 'status.disconnected': '未接続', 'status.unavailable': '現在サインイン状態を確認できません', 'status.connected': '接続済み', + 'step.downloading': 'Tencent Meeting のスキルをダウンロード中', 'step.authorizing': 'Tencent Meeting ページでの認可を待っています', 'step.connecting': '接続中', 'step.signing-out': 'サインアウト中', 'detail.disconnected': 'Tencent Meeting にサインインすると、会話の中で会議、録画、議事録、会議レポートなどの機能を使用できます。', 'detail.unavailable': '現在のサインイン状態は保持されています。しばらくしてから再試行してください。', + 'detail.missing': 'Tencent Meeting のスキルをダウンロードできませんでした。このコンピューターから GitHub にアクセスできることを確認してから、再試行してください。', 'detail.connected': '{name} としてサインインしています。会話の中でエージェントに Tencent Meeting の使用を直接依頼できます。', 'detail.authorizing': '開いた Tencent Meeting ページで認可を確定し、完了したらここに戻って結果を確認してください。ページが開かない場合は、「Tencent Meeting ページを開く」を選択してください。', - 'skills.downloading': 'GitHub から Tencent Meeting のスキルをダウンロードしています。ダウンロードが完了すると、会話の中で使用できます。', - 'skills.failed': 'Tencent Meeting のスキルをダウンロードできなかったため、エージェントはまだ Tencent Meeting のガイドを使用できません。このコンピューターから GitHub にアクセスできることを確認してから、再試行してください。', hint: 'Tencent Meeting アカウントは、このコンピューターのターミナルにある tmeet と共有されます。プラグインをオフにしてもサインアウトはされません。', failed: '操作が完了しませんでした。もう一度お試しください。', 'action.connect': 'Tencent Meeting を接続', @@ -115,15 +115,15 @@ export const es: Record = { 'status.disconnected': 'No conectado', 'status.unavailable': 'No se puede confirmar el inicio de sesión en este momento', 'status.connected': 'Conectado', + 'step.downloading': 'Descargando la habilidad de Tencent Meeting', 'step.authorizing': 'Esperando la autorización en la página de Tencent Meeting', 'step.connecting': 'Conectando', 'step.signing-out': 'Cerrando sesión', 'detail.disconnected': 'Inicie sesión en Tencent Meeting para usar reuniones, grabaciones, actas, informes de reuniones y otras funciones en las conversaciones.', 'detail.unavailable': 'Se conserva el inicio de sesión actual. Inténtelo de nuevo más tarde.', + 'detail.missing': 'No se pudo descargar la habilidad de Tencent Meeting. Compruebe que esta computadora puede acceder a GitHub y vuelva a intentarlo.', 'detail.connected': 'Sesión iniciada como {name}. Pida al agente que use Tencent Meeting directamente en una conversación.', 'detail.authorizing': 'Confirme la autorización en la página de Tencent Meeting que se abrió y luego vuelva aquí para ver el resultado. Si la página no se abrió, seleccione “Abrir página de Tencent Meeting”.', - 'skills.downloading': 'Descargando la habilidad de Tencent Meeting desde GitHub. Estará disponible en las conversaciones cuando termine la descarga.', - 'skills.failed': 'No se pudo descargar la habilidad de Tencent Meeting, por lo que el agente aún no puede usar la guía de Tencent Meeting. Compruebe que esta computadora puede acceder a GitHub y vuelva a intentarlo.', hint: 'La cuenta de Tencent Meeting se comparte con tmeet en la terminal de esta computadora. Desactivar el complemento no cierra su sesión.', failed: 'La acción no se completó. Inténtelo de nuevo.', 'action.connect': 'Conectar Tencent Meeting', @@ -150,15 +150,15 @@ export const fr: Record = { 'status.disconnected': 'Non connecté', 'status.unavailable': 'Impossible de confirmer la connexion pour le moment', 'status.connected': 'Connecté', + 'step.downloading': 'Téléchargement de la compétence Tencent Meeting', 'step.authorizing': 'En attente de l’autorisation sur la page Tencent Meeting', 'step.connecting': 'Connexion en cours', 'step.signing-out': 'Déconnexion en cours', 'detail.disconnected': 'Connectez-vous à Tencent Meeting pour utiliser les réunions, les enregistrements, les comptes rendus, les rapports de réunion et d’autres fonctionnalités dans les conversations.', 'detail.unavailable': 'La connexion existante est conservée. Réessayez plus tard.', + 'detail.missing': 'Impossible de télécharger la compétence Tencent Meeting. Vérifiez que cet ordinateur peut accéder à GitHub, puis réessayez.', 'detail.connected': 'Connecté en tant que {name}. Demandez à l’agent d’utiliser Tencent Meeting directement dans une conversation.', 'detail.authorizing': 'Confirmez l’autorisation sur la page Tencent Meeting qui s’est ouverte, puis revenez ici pour voir le résultat. Si la page ne s’est pas ouverte, sélectionnez « Ouvrir la page Tencent Meeting ».', - 'skills.downloading': 'Téléchargement de la compétence Tencent Meeting depuis GitHub. Elle sera disponible dans les conversations une fois le téléchargement terminé.', - 'skills.failed': 'La compétence Tencent Meeting n’a pas pu être téléchargée : l’agent ne peut donc pas encore utiliser le guide Tencent Meeting. Vérifiez que cet ordinateur peut accéder à GitHub, puis réessayez.', hint: 'Le compte Tencent Meeting est partagé avec tmeet dans le terminal de cet ordinateur. Désactiver le plugin ne le déconnecte pas.', failed: 'L’action n’a pas abouti. Réessayez.', 'action.connect': 'Connecter Tencent Meeting', @@ -185,15 +185,15 @@ export const de: Record = { 'status.disconnected': 'Nicht verbunden', 'status.unavailable': 'Anmeldung kann gerade nicht bestätigt werden', 'status.connected': 'Verbunden', + 'step.downloading': 'Die Fertigkeit von Tencent Meeting wird heruntergeladen', 'step.authorizing': 'Warten auf die Autorisierung auf der Tencent Meeting-Seite', 'step.connecting': 'Wird verbunden', 'step.signing-out': 'Wird abgemeldet', 'detail.disconnected': 'Melden Sie sich bei Tencent Meeting an, um Besprechungen, Aufzeichnungen, Protokolle, Besprechungsberichte und weitere Funktionen in Unterhaltungen zu verwenden.', 'detail.unavailable': 'Die bestehende Anmeldung bleibt erhalten. Versuchen Sie es später erneut.', + 'detail.missing': 'Die Fertigkeit von Tencent Meeting konnte nicht heruntergeladen werden. Prüfen Sie, ob dieser Computer GitHub erreichen kann, und versuchen Sie es dann erneut.', 'detail.connected': 'Angemeldet als {name}. Bitten Sie den Agenten, Tencent Meeting direkt in einer Unterhaltung zu verwenden.', 'detail.authorizing': 'Bestätigen Sie die Autorisierung auf der geöffneten Tencent Meeting-Seite und kehren Sie dann hierher zurück, um das Ergebnis zu sehen. Falls sich die Seite nicht geöffnet hat, wählen Sie „Tencent Meeting-Seite öffnen“.', - 'skills.downloading': 'Die Fertigkeit von Tencent Meeting wird von GitHub heruntergeladen. Sie steht in Unterhaltungen zur Verfügung, sobald der Download abgeschlossen ist.', - 'skills.failed': 'Die Fertigkeit von Tencent Meeting konnte nicht heruntergeladen werden, daher kann der Agent die Tencent Meeting-Anleitung noch nicht verwenden. Prüfen Sie, ob dieser Computer GitHub erreichen kann, und versuchen Sie es dann erneut.', hint: 'Das Tencent Meeting-Konto wird mit tmeet im Terminal dieses Computers geteilt. Wenn Sie das Plugin deaktivieren, bleibt es angemeldet.', failed: 'Die Aktion wurde nicht abgeschlossen. Versuchen Sie es erneut.', 'action.connect': 'Tencent Meeting verbinden', @@ -220,15 +220,15 @@ export const ru: Record = { 'status.disconnected': 'Не подключено', 'status.unavailable': 'Сейчас не удаётся подтвердить вход', 'status.connected': 'Подключено', + 'step.downloading': 'Загрузка навыка Tencent Meeting', 'step.authorizing': 'Ожидание авторизации на странице Tencent Meeting', 'step.connecting': 'Подключение', 'step.signing-out': 'Выполняется выход', 'detail.disconnected': 'Войдите в Tencent Meeting, чтобы использовать в беседах встречи, записи, протоколы, отчёты о встречах и другие функции.', 'detail.unavailable': 'Текущий вход сохранён. Повторите попытку позже.', + 'detail.missing': 'Не удалось загрузить навык Tencent Meeting. Убедитесь, что этот компьютер может подключиться к GitHub, затем повторите попытку.', 'detail.connected': 'Выполнен вход как {name}. Попросите агента использовать Tencent Meeting прямо в беседе.', 'detail.authorizing': 'Подтвердите авторизацию на открывшейся странице Tencent Meeting, затем вернитесь сюда, чтобы увидеть результат. Если страница не открылась, нажмите «Открыть страницу Tencent Meeting».', - 'skills.downloading': 'Навык Tencent Meeting загружается с GitHub. Он станет доступен в беседах, когда загрузка завершится.', - 'skills.failed': 'Не удалось загрузить навык Tencent Meeting, поэтому агент пока не может использовать руководство Tencent Meeting. Убедитесь, что этот компьютер может подключиться к GitHub, затем повторите попытку.', hint: 'Аккаунт Tencent Meeting общий с tmeet в терминале этого компьютера. Отключение плагина не приводит к выходу из аккаунта.', failed: 'Действие не завершено. Повторите попытку.', 'action.connect': 'Подключить Tencent Meeting', @@ -255,15 +255,15 @@ export const pt: Record = { 'status.disconnected': 'Não conectado', 'status.unavailable': 'Não é possível confirmar o login no momento', 'status.connected': 'Conectado', + 'step.downloading': 'Baixando a habilidade do Tencent Meeting', 'step.authorizing': 'Aguardando a autorização na página do Tencent Meeting', 'step.connecting': 'Conectando', 'step.signing-out': 'Saindo', 'detail.disconnected': 'Entre no Tencent Meeting para usar reuniões, gravações, atas, relatórios de reunião e outros recursos nas conversas.', 'detail.unavailable': 'O login atual foi mantido. Tente novamente mais tarde.', + 'detail.missing': 'Não foi possível baixar a habilidade do Tencent Meeting. Verifique se este computador consegue acessar o GitHub e tente novamente.', 'detail.connected': 'Conectado como {name}. Peça ao agente que use o Tencent Meeting diretamente em uma conversa.', 'detail.authorizing': 'Confirme a autorização na página do Tencent Meeting que foi aberta e depois volte aqui para ver o resultado. Se a página não abriu, selecione “Abrir página do Tencent Meeting”.', - 'skills.downloading': 'Baixando a habilidade do Tencent Meeting do GitHub. Ela ficará disponível nas conversas quando o download terminar.', - 'skills.failed': 'Não foi possível baixar a habilidade do Tencent Meeting, então o agente ainda não pode usar o guia do Tencent Meeting. Verifique se este computador consegue acessar o GitHub e tente novamente.', hint: 'A conta do Tencent Meeting é compartilhada com o tmeet no terminal deste computador. Desativar o plugin não encerra a sessão dela.', failed: 'A ação não foi concluída. Tente novamente.', 'action.connect': 'Conectar Tencent Meeting', diff --git a/packages/connector/tencent-meeting/src/presentation.ts b/packages/connector/tencent-meeting/src/presentation.ts index 58a22acb52..1f95e68ec8 100644 --- a/packages/connector/tencent-meeting/src/presentation.ts +++ b/packages/connector/tencent-meeting/src/presentation.ts @@ -1,10 +1,8 @@ /** The Tencent Meeting account section the Plugins page shows for each Host view. */ import type { CliAccountText } from '@deepseek-ai/dsh-cli-account/types' import type { - ConnectorAccountButton, ConnectorAccountCopy, ConnectorAccountDisplay, ConnectorAccountFailure, ConnectorAccountNote, - ConnectorAccountOperation, + ConnectorAccountButton, ConnectorAccountCopy, ConnectorAccountDisplay, ConnectorAccountFailure, ConnectorAccountOperation, } from '@deepseek-ai/dsh-client-ui-connector-account/types' -import type { UpstreamSkillsState } from '@deepseek-ai/dsh-upstream-skills/types' import { assertNever } from '@deepseek-ai/dsh-util-values' import type { TencentMeetingTextKey } from './locales.ts' import type { TencentMeetingOperationKind, TencentMeetingState } from './types.ts' @@ -46,66 +44,64 @@ const SIGN_IN = { kind: 'start', operation: 'sign-in' } as const const SIGN_OUT = { kind: 'start', operation: 'sign-out' } as const /* jscpd:ignore-end */ -/* jscpd:ignore-start -- CLI app plugins whose guides download report the same states, each in its own text. */ -/** The row that reports a guide that is not in place yet; a failed download offers a check, which restarts it. */ -function skillsNotes(skills: UpstreamSkillsState, text: Text): ConnectorAccountNote[] { - switch (skills) { - case 'installed': return [] - case 'downloading': return [{ text: text('skills.downloading') }] - case 'failed': return [{ text: text('skills.failed'), button: { label: text('action.retry'), command: CHECK } }] - /* v8 ignore next -- closed skills state union */ - default: return assertNever(skills) - } -} -/* jscpd:ignore-end */ - type Operation = NonNullable +/* jscpd:ignore-start -- CLI app plugin pages map a sign-in or sign-out in progress to the same open-link and cancel buttons. */ +function cancelButton(text: Text): ConnectorAccountButton { + return { label: text('action.cancel'), command: { kind: 'cancel' }, variant: 'ghost' } +} + function step(operation: Operation): 'step.authorizing' | 'step.connecting' | 'step.signing-out' { if (operation.kind === 'sign-out') return 'step.signing-out' return operation.phase === 'authorizing' ? 'step.authorizing' : 'step.connecting' } /** The section while a sign-in or sign-out runs: its step, the authorization page while waiting there, and cancel. */ -function presentOperation(operation: Operation, notes: ConnectorAccountNote[], text: Text): ConnectorAccountDisplay { +function presentOperation(operation: Operation, text: Text): ConnectorAccountDisplay { const authorizing = step(operation) === 'step.authorizing' && operation.authorizationUrl !== undefined const buttons: ConnectorAccountButton[] = [] if (authorizing) buttons.push({ label: text('action.open'), command: { kind: 'open' }, variant: 'primary' }) - if (operation.cancellable) buttons.push({ label: text('action.cancel'), command: { kind: 'cancel' }, variant: 'ghost' }) + if (operation.cancellable) buttons.push(cancelButton(text)) return { - phase: 'connecting', status: text(step(operation)), badge: text('badge.connecting'), buttons, notes, + phase: 'connecting', status: text(step(operation)), badge: text('badge.connecting'), buttons, notes: [], ...authorizing ? { detail: text('detail.authorizing') } : {}, } } +/* jscpd:ignore-end */ /** * The account section for one Host view. * @param view - the default tmeet account, the operation in progress, and the last result. * @param text - writes a key of the Tencent Meeting text in every shipped language. - * @returns the phase, status, tag, buttons, detail, guide download row, and failure guidance. + * @returns the phase, status, tag, buttons, detail, and failure guidance. */ export function presentAccount(view: TencentMeetingState, text: Text): ConnectorAccountDisplay { - const notes = skillsNotes(view.account.skills, text) const { account, operation } = view - if (operation?.kind === 'check') return { phase: 'checking', status: text('status.checking'), buttons: [], notes } - if (operation !== undefined) return presentOperation(operation, notes, text) + /* jscpd:ignore-start -- CLI app plugins that sign in and out show the same running check and account states, each with its own text. */ + if (operation?.kind === 'check') { + return { + phase: 'checking', status: text(operation.phase === 'downloading' ? 'step.downloading' : 'status.checking'), + buttons: operation.cancellable ? [cancelButton(text)] : [], notes: [], + } + } + if (operation !== undefined) return presentOperation(operation, text) const failed = view.result?.outcome === 'failed' // The Service adds the failed command and its exit code. const failure: { failure?: ConnectorAccountFailure } = failed ? { failure: { text: text('failed') } } : {} - const unavailable: ConnectorAccountDisplay = { + const unavailable = (missing: boolean): ConnectorAccountDisplay => ({ phase: 'unavailable', status: text('status.unavailable'), badge: text('badge.unavailable'), - buttons: [{ label: text('action.retry'), command: CHECK }], detail: text('detail.unavailable'), notes, ...failure, - } + buttons: [{ label: text('action.retry'), command: CHECK }], detail: text(missing ? 'detail.missing' : 'detail.unavailable'), notes: [], ...failure, + }) switch (account.state) { - case 'unchecked': return failed ? unavailable : { phase: 'checking', status: text('status.checking'), buttons: [], notes } - case 'unverified': return unavailable + case 'unchecked': return failed ? unavailable(false) : { phase: 'checking', status: text('status.checking'), buttons: [], notes: [] } + case 'not-installed': return unavailable(true) + case 'unverified': return unavailable(false) case 'signed-out': return { phase: 'disconnected', status: text('status.disconnected'), badge: text('badge.disconnected'), buttons: [{ label: text('action.connect'), command: SIGN_IN, variant: 'primary' }], connect: SIGN_IN, - detail: text('detail.disconnected'), notes, ...failure, + detail: text('detail.disconnected'), notes: [], ...failure, } - /* jscpd:ignore-start -- CLI app plugins that sign out offer the same confirmed sign-out button. */ case 'connected': return { phase: 'connected', status: text('status.connected'), badge: text('badge.connected'), @@ -113,7 +109,7 @@ export function presentAccount(view: TencentMeetingState, text: Text): Connector label: text('action.signOut'), command: SIGN_OUT, confirm: { title: text('signOut.title'), body: text('signOut.body'), label: text('action.signOut') }, }], - detail: text('detail.connected', { name: account.userName }), notes, ...failure, + detail: text('detail.connected', { name: account.userName }), notes: [], ...failure, } /* jscpd:ignore-end */ /* v8 ignore next -- closed account state union */ diff --git a/packages/connector/tencent-meeting/src/types.ts b/packages/connector/tencent-meeting/src/types.ts index 1cd5b58000..649cf54228 100644 --- a/packages/connector/tencent-meeting/src/types.ts +++ b/packages/connector/tencent-meeting/src/types.ts @@ -1,24 +1,20 @@ /** Credential-free Tencent Meeting account and operation views the Plugins page presenter reads. */ import type { CliAccountView } from '@deepseek-ai/dsh-cli-account/types' -import type { UpstreamSkillsState } from '@deepseek-ai/dsh-upstream-skills/types' -/** The default tmeet account as the latest `auth status` observed it. */ -export type TencentMeetingSignIn = - | { readonly state: 'unchecked' | 'signed-out' | 'unverified' } +/** + * The default tmeet account as the latest `auth status` observed it. `not-installed` means the upstream guide was + * missing and the download that check waited for did not finish. + */ +export type TencentMeetingAccountState = + | { readonly state: 'unchecked' | 'not-installed' | 'signed-out' | 'unverified' } | { readonly state: 'connected'; readonly userName: string } -/** The default tmeet account and where the upstream guide stands. */ -export type TencentMeetingAccountState = TencentMeetingSignIn & { - /** Whether the guide the `tencent-meeting` skill indexes is in place, downloading, or unavailable until a check retries it. */ - readonly skills: UpstreamSkillsState -} - /** The account operations the Plugins page starts. */ export type TencentMeetingOperationKind = 'check' | 'sign-in' | 'sign-out' /** Tencent Meeting steps of an operation, besides the Service's `checking` and `cancelling`. */ -export type TencentMeetingPhase = 'authorizing' | 'signing-out' +export type TencentMeetingPhase = 'downloading' | 'authorizing' | 'signing-out' /** The tmeet commands an operation runs; a failed operation reports its last one with that command's exit code. */ export type TencentMeetingCommand = 'auth-status' | 'auth-login' | 'auth-logout' diff --git a/packages/connector/tencent-meeting/tests/account.spec.ts b/packages/connector/tencent-meeting/tests/account.spec.ts index e66c9d0332..e33cc3185b 100644 --- a/packages/connector/tencent-meeting/tests/account.spec.ts +++ b/packages/connector/tencent-meeting/tests/account.spec.ts @@ -1,5 +1,8 @@ -/** Account operations over a scripted tmeet: status text, sign-in, sign-out, cancellation, and the Plugins page wiring. */ -import { mkdtemp, rm } from 'node:fs/promises' +/** + * Account operations over a scripted tmeet: status text, the guide's download a check waits for, sign-in, sign-out, + * cancellation, and the Plugins page wiring. + */ +import { mkdir, mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import type { Context } from '@deepseek-ai/cordis' @@ -7,6 +10,7 @@ import type { ConnectorOperationId } from '@deepseek-ai/dsh-client-ui-connector- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { executableFileName } from '../src/directory.ts' import * as TencentMeeting from '../src/index.ts' +import { TMEET_SKILLS } from '../src/skills.ts' import type { TencentMeetingOperationKind, TencentMeetingState } from '../src/types.ts' import { createHost, type CliReply, type ScriptedProcess, type ScriptedSubprocess, type TencentMeetingPage } from './harness.ts' @@ -83,11 +87,11 @@ describe('Tencent Meeting account operations', () => { beforeEach(() => load()) it.each<[string, CliReply, TencentMeetingState['account']]>([ - ['a sign-in the server accepts', CONNECTED, { state: 'connected', userName: '测试 用户', skills: 'installed' }], - ['no sign-in', NOT_LOGGED_IN, { state: 'signed-out', skills: 'installed' }], - ['a sign-in the CLI cleared after a failed refresh', SESSION_EXPIRED, { state: 'signed-out', skills: 'installed' }], - ['a sign-in whose refresh token expired', REFRESH_EXPIRED, { state: 'signed-out', skills: 'installed' }], - ['a stored sign-in the server did not confirm', UNVERIFIED, { state: 'unverified', skills: 'installed' }], + ['a sign-in the server accepts', CONNECTED, { state: 'connected', userName: '测试 用户' }], + ['no sign-in', NOT_LOGGED_IN, { state: 'signed-out' }], + ['a sign-in the CLI cleared after a failed refresh', SESSION_EXPIRED, { state: 'signed-out' }], + ['a sign-in whose refresh token expired', REFRESH_EXPIRED, { state: 'signed-out' }], + ['a stored sign-in the server did not confirm', UNVERIFIED, { state: 'unverified' }], ])('checks %s', async (_name, reply, expected) => { script[STATUS] = [reply] const id = start('check') @@ -102,7 +106,7 @@ describe('Tencent Meeting account operations', () => { script[STATUS] = [reply] const result = await settled(start('check')) expect(result).toEqual({ - account: { state: 'unchecked', skills: 'installed' }, + account: { state: 'unchecked' }, result: { id: result.result?.id, kind: 'check', outcome: 'failed', failure: { command: 'auth-status', exitCode: reply.exitCode ?? 0 } }, }) expect(errors()).toEqual([['tencent-meeting: account operation failed: %o', { @@ -125,9 +129,7 @@ describe('Tencent Meeting account operations', () => { await vi.waitFor(() => { expect(account.snapshot().operation).toMatchObject({ phase: 'authorizing', authorizationUrl: LOGIN_LINK }) }) authorizing.reply({ stdout: 'Login successful. Start managing your meetings using tmeet.\n' }) - expect(await settled(id)).toEqual({ - account: { state: 'connected', userName: '测试 用户', skills: 'installed' }, result: { id, kind: 'sign-in', outcome: 'succeeded' }, - }) + expect(await settled(id)).toEqual({ account: { state: 'connected', userName: '测试 用户' }, result: { id, kind: 'sign-in', outcome: 'succeeded' } }) expect(commands()).toEqual([LOGIN, STATUS]) expect(errors()).toEqual([]) }) @@ -152,7 +154,7 @@ describe('Tencent Meeting account operations', () => { const cancelling = account.cancel(id) expect(account.snapshot().operation).toEqual({ id, kind: 'sign-in', phase: 'cancelling', cancellable: false }) await cancelling - expect(account.snapshot()).toEqual({ account: { state: 'unchecked', skills: 'installed' }, result: { id, kind: 'sign-in', outcome: 'cancelled' } }) + expect(account.snapshot()).toEqual({ account: { state: 'unchecked' }, result: { id, kind: 'sign-in', outcome: 'cancelled' } }) expect(subprocess.processes[0]?.terminated).toBe(true) expect(errors()).toEqual([]) }) @@ -167,7 +169,7 @@ describe('Tencent Meeting account operations', () => { await account.cancel(id) signingOut.reply({ stdout: 'Logout success, welcome to use it again.\n' }) - expect(await settled(id)).toEqual({ account: { state: 'signed-out', skills: 'installed' }, result: { id, kind: 'sign-out', outcome: 'succeeded' } }) + expect(await settled(id)).toEqual({ account: { state: 'signed-out' }, result: { id, kind: 'sign-out', outcome: 'succeeded' } }) expect(commands()).toEqual([LOGOUT, STATUS]) }) @@ -179,41 +181,70 @@ describe('Tencent Meeting account operations', () => { }) }) -describe('Tencent Meeting guide the plugin downloads', () => { +describe('Tencent Meeting guide a check waits for', () => { let home: string /** Answers each request for the guide's archive. */ - let archive: () => Promise + let archive: (signal: AbortSignal) => Promise + + /** A request that stays unanswered until its download is stopped. */ + const unanswered = (signal: AbortSignal): Promise => new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => { reject(signal.reason as Error) }, { once: true }) + }) + /** Where the upstream skills Service publishes the guide without a profile. */ + const published = (): string => join(home, 'cache', 'tencent-meeting', `skills-${TMEET_SKILLS.sha256.slice(0, 16)}`) beforeEach(async () => { home = await mkdtemp(join(tmpdir(), 'dsh-tencent-meeting-home-')) vi.stubEnv('DSH_HOME', home) - vi.stubGlobal('fetch', () => archive()) + vi.stubGlobal('fetch', (_url: string, init: { signal: AbortSignal }) => archive(init.signal)) }) afterEach(() => rm(home, { recursive: true, force: true })) - it('restarts a failed download of the guide on each check without waiting for it, and reports the state it leaves', async () => { + it('reports a guide whose download did not finish as not installed, without running a command', async () => { archive = () => Promise.reject(new Error('offline')) await load({}) - await vi.waitFor(() => { expect(account.snapshot().account.skills).toBe('failed') }) + expect(account.snapshot()).toEqual({ account: { state: 'unchecked' } }) - archive = () => new Promise(() => {}) - script[STATUS] = [NOT_LOGGED_IN] const id = start('check') - expect(account.snapshot().account).toEqual({ state: 'unchecked', skills: 'downloading' }) - expect(await settled(id)).toEqual({ account: { state: 'signed-out', skills: 'downloading' }, result: { id, kind: 'check', outcome: 'succeeded' } }) + expect(account.snapshot().operation).toEqual({ id, kind: 'check', phase: 'downloading', cancellable: true }) + expect(await settled(id)).toEqual({ account: { state: 'not-installed' }, result: { id, kind: 'check', outcome: 'failed' } }) + expect(errors()).toEqual([['tencent-meeting: account operation failed: %o', { id, kind: 'check', phase: 'downloading' }]]) + expect(commands()).toEqual([]) }) - it('reports a new state of the guide with the current account', async () => { - const download = Promise.withResolvers() - archive = () => download.promise + it('downloads the guide again on the next check, in a step of its own before the status command', async () => { + archive = () => Promise.reject(new Error('offline')) await load({}) + await settled(start('check')) + + const request = Promise.withResolvers() + archive = () => request.promise script[STATUS] = [NOT_LOGGED_IN] - expect((await settled(start('check'))).account).toEqual({ state: 'signed-out', skills: 'downloading' }) + const id = start('check') + expect(account.snapshot().operation).toEqual({ id, kind: 'check', phase: 'downloading', cancellable: true }) + expect(commands()).toEqual([]) + // No fixture archive matches the pinned digest, so the guide arrives the way another process publishes it. + await mkdir(published(), { recursive: true }) + request.reject(new Error('offline')) - download.reject(new Error('offline')) + expect(await settled(id)).toEqual({ account: { state: 'signed-out' }, result: { id, kind: 'check', outcome: 'succeeded' } }) + expect(commands()).toEqual([STATUS]) + }) - await vi.waitFor(() => { expect(account.snapshot().account).toEqual({ state: 'signed-out', skills: 'failed' }) }) + it('cancels a download of the guide, which leaves it not installed and runs no command', async () => { + archive = unanswered + await load({}) + const id = start('check') + expect(account.snapshot().operation).toEqual({ id, kind: 'check', phase: 'downloading', cancellable: true }) + + const cancelling = account.cancel(id) + expect(account.snapshot().operation).toEqual({ id, kind: 'check', phase: 'cancelling', cancellable: false }) + await cancelling + + expect(account.snapshot()).toEqual({ account: { state: 'not-installed' }, result: { id, kind: 'check', outcome: 'cancelled' } }) + expect(commands()).toEqual([]) + expect(errors()).toEqual([]) }) }) @@ -226,9 +257,9 @@ describe('Tencent Meeting on the Plugins page', () => { script[STATUS] = [NOT_LOGGED_IN] account.refresh() const check = account.snapshot().operation - expect(account.snapshot()).toMatchObject({ account: { state: 'unchecked', skills: 'installed' }, operation: { kind: 'check' } }) + expect(account.snapshot()).toMatchObject({ account: { state: 'unchecked' }, operation: { kind: 'check' } }) expect(await finished(check!.id)).toMatchObject({ kind: 'check', outcome: 'succeeded' }) - expect(account.snapshot().account).toEqual({ state: 'signed-out', skills: 'installed' }) + expect(account.snapshot().account).toEqual({ state: 'signed-out' }) expect(subprocess.lookups[0]?.command).toBe(join(binDir, executableFileName(process.platform))) expect(await finished(start('check'))).toMatchObject({ kind: 'check', outcome: 'succeeded' }) diff --git a/packages/connector/tencent-meeting/tests/plugin.spec.ts b/packages/connector/tencent-meeting/tests/plugin.spec.ts index 63f4579922..e705995231 100644 --- a/packages/connector/tencent-meeting/tests/plugin.spec.ts +++ b/packages/connector/tencent-meeting/tests/plugin.spec.ts @@ -54,15 +54,17 @@ describe('Tencent Meeting plugin', () => { expect(await ctx.skills.get('tmeet-skill')).toBeUndefined() }) - it('reports the guide as downloading and then failed when no skills URL answers, and lists no skill', async () => { + it('gives no CLI path and lists no skill while the guide is missing, as when no skills URL answers', async () => { const home = await mkdtemp(join(tmpdir(), 'dsh-tencent-meeting-home-')) vi.stubEnv('DSH_HOME', home) try { await start({ skillsUrls: ['https://127.0.0.1:9'], skillsTimeoutMs: 5_000 }) await ctx.plugin(TencentMeeting, { binDir }) - const account = host.pages[0]!.source - expect(account.snapshot().account.skills).toBe('downloading') - await vi.waitFor(() => { expect(account.snapshot().account.skills).toBe('failed') }, { timeout: 10_000 }) + expect(await runtimeContext()).toEqual([]) + const warnings = (): unknown[] => ctx.logger.buffer.filter(message => message.type === 'warn').map((message): unknown => message.args[0]) + await vi.waitFor(() => { expect(warnings()).toContain('tencent-meeting: the upstream skills are not available') }, { timeout: 10_000 }) + expect(host.pages[0]!.source.snapshot()).toEqual({ account: { state: 'unchecked' } }) + expect(await runtimeContext()).toEqual([]) expect(await ctx.skills.list()).toEqual([]) } finally { await rm(home, { recursive: true, force: true }) @@ -91,7 +93,7 @@ describe('Tencent Meeting plugin', () => { const fiber = await ctx.plugin(TencentMeeting, { binDir, skillsDir }) expect(host.pages).toHaveLength(1) expect(host.pages[0]).toMatchObject({ key: TENCENT_MEETING_PACKAGE, packageName: TENCENT_MEETING_PACKAGE }) - expect(host.pages[0]!.source.snapshot().account).toEqual({ state: 'unchecked', skills: 'installed' }) + expect(host.pages[0]!.source.snapshot().account).toEqual({ state: 'unchecked' }) await fiber.dispose() diff --git a/packages/connector/tencent-meeting/tests/presentation.spec.ts b/packages/connector/tencent-meeting/tests/presentation.spec.ts index 6daab5ea6b..2955459c2d 100644 --- a/packages/connector/tencent-meeting/tests/presentation.spec.ts +++ b/packages/connector/tencent-meeting/tests/presentation.spec.ts @@ -1,4 +1,4 @@ -/** The Tencent Meeting section offers each state's next step, the guide download row, and failure guidance, in every shipped language. */ +/** The Tencent Meeting section offers each state's next step, the guide download step, and failure guidance, in every shipped language. */ import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' import type { ConnectorAccountDisplay, ConnectorOperationId } from '@deepseek-ai/dsh-client-ui-connector-account/types' import { rm } from 'node:fs/promises' @@ -37,8 +37,8 @@ afterAll(async () => { const presentAccount = (view: TencentMeetingState): ConnectorAccountDisplay => page.present(view) -const SIGNED_OUT: TencentMeetingState = { account: { state: 'signed-out', skills: 'installed' } } -const CONNECTED: TencentMeetingState = { account: { state: 'connected', userName: '测试用户', skills: 'installed' } } +const SIGNED_OUT: TencentMeetingState = { account: { state: 'signed-out' } } +const CONNECTED: TencentMeetingState = { account: { state: 'connected', userName: '测试用户' } } it('offers the next step while signing in', () => { let shown = presentAccount(SIGNED_OUT) @@ -60,7 +60,7 @@ it('offers the next step while signing in', () => { for (const view of [ { ...SIGNED_OUT, operation: { id: OP, kind: 'check', phase: 'checking', cancellable: false } }, - { account: { state: 'unchecked', skills: 'installed' } }, + { account: { state: 'unchecked' } }, ] as const satisfies readonly TencentMeetingState[]) { shown = presentAccount(view) expect(shown).toMatchObject({ phase: 'checking', status: say('status.checking'), buttons: [] }) @@ -94,8 +94,8 @@ it('reports a failed sign-in with its diagnostic items, and no failure for a can it('retries an unconfirmed or unreadable sign-in by checking again', () => { for (const view of [ - { account: { state: 'unverified', skills: 'installed' } }, - { account: { state: 'unchecked', skills: 'installed' }, result: { id: OP, kind: 'check', outcome: 'failed', failure: { command: 'auth-status', exitCode: 2 } } }, + { account: { state: 'unverified' } }, + { account: { state: 'unchecked' }, result: { id: OP, kind: 'check', outcome: 'failed', failure: { command: 'auth-status', exitCode: 2 } } }, ] as const satisfies readonly TencentMeetingState[]) { const shown = presentAccount(view) expect(shown).toMatchObject({ phase: 'unavailable', status: say('status.unavailable'), badge: say('badge.unavailable'), detail: say('detail.unavailable') }) @@ -103,10 +103,16 @@ it('retries an unconfirmed or unreadable sign-in by checking again', () => { } }) -it('reports a guide that is downloading, and retries a failed download by checking again', () => { - expect(presentAccount({ account: { state: 'signed-out', skills: 'downloading' } }).notes).toMatchObject([{ text: say('skills.downloading') }]) - const [note] = presentAccount({ account: { state: 'signed-out', skills: 'failed' } }).notes - expect(note).toMatchObject({ text: say('skills.failed'), button: { label: say('action.retry'), command: CHECK } }) +it('shows the guide\'s download with its cancel, and retries one that did not finish by checking again', () => { + let shown = presentAccount({ account: { state: 'unchecked' }, operation: { id: OP, kind: 'check', phase: 'downloading', cancellable: true } }) + expect(shown).toMatchObject({ phase: 'checking', status: say('step.downloading'), notes: [] }) + expect(shown.buttons).toMatchObject([{ label: say('action.cancel'), command: { kind: 'cancel' }, variant: 'ghost' }]) + + shown = presentAccount({ account: { state: 'not-installed' }, result: { id: OP, kind: 'check', outcome: 'failed' } }) + expect(shown).toMatchObject({ phase: 'unavailable', status: say('status.unavailable'), badge: say('badge.unavailable'), detail: say('detail.missing') }) + expect(shown.buttons).toMatchObject([{ label: say('action.retry'), command: CHECK }]) + expect(shown.failure).toMatchObject({ text: say('failed') }) + expect(presentAccount({ account: { state: 'not-installed' }, result: { id: OP, kind: 'check', outcome: 'cancelled' } }).failure).toBeUndefined() }) it('names the section, its activation prompt, and the notices of signing in and out', () => { diff --git a/packages/connector/upstream-skills/README.i18n.yaml b/packages/connector/upstream-skills/README.i18n.yaml index 3889c9128b..7f11410162 100644 --- a/packages/connector/upstream-skills/README.i18n.yaml +++ b/packages/connector/upstream-skills/README.i18n.yaml @@ -24,8 +24,8 @@ en: 2ac0be96902c0c7c zh: a6412287a1ac4487 /deepseek-ai-dsh-upstream-skills/use-this-package/register-an-entry-skill: - en: 61da62916206ff64 - zh: 0aff27fbd61238ae + en: 8ba04e0ca076a81e + zh: 969b585ff95d302b /deepseek-ai-dsh-upstream-skills/use-this-package/kept-files-and-verification: en: 0633b5470e6b4e6c zh: 419916b5b305aa7d @@ -36,8 +36,8 @@ en: ea5587081cc3b471 zh: e0993a154ae79dc1 /deepseek-ai-dsh-upstream-skills/understand-the-implementation: - en: 620b702a4b6c162c - zh: 209f776f7c49ddd0 + en: 537457cf313ad305 + zh: 758f4b2ad9dd219c /deepseek-ai-dsh-upstream-skills/further-exploration: en: 95c015940a49bef1 zh: d1d3c6162cd4fa68 @@ -48,8 +48,8 @@ en: 2a09699bc1130758 zh: 972fc624936c8c2f /deepseek-ai-dsh-upstream-skills/known-limitations-and-deferred-work: - en: 25e90bc332e990a7 - zh: 3a4a3face42b5c13 + en: ccfee027aaa0129c + zh: 86cb268d538447c5 /deepseek-ai-dsh-upstream-skills/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/connector/upstream-skills/README.md b/packages/connector/upstream-skills/README.md index 24740cd9af..bfc1e25b4a 100644 --- a/packages/connector/upstream-skills/README.md +++ b/packages/connector/upstream-skills/README.md @@ -77,18 +77,18 @@ export function apply(ctx: Context, config: Config): void { set: VENDOR_SKILLS, skillsDir: config.skillsDir, }) - skills.watch((state) => { ctx.logger.info(`vendor: upstream skills ${state}`) }) + if (!skills.installed()) ctx.logger.info('vendor: downloading the upstream skills') } ``` -`register` reads the entry's name and description from its YAML frontmatter, registers a skill provider under `name`, and starts the download unless the files are already in place. The registration belongs to the plugin whose `ctx` made the call: unloading that plugin aborts the download, removes the provider, and ends the notifications. A second registration under one `name` throws and leaves the first in place. +`register` reads the entry's name and description from its YAML frontmatter, registers a skill provider under `name`, and starts the download unless the files are already in place. The registration belongs to the plugin whose `ctx` made the call: unloading that plugin aborts the download and removes the provider. A second registration under one `name` throws and leaves the first in place. - `name` is the skill provider's name, the prefix of the plugin's errors and log records, and the directory under `$DSH_HOME/cache` that receives the download. - `entry` is the absolute path of the packaged entry `SKILL.md`, whose body refers to the upstream files by their repository paths, such as `skills//SKILL.md`. - `set` is the pin that `scripts/upstream-skills-digest.ts` prints. -- `skillsDir` is the plugin's own optional config field: a directory that already holds the kept files at their repository paths. When it is set, nothing is downloaded, and a path that is not a directory makes `register` throw. +- `skillsDir` is the plugin's own optional config field: a directory that already holds the kept files at their repository paths. When it is set, nothing is downloaded: a path that is not a directory makes `register` throw, and a directory removed later makes `install` reject. -The returned handle serves the plugin's account view and check. `directory` is `skillsDir`; otherwise it is `$DSH_HOME/cache///skills-` in a profile and `$DSH_HOME/cache//skills-` without one. `state` is `downloading` while a download runs, otherwise `installed` when that directory exists and `failed` when it does not. `watch(listener)` reports each start and end of a download, and `retry()` starts another download after a failure and returns at once. A plugin shows the state beside its account and calls `retry()` from its check without waiting, so a slow download never holds its account operations. A failed download is logged as a warning. `dispose()` withdraws the registration before the plugin unloads. The contracts in [`src/index.ts`](src/index.ts) and [`src/types.ts`](src/types.ts) are authoritative. +The returned handle serves the plugin's account check. `directory` is `skillsDir`; otherwise it is `$DSH_HOME/cache///skills-` in a profile and `$DSH_HOME/cache//skills-` without one. `installed()` tells whether that directory exists. `install(signal)` returns at once when it does; otherwise it waits for the running download, or starts one when none runs, and rejects when that download fails. Aborting `signal` stops the download, also for every other caller that waits for it. A plugin registered with `ctx.cliAccounts` passes the two as its [`prepare` step](../cli-account/README.md#prepare-before-a-check), `ready: () => skills.installed()` and `run: signal => skills.install(signal)`: its account check then waits for the files, the model gets the CLI's path only once they are in place, and the Plugins page's retry downloads them again. A failed download is logged as a warning. `dispose()` withdraws the registration before the plugin unloads. The contracts in [`src/index.ts`](src/index.ts) and [`src/types.ts`](src/types.ts) are authoritative. ### Kept files and verification @@ -110,7 +110,7 @@ Each profile that `dsh` launches has a directory of its own for a plugin's files
Implementation internals — click to expand -`register` runs in the calling plugin's context, so the skill provider is an effect of that plugin and is removed with it. The provider lists the entry only while the handle's `directory` exists, with source `bundled` at the bundled rank, so a project or user skill of the same name wins. It returns a complete, empty list before publishing, because an incomplete observation would make the whole skill catalog incomplete; publishing invalidates the catalog instead, as does a failed download that finds a directory another process published. One download runs at a time, and the provider registration's signal aborts it when the plugin unloads. Kept files are held in memory, bounded by `bytes`, until they match the digest, so no unverified file reaches the disk; files outside the selection are read and dropped, so `skillsTimeoutMs` bounds the time spent on them. +`register` runs in the calling plugin's context, so the skill provider is an effect of that plugin and is removed with it. The provider lists the entry only while the handle's `directory` exists, with source `bundled` at the bundled rank, so a project or user skill of the same name wins. It returns a complete, empty list before publishing, because an incomplete observation would make the whole skill catalog incomplete; publishing invalidates the catalog instead, as does a failed download that finds a directory another process published. One download runs at a time: every `install` call made while it runs waits for it, the abort of any such caller's signal stops it, and the provider registration's signal aborts it when the plugin unloads. Kept files are held in memory, bounded by `bytes`, until they match the digest, so no unverified file reaches the disk; files outside the selection are read and dropped, so `skillsTimeoutMs` bounds the time spent on them. | File | Role | |---|---| @@ -146,7 +146,7 @@ A load that finds the files in place lists the entry in the session's first cata -- The first load after a new pin needs GitHub or a configured mirror; until a download succeeds, the entry skill is not listed and the plugin shows the `failed` state. +- The first load after a new pin needs GitHub or a configured mirror; until a download succeeds, the entry skill is not listed, and a plugin whose account check waits for the files reports the failed download instead of the account. - Each profile that loads a plugin downloads its own copy of the pin. - Processes of one profile can run different versions of a plugin at the same time, such as one started before a plugin update and one started after it. The later one deletes the pin the earlier one reads: the earlier process lists no entry skill, and its agents cannot open the guides, until its next check has downloaded the pin again. Both pins then stay until a process of the profile loads the plugin again. - Removing a plugin leaves its pin in the cache. A process that exits while it writes a download leaves its `.skills--` staging directory there too. Nothing deletes either. diff --git a/packages/connector/upstream-skills/README.zh.md b/packages/connector/upstream-skills/README.zh.md index ab508ee612..0e66eb1949 100644 --- a/packages/connector/upstream-skills/README.zh.md +++ b/packages/connector/upstream-skills/README.zh.md @@ -77,18 +77,18 @@ export function apply(ctx: Context, config: Config): void { set: VENDOR_SKILLS, skillsDir: config.skillsDir, }) - skills.watch((state) => { ctx.logger.info(`vendor: upstream skills ${state}`) }) + if (!skills.installed()) ctx.logger.info('vendor: downloading the upstream skills') } ``` -`register` 从入口的 YAML frontmatter 读取名称和描述,以 `name` 注册一个技能提供方,文件不在位时开始下载。注册属于用其 `ctx` 发起调用的插件:该插件卸载时,下载被中止,提供方被移除,通知停止。以同一个 `name` 再次注册会抛出异常,第一次注册保持不变。 +`register` 从入口的 YAML frontmatter 读取名称和描述,以 `name` 注册一个技能提供方,文件不在位时开始下载。注册属于用其 `ctx` 发起调用的插件:该插件卸载时,下载被中止,提供方被移除。以同一个 `name` 再次注册会抛出异常,第一次注册保持不变。 - `name` 是技能提供方的名称、插件的错误和日志记录的前缀,也是 `$DSH_HOME/cache` 下接收下载内容的目录。 - `entry` 是随包发布的入口 `SKILL.md` 的绝对路径,其正文按仓库路径引用上游文件,例如 `skills/<子指南>/SKILL.md`。 - `set` 是 `scripts/upstream-skills-digest.ts` 输出的固定信息。 -- `skillsDir` 是插件自己的可选配置字段:一个已按仓库路径存放保留文件的目录。设置后不下载,路径不是目录时 `register` 抛出异常。 +- `skillsDir` 是插件自己的可选配置字段:一个已按仓库路径存放保留文件的目录。设置后不下载:路径不是目录时 `register` 抛出异常,目录之后被移除时 `install` 以异常结束。 -返回的句柄供插件的账号视图和检查使用。`directory` 是 `skillsDir`;没有设置时,在 profile 中是 `$DSH_HOME/cache///skills-<摘要前 16 位>`,没有 profile 时是 `$DSH_HOME/cache//skills-<摘要前 16 位>`。下载进行中时 `state` 为 `downloading`,否则这个目录存在时为 `installed`,不存在时为 `failed`。`watch(listener)` 报告每次下载的开始和结束;`retry()` 在失败后开始新的下载,并立即返回。插件在账号旁显示这个状态,并在检查中调用 `retry()` 而不等待,因此下载再慢也不会占住账号操作。下载失败会记为警告。`dispose()` 在插件卸载之前撤回注册。以 [`src/index.ts`](src/index.ts) 和 [`src/types.ts`](src/types.ts) 中的约定为准。 +返回的句柄供插件的账号检查使用。`directory` 是 `skillsDir`;没有设置时,在 profile 中是 `$DSH_HOME/cache///skills-<摘要前 16 位>`,没有 profile 时是 `$DSH_HOME/cache//skills-<摘要前 16 位>`。`installed()` 返回这个目录是否存在。目录存在时 `install(signal)` 立即返回;否则它等待进行中的下载,没有下载在进行时开始一次,下载失败时以异常结束。中止 `signal` 会停止这次下载,其他等待它的调用方也随之结束。通过 `ctx.cliAccounts` 注册的插件把这两个方法作为它的 [`prepare` 步骤](../cli-account/README.zh.md#prepare-before-a-check)传入,即 `ready: () => skills.installed()` 和 `run: signal => skills.install(signal)`:它的账号检查于是等文件就位,模型只在文件就位后得到 CLI 的路径,插件页的重试会重新下载。下载失败会记为警告。`dispose()` 在插件卸载之前撤回注册。以 [`src/index.ts`](src/index.ts) 和 [`src/types.ts`](src/types.ts) 中的约定为准。 ### 保留的文件与校验 @@ -110,7 +110,7 @@ Service 按顺序从每个 `skillsUrls` 前缀下载 `<前缀>// 实现内部细节——点击展开 -`register` 在调用方插件的 context 中运行,因此技能提供方是该插件的 effect,随它一起移除。提供方只在句柄的 `directory` 存在时列出入口技能,来源为 `bundled`、使用内置技能的优先级,因此同名的项目或用户技能优先。发布前它返回完整的空列表,因为不完整的结果会让整个技能目录变成不完整;发布后改为使目录失效;下载失败但发现另一个进程已发布目录时也使目录失效。同一时间只运行一次下载,卸载插件时,提供方注册的信号会中止它。保留文件在与摘要一致之前只存在内存中,总量受 `bytes` 限制,因此未经校验的文件不会写入磁盘;选择范围之外的文件读取后即丢弃,花在它们上面的时间受 `skillsTimeoutMs` 限制。 +`register` 在调用方插件的 context 中运行,因此技能提供方是该插件的 effect,随它一起移除。提供方只在句柄的 `directory` 存在时列出入口技能,来源为 `bundled`、使用内置技能的优先级,因此同名的项目或用户技能优先。发布前它返回完整的空列表,因为不完整的结果会让整个技能目录变成不完整;发布后改为使目录失效;下载失败但发现另一个进程已发布目录时也使目录失效。同一时间只运行一次下载:下载进行中的每次 `install` 调用都等待它,其中任一调用方的 signal 中止都会停止它,卸载插件时,提供方注册的信号也会中止它。保留文件在与摘要一致之前只存在内存中,总量受 `bytes` 限制,因此未经校验的文件不会写入磁盘;选择范围之外的文件读取后即丢弃,花在它们上面的时间受 `skillsTimeoutMs` 限制。 | 文件 | 职责 | |---|---| @@ -146,7 +146,7 @@ Service 按顺序从每个 `skillsUrls` 前缀下载 `<前缀>// -- 换用新的固定提交后,首次加载需要能访问 GitHub 或配置的镜像;下载成功之前,入口技能不会列出,插件显示 `failed` 状态。 +- 换用新的固定提交后,首次加载需要能访问 GitHub 或配置的镜像;下载成功之前,入口技能不会列出,账号检查等待这些文件的插件报告下载失败,而不是账号。 - 每个加载该插件的 profile 都各自下载一份固定提交。 - 同一个 profile 的多个进程可以同时运行同一插件的不同版本,例如一个在插件更新之前启动,另一个在更新之后启动。后启动的进程会删除先启动的进程正在读取的固定提交:先启动的进程不再列出入口技能,其中的 Agent 也打不开子指南,直到它下一次检查重新下载完成。此后两个固定提交都保留,直到这个 profile 的某个进程再次加载该插件。 - 移除插件后,它的固定提交仍留在缓存中。进程在写入下载内容时退出,也会在那里留下它的暂存目录 `.skills-<摘要>-`。两者都不会被删除。 diff --git a/packages/connector/upstream-skills/src/index.ts b/packages/connector/upstream-skills/src/index.ts index d4deab4914..8b88d45d17 100644 --- a/packages/connector/upstream-skills/src/index.ts +++ b/packages/connector/upstream-skills/src/index.ts @@ -20,7 +20,7 @@ import type { SkillCandidate, SkillDefinition, SkillProvider, SkillProviderContr import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { parse as parseYaml } from 'yaml' import { downloadSkillSet, writeFiles } from './archive.ts' -import type { UpstreamSkillsHandle, UpstreamSkillsRegistration, UpstreamSkillsState } from './types.ts' +import type { UpstreamSkillsHandle, UpstreamSkillsRegistration } from './types.ts' export type * from './types.ts' @@ -64,11 +64,12 @@ export default class UpstreamSkills extends Service { /** * Register the calling plugin's entry skill and start downloading the upstream files unless they are in place. The * download starts at load so that a session without a client also gets the skill; a failure is logged as a warning - * and waits for `retry()`. In a profile, the files go to that profile's own directory for the plugin, and the - * registration deletes the other pins there once, the first time its own pin is in place. The registration belongs - * to the calling plugin: unloading that plugin aborts the download and removes the entry skill. + * and the files stay missing until a call of `install()` downloads them. In a profile, the files go to that + * profile's own directory for the plugin, and the registration deletes the other pins there once, the first time its + * own pin is in place. The registration belongs to the calling plugin: unloading that plugin aborts the download and + * removes the entry skill. * @param registration - the plugin's provider name, entry, pinned files, and optional skills directory. - * @returns the handle the plugin's view observes and its check retries. + * @returns the handle the plugin reads the files' presence from and waits for the download through. * @throws when the entry has no skill name or description in its frontmatter, `skillsDir` is not a directory, or a * skill provider named `name` is already registered. */ @@ -79,13 +80,12 @@ export default class UpstreamSkills extends Service { provider = new UpstreamSkillProvider(registration, this.config, control, caller.logger, caller.get('profileContext')) return provider }) - provider.retry() + provider.start() provider.prune() return { directory: provider.directory, - get state() { return provider.state }, - watch: listener => provider.watch(listener), - retry: () => { provider.retry() }, + installed: () => provider.installed(), + install: signal => provider.install(signal), dispose: withdraw, } } @@ -94,6 +94,13 @@ export default class UpstreamSkills extends Service { /** The prefix of the directory name a pin is published under; the first 16 digits of its digest follow. */ const PIN_PREFIX = 'skills-' +/** One download of the upstream files: the controller that stops it, and its end. */ +interface Download { + readonly controller: AbortController + /** Resolves once the files are in place; rejects with what stopped or failed the download while they are not. */ + readonly done: Promise +} + /** Lists the entry skill while its upstream files are in place, and owns their download. */ class UpstreamSkillProvider implements SkillProvider { readonly name: string @@ -108,8 +115,8 @@ class UpstreamSkillProvider implements SkillProvider { private pruned = false private readonly candidate: SkillCandidate private readonly content: string - private readonly listeners = new Set<(state: UpstreamSkillsState) => void>() - private running = false + /** The running download, which every `install()` call made while it runs waits for. */ + private download: Download | undefined constructor( private readonly options: UpstreamSkillsRegistration, @@ -123,8 +130,7 @@ class UpstreamSkillProvider implements SkillProvider { const pin = `${PIN_PREFIX}${options.set.sha256.slice(0, 16)}` if (skillsDir !== undefined) { this.directory = resolve(skillsDir) - const remedy = `set it to a directory holding the files of ${options.set.directory} at their repository paths` - if (!this.installed()) throw new Error(`${options.name}: skillsDir ${skillsDir} is not a directory; ${remedy}`) + if (!this.installed()) throw this.missing(skillsDir) } else if (profile === undefined) { this.directory = dshCachePath(options.name, pin) } else { @@ -147,11 +153,6 @@ class UpstreamSkillProvider implements SkillProvider { } } - get state(): UpstreamSkillsState { - if (this.running) return 'downloading' - return this.installed() ? 'installed' : 'failed' - } - list(): Promise { return Promise.resolve(this.installed() ? [this.candidate] : []) } @@ -162,30 +163,30 @@ class UpstreamSkillProvider implements SkillProvider { return Promise.resolve({ ...summary, content: this.content }) } - watch(listener: (state: UpstreamSkillsState) => void): () => void { - this.listeners.add(listener) - return () => { this.listeners.delete(listener) } + installed(): boolean { + return statSync(this.directory, { throwIfNoEntry: false })?.isDirectory() === true } - retry(): void { - const { signal } = this.control - if (this.state !== 'failed' || this.options.skillsDir !== undefined || signal.aborted) return - this.running = true - this.notify() - void this.install(signal).then( - () => { this.control.invalidate() }, - (error: unknown) => { - if (signal.aborted) return - // Another process may have published the directory while this download failed. - if (this.installed()) this.control.invalidate() - else this.logger.warn(`${this.name}: the upstream skills are not available`, error) - }, - ).finally(() => { - this.running = false - if (signal.aborted) return - this.notify() - this.prune() - }) + /** Start the download at load unless the files are in place. No caller waits for it; its failure is logged. */ + start(): void { + if (!this.installed()) this.begin() + } + + /** Wait for the files as {@link UpstreamSkillsHandle.install} states: join the running download or begin one. */ + async install(signal: AbortSignal): Promise { + if (this.installed()) return + signal.throwIfAborted() + this.control.signal.throwIfAborted() + const { skillsDir } = this.options + if (skillsDir !== undefined) throw this.missing(skillsDir) + const download = this.download ?? this.begin() + const stop = (): void => { download.controller.abort(signal.reason) } + signal.addEventListener('abort', stop, { once: true }) + try { + await download.done + } finally { + signal.removeEventListener('abort', stop) + } } /** @@ -209,17 +210,45 @@ class UpstreamSkillProvider implements SkillProvider { }) } - private installed(): boolean { - return statSync(this.directory, { throwIfNoEntry: false })?.isDirectory() === true + /** The error for a configured `skillsDir` that is not a directory. */ + private missing(skillsDir: string): Error { + const remedy = `set it to a directory holding the files of ${this.options.set.directory} at their repository paths` + return new Error(`${this.name}: skillsDir ${skillsDir} is not a directory; ${remedy}`) } - private notify(): void { - const { state } = this - for (const listener of this.listeners) listener(state) + private begin(): Download { + const controller = new AbortController() + const done = this.run(controller) + // The download started at load has no caller; `run` logs its failure. + void done.catch(() => {}) + this.download = { controller, done } + return this.download + } + + /** + * Run one download to its end. It stops when `controller` aborts or the registration is withdrawn, neither of which + * is logged; any other failure is logged as a warning. + */ + private async run(controller: AbortController): Promise { + const signal = AbortSignal.any([controller.signal, this.control.signal]) + try { + await this.publish(signal) + } catch (error) { + // Another process may have published the directory while this download failed. + if (!this.installed()) { + if (!signal.aborted) this.logger.warn(`${this.name}: the upstream skills are not available`, error) + throw error + } + } finally { + this.download = undefined + } + if (this.control.signal.aborted) return + this.control.invalidate() + this.prune() } /** Download and verify the files, then publish them by renaming a sibling staging directory. */ - private async install(signal: AbortSignal): Promise { + private async publish(signal: AbortSignal): Promise { const { skillsUrls, skillsTimeoutMs } = this.config const files = await downloadSkillSet(this.options.set, skillsUrls, skillsTimeoutMs, signal, (message, error) => { this.logger.warn(`${this.name}: ${message}`, error) diff --git a/packages/connector/upstream-skills/src/types.ts b/packages/connector/upstream-skills/src/types.ts index e19b23ad5d..e9bdb853da 100644 --- a/packages/connector/upstream-skills/src/types.ts +++ b/packages/connector/upstream-skills/src/types.ts @@ -1,4 +1,4 @@ -/** The pinned upstream files of an entry skill, its registration, and the handle its plugin observes. */ +/** The pinned upstream files of an entry skill, its registration, and the handle its plugin waits for them through. */ /** Which files of a GitHub repository an upstream skill set keeps. */ export interface UpstreamSkillSelection { @@ -22,9 +22,6 @@ export interface UpstreamSkillSet extends UpstreamSkillSelection { readonly sha256: string } -/** Where an entry skill's upstream files stand: in place, being downloaded, or neither. */ -export type UpstreamSkillsState = 'installed' | 'downloading' | 'failed' - /** One plugin's packaged entry skill and the upstream files it indexes. */ export interface UpstreamSkillsRegistration { /** The skill provider's name, also the directory under `$DSH_HOME/cache` that receives the download. */ @@ -41,16 +38,21 @@ export interface UpstreamSkillsRegistration { export interface UpstreamSkillsHandle { /** The directory the entry skill resolves relative paths against: `skillsDir`, or the published cache directory. */ readonly directory: string - /** `downloading` while a download runs, otherwise `installed` when `directory` exists and `failed` when it does not. */ - readonly state: UpstreamSkillsState /** - * Call a listener each time a download starts and each time it settles. - * @param listener - receives the state after the change. - * @returns the disposer that removes the listener. + * Tell whether the upstream files are in place. + * @returns whether `directory` exists. */ - watch(listener: (state: UpstreamSkillsState) => void): () => void - /** Start a download when the state is `failed`, unless `skillsDir` is set or the registration is withdrawn; return at once. */ - retry(): void + installed(): boolean + /** + * Wait until the upstream files are in place: return at once when they are, otherwise wait for the running download, + * or start one when none runs. Aborting `signal` stops that download, also for every other caller that waits for it. + * @param signal - stops the download and the wait. + * @returns once `directory` exists. + * @throws the reason of `signal` after it aborts; the withdrawal reason after the registration is withdrawn; when the + * configured `skillsDir` is no longer a directory, without a download; otherwise what failed the download, which + * is also logged as a warning. + */ + install(signal: AbortSignal): Promise /** Withdraw the registration before the plugin unloads: abort a running download and remove the entry skill. */ dispose(): void } diff --git a/packages/connector/upstream-skills/tests/service.spec.ts b/packages/connector/upstream-skills/tests/service.spec.ts index 3855909d38..b5f7a352a9 100644 --- a/packages/connector/upstream-skills/tests/service.spec.ts +++ b/packages/connector/upstream-skills/tests/service.spec.ts @@ -1,6 +1,6 @@ /** - * `ctx.upstreamSkills` lists a plugin's entry skill over its upstream files: a configured directory, downloads, retries, - * withdrawal, and a profile's own directory, where the pin in place replaces the earlier ones. + * `ctx.upstreamSkills` lists a plugin's entry skill over its upstream files: a configured directory, downloads, waits + * for them, withdrawal, and a profile's own directory, where the pin in place replaces the earlier ones. */ import { mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' @@ -9,7 +9,7 @@ import { Context } from '@deepseek-ai/cordis' import type { ProfileContext } from '@deepseek-ai/dsh-app-boot' import SkillRegistry from '@deepseek-ai/dsh-skill' import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' -import UpstreamSkills, { type Config, type UpstreamSkillsHandle, type UpstreamSkillSet, type UpstreamSkillsState } from '../src/index.ts' +import UpstreamSkills, { type Config, type UpstreamSkillsHandle, type UpstreamSkillSet } from '../src/index.ts' import { KEPT, archivePath, pin, repository, serve, startHost, type ArchiveHost } from './harness.ts' const renameHook = vi.hoisted(() => ({ before: undefined as ((from: string, to: string) => Promise) | undefined })) @@ -109,18 +109,11 @@ async function sources(config: Partial): Promise { const registration = (skillsDir?: string, pinned: UpstreamSkillSet = set, path = entry) => ({ name: 'vendor', entry: path, set: pinned, skillsDir }) const register = (skillsDir?: string, pinned: UpstreamSkillSet = set, path = entry): UpstreamSkillsHandle => ctx.intercept('logger', { level: WARN_LEVEL }).upstreamSkills.register(registration(skillsDir, pinned, path)) -/** Resolve with the state once no download runs. */ -const settled = (skills: UpstreamSkillsHandle) => new Promise((resolve) => { - if (skills.state !== 'downloading') { - resolve(skills.state) - return - } - const stop = skills.watch((state) => { - if (state === 'downloading') return - stop() - resolve(state) - }) -}) +/** A signal that no test aborts, for a caller that waits until the download ends. */ +const unaborted = () => new AbortController().signal +/** Wait for the running download, or for a new one when none runs. @returns whether the files are in place at its end. */ +const downloaded = (skills: UpstreamSkillsHandle) => skills.install(unaborted()).then(() => true, () => false) +const WITHDRAWN = 'skill provider "vendor" disposed' /** Serve the archive only after `release()`, so a test observes the download while it runs. */ const gated = (body: Buffer) => { const gate = new Promise((resolve) => { release = resolve }) @@ -155,25 +148,24 @@ describe('register', () => { it('lists the entry over a configured skills directory at once and downloads nothing', async () => { const skills = register(fixtures) expect(skills.directory).toBe(fixtures) - expect(skills.state).toBe('installed') - skills.retry() + expect(skills.installed()).toBe(true) + await skills.install(unaborted()) expect(await ctx.skills.list()).toEqual(listed(fixtures)) expect(await ctx.skills.get('vendor')).toEqual({ ...listed(fixtures)[0], content: BODY }) expect(host.requests).toEqual([]) }) - it('names a skills directory that is missing at load, and reports one removed later as failed without downloading', async () => { + it('names a skills directory that is missing at load or removed later, and downloads nothing into it', async () => { const missing = join(home, 'missing') - expect(() => register(missing)) - .toThrow(`vendor: skillsDir ${missing} is not a directory; set it to a directory holding the files of skills at their repository paths`) + const named = `vendor: skillsDir ${missing} is not a directory; set it to a directory holding the files of skills at their repository paths` + expect(() => register(missing)).toThrow(named) await mkdir(missing) const skills = register(missing) expect(await ctx.skills.list()).toEqual(listed(missing)) await rm(missing, { recursive: true }) expect(await ctx.skills.get('vendor')).toBeUndefined() - expect(skills.state).toBe('failed') - skills.retry() - expect(skills.state).toBe('failed') + expect(skills.installed()).toBe(false) + await expect(skills.install(unaborted())).rejects.toThrow(named) expect(host.requests).toEqual([]) }) @@ -194,14 +186,12 @@ describe('register', () => { it('downloads at load and lists the entry once the files are published at their repository paths', async () => { host.routes[archivePath(set)] = gated(repository()) const skills = register() - const states: UpstreamSkillsState[] = [] - skills.watch((state) => { states.push(state) }) expect(skills.directory).toBe(published()) - expect(skills.state).toBe('downloading') + expect(skills.installed()).toBe(false) expect(await ctx.skills.list()).toEqual([]) release() - expect(await settled(skills)).toBe('installed') - expect(states).toEqual(['installed']) + await skills.install(unaborted()) + expect(skills.installed()).toBe(true) expect(await ctx.skills.list()).toEqual(listed(published())) for (const [path, content] of Object.entries(KEPT)) expect(await readFile(join(published(), path), 'utf8')).toBe(content) expect((await readdir(join(published(), 'skills', 'alpha'))).toSorted()).toEqual(['SKILL.md', 'references']) @@ -213,7 +203,7 @@ describe('register', () => { await mkdir(join(cache(), EARLIER), { recursive: true }) host.routes[archivePath(set)] = serve(repository()) const skills = register() - expect(await settled(skills)).toBe('installed') + expect(await downloaded(skills)).toBe(true) expect(await ctx.skills.list()).toEqual(listed(published())) expect((await readdir(cache())).toSorted()).toEqual([EARLIER, CURRENT].toSorted()) }) @@ -222,7 +212,7 @@ describe('register', () => { host.routes[archivePath(set, '/mirror')] = serve(repository()) await sources({ skillsUrls: [`${BASE}/missing`, `${BASE}/mirror/`] }) const skills = register() - expect(await settled(skills)).toBe('installed') + expect(await downloaded(skills)).toBe(true) expect(await ctx.skills.list()).toEqual(listed(published())) expect(warnings()).toEqual([`vendor: downloading the upstream skills from ${BASE}/missing failed`]) }) @@ -233,7 +223,7 @@ describe('register', () => { // The limit applies to each URL, so it also bounds the mirror on a loaded machine. await sources({ skillsUrls: [`${BASE}/slow`, `${BASE}/mirror`], skillsTimeoutMs: 3_000 }) const skills = register() - expect(await settled(skills)).toBe('installed') + expect(await downloaded(skills)).toBe(true) expect(warnings()).toEqual([`vendor: downloading the upstream skills from ${BASE}/slow failed`]) // Depending on which stream observes the abort first, the time limit arrives as the TimeoutError or as its cause. const timedOut = (error: unknown) => error instanceof Error && [error.name, error.cause instanceof Error ? error.cause.name : ''].includes('TimeoutError') @@ -245,7 +235,9 @@ describe('register', () => { host.routes[archivePath(set, '/changed')] = serve(repository({ ...KEPT, LICENSE: 'MIT-License\n' })) await sources({ skillsUrls: [`${BASE}/empty`, `${BASE}/changed`] }) const skills = register() - expect(await settled(skills)).toBe('failed') + await expect(skills.install(unaborted())).rejects + .toThrow(`could not download the upstream skills of vendor/skills-repo at ${set.commit} from any skills URL`) + expect(skills.installed()).toBe(false) expect(warnings()).toEqual([ `vendor: downloading the upstream skills from ${BASE}/empty failed`, `vendor: downloading the upstream skills from ${BASE}/changed failed`, @@ -259,21 +251,36 @@ describe('register', () => { expect(await ctx.skills.list()).toEqual([]) }) - it('retries a failed download without waiting for it, ignores a retry while one runs or after the files are in place', async () => { + it('downloads again after a failure, and has every caller wait for the one running download', async () => { host.routes[archivePath(set)] = (response) => { response.writeHead(500).end() } const skills = register() - expect(await settled(skills)).toBe('failed') + expect(await downloaded(skills)).toBe(false) host.routes[archivePath(set)] = gated(repository()) - const states: UpstreamSkillsState[] = [] - const stop = skills.watch((state) => { states.push(state) }) - skills.retry() - expect(skills.state).toBe('downloading') - skills.retry() + const callers = [skills.install(unaborted()), skills.install(unaborted())] + await vi.waitFor(() => { expect(host.requests).toEqual([archivePath(set), archivePath(set)]) }) + expect(skills.installed()).toBe(false) release() - expect(await settled(skills)).toBe('installed') - stop() - skills.retry() - expect(states).toEqual(['downloading', 'installed']) + await Promise.all(callers) + await skills.install(unaborted()) + expect(await ctx.skills.list()).toEqual(listed(published())) + expect(host.requests).toEqual([archivePath(set), archivePath(set)]) + }) + + it('stops the download without a warning when a waiting caller aborts, and downloads again for the next caller', async () => { + host.routes[archivePath(set)] = gated(repository()) + const skills = register() + const caller = new AbortController() + const stopped = expect(skills.install(caller.signal)).rejects.toThrow('cancelled on the page') + await vi.waitFor(() => { expect(host.requests).toEqual([archivePath(set)]) }) + caller.abort(new Error('cancelled on the page')) + await stopped + expect(skills.installed()).toBe(false) + await expect(skills.install(caller.signal)).rejects.toThrow('cancelled on the page') + expect(warnings()).toEqual([]) + expect(host.requests).toEqual([archivePath(set)]) + + host.routes[archivePath(set)] = serve(repository()) + await skills.install(unaborted()) expect(await ctx.skills.list()).toEqual(listed(published())) expect(host.requests).toEqual([archivePath(set), archivePath(set)]) }) @@ -281,7 +288,7 @@ describe('register', () => { it('keeps a directory another process published before load', async () => { await mkdir(published(), { recursive: true }) const skills = register() - expect(skills.state).toBe('installed') + expect(skills.installed()).toBe(true) expect(await ctx.skills.list()).toEqual(listed(published())) expect(host.requests).toEqual([]) }) @@ -293,7 +300,7 @@ describe('register', () => { await writeFile(join(to, 'other'), 'published by another process') } const skills = register() - expect(await settled(skills)).toBe('installed') + expect(await downloaded(skills)).toBe(true) expect(await readdir(published())).toEqual(['other']) expect(await readdir(cache())).toEqual([CURRENT]) }) @@ -305,10 +312,11 @@ describe('register', () => { response.writeHead(500).end() } const skills = register() + const ended = downloaded(skills) expect(await ctx.skills.list()).toEqual([]) await mkdir(published(), { recursive: true }) release() - expect(await settled(skills)).toBe('installed') + expect(await ended).toBe(true) expect(await ctx.skills.list()).toEqual(listed(published())) expect(warnings()).toEqual([`vendor: downloading the upstream skills from ${BASE} failed`]) }) @@ -317,7 +325,7 @@ describe('register', () => { host.routes[archivePath(set)] = serve(repository()) renameHook.before = async (from) => { await rm(from, { recursive: true }) } const skills = register() - expect(await settled(skills)).toBe('failed') + expect(await downloaded(skills)).toBe(false) expect(logged().at(-1)?.error).toMatchObject({ code: 'ENOENT' }) expect(await readdir(cache())).toEqual([]) }) @@ -328,18 +336,17 @@ describe('register', () => { expect(await ctx.skills.list()).toEqual(listed(fixtures)) }) - it('removes the entry and aborts a running download without a warning or a state change when the registering plugin unloads', async () => { + it('removes the entry and aborts a running download without a warning when the registering plugin unloads', async () => { let skills!: UpstreamSkillsHandle const app = Object.assign((inner: Context) => { skills = inner.upstreamSkills.register(registration()) }, { inject: ['upstreamSkills'] }) host.routes[archivePath(set)] = gated(repository()) const fiber = await ctx.intercept('logger', { level: WARN_LEVEL }).plugin(app) - const states: UpstreamSkillsState[] = [] - skills.watch((state) => { states.push(state) }) + const aborted = expect(skills.install(unaborted())).rejects.toThrow(WITHDRAWN) await vi.waitFor(() => { expect(host.requests).toEqual([archivePath(set)]) }) await fiber.dispose() - await vi.waitFor(() => { expect(skills.state).toBe('failed') }) - skills.retry() - expect(states).toEqual([]) + await aborted + await expect(skills.install(unaborted())).rejects.toThrow(WITHDRAWN) + expect(skills.installed()).toBe(false) expect(warnings()).toEqual([]) expect(host.requests).toEqual([archivePath(set)]) @@ -366,10 +373,11 @@ describe('register', () => { it('withdraws the entry through the handle before the plugin unloads and aborts its download', async () => { host.routes[archivePath(set)] = gated(repository()) const skills = register() + const aborted = expect(skills.install(unaborted())).rejects.toThrow(WITHDRAWN) await vi.waitFor(() => { expect(host.requests).toEqual([archivePath(set)]) }) skills.dispose() - await vi.waitFor(() => { expect(skills.state).toBe('failed') }) - skills.retry() + await aborted + await expect(skills.install(unaborted())).rejects.toThrow(WITHDRAWN) expect(host.requests).toEqual([archivePath(set)]) expect(warnings()).toEqual([]) await mkdir(published(), { recursive: true }) @@ -397,7 +405,7 @@ describe('register in a profile', () => { host.routes[archivePath(set)] = serve(repository()) const skills = register() expect(skills.directory).toBe(join(pins(), CURRENT)) - expect(await settled(skills)).toBe('installed') + expect(await downloaded(skills)).toBe(true) expect(await ctx.skills.list()).toEqual(listed(join(pins(), CURRENT))) for (const [path, content] of Object.entries(KEPT)) expect(await readFile(join(pins(), CURRENT, path), 'utf8')).toBe(content) expect(await readdir(pins())).toEqual([CURRENT]) @@ -410,10 +418,10 @@ describe('register in a profile', () => { for (const directory of [join(pins(), EARLIER), ...untouched]) await mkdir(directory, { recursive: true }) host.routes[archivePath(set)] = gated(repository()) const skills = register() - expect(skills.state).toBe('downloading') + expect(skills.installed()).toBe(false) expect(await entries(pins())).toEqual([staging, EARLIER].toSorted()) release() - expect(await settled(skills)).toBe('installed') + expect(await downloaded(skills)).toBe(true) await vi.waitFor(async () => { expect(await entries(pins())).toEqual([staging, CURRENT].toSorted()) }) for (const directory of untouched) expect((await stat(directory)).isDirectory()).toBe(true) expect(warnings()).toEqual([]) @@ -422,7 +430,7 @@ describe('register in a profile', () => { it('replaces the earlier pins at load when the pin is already in place, without a download', async () => { for (const name of [CURRENT, EARLIER]) await mkdir(join(pins(), name), { recursive: true }) const skills = register() - expect(skills.state).toBe('installed') + expect(skills.installed()).toBe(true) await vi.waitFor(async () => { expect(await readdir(pins())).toEqual([CURRENT]) }) expect(await ctx.skills.list()).toEqual(listed(join(pins(), CURRENT))) expect(host.requests).toEqual([]) @@ -433,18 +441,17 @@ describe('register in a profile', () => { await mkdir(join(pins(), EARLIER), { recursive: true }) host.routes[archivePath(set)] = serve(repository()) const skills = register() - expect(await settled(skills)).toBe('installed') + expect(await downloaded(skills)).toBe(true) await vi.waitFor(async () => { expect(await readdir(pins())).toEqual([CURRENT]) }) // Another process of the profile, running another plugin version, publishes its pin and deletes this one. await mkdir(join(pins(), other)) await rm(join(pins(), CURRENT), { recursive: true }) - expect(skills.state).toBe('failed') + expect(skills.installed()).toBe(false) const before = listHook.listed.length - skills.retry() - expect(await settled(skills)).toBe('installed') + await skills.install(unaborted()) - // The deletion starts by listing the directory, in the same turn in which the download settles. + // The deletion starts by listing the directory, before the wait for the download ends. expect(listHook.listed.slice(before)).not.toContain(pins()) expect(await entries(pins())).toEqual([CURRENT, other].toSorted()) expect(await ctx.skills.list()).toEqual(listed(join(pins(), CURRENT))) @@ -455,10 +462,26 @@ describe('register in a profile', () => { await mkdir(join(pins(), EARLIER), { recursive: true }) host.routes[archivePath(set)] = (response) => { response.writeHead(500).end() } const skills = register() - expect(await settled(skills)).toBe('failed') + expect(await downloaded(skills)).toBe(false) expect(await readdir(pins())).toEqual([EARLIER]) }) + it('keeps the earlier pins when the registration is withdrawn during its download, although another process published the pin', async () => { + await mkdir(join(pins(), EARLIER), { recursive: true }) + host.routes[archivePath(set)] = gated(repository()) + const skills = register() + const ended = downloaded(skills) + await vi.waitFor(() => { expect(host.requests).toEqual([archivePath(set)]) }) + await mkdir(join(pins(), CURRENT)) + const before = listHook.listed.length + skills.dispose() + expect(await ended).toBe(true) + + // The deletion would start by listing the directory, before the wait for the download ends. + expect(listHook.listed.slice(before)).not.toContain(pins()) + expect(await entries(pins())).toEqual([EARLIER, CURRENT].toSorted()) + }) + it('logs an earlier pin that cannot be deleted, keeps it, and still lists the entry', async () => { for (const name of [CURRENT, EARLIER]) await mkdir(join(pins(), name), { recursive: true }) const refused = Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' }) diff --git a/packages/connector/wecom/README.i18n.yaml b/packages/connector/wecom/README.i18n.yaml index 1859149b15..d10a02a84b 100644 --- a/packages/connector/wecom/README.i18n.yaml +++ b/packages/connector/wecom/README.i18n.yaml @@ -21,17 +21,17 @@ en: 6227d6e43ec8c108 zh: 48e0f252de253d14 /deepseek-ai-dsh-wecom/use-this-package/what-you-get: - en: 7581623b2b257fe0 - zh: cdd670dfd6d0183d + en: bb320b233ab74df2 + zh: 337d1d1b213a8c60 /deepseek-ai-dsh-wecom/use-this-package/authorization-operations: - en: a5d3467ec57a5657 - zh: ea5a0e1c3c539046 + en: fb54bdc729deed65 + zh: b2ee5587d647007c /deepseek-ai-dsh-wecom/use-this-package/configure: en: dfbcda32182eb7eb zh: 554086e7081a313a /deepseek-ai-dsh-wecom/understand-the-implementation: - en: 2b6b63d9e4e2e41c - zh: 6268453811f2efcb + en: 6d08d4dfc693feaa + zh: 3e46d277d1aedd07 /deepseek-ai-dsh-wecom/further-exploration: en: 7a8fda721faaf5ef zh: b4233b8a77994ae6 @@ -66,8 +66,8 @@ en: b5fed52af6c0d771 zh: 25b7aa5297583030 /deepseek-ai-dsh-wecom/model-experience/cli-path/what-the-model-sees: - en: 44f38c8383be971a - zh: 5975e1948617e18b + en: c340fa204afb8343 + zh: ad639d6b3e5e1648 /deepseek-ai-dsh-wecom/model-experience/cli-path/what-the-model-sees/runtime-context-entry: en: c91314832f78f460 zh: aac156ea0b5b816a @@ -78,11 +78,11 @@ en: 2caf581d193f3dba zh: 3b5e94d4cc69ca3b /deepseek-ai-dsh-wecom/model-experience/cli-path/kv-cache-effect: - en: 67398dd4e4b02db9 - zh: a873eacd006fa656 + en: 3697d00addea159f + zh: f194c6b014b355ca /deepseek-ai-dsh-wecom/known-limitations-and-deferred-work: - en: 7a9e3ee8135294ee - zh: a016e5b728757c1f + en: 12d8c9be02ef0f91 + zh: 968f825df170ac00 /deepseek-ai-dsh-wecom/known-limitations-and-deferred-work/dev-note: en: 71cc23fc507e649e zh: 3dbd0498845467cc diff --git a/packages/connector/wecom/README.md b/packages/connector/wecom/README.md index dc3e048da8..e5314d1696 100644 --- a/packages/connector/wecom/README.md +++ b/packages/connector/wecom/README.md @@ -40,7 +40,7 @@ dsh plugin --profile web remove @deepseek-ai/dsh-wecom After the plugin loads, one `wecom` skill joins the skill catalog. The agent loads it with the `skill` tool, opens the guide it needs, such as `wecomcli-doc` or `wecomcli-message`, with the file tools, and runs `wecom-cli` by that path through the ordinary Shell tools under the current sandbox and approval policy. When `wecom-cli auth show --status` reports no authorization, the agent asks the user to connect WeCom on the plugin page; it runs the CLI's own `auth init` only when the user asks to finish it in the conversation, and requests `sandbox_permissions` with a `justification` on the first attempt because the command writes outside the workspace. When a command returns `errcode` 853004 (`cli token expired`), the agent does not ask for a new authorization or pass on the server's upgrade advice: it reruns the command with `sandbox_permissions` and a `justification`, because in the file sandbox the CLI cannot save the token it just refreshed. -The guides come from `skills/` of `WecomTeam/wecom-cli` at commit `4c74ff2`. The row downloads that commit's archive when it loads and keeps the verified files in `$DSH_HOME/cache/wecom/`; until they are in place, the catalog has no `wecom` skill and the plugin page reports the download. A failed download is retried by the page's check. +The guides come from `skills/` of `WecomTeam/wecom-cli` at commit `4c74ff2`. The row downloads that commit's archive when it loads and keeps the verified files in `$DSH_HOME/cache/wecom/`; until they are in place, the catalog has no `wecom` skill, the runtime context gives no `wecom-cli` path, and the plugin page shows the download instead of the authorization. The page's check waits for the download and shows it as a step with **Cancel**. A download that does not finish leaves the authorization at `not-installed`: the page reports that the skills could not be downloaded and offers **Retry**, and the next check downloads again. Turning the plugin off in Plugin Manager withdraws the skills, the path from runtime context, and the authorization section. The CLI authorization and the downloaded guides stay in place. @@ -51,11 +51,11 @@ The Plugins page drives these operations through the connector account registry, | Operation | Effect | |---|---| -| `check` | Checks the authorization again; each browser that opens the Web app starts one when no operation runs | +| `check` | Waits for the guides' download while they are missing, starting one when none runs, then checks the authorization again; each browser that opens the Web app starts one when no operation runs | | `connect` | Runs `auth init --noninteractive --no-browser`, waits for the user to scan the QR code, then checks that the CLI reports the bot authorized. The authorized section offers it again as changing the bot, after a confirmation, because the new binding replaces the one the terminal shares | -| Cancel | Cancels the connection while it waits for the scan and waits for its command to exit; other steps are ignored | +| Cancel | Cancels the connection while it waits for the scan, or a check while it waits for the guides' download, and waits for the command or download to stop; other steps are ignored | -A check runs `auth show`. The authorization reads `authorized` or `unauthorized` from the CLI's `Status` line, and the bound bot's id from its `Bot ID` line, which the section shows when the CLI prints one; any other output or a nonzero exit fails the check and keeps the previous state. Each link that `auth init` prints alone on a stdout line is offered only when it is an HTTPS address on `work.weixin.qq.com`. Results report succeeded, cancelled, or failed. Failures show the command and the observed exit code on the page and in the Host log; the CLI's output, which can carry the QR-code session, is omitted. `wecom-cli` has no command that revokes the authorization, so the plugin offers no disconnect. The process running DSH needs access to the CLI configuration; `DSH_HOME` does not relocate it. +A check runs `auth show`. The authorization reads `authorized` or `unauthorized` from the CLI's `Status` line, and the bound bot's id from its `Bot ID` line, which the section shows when the CLI prints one; any other output or a nonzero exit fails the check and keeps the previous state; a download that does not finish leaves `not-installed`. Each link that `auth init` prints alone on a stdout line is offered only when it is an HTTPS address on `work.weixin.qq.com`. Results report succeeded, cancelled, or failed. Failures show the command and the observed exit code on the page and in the Host log; the CLI's output, which can carry the QR-code session, is omitted. `wecom-cli` has no command that revokes the authorization, so the plugin offers no disconnect. The process running DSH needs access to the CLI configuration; `DSH_HOME` does not relocate it. ### Configure @@ -76,7 +76,7 @@ The generated [config catalog](../../../docs/config-catalog.md#deepseek-aidsh-we
Implementation internals — click to expand -[`cordis.patch.yml`](cordis.patch.yml) inserts this package as the `wecom` row after the profile's other layers, and the Plugins page keys the authorization section by this package name. [`src/index.ts`](src/index.ts) is a function plugin. It checks that `binDir/wecom-cli` (`wecom-cli.exe` on Windows) is executable, registers the `wecom` skill with `ctx.upstreamSkills` under the pin in [`src/skills.ts`](src/skills.ts), and registers that path and the authorization with `ctx.cliAccounts`. The account view carries the download state, and each check restarts a failed download without waiting for it. [`src/directory.ts`](src/directory.ts) resolves the platform package that `@wecom/cli` installs as an optional dependency. The [CLI account Service](../cli-account/README.md) gives the model that path in runtime context, runs each command by the same path, runs one operation at a time, and reports a failed command by its exit code. [`src/account.ts`](src/account.ts) carries out each operation with the WeCom commands and reads the QR-code link from the output lines of `auth init`. [`src/presentation.ts`](src/presentation.ts) maps each view to the section the registry serves, in the text of [`src/locales.ts`](src/locales.ts). Disposal cancels the active operation, aborts running commands, and settles after their processes exit. +[`cordis.patch.yml`](cordis.patch.yml) inserts this package as the `wecom` row after the profile's other layers, and the Plugins page keys the authorization section by this package name. [`src/index.ts`](src/index.ts) is a function plugin. It checks that `binDir/wecom-cli` (`wecom-cli.exe` on Windows) is executable, registers the `wecom` skill with `ctx.upstreamSkills` under the pin in [`src/skills.ts`](src/skills.ts), and registers that path and the authorization with `ctx.cliAccounts`. The registration's [`prepare` step](../cli-account/README.md#prepare-before-a-check) is the skill handle's `installed` and `install`, so each check first waits for the guides' download and starts one when none runs. [`src/directory.ts`](src/directory.ts) resolves the platform package that `@wecom/cli` installs as an optional dependency. The [CLI account Service](../cli-account/README.md) gives the model that path in runtime context while the guides are in place, runs the `prepare` step before a check's first command while they are missing, runs each command by the same path, runs one operation at a time, and reports a failed command by its exit code. [`src/account.ts`](src/account.ts) carries out each operation with the WeCom commands and reads the QR-code link from the output lines of `auth init`. [`src/presentation.ts`](src/presentation.ts) maps each view to the section the registry serves, in the text of [`src/locales.ts`](src/locales.ts). Disposal cancels the active operation, aborts running commands and the guides' download, and settles after the commands' processes exit. [`skills/wecom/SKILL.md`](skills/wecom/SKILL.md) is the only skill this package carries: the DSH guidance, an index of the guides, and how to open them. Upstream publishes the guides only in its repository and not in the npm package, so the [upstream skills Service](../upstream-skills/README.md) downloads them; they are files under the skill's base directory, not separate skills. Where the DSH guidance and `wecomcli-shared` disagree, the entry tells the agent to follow the DSH guidance: it uses the plugin's `wecom-cli` instead of installing one, and sends authorization to the plugin page. References are ordinary files in each guide's directory. @@ -130,7 +130,7 @@ Loading appends a tool result and does not rewrite earlier context. #### What the model sees -While the row is loaded, the [CLI account Service](../cli-account/README.md#model-experience) adds one required runtime-context entry with the path of `wecom-cli` in `binDir`, which defaults to the `bin` directory of the platform package that `@wecom/cli` installs. The second line covers the guide scripts that call `wecom-cli` by name, such as `build_page.py`. +While the row is loaded and the guides are in place, the [CLI account Service](../cli-account/README.md#model-experience) adds one required runtime-context entry with the path of `wecom-cli` in `binDir`, which defaults to the `bin` directory of the platform package that `@wecom/cli` installs. The second line covers the guide scripts that call `wecom-cli` by name, such as `build_page.py`. ##### Runtime-context entry @@ -152,7 +152,7 @@ Two lines of about 280 characters plus the path and its directory in each runtim #### KV Cache effect -The system prompt does not change; loading or unloading the row, or a changed path, appends one runtime-context snapshot. +The system prompt does not change; finishing the guides' download, loading or unloading the row, or a changed path appends one runtime-context snapshot. ## Known Limitations and Deferred Work @@ -163,7 +163,7 @@ The system prompt does not change; loading or unloading the row, or a changed pa - The plugin uses the CLI's default configuration. Authorizing from DSH affects the user's own terminal, and there is no DSH-private bot or bot picker. `wecom-cli` cannot revoke the authorization, so neither the page nor turning the plugin off removes it; the page can only replace the bound bot with another one. - Connection reads the QR-code link from the plain-text output of `auth init --noninteractive --no-browser`; a CLI version that changes that output fails the connection with a retryable result. - The guides follow upstream commit `4c74ff2`; updating them means a new pin from `scripts/upstream-skills-digest.ts`, after which the entry's index and DSH guidance must be checked against the new guides. -- The first load after a new pin needs access to GitHub or a configured mirror; until a download succeeds, the agent has no `wecom` skill. +- The first load after a new pin needs access to GitHub or a configured mirror; until a download succeeds, the agent has neither the `wecom` skill nor the `wecom-cli` path, and the page offers no authorization. A computer that reaches neither needs `skillsDir`. A headless profile has no page check, so a download that failed at load is repeated only at the next load. - The downloaded guides stay in `$DSH_HOME/cache/wecom/` after the plugin is removed or pins another commit. - In the file sandbox, `wecom-cli` reads the saved authorization without writing, so commands run there until the saved token expires. It then cannot save the refreshed token in its configuration directory outside the workspace, and the command returns `errcode` 853004 with the server's upgrade advice. Rerunning that command needs one single-command approval, after which commands run in the sandbox again until the next expiry. The page's check reads only local state and does not refresh the token. diff --git a/packages/connector/wecom/README.zh.md b/packages/connector/wecom/README.zh.md index 60535732d1..e7a6712731 100644 --- a/packages/connector/wecom/README.zh.md +++ b/packages/connector/wecom/README.zh.md @@ -40,7 +40,7 @@ dsh plugin --profile web remove @deepseek-ai/dsh-wecom 插件加载后,一个 `wecom` skill 进入 skill 目录。agent 用 `skill` 工具加载它,用文件工具打开所需的子指南(例如 `wecomcli-doc` 或 `wecomcli-message`),并在当前沙箱与审批策略下通过普通 Shell 工具按这个路径运行 `wecom-cli`。`wecom-cli auth show --status` 报告未授权时,agent 会请用户到插件页连接企业微信;只有用户要求在对话中完成时,才运行 CLI 自带的 `auth init`,并且因为该命令会写入工作区之外,第一次尝试就带 `justification` 申请 `sandbox_permissions`。命令返回 `errcode` 853004(`cli token expired`)时,agent 不会请用户重新授权,也不会转述服务端的升级建议,而是带 `sandbox_permissions` 和 `justification` 重跑同一条命令,因为在文件沙箱下 CLI 保存不了刚换到的 token。 -子指南来自 `WecomTeam/wecom-cli` 在提交 `4c74ff2` 时的 `skills/`。该行加载时下载这个提交的归档,并把校验后的文件保存在 `$DSH_HOME/cache/wecom/`;文件就位之前,skill 目录中没有 `wecom` skill,插件页会报告下载状态。下载失败时,由插件页的检查重试。 +子指南来自 `WecomTeam/wecom-cli` 在提交 `4c74ff2` 时的 `skills/`。该行加载时下载这个提交的归档,并把校验后的文件保存在 `$DSH_HOME/cache/wecom/`;文件就位之前,skill 目录中没有 `wecom` skill,运行时上下文不给出 `wecom-cli` 路径,插件页显示的是下载而不是授权。插件页的检查会等待下载,并把它显示为一个带**取消**的步骤。没有完成的下载使授权处于 `not-installed`:页面提示没能下载技能并提供**重试**,下一次检查会重新下载。 在 Plugin Manager 中关闭插件会撤下 skill、运行时上下文中的路径和授权区块,CLI 的授权和已下载的子指南保持不变。 @@ -51,11 +51,11 @@ dsh plugin --profile web remove @deepseek-ai/dsh-wecom | 操作 | 作用 | |---|---| -| `check` | 重新检查授权;没有操作运行时,每个打开 Web 应用的浏览器会触发一次 | +| `check` | 子指南缺失时先等待它们下载完成(没有下载在运行时发起一次),然后重新检查授权;没有操作运行时,每个打开 Web 应用的浏览器会触发一次 | | `connect` | 运行 `auth init --noninteractive --no-browser`,等待用户扫码,然后确认 CLI 报告机器人已授权。已授权的区块以“更换机器人”再次提供它,需先确认,因为新绑定会替换终端共用的那一个 | -| 取消 | 在等待扫码期间取消连接并等待其命令退出;其他步骤会被忽略 | +| 取消 | 在等待扫码期间取消连接,或在检查等待子指南下载期间取消检查,并等待命令或下载停止;其他步骤会被忽略 | -检查运行 `auth show`。授权状态从 CLI 输出的 `Status` 行读作 `authorized` 或 `unauthorized`,CLI 打印 `Bot ID` 行时,从中读取已绑定机器人的 id 并显示在区块中;其他输出或非零退出码会使检查失败,并保留之前的状态。`auth init` 在 stdout 中单独一行打印的链接,只有是 `work.weixin.qq.com` 上的 HTTPS 地址时才会提供。结果分为成功、已取消和失败。失败时,页面和 Host 日志显示命令和观察到的退出码;CLI 的输出可能带有扫码会话,因此不保留。`wecom-cli` 没有撤销授权的命令,因此插件不提供断开连接。运行 DSH 的进程需要能访问 CLI 配置;`DSH_HOME` 不会迁移它。 +检查运行 `auth show`。授权状态从 CLI 输出的 `Status` 行读作 `authorized` 或 `unauthorized`,CLI 打印 `Bot ID` 行时,从中读取已绑定机器人的 id 并显示在区块中;其他输出或非零退出码会使检查失败,并保留之前的状态;没有完成的下载使状态成为 `not-installed`。`auth init` 在 stdout 中单独一行打印的链接,只有是 `work.weixin.qq.com` 上的 HTTPS 地址时才会提供。结果分为成功、已取消和失败。失败时,页面和 Host 日志显示命令和观察到的退出码;CLI 的输出可能带有扫码会话,因此不保留。`wecom-cli` 没有撤销授权的命令,因此插件不提供断开连接。运行 DSH 的进程需要能访问 CLI 配置;`DSH_HOME` 不会迁移它。 ### 配置 @@ -76,7 +76,7 @@ dsh plugin --profile web remove @deepseek-ai/dsh-wecom
实现内部机制——点击展开 -[`cordis.patch.yml`](cordis.patch.yml) 在 profile 其他层之后把本包作为 `wecom` 行插入,插件页以本包名作为授权区块的 key。[`src/index.ts`](src/index.ts) 是一个函数插件。它检查 `binDir/wecom-cli`(Windows 上为 `wecom-cli.exe`)是否可执行,按 [`src/skills.ts`](src/skills.ts) 中的固定信息把 `wecom` skill 注册到 `ctx.upstreamSkills`,并把这个路径和授权注册到 `ctx.cliAccounts`。账号视图携带下载状态,每次检查都会在不等待的情况下重新开始失败的下载。[`src/directory.ts`](src/directory.ts) 定位 `@wecom/cli` 作为可选依赖安装的平台包。[CLI 账号 Service](../cli-account/README.zh.md) 在运行时上下文中把这个路径告诉模型,按同一路径运行每条命令,一次执行一个操作,并以退出码报告失败的命令。[`src/account.ts`](src/account.ts) 用企业微信的命令完成每个操作,并从 `auth init` 的输出行中读取扫码链接。[`src/presentation.ts`](src/presentation.ts) 用 [`src/locales.ts`](src/locales.ts) 中的文案,把每个视图映射为注册表提供的区块。释放时取消进行中的操作,中止正在运行的命令,并在这些进程退出后完成。 +[`cordis.patch.yml`](cordis.patch.yml) 在 profile 其他层之后把本包作为 `wecom` 行插入,插件页以本包名作为授权区块的 key。[`src/index.ts`](src/index.ts) 是一个函数插件。它检查 `binDir/wecom-cli`(Windows 上为 `wecom-cli.exe`)是否可执行,按 [`src/skills.ts`](src/skills.ts) 中的固定信息把 `wecom` skill 注册到 `ctx.upstreamSkills`,并把这个路径和授权注册到 `ctx.cliAccounts`。这次注册的 [`prepare` 步骤](../cli-account/README.zh.md#prepare-before-a-check)就是 skill 句柄的 `installed` 和 `install`,因此每次检查都先等待子指南下载完成,没有下载在运行时发起一次。[`src/directory.ts`](src/directory.ts) 定位 `@wecom/cli` 作为可选依赖安装的平台包。[CLI 账号 Service](../cli-account/README.zh.md) 在子指南就位期间于运行时上下文中把这个路径告诉模型,在它们缺失时于检查的第一条命令之前运行 `prepare` 步骤,按同一路径运行每条命令,一次执行一个操作,并以退出码报告失败的命令。[`src/account.ts`](src/account.ts) 用企业微信的命令完成每个操作,并从 `auth init` 的输出行中读取扫码链接。[`src/presentation.ts`](src/presentation.ts) 用 [`src/locales.ts`](src/locales.ts) 中的文案,把每个视图映射为注册表提供的区块。释放时取消进行中的操作,中止正在运行的命令和子指南的下载,并在这些命令的进程退出后完成。 [`skills/wecom/SKILL.md`](skills/wecom/SKILL.md) 是本包携带的唯一 skill:DSH 指引、子指南索引和打开方式。上游只在其仓库发布这些子指南,没有放进 npm 包,因此由[上游技能 Service](../upstream-skills/README.zh.md) 下载;它们是 skill 基础目录下的文件,不是独立的 skill。DSH 指引与 `wecomcli-shared` 不一致时,总入口要求 agent 以 DSH 指引为准:使用插件提供的 `wecom-cli`,不再自行安装,并把授权引导到插件页。引用文件是每个子指南目录中的普通文件。 @@ -130,7 +130,7 @@ skill 目录只列出一个 `wecom` skill。其中文描述列出它覆盖的企 #### 模型看到什么 -该行加载期间,[CLI 账号 Service](../cli-account/README.zh.md#model-experience) 添加一条必需的运行时上下文,给出 `binDir` 中 `wecom-cli` 的路径;`binDir` 默认是 `@wecom/cli` 安装的平台包的 `bin` 目录。第二行针对按名称调用 `wecom-cli` 的子指南脚本,例如 `build_page.py`。 +该行加载且子指南就位期间,[CLI 账号 Service](../cli-account/README.zh.md#model-experience) 添加一条必需的运行时上下文,给出 `binDir` 中 `wecom-cli` 的路径;`binDir` 默认是 `@wecom/cli` 安装的平台包的 `bin` 目录。第二行针对按名称调用 `wecom-cli` 的子指南脚本,例如 `build_page.py`。 ##### 运行时上下文条目 @@ -152,7 +152,7 @@ Scripts in the WeCom skill call `wecom-cli` by name; start only the commands tha #### KV Cache 影响 -系统提示词不变;加载或卸载该行、或路径变化时,追加一份运行时上下文快照。 +系统提示词不变;子指南下载完成、加载或卸载该行、或路径变化时,追加一份运行时上下文快照。 ## 已知限制与延期工作 @@ -163,7 +163,7 @@ Scripts in the WeCom skill call `wecom-cli` by name; start only the commands tha - 插件使用 CLI 的默认配置。在 DSH 中授权会影响用户自己的终端,没有 DSH 私有机器人或机器人选择器。`wecom-cli` 无法撤销授权,因此页面和关闭插件都不会移除它;页面只能把已绑定的机器人换成另一个。 - 连接从 `auth init --noninteractive --no-browser` 的纯文本输出中读取扫码链接;CLI 版本改变该输出时,连接以可重试的结果失败。 - 子指南跟随上游提交 `4c74ff2`;更新时要用 `scripts/upstream-skills-digest.ts` 生成新的固定信息,之后按新的子指南核对总入口的索引和 DSH 指引。 -- 换用新的固定提交后,首次加载需要能访问 GitHub 或配置的镜像;下载成功之前,agent 没有 `wecom` skill。 +- 换用新的固定提交后,首次加载需要能访问 GitHub 或配置的镜像;下载成功之前,agent 既没有 `wecom` skill 也没有 `wecom-cli` 路径,页面也不提供授权。两者都访问不到的电脑需要设置 `skillsDir`。headless profile 没有页面的检查,因此加载时失败的下载要到下一次加载才会重试。 - 插件卸载或改为固定其他提交后,已下载的子指南仍留在 `$DSH_HOME/cache/wecom/`。 - 在文件沙箱下,`wecom-cli` 读取已保存的授权时不需要写入,所以在已保存的 token 过期之前命令可以直接运行。token 过期后,CLI 无法把刚换到的 token 保存到工作区之外的配置目录,命令会返回 `errcode` 853004 和服务端的升级建议。重跑这条命令需要一次单条命令审批,之后命令又可以在沙箱中运行,直到下一次过期。页面的检查只读取本地状态,不会刷新 token。 diff --git a/packages/connector/wecom/src/account.ts b/packages/connector/wecom/src/account.ts index 023d18e080..8c182d9bff 100644 --- a/packages/connector/wecom/src/account.ts +++ b/packages/connector/wecom/src/account.ts @@ -4,7 +4,6 @@ */ import type { CliOperationControl } from '@deepseek-ai/dsh-cli-account/types' -import type { UpstreamSkillsHandle } from '@deepseek-ai/dsh-upstream-skills/types' import { assertNever } from '@deepseek-ai/dsh-util-values' import type { WecomAccountState, WecomCommand, WecomOperationKind, WecomPhase } from './types.ts' @@ -15,32 +14,27 @@ const BOT_LINE = /^Bot ID:[ \t]*(\S+)[ \t]*$/mu type Control = CliOperationControl -/** The upstream guides whose state the account carries and whose failed download each check restarts. */ -type Guides = Pick - -/* jscpd:ignore-start -- CLI app plugins with downloaded guides bind their operations to the guides alike. */ /** - * Bind the WeCom account operations to the upstream guides. - * @param guides - the registered upstream guides. - * @returns the function that carries out one operation with wecom-cli and publishes the authorization each check - * observes; it throws when a command fails, prints an unknown status, or leaves no authorization after a binding. + * Carry out one account operation with wecom-cli and publish the authorization each check observes. + * @param kind - the requested operation. + * @param control - phase changes, link offers, command runs, and account updates for this operation. + * @param signal - aborts on cancellation and when the plugin unloads. + * @returns after the operation finishes. + * @throws when a command fails, prints an unknown status, or leaves no authorization after a binding. */ -export function performWith(guides: Guides): (kind: WecomOperationKind, control: Control, signal: AbortSignal) => Promise { - return async (kind, control, signal) => { - switch (kind) { - case 'check': - await check(guides, control, signal) - return - case 'connect': return connect(guides, control, signal) - /* v8 ignore next -- closed operation kind union */ - default: return assertNever(kind) - } +export async function perform(kind: WecomOperationKind, control: Control, signal: AbortSignal): Promise { + switch (kind) { + case 'check': + await check(control, signal) + return + case 'connect': return connect(control, signal) + /* v8 ignore next -- closed operation kind union */ + default: return assertNever(kind) } } -/* jscpd:ignore-end */ /** Bind a bot through the CLI's QR-code page, then confirm the CLI reports it authorized. */ -async function connect(guides: Guides, control: Control, signal: AbortSignal): Promise { +async function connect(control: Control, signal: AbortSignal): Promise { control.stage('authorizing') const init = await control.run('auth-init', ['auth', 'init', '--noninteractive', '--no-browser'], signal, { awaitsUser: true, @@ -51,19 +45,18 @@ async function connect(guides: Guides, control: Control, signal: AbortSignal): P }) if (init.exitCode !== 0) throw new Error(`wecom: auth init exited with ${String(init.exitCode)}`) control.stage('checking') - if ((await check(guides, control, signal)).state !== 'authorized') throw new Error('wecom: auth init left no authorization') + if ((await check(control, signal)).state !== 'authorized') throw new Error('wecom: auth init left no authorization') } -/** Restart a failed download of the guides without waiting for it, then read the authorization state, publish it, and return it. */ -async function check(guides: Guides, control: Control, signal: AbortSignal): Promise { - guides.retry() +/** Read the authorization state, publish it, and return it. */ +async function check(control: Control, signal: AbortSignal): Promise { const result = await control.run('auth-status', ['auth', 'show'], signal) const state = STATUS_LINE.exec(result.stdout)?.[1] if (result.exitCode !== 0 || (state !== 'authorized' && state !== 'unauthorized')) { throw new Error(`wecom: auth show exited with ${String(result.exitCode)} or printed an unknown status`) } const botId = state === 'authorized' ? BOT_LINE.exec(result.stdout)?.[1] : undefined - const account: WecomAccountState = { state, ...botId === undefined ? {} : { botId }, skills: guides.state } + const account: WecomAccountState = { state, ...botId === undefined ? {} : { botId } } control.publish(account) return account } diff --git a/packages/connector/wecom/src/index.ts b/packages/connector/wecom/src/index.ts index 75bb2dfec7..92b6bc0507 100644 --- a/packages/connector/wecom/src/index.ts +++ b/packages/connector/wecom/src/index.ts @@ -1,8 +1,8 @@ /** - * WeCom plugin: registers the managed wecom-cli and its authorization with `ctx.cliAccounts`, which tells the model the - * CLI's absolute path and shows the authorization on the Plugins page, and registers the `wecom` entry skill with - * `ctx.upstreamSkills`, which downloads the upstream guides it indexes. The CLI's authorization is shared with the - * user's own terminal. + * WeCom plugin: registers the `wecom` entry skill with `ctx.upstreamSkills`, which downloads the upstream guides it + * indexes, and registers the managed wecom-cli and its authorization with `ctx.cliAccounts`, which tells the model the + * CLI's absolute path once the guides are in place and shows the authorization on the Plugins page. The CLI's + * authorization is shared with the user's own terminal. * @module @deepseek-ai/dsh-wecom */ @@ -10,7 +10,7 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-cli-account' import type {} from '@deepseek-ai/dsh-upstream-skills' -import { performWith } from './account.ts' +import { perform } from './account.ts' import { PROGRAM, resolveCliExecutable } from './directory.ts' import { dictionaries, type WecomTextKey } from './locales.ts' import { copy, operations, presentAccount, WECOM_PACKAGE } from './presentation.ts' @@ -39,7 +39,7 @@ export const Config: z = z.object({ }) /** - * Register the entry skill, and the CLI with its authorization, whose view follows the guides' download. + * Register the entry skill, and the CLI with its authorization, whose check first waits for the guides' download. * @param ctx - Context carrying the CLI account Service and the upstream skills Service. * @param config - CLI location and the guides' directory. * @throws when `wecom-cli` is not executable or `skillsDir` is not a directory. @@ -47,20 +47,25 @@ export const Config: z = z.object({ export function apply(ctx: Context, config: Config): void { const executable = resolveCliExecutable(config.binDir) const guides = ctx.upstreamSkills.register({ name, entry: ENTRY, set: WECOM_SKILLS, skillsDir: config.skillsDir }) - const account = ctx.cliAccounts.register({ + ctx.cliAccounts.register({ name, packageName: WECOM_PACKAGE, cli: { product: 'WeCom', program: PROGRAM, executable, scripts: true }, - account: { state: 'unchecked', skills: guides.state }, + prepare: { + phase: 'downloading', + unprepared: { state: 'not-installed' }, + ready: () => guides.installed(), + run: signal => guides.install(signal), + }, + account: { state: 'unchecked' }, check: 'check', - cancellable: ['authorizing'], + cancellable: ['downloading', 'authorizing'], authorizationHosts: ['work.weixin.qq.com'], - perform: performWith(guides), + perform, dictionaries, operations, copy, present: presentAccount, }) - ctx.effect(() => guides.watch((skills) => { account.publish({ ...account.snapshot().account, skills }) }), 'wecom: guides') } /* jscpd:ignore-end */ diff --git a/packages/connector/wecom/src/locales.ts b/packages/connector/wecom/src/locales.ts index 625833cb44..5902b09cda 100644 --- a/packages/connector/wecom/src/locales.ts +++ b/packages/connector/wecom/src/locales.ts @@ -7,14 +7,14 @@ export const zh = { 'status.disconnected': '未授权', 'status.unavailable': '暂时无法读取授权状态', 'status.connected': '已授权', + 'step.downloading': '正在下载企业微信技能', 'step.authorizing': '等待扫码授权', 'step.connecting': '正在确认授权', 'detail.disconnected': '用企业微信扫码绑定一个智能机器人。授权后,可以在对话中通过这个机器人使用企业微信的文档、日程、会议、待办和消息等功能。', 'detail.unavailable': '没能读取 wecom-cli 的授权状态,可以稍后重试。', + 'detail.missing': '没能下载企业微信技能,请确认这台电脑能访问 GitHub,然后重试。', 'detail.connected': '可以在对话中直接请 Agent 使用企业微信。', 'detail.authorizing': '在打开的页面中用企业微信扫码并确认,完成后回到这里查看结果。页面没有打开时,点击“打开扫码页面”。', - 'skills.downloading': '正在从 GitHub 下载企业微信技能,下载完成后即可在对话中使用。', - 'skills.failed': '企业微信技能没能下载,Agent 暂时用不了企业微信的子指南。请确认这台电脑能访问 GitHub,然后重试。', hint: '授权与这台电脑终端里的 wecom-cli 共用;关闭插件不会解除授权。', failed: '操作未完成,请重试', 'action.connect': '连接企业微信', @@ -44,14 +44,14 @@ export const en: Record = { 'status.disconnected': 'Not authorized', 'status.unavailable': 'Cannot read authorization right now', 'status.connected': 'Authorized', + 'step.downloading': 'Downloading the WeCom skills', 'step.authorizing': 'Waiting for the QR code scan', 'step.connecting': 'Confirming authorization', 'detail.disconnected': 'Scan a QR code with WeCom to bind a smart bot. After that, you can use WeCom docs, calendar, meetings, to-dos, messages, and other features through this bot in conversations.', 'detail.unavailable': 'The wecom-cli authorization could not be read. Try again later.', + 'detail.missing': 'The WeCom skills could not be downloaded. Check that this computer can reach GitHub, then retry.', 'detail.connected': 'Ask the agent to use WeCom directly in a conversation.', 'detail.authorizing': 'Scan the QR code with WeCom on the page that opened and confirm, then come back here to see the result. If the page did not open, select Open QR code page.', - 'skills.downloading': 'Downloading the WeCom skills from GitHub. They become available in conversations when the download finishes.', - 'skills.failed': 'The WeCom skills could not be downloaded, so the agent cannot use the WeCom guides yet. Check that this computer can reach GitHub, then retry.', hint: 'The authorization is shared with wecom-cli in this computer\'s terminal. Turning the plugin off does not revoke it.', failed: 'The action did not finish. Try again.', 'action.connect': 'Connect WeCom', @@ -78,14 +78,14 @@ export const ja: Record = { 'status.disconnected': '未認可', 'status.unavailable': '現在認可状態を読み取れません', 'status.connected': '認可済み', + 'step.downloading': 'WeCom のスキルをダウンロード中', 'step.authorizing': 'QR コードのスキャン待ち', 'step.connecting': '認可を確定中', 'detail.disconnected': 'WeCom で QR コードをスキャンしてスマートボットを紐付けます。その後、会話の中でこのボットを通じて WeCom のドキュメント、カレンダー、会議、ToDo、メッセージなどの機能を使用できます。', 'detail.unavailable': 'wecom-cli の認可状態を読み取れませんでした。しばらくしてから再試行してください。', + 'detail.missing': 'WeCom のスキルをダウンロードできませんでした。このコンピューターから GitHub にアクセスできることを確認してから、再試行してください。', 'detail.connected': '会話の中でエージェントに WeCom の使用を直接依頼できます。', 'detail.authorizing': '開いたページで WeCom を使って QR コードをスキャンして確定し、完了したらここに戻って結果を確認してください。ページが開かない場合は、「QR コードページを開く」を選択してください。', - 'skills.downloading': 'GitHub から WeCom のスキルをダウンロードしています。ダウンロードが完了すると、会話の中で使用できます。', - 'skills.failed': 'WeCom のスキルをダウンロードできなかったため、エージェントはまだ WeCom のガイドを使用できません。このコンピューターから GitHub にアクセスできることを確認してから、再試行してください。', hint: '認可は、このコンピューターのターミナルにある wecom-cli と共有されます。プラグインをオフにしても認可は解除されません。', failed: '操作が完了しませんでした。もう一度お試しください。', 'action.connect': 'WeCom を接続', @@ -112,14 +112,14 @@ export const es: Record = { 'status.disconnected': 'Sin autorizar', 'status.unavailable': 'No se puede leer la autorización en este momento', 'status.connected': 'Autorizado', + 'step.downloading': 'Descargando las habilidades de WeCom', 'step.authorizing': 'Esperando el escaneo del código QR', 'step.connecting': 'Confirmando la autorización', 'detail.disconnected': 'Escanee un código QR con WeCom para vincular un bot inteligente. Después, podrá usar en las conversaciones, a través de este bot, los documentos, el calendario, las reuniones, las tareas pendientes, los mensajes y otras funciones de WeCom.', 'detail.unavailable': 'No se pudo leer la autorización de wecom-cli. Inténtelo de nuevo más tarde.', + 'detail.missing': 'No se pudieron descargar las habilidades de WeCom. Compruebe que esta computadora puede acceder a GitHub y vuelva a intentarlo.', 'detail.connected': 'Pida al agente que use WeCom directamente en una conversación.', 'detail.authorizing': 'Escanee el código QR con WeCom en la página que se abrió y confirme; luego vuelva aquí para ver el resultado. Si la página no se abrió, seleccione “Abrir página del código QR”.', - 'skills.downloading': 'Descargando las habilidades de WeCom desde GitHub. Estarán disponibles en las conversaciones cuando termine la descarga.', - 'skills.failed': 'No se pudieron descargar las habilidades de WeCom, por lo que el agente aún no puede usar las guías de WeCom. Compruebe que esta computadora puede acceder a GitHub y vuelva a intentarlo.', hint: 'La autorización se comparte con wecom-cli en la terminal de esta computadora. Desactivar el complemento no la revoca.', failed: 'La acción no se completó. Inténtelo de nuevo.', 'action.connect': 'Conectar WeCom', @@ -146,14 +146,14 @@ export const fr: Record = { 'status.disconnected': 'Non autorisé', 'status.unavailable': 'Impossible de lire l’autorisation pour le moment', 'status.connected': 'Autorisé', + 'step.downloading': 'Téléchargement des compétences WeCom', 'step.authorizing': 'En attente du scan du code QR', 'step.connecting': 'Confirmation de l’autorisation', 'detail.disconnected': 'Scannez un code QR avec WeCom pour lier un bot intelligent. Vous pourrez ensuite utiliser dans les conversations, via ce bot, les documents, le calendrier, les réunions, les tâches, les messages et les autres fonctionnalités de WeCom.', 'detail.unavailable': 'Impossible de lire l’autorisation de wecom-cli. Réessayez plus tard.', + 'detail.missing': 'Impossible de télécharger les compétences WeCom. Vérifiez que cet ordinateur peut accéder à GitHub, puis réessayez.', 'detail.connected': 'Demandez à l’agent d’utiliser WeCom directement dans une conversation.', 'detail.authorizing': 'Scannez le code QR avec WeCom sur la page qui s’est ouverte et confirmez, puis revenez ici pour voir le résultat. Si la page ne s’est pas ouverte, sélectionnez « Ouvrir la page du code QR ».', - 'skills.downloading': 'Téléchargement des compétences WeCom depuis GitHub. Elles seront disponibles dans les conversations une fois le téléchargement terminé.', - 'skills.failed': 'Les compétences WeCom n’ont pas pu être téléchargées : l’agent ne peut donc pas encore utiliser les guides WeCom. Vérifiez que cet ordinateur peut accéder à GitHub, puis réessayez.', hint: 'L’autorisation est partagée avec wecom-cli dans le terminal de cet ordinateur. Désactiver le plugin ne la révoque pas.', failed: 'L’action n’a pas abouti. Réessayez.', 'action.connect': 'Connecter WeCom', @@ -180,14 +180,14 @@ export const de: Record = { 'status.disconnected': 'Nicht autorisiert', 'status.unavailable': 'Autorisierung kann gerade nicht gelesen werden', 'status.connected': 'Autorisiert', + 'step.downloading': 'Die Fertigkeiten von WeCom werden heruntergeladen', 'step.authorizing': 'Warten auf das Scannen des QR-Codes', 'step.connecting': 'Autorisierung wird bestätigt', 'detail.disconnected': 'Scannen Sie mit WeCom einen QR-Code, um einen smarten Bot zu verknüpfen. Danach können Sie über diesen Bot Dokumente, Kalender, Besprechungen, Aufgaben, Nachrichten und weitere Funktionen von WeCom in Unterhaltungen verwenden.', 'detail.unavailable': 'Die Autorisierung von wecom-cli konnte nicht gelesen werden. Versuchen Sie es später erneut.', + 'detail.missing': 'Die Fertigkeiten von WeCom konnten nicht heruntergeladen werden. Prüfen Sie, ob dieser Computer GitHub erreichen kann, und versuchen Sie es dann erneut.', 'detail.connected': 'Bitten Sie den Agenten, WeCom direkt in einer Unterhaltung zu verwenden.', 'detail.authorizing': 'Scannen Sie auf der geöffneten Seite den QR-Code mit WeCom, bestätigen Sie und kehren Sie dann hierher zurück, um das Ergebnis zu sehen. Falls sich die Seite nicht geöffnet hat, wählen Sie „QR-Code-Seite öffnen“.', - 'skills.downloading': 'Die Fertigkeiten von WeCom werden von GitHub heruntergeladen. Sie stehen in Unterhaltungen zur Verfügung, sobald der Download abgeschlossen ist.', - 'skills.failed': 'Die Fertigkeiten von WeCom konnten nicht heruntergeladen werden, daher kann der Agent die WeCom-Anleitungen noch nicht verwenden. Prüfen Sie, ob dieser Computer GitHub erreichen kann, und versuchen Sie es dann erneut.', hint: 'Die Autorisierung wird mit wecom-cli im Terminal dieses Computers geteilt. Wenn Sie das Plugin deaktivieren, wird sie nicht widerrufen.', failed: 'Die Aktion wurde nicht abgeschlossen. Versuchen Sie es erneut.', 'action.connect': 'WeCom verbinden', @@ -214,14 +214,14 @@ export const ru: Record = { 'status.disconnected': 'Не авторизовано', 'status.unavailable': 'Сейчас не удаётся прочитать состояние авторизации', 'status.connected': 'Авторизовано', + 'step.downloading': 'Загрузка навыков WeCom', 'step.authorizing': 'Ожидание сканирования QR-кода', 'step.connecting': 'Подтверждение авторизации', 'detail.disconnected': 'Отсканируйте QR-код в WeCom, чтобы привязать умного бота. После этого в беседах через этого бота можно будет использовать документы, календарь, встречи, задачи, сообщения и другие функции WeCom.', 'detail.unavailable': 'Не удалось прочитать авторизацию wecom-cli. Повторите попытку позже.', + 'detail.missing': 'Не удалось загрузить навыки WeCom. Убедитесь, что этот компьютер может подключиться к GitHub, затем повторите попытку.', 'detail.connected': 'Попросите агента использовать WeCom прямо в беседе.', 'detail.authorizing': 'Отсканируйте QR-код в WeCom на открывшейся странице и подтвердите, затем вернитесь сюда, чтобы увидеть результат. Если страница не открылась, нажмите «Открыть страницу с QR-кодом».', - 'skills.downloading': 'Навыки WeCom загружаются с GitHub. Они станут доступны в беседах, когда загрузка завершится.', - 'skills.failed': 'Не удалось загрузить навыки WeCom, поэтому агент пока не может использовать руководства WeCom. Убедитесь, что этот компьютер может подключиться к GitHub, затем повторите попытку.', hint: 'Авторизация общая с wecom-cli в терминале этого компьютера. Отключение плагина её не отменяет.', failed: 'Действие не завершено. Повторите попытку.', 'action.connect': 'Подключить WeCom', @@ -248,14 +248,14 @@ export const pt: Record = { 'status.disconnected': 'Não autorizado', 'status.unavailable': 'Não é possível ler a autorização no momento', 'status.connected': 'Autorizado', + 'step.downloading': 'Baixando as habilidades do WeCom', 'step.authorizing': 'Aguardando a leitura do código QR', 'step.connecting': 'Confirmando a autorização', 'detail.disconnected': 'Leia um código QR com o WeCom para vincular um bot inteligente. Depois disso, você poderá usar nas conversas, por meio desse bot, os documentos, a agenda, as reuniões, as tarefas, as mensagens e outros recursos do WeCom.', 'detail.unavailable': 'Não foi possível ler a autorização do wecom-cli. Tente novamente mais tarde.', + 'detail.missing': 'Não foi possível baixar as habilidades do WeCom. Verifique se este computador consegue acessar o GitHub e tente novamente.', 'detail.connected': 'Peça ao agente que use o WeCom diretamente em uma conversa.', 'detail.authorizing': 'Leia o código QR com o WeCom na página que foi aberta e confirme; depois volte aqui para ver o resultado. Se a página não abriu, selecione “Abrir página do código QR”.', - 'skills.downloading': 'Baixando as habilidades do WeCom do GitHub. Elas ficarão disponíveis nas conversas quando o download terminar.', - 'skills.failed': 'Não foi possível baixar as habilidades do WeCom, então o agente ainda não pode usar os guias do WeCom. Verifique se este computador consegue acessar o GitHub e tente novamente.', hint: 'A autorização é compartilhada com o wecom-cli no terminal deste computador. Desativar o plugin não a revoga.', failed: 'A ação não foi concluída. Tente novamente.', 'action.connect': 'Conectar WeCom', diff --git a/packages/connector/wecom/src/presentation.ts b/packages/connector/wecom/src/presentation.ts index 86b1bc2d03..fecdb017e3 100644 --- a/packages/connector/wecom/src/presentation.ts +++ b/packages/connector/wecom/src/presentation.ts @@ -1,10 +1,8 @@ /** The WeCom authorization section the Plugins page shows for each Host view. */ import type { CliAccountText } from '@deepseek-ai/dsh-cli-account/types' import type { - ConnectorAccountButton, ConnectorAccountCopy, ConnectorAccountDisplay, ConnectorAccountFailure, ConnectorAccountNote, - ConnectorAccountOperation, + ConnectorAccountButton, ConnectorAccountCopy, ConnectorAccountDisplay, ConnectorAccountFailure, ConnectorAccountOperation, } from '@deepseek-ai/dsh-client-ui-connector-account/types' -import type { UpstreamSkillsState } from '@deepseek-ai/dsh-upstream-skills/types' import { assertNever } from '@deepseek-ai/dsh-util-values' import type { WecomTextKey } from './locales.ts' import type { WecomOperationKind, WecomState } from './types.ts' @@ -44,24 +42,15 @@ const CHECK = { kind: 'start', operation: 'check' } as const const CONNECT = { kind: 'start', operation: 'connect' } as const /* jscpd:ignore-end */ -/* jscpd:ignore-start -- CLI app plugins whose guides download report the same states, each in its own text. */ -/** The row that reports guides that are not in place yet; a failed download offers a check, which restarts it. */ -function skillsNotes(skills: UpstreamSkillsState, text: Text): ConnectorAccountNote[] { - switch (skills) { - case 'installed': return [] - case 'downloading': return [{ text: text('skills.downloading') }] - case 'failed': return [{ text: text('skills.failed'), button: { label: text('action.retry'), command: CHECK } }] - /* v8 ignore next -- closed skills state union */ - default: return assertNever(skills) - } +function cancelButton(text: Text): ConnectorAccountButton { + return { label: text('action.cancel'), command: { kind: 'cancel' }, variant: 'ghost' } } -/* jscpd:ignore-end */ /** The bound bot's QR-code page and the operation's cancel, while an authorization runs. */ function connectingButtons(operation: NonNullable, text: Text): ConnectorAccountButton[] { const buttons: ConnectorAccountButton[] = [] if (operation.authorizationUrl !== undefined) buttons.push({ label: text('action.open'), command: { kind: 'open' }, variant: 'primary' }) - if (operation.cancellable) buttons.push({ label: text('action.cancel'), command: { kind: 'cancel' }, variant: 'ghost' }) + if (operation.cancellable) buttons.push(cancelButton(text)) return buttons } @@ -69,34 +58,40 @@ function connectingButtons(operation: NonNullable, text * The authorization section for one Host view. * @param view - the authorization, the operation in progress, and the last result. * @param text - writes a key of the WeCom text in every shipped language. - * @returns the phase, status, tag, buttons, detail, bound-bot and guide download rows, and failure guidance. + * @returns the phase, status, tag, buttons, detail, bound-bot row, and failure guidance. */ export function presentAccount(view: WecomState, text: Text): ConnectorAccountDisplay { - const notes = skillsNotes(view.account.skills, text) const { operation } = view - if (operation?.kind === 'check') return { phase: 'checking', status: text('status.checking'), buttons: [], notes } + /* jscpd:ignore-start -- CLI app plugins whose check waits for a download show a running check alike, each with its own text. */ + if (operation?.kind === 'check') { + return { + phase: 'checking', status: text(operation.phase === 'downloading' ? 'step.downloading' : 'status.checking'), + buttons: operation.cancellable ? [cancelButton(text)] : [], notes: [], + } + } + /* jscpd:ignore-end */ if (operation !== undefined) { return { phase: 'connecting', status: text(operation.phase === 'authorizing' ? 'step.authorizing' : 'step.connecting'), - badge: text('badge.connecting'), buttons: connectingButtons(operation, text), notes, + badge: text('badge.connecting'), buttons: connectingButtons(operation, text), notes: [], ...operation.authorizationUrl === undefined ? {} : { detail: text('detail.authorizing') }, } } const failed = view.result?.outcome === 'failed' // The Service adds the failed command and its exit code. const failure: { failure?: ConnectorAccountFailure } = failed ? { failure: { text: text('failed') } } : {} + const unavailable = (missing: boolean): ConnectorAccountDisplay => ({ + phase: 'unavailable', status: text('status.unavailable'), badge: text('badge.unavailable'), + buttons: [{ label: text('action.retry'), command: CHECK }], detail: text(missing ? 'detail.missing' : 'detail.unavailable'), notes: [], ...failure, + }) switch (view.account.state) { - case 'unchecked': - if (!failed) return { phase: 'checking', status: text('status.checking'), buttons: [], notes } - return { - phase: 'unavailable', status: text('status.unavailable'), badge: text('badge.unavailable'), - buttons: [{ label: text('action.retry'), command: CHECK }], detail: text('detail.unavailable'), notes, ...failure, - } + case 'unchecked': return failed ? unavailable(false) : { phase: 'checking', status: text('status.checking'), buttons: [], notes: [] } + case 'not-installed': return unavailable(true) case 'unauthorized': return { phase: 'disconnected', status: text('status.disconnected'), badge: text('badge.disconnected'), buttons: [{ label: text('action.connect'), command: CONNECT, variant: 'primary' }], connect: CONNECT, - detail: text('detail.disconnected'), notes, ...failure, + detail: text('detail.disconnected'), notes: [], ...failure, } case 'authorized': return { @@ -107,7 +102,7 @@ export function presentAccount(view: WecomState, text: Text): ConnectorAccountDi confirm: { title: text('rebind.title'), body: text('rebind.body'), label: text('action.rebind') }, }], detail: text('detail.connected'), - notes: [...view.account.botId === undefined ? [] : [{ text: text('bot.bound', { id: view.account.botId }) }], ...notes], + notes: view.account.botId === undefined ? [] : [{ text: text('bot.bound', { id: view.account.botId }) }], ...failure, } /* v8 ignore next -- closed account state union */ diff --git a/packages/connector/wecom/src/types.ts b/packages/connector/wecom/src/types.ts index 39bea76947..41943bc18e 100644 --- a/packages/connector/wecom/src/types.ts +++ b/packages/connector/wecom/src/types.ts @@ -1,22 +1,22 @@ /** Credential-free WeCom authorization and operation views the Plugins page presenter reads. */ import type { CliAccountView } from '@deepseek-ai/dsh-cli-account/types' -import type { UpstreamSkillsState } from '@deepseek-ai/dsh-upstream-skills/types' -/** The CLI's authorization as the latest `auth show` reported it, and where the upstream guides stand. */ +/** + * The CLI's authorization as the latest `auth show` reported it. `not-installed` means the upstream guides were + * missing and the download that check waited for did not finish. + */ export interface WecomAccountState { - readonly state: 'unchecked' | 'unauthorized' | 'authorized' + readonly state: 'unchecked' | 'not-installed' | 'unauthorized' | 'authorized' /** The bound bot's id, when the CLI reports one with an authorized state. */ readonly botId?: string - /** Whether the guides the `wecom` skill indexes are in place, downloading, or unavailable until a check retries them. */ - readonly skills: UpstreamSkillsState } /** The operations the Plugins page starts. */ export type WecomOperationKind = 'check' | 'connect' -/** The WeCom step of an operation, besides the Service's `checking` and `cancelling`. */ -export type WecomPhase = 'authorizing' +/** WeCom steps of an operation, besides the Service's `checking` and `cancelling`. */ +export type WecomPhase = 'downloading' | 'authorizing' /** The wecom-cli commands an operation runs; a failed operation reports its last one with that command's exit code. */ export type WecomCommand = 'auth-init' | 'auth-status' diff --git a/packages/connector/wecom/tests/account.spec.ts b/packages/connector/wecom/tests/account.spec.ts index e7f74ae04d..4ef7155ea1 100644 --- a/packages/connector/wecom/tests/account.spec.ts +++ b/packages/connector/wecom/tests/account.spec.ts @@ -1,5 +1,8 @@ -/** Authorization operations over a scripted wecom-cli: checks, QR-code connection, cancellation, and the Plugins page wiring. */ -import { mkdtemp, rm } from 'node:fs/promises' +/** + * Authorization operations over a scripted wecom-cli: checks, the guides' download a check waits for, QR-code + * connection, cancellation, and the Plugins page wiring. + */ +import { mkdir, mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import type { Context } from '@deepseek-ai/cordis' @@ -7,6 +10,7 @@ import type { ConnectorOperationId } from '@deepseek-ai/dsh-client-ui-connector- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { executableFileName } from '../src/directory.ts' import * as Wecom from '../src/index.ts' +import { WECOM_SKILLS } from '../src/skills.ts' import type { WecomOperationKind, WecomState } from '../src/types.ts' import { createHost, type CliReply, type ScriptedProcess, type ScriptedSubprocess, type WecomPage } from './harness.ts' @@ -69,9 +73,9 @@ describe('WeCom account operations', () => { beforeEach(() => load()) it.each<[string, CliReply, WecomState['account']]>([ - ['an authorized bot', AUTHORIZED, { state: 'authorized', botId: 'bot-1', skills: 'installed' }], - ['an authorized bot whose id the CLI omits', { stdout: 'Status: authorized\n' }, { state: 'authorized', skills: 'installed' }], - ['no authorization', UNAUTHORIZED, { state: 'unauthorized', skills: 'installed' }], + ['an authorized bot', AUTHORIZED, { state: 'authorized', botId: 'bot-1' }], + ['an authorized bot whose id the CLI omits', { stdout: 'Status: authorized\n' }, { state: 'authorized' }], + ['no authorization', UNAUTHORIZED, { state: 'unauthorized' }], ])('checks %s', async (_name, reply, expected) => { script[STATUS] = [reply] const id = start('check') @@ -86,7 +90,7 @@ describe('WeCom account operations', () => { script[STATUS] = [reply] const result = await settled(start('check')) expect(result).toEqual({ - account: { state: 'unchecked', skills: 'installed' }, + account: { state: 'unchecked' }, result: { id: result.result?.id, kind: 'check', outcome: 'failed', failure: { command: 'auth-status', exitCode: reply.exitCode ?? 0 } }, }) expect(errors()).toEqual([['wecom: account operation failed: %o', { @@ -113,7 +117,7 @@ describe('WeCom account operations', () => { await vi.waitFor(() => { expect(account.snapshot().operation).toMatchObject({ phase: 'authorizing', authorizationUrl: QR_LINK }) }) authorizing.reply({ stdout: 'Authorized\n' }) - expect(await settled(id)).toEqual({ account: { state: 'authorized', botId: 'bot-1', skills: 'installed' }, result: { id, kind: 'connect', outcome: 'succeeded' } }) + expect(await settled(id)).toEqual({ account: { state: 'authorized', botId: 'bot-1' }, result: { id, kind: 'connect', outcome: 'succeeded' } }) stop() expect(offered).toEqual([QR_LINK]) expect(commands()).toEqual([INIT, STATUS]) @@ -140,7 +144,7 @@ describe('WeCom account operations', () => { const cancelling = account.cancel(id) expect(account.snapshot().operation).toEqual({ id, kind: 'connect', phase: 'cancelling', cancellable: false }) await cancelling - expect(account.snapshot()).toEqual({ account: { state: 'unchecked', skills: 'installed' }, result: { id, kind: 'connect', outcome: 'cancelled' } }) + expect(account.snapshot()).toEqual({ account: { state: 'unchecked' }, result: { id, kind: 'connect', outcome: 'cancelled' } }) expect(subprocess.processes[0]?.terminated).toBe(true) expect(errors()).toEqual([]) }) @@ -158,41 +162,70 @@ describe('WeCom account operations', () => { }) }) -describe('WeCom guides the plugin downloads', () => { +describe('WeCom guides a check waits for', () => { let home: string /** Answers each request for the guides' archive. */ - let archive: () => Promise + let archive: (signal: AbortSignal) => Promise + + /** A request that stays unanswered until its download is stopped. */ + const unanswered = (signal: AbortSignal): Promise => new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => { reject(signal.reason as Error) }, { once: true }) + }) + /** Where the upstream skills Service publishes the guides without a profile. */ + const published = (): string => join(home, 'cache', 'wecom', `skills-${WECOM_SKILLS.sha256.slice(0, 16)}`) beforeEach(async () => { home = await mkdtemp(join(tmpdir(), 'dsh-wecom-home-')) vi.stubEnv('DSH_HOME', home) - vi.stubGlobal('fetch', () => archive()) + vi.stubGlobal('fetch', (_url: string, init: { signal: AbortSignal }) => archive(init.signal)) }) afterEach(() => rm(home, { recursive: true, force: true })) - it('restarts a failed download of the guides on each check without waiting for it, and reports the state it leaves', async () => { + it('reports guides whose download did not finish as not installed, without running a command', async () => { archive = () => Promise.reject(new Error('offline')) await load({}) - await vi.waitFor(() => { expect(account.snapshot().account.skills).toBe('failed') }) + expect(account.snapshot()).toEqual({ account: { state: 'unchecked' } }) - archive = () => new Promise(() => {}) - script[STATUS] = [AUTHORIZED] const id = start('check') - expect(account.snapshot().account).toEqual({ state: 'unchecked', skills: 'downloading' }) - expect(await settled(id)).toEqual({ account: { state: 'authorized', botId: 'bot-1', skills: 'downloading' }, result: { id, kind: 'check', outcome: 'succeeded' } }) + expect(account.snapshot().operation).toEqual({ id, kind: 'check', phase: 'downloading', cancellable: true }) + expect(await settled(id)).toEqual({ account: { state: 'not-installed' }, result: { id, kind: 'check', outcome: 'failed' } }) + expect(errors()).toEqual([['wecom: account operation failed: %o', { id, kind: 'check', phase: 'downloading' }]]) + expect(commands()).toEqual([]) }) - it('reports a new state of the guides with the current authorization', async () => { - const download = Promise.withResolvers() - archive = () => download.promise + it('downloads the guides again on the next check, in a step of its own before the status command', async () => { + archive = () => Promise.reject(new Error('offline')) await load({}) + await settled(start('check')) + + const request = Promise.withResolvers() + archive = () => request.promise script[STATUS] = [AUTHORIZED] - expect((await settled(start('check'))).account).toEqual({ state: 'authorized', botId: 'bot-1', skills: 'downloading' }) + const id = start('check') + expect(account.snapshot().operation).toEqual({ id, kind: 'check', phase: 'downloading', cancellable: true }) + expect(commands()).toEqual([]) + // No fixture archive matches the pinned digest, so the guides arrive the way another process publishes them. + await mkdir(published(), { recursive: true }) + request.reject(new Error('offline')) - download.reject(new Error('offline')) + expect(await settled(id)).toEqual({ account: { state: 'authorized', botId: 'bot-1' }, result: { id, kind: 'check', outcome: 'succeeded' } }) + expect(commands()).toEqual([STATUS]) + }) - await vi.waitFor(() => { expect(account.snapshot().account).toEqual({ state: 'authorized', botId: 'bot-1', skills: 'failed' }) }) + it('cancels a download of the guides, which leaves them not installed and runs no command', async () => { + archive = unanswered + await load({}) + const id = start('check') + expect(account.snapshot().operation).toEqual({ id, kind: 'check', phase: 'downloading', cancellable: true }) + + const cancelling = account.cancel(id) + expect(account.snapshot().operation).toEqual({ id, kind: 'check', phase: 'cancelling', cancellable: false }) + await cancelling + + expect(account.snapshot()).toEqual({ account: { state: 'not-installed' }, result: { id, kind: 'check', outcome: 'cancelled' } }) + expect(commands()).toEqual([]) + expect(errors()).toEqual([]) }) }) @@ -205,9 +238,9 @@ describe('WeCom on the Plugins page', () => { script[STATUS] = [UNAUTHORIZED] account.refresh() const check = account.snapshot().operation - expect(account.snapshot()).toMatchObject({ account: { state: 'unchecked', skills: 'installed' }, operation: { kind: 'check' } }) + expect(account.snapshot()).toMatchObject({ account: { state: 'unchecked' }, operation: { kind: 'check' } }) expect(await finished(check!.id)).toMatchObject({ kind: 'check', outcome: 'succeeded' }) - expect(account.snapshot().account).toEqual({ state: 'unauthorized', skills: 'installed' }) + expect(account.snapshot().account).toEqual({ state: 'unauthorized' }) expect(subprocess.lookups[0]?.command).toBe(join(binDir, executableFileName(process.platform))) expect(await finished(start('check'))).toMatchObject({ kind: 'check', outcome: 'succeeded' }) diff --git a/packages/connector/wecom/tests/plugin.spec.ts b/packages/connector/wecom/tests/plugin.spec.ts index b958e87041..75da31b908 100644 --- a/packages/connector/wecom/tests/plugin.spec.ts +++ b/packages/connector/wecom/tests/plugin.spec.ts @@ -53,15 +53,17 @@ describe('WeCom plugin', () => { expect(await ctx.skills.get('wecomcli-shared')).toBeUndefined() }) - it('reports the guides as downloading and then failed when no skills URL answers, and lists no skill', async () => { + it('gives no CLI path and lists no skill while the guides are missing, as when no skills URL answers', async () => { const home = await mkdtemp(join(tmpdir(), 'dsh-wecom-home-')) vi.stubEnv('DSH_HOME', home) try { await start({ skillsUrls: ['https://127.0.0.1:9'], skillsTimeoutMs: 5_000 }) await ctx.plugin(Wecom, { binDir }) - const account = host.pages[0]!.source - expect(account.snapshot().account.skills).toBe('downloading') - await vi.waitFor(() => { expect(account.snapshot().account.skills).toBe('failed') }, { timeout: 10_000 }) + expect(await runtimeContext()).toEqual([]) + const warnings = (): unknown[] => ctx.logger.buffer.filter(message => message.type === 'warn').map((message): unknown => message.args[0]) + await vi.waitFor(() => { expect(warnings()).toContain('wecom: the upstream skills are not available') }, { timeout: 10_000 }) + expect(host.pages[0]!.source.snapshot()).toEqual({ account: { state: 'unchecked' } }) + expect(await runtimeContext()).toEqual([]) expect(await ctx.skills.list()).toEqual([]) } finally { await rm(home, { recursive: true, force: true }) @@ -90,7 +92,7 @@ describe('WeCom plugin', () => { const fiber = await ctx.plugin(Wecom, { binDir, skillsDir }) expect(host.pages).toHaveLength(1) expect(host.pages[0]).toMatchObject({ key: WECOM_PACKAGE, packageName: WECOM_PACKAGE }) - expect(host.pages[0]!.source.snapshot().account).toEqual({ state: 'unchecked', skills: 'installed' }) + expect(host.pages[0]!.source.snapshot().account).toEqual({ state: 'unchecked' }) await fiber.dispose() diff --git a/packages/connector/wecom/tests/presentation.spec.ts b/packages/connector/wecom/tests/presentation.spec.ts index fa421addf4..166598ca0c 100644 --- a/packages/connector/wecom/tests/presentation.spec.ts +++ b/packages/connector/wecom/tests/presentation.spec.ts @@ -1,4 +1,4 @@ -/** The WeCom section offers each state's next step, the guide download rows, and failure guidance, in every shipped language. */ +/** The WeCom section offers each state's next step, the guides' download step, and failure guidance, in every shipped language. */ import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' import type { ConnectorAccountDisplay, ConnectorOperationId } from '@deepseek-ai/dsh-client-ui-connector-account/types' import { rm } from 'node:fs/promises' @@ -36,7 +36,7 @@ afterAll(async () => { const presentAccount = (view: WecomState): ConnectorAccountDisplay => page.present(view) -const unauthorized = { state: 'unauthorized', skills: 'installed' } as const +const unauthorized = { state: 'unauthorized' } as const it('offers the next step for each state', () => { let shown = presentAccount({ account: unauthorized }) @@ -61,18 +61,18 @@ it('offers the next step for each state', () => { shown = presentAccount({ account: unauthorized, operation: { id: OP, kind: 'connect', phase: 'checking', cancellable: false } }) expect(shown).toMatchObject({ status: say('step.connecting'), buttons: [] }) - shown = presentAccount({ account: { state: 'authorized', botId: 'bot-1', skills: 'installed' } }) + shown = presentAccount({ account: { state: 'authorized', botId: 'bot-1' } }) expect(shown).toMatchObject({ phase: 'connected', status: say('status.connected'), badge: say('badge.connected'), detail: say('detail.connected') }) expect(shown.buttons).toMatchObject([{ label: say('action.rebind'), command: CONNECT, confirm: { title: say('rebind.title'), body: say('rebind.body'), label: say('action.rebind') }, }]) expect(shown.notes).toMatchObject([{ text: { zh: '已绑定机器人:bot-1', en: 'Bound bot: bot-1' } }]) - expect(presentAccount({ account: { state: 'authorized', skills: 'installed' } }).notes).toEqual([]) + expect(presentAccount({ account: { state: 'authorized' } }).notes).toEqual([]) for (const view of [ - { account: { state: 'authorized', skills: 'installed' }, operation: { id: OP, kind: 'check', phase: 'checking', cancellable: false } }, - { account: { state: 'unchecked', skills: 'installed' } }, + { account: { state: 'authorized' }, operation: { id: OP, kind: 'check', phase: 'checking', cancellable: false } }, + { account: { state: 'unchecked' } }, ] as const satisfies readonly WecomState[]) { shown = presentAccount(view) expect(shown).toMatchObject({ phase: 'checking', status: say('status.checking'), buttons: [] }) @@ -87,24 +87,30 @@ it('reports a failed connection with its diagnostic items, and no failure for a shown = presentAccount({ account: unauthorized, result: { id: OP, kind: 'connect', outcome: 'failed' } }) expect(shown.failure).toMatchObject({ text: say('failed') }) expect(shown.failure).not.toHaveProperty('details') - shown = presentAccount({ account: { state: 'authorized', skills: 'installed' }, result: { id: OP, kind: 'connect', outcome: 'failed' } }) + shown = presentAccount({ account: { state: 'authorized' }, result: { id: OP, kind: 'connect', outcome: 'failed' } }) expect(shown.failure).toBeDefined() expect(presentAccount({ account: unauthorized, result: { id: OP, kind: 'connect', outcome: 'cancelled' } }).failure).toBeUndefined() }) it('retries an unreadable authorization by checking again', () => { const shown = presentAccount({ - account: { state: 'unchecked', skills: 'installed' }, result: { id: OP, kind: 'check', outcome: 'failed', failure: { command: 'auth-status', exitCode: 1 } }, + account: { state: 'unchecked' }, result: { id: OP, kind: 'check', outcome: 'failed', failure: { command: 'auth-status', exitCode: 1 } }, }) expect(shown).toMatchObject({ phase: 'unavailable', status: say('status.unavailable'), badge: say('badge.unavailable'), detail: say('detail.unavailable') }) expect(shown.buttons).toMatchObject([{ label: say('action.retry'), command: CHECK }]) expect(shown.failure?.details).toEqual(['auth-status', 'exit 1']) }) -it('reports guides that are downloading, and retries a failed download by checking again', () => { - expect(presentAccount({ account: { state: 'authorized', skills: 'downloading' } }).notes).toMatchObject([{ text: say('skills.downloading') }]) - const [note] = presentAccount({ account: { state: 'authorized', skills: 'failed' } }).notes - expect(note).toMatchObject({ text: say('skills.failed'), button: { label: say('action.retry'), command: CHECK } }) +it('shows the guides\' download with its cancel, and retries one that did not finish by checking again', () => { + let shown = presentAccount({ account: { state: 'unchecked' }, operation: { id: OP, kind: 'check', phase: 'downloading', cancellable: true } }) + expect(shown).toMatchObject({ phase: 'checking', status: say('step.downloading'), notes: [] }) + expect(shown.buttons).toMatchObject([{ label: say('action.cancel'), command: { kind: 'cancel' }, variant: 'ghost' }]) + + shown = presentAccount({ account: { state: 'not-installed' }, result: { id: OP, kind: 'check', outcome: 'failed' } }) + expect(shown).toMatchObject({ phase: 'unavailable', status: say('status.unavailable'), badge: say('badge.unavailable'), detail: say('detail.missing') }) + expect(shown.buttons).toMatchObject([{ label: say('action.retry'), command: CHECK }]) + expect(shown.failure).toMatchObject({ text: say('failed') }) + expect(presentAccount({ account: { state: 'not-installed' }, result: { id: OP, kind: 'check', outcome: 'cancelled' } }).failure).toBeUndefined() }) it('names the section, its activation prompt, and the notice a connection reports', () => { diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 62485721c4..5dd6944cd9 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -599,7 +599,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ methods: [ { signature: 'register( registration: CliAccountRegistration, ): CliAccountHandle', - description: 'Register the calling plugin\'s CLI and account: add the CLI\'s absolute path to required runtime context, run the plugin\'s account operations one at a time, and show the account on the Plugins page while `connectorAccounts` is loaded. The registration belongs to the calling plugin: unloading that plugin withdraws it, after the active operation and the CLI processes it started have stopped.', + description: 'Register the calling plugin\'s CLI and account: add the CLI\'s absolute path to required runtime context, run the plugin\'s account operations one at a time, and show the account on the Plugins page while `connectorAccounts` is loaded. With a `prepare` step, the path stays out of runtime context while the step reports that something is missing, and each check first runs the step. The registration belongs to the calling plugin: unloading that plugin withdraws it, after the active operation and the CLI processes it started have stopped.', parameters: [{ name: 'registration', description: 'the plugin\'s CLI, account operations, and Plugins page text.' }], returns: 'the handle for the plugin\'s own reads and updates of the account.', throws: ['when the runtime-context name `:cli` is already registered.'], @@ -5023,9 +5023,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ methods: [ { signature: 'register(registration: UpstreamSkillsRegistration): UpstreamSkillsHandle', - description: 'Register the calling plugin\'s entry skill and start downloading the upstream files unless they are in place. The download starts at load so that a session without a client also gets the skill; a failure is logged as a warning and waits for `retry()`. In a profile, the files go to that profile\'s own directory for the plugin, and the registration deletes the other pins there once, the first time its own pin is in place. The registration belongs to the calling plugin: unloading that plugin aborts the download and removes the entry skill.', + description: 'Register the calling plugin\'s entry skill and start downloading the upstream files unless they are in place. The download starts at load so that a session without a client also gets the skill; a failure is logged as a warning and the files stay missing until a call of `install()` downloads them. In a profile, the files go to that profile\'s own directory for the plugin, and the registration deletes the other pins there once, the first time its own pin is in place. The registration belongs to the calling plugin: unloading that plugin aborts the download and removes the entry skill.', parameters: [{ name: 'registration', description: 'the plugin\'s provider name, entry, pinned files, and optional skills directory.' }], - returns: 'the handle the plugin\'s view observes and its check retries.', + returns: 'the handle the plugin reads the files\' presence from and waits for the download through.', throws: ['when the entry has no skill name or description in its frontmatter, `skillsDir` is not a directory, or a skill provider named `name` is already registered.'], }, ], @@ -6846,9 +6846,13 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'CliAccountHandle', declaration: 'export interface CliAccountHandle {\n snapshot(): CliAccountView;\n publish(account: Account): void;\n refresh(): void;\n dispose(): Promise;\n}', }, + { + name: 'CliAccountPreparation', + declaration: 'export interface CliAccountPreparation {\n readonly phase: Phase;\n readonly unprepared: Account;\n ready(): boolean;\n run(signal: AbortSignal): Promise;\n}', + }, { name: 'CliAccountRegistration', - declaration: 'export interface CliAccountRegistration {\n readonly name: string;\n readonly packageName: string;\n readonly cli: CliPathContext;\n readonly account: Account;\n readonly check: Kind;\n readonly cancellable: readonly Phase[];\n readonly authorizationHosts: readonly string[];\n perform(kind: Kind, control: CliOperationControl, signal: AbortSignal): Promise;\n readonly dictionaries: CliAccountDictionaries;\n operations(text: CliAccountText): readonly ConnectorAccountOperation[];\n copy(text: CliAccountText): ConnectorAccountCopy;\n present(view: CliAccountView, text: CliAccountText): ConnectorAccountDisplay;\n}', + declaration: 'export interface CliAccountRegistration {\n readonly name: string;\n readonly packageName: string;\n readonly cli: CliPathContext;\n readonly prepare?: CliAccountPreparation;\n readonly account: Account;\n readonly check: Kind;\n readonly cancellable: readonly Phase[];\n readonly authorizationHosts: readonly string[];\n perform(kind: Kind, control: CliOperationControl, signal: AbortSignal): Promise;\n readonly dictionaries: CliAccountDictionaries;\n operations(text: CliAccountText): readonly ConnectorAccountOperation[];\n copy(text: CliAccountText): ConnectorAccountCopy;\n present(view: CliAccountView, text: CliAccountText): ConnectorAccountDisplay;\n}', }, { name: 'CliAccountText', @@ -6876,7 +6880,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'CliPathContext', - declaration: 'export interface CliPathContext {\n readonly product: string;\n readonly program: string;\n readonly executable: string;\n readonly scripts?: boolean;\n readonly ready?: () => boolean;\n}', + declaration: 'export interface CliPathContext {\n readonly product: string;\n readonly program: string;\n readonly executable: string;\n readonly scripts?: boolean;\n}', }, { name: 'CliRunOptions', @@ -11548,16 +11552,12 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'UpstreamSkillsHandle', - declaration: 'export interface UpstreamSkillsHandle {\n readonly directory: string;\n readonly state: UpstreamSkillsState;\n watch(listener: (state: UpstreamSkillsState) => void): () => void;\n retry(): void;\n dispose(): void;\n}', + declaration: 'export interface UpstreamSkillsHandle {\n readonly directory: string;\n installed(): boolean;\n install(signal: AbortSignal): Promise;\n dispose(): void;\n}', }, { name: 'UpstreamSkillsRegistration', declaration: 'export interface UpstreamSkillsRegistration {\n readonly name: string;\n readonly entry: string;\n readonly set: UpstreamSkillSet;\n readonly skillsDir?: string | undefined;\n}', }, - { - name: 'UpstreamSkillsState', - declaration: 'export type UpstreamSkillsState = \'installed\' | \'downloading\' | \'failed\';', - }, { name: 'UserMessage', declaration: 'export interface UserMessage extends MessageBase {\n readonly role: \'user\';\n}', From cfe3319a7045e5faf202c5c8c872a47e355238ab Mon Sep 17 00:00:00 2001 From: gengruilin Date: Sun, 22 Nov 2026 14:06:34 +0800 Subject: [PATCH 3/8] fix(cli-account): reset the unprepared account once nothing is missing After a prepare step that failed or was cancelled, the published account is the registration's `unprepared` object. A later check that found nothing missing, because its own step succeeded or the files arrived another way, ran `perform` with that account still published; a `perform` that failed without publishing left it, so the page kept reporting a missing download that was in place. The Service now publishes the registration's first account before `perform` in that case. Feishu shows the retry view for a check that failed before the account was read; it showed the checking view without a button. Refs #8942 --- docs/subsystems/boot.md | 5 ++-- docs/subsystems/boot.zh.md | 5 ++-- .../connector/cli-account/README.i18n.yaml | 4 +-- packages/connector/cli-account/README.md | 2 +- packages/connector/cli-account/README.zh.md | 2 +- packages/connector/cli-account/src/index.ts | 25 ++++++++++------- packages/connector/cli-account/src/types.ts | 5 +++- .../cli-account/tests/service.spec.ts | 26 ++++++++++++++++++ packages/connector/dingtalk/README.i18n.yaml | 4 +-- packages/connector/dingtalk/README.md | 2 +- packages/connector/dingtalk/README.zh.md | 2 +- packages/connector/feishu/README.i18n.yaml | 4 +-- packages/connector/feishu/README.md | 2 +- packages/connector/feishu/README.zh.md | 2 +- packages/connector/feishu/src/presentation.ts | 21 +++++++-------- .../connector/feishu/tests/download.spec.ts | 27 +++++++++++++++++++ .../feishu/tests/presentation.spec.ts | 12 +++++++++ .../tencent-meeting/README.i18n.yaml | 4 +-- packages/connector/tencent-meeting/README.md | 2 +- .../connector/tencent-meeting/README.zh.md | 2 +- packages/connector/wecom/README.i18n.yaml | 4 +-- packages/connector/wecom/README.md | 2 +- packages/connector/wecom/README.zh.md | 2 +- .../extensions/tool-cordis/src/api-catalog.ts | 2 +- 24 files changed, 121 insertions(+), 47 deletions(-) diff --git a/docs/subsystems/boot.md b/docs/subsystems/boot.md index 9a460428fb..4973b83d42 100644 --- a/docs/subsystems/boot.md +++ b/docs/subsystems/boot.md @@ -127,8 +127,9 @@ Holds what CLI app plugins register: for each plugin, the CLI path the model rea * Register the calling plugin's CLI and account: add the CLI's absolute path to required runtime context, run the * plugin's account operations one at a time, and show the account on the Plugins page while `connectorAccounts` is * loaded. With a `prepare` step, the path stays out of runtime context while the step reports that something is - * missing, and each check first runs the step. The registration belongs to the calling plugin: unloading that plugin - * withdraws it, after the active operation and the CLI processes it started have stopped. + * missing, and each check first runs the step; a check that starts with nothing missing replaces an account the + * step left `unprepared` with the registration's first account. The registration belongs to the calling plugin: + * unloading that plugin withdraws it, after the active operation and the CLI processes it started have stopped. * @param registration - the plugin's CLI, account operations, and Plugins page text. * @returns the handle for the plugin's own reads and updates of the account. * @throws when the runtime-context name `:cli` is already registered. diff --git a/docs/subsystems/boot.zh.md b/docs/subsystems/boot.zh.md index 7b8d4265f0..461b89b4c5 100644 --- a/docs/subsystems/boot.zh.md +++ b/docs/subsystems/boot.zh.md @@ -127,8 +127,9 @@ Holds what CLI app plugins register: for each plugin, the CLI path the model rea * Register the calling plugin's CLI and account: add the CLI's absolute path to required runtime context, run the * plugin's account operations one at a time, and show the account on the Plugins page while `connectorAccounts` is * loaded. With a `prepare` step, the path stays out of runtime context while the step reports that something is - * missing, and each check first runs the step. The registration belongs to the calling plugin: unloading that plugin - * withdraws it, after the active operation and the CLI processes it started have stopped. + * missing, and each check first runs the step; a check that starts with nothing missing replaces an account the + * step left `unprepared` with the registration's first account. The registration belongs to the calling plugin: + * unloading that plugin withdraws it, after the active operation and the CLI processes it started have stopped. * @param registration - the plugin's CLI, account operations, and Plugins page text. * @returns the handle for the plugin's own reads and updates of the account. * @throws when the runtime-context name `:cli` is already registered. diff --git a/packages/connector/cli-account/README.i18n.yaml b/packages/connector/cli-account/README.i18n.yaml index dc32284333..762b6c5068 100644 --- a/packages/connector/cli-account/README.i18n.yaml +++ b/packages/connector/cli-account/README.i18n.yaml @@ -27,8 +27,8 @@ en: a1878b0a5129ad53 zh: bd920a3c5f985d03 /deepseek-ai-dsh-cli-account/use-this-package/prepare-before-a-check: - en: d872850f76f7cc99 - zh: 4389f3750c92e2db + en: b9106609a486789b + zh: 27b2a23e53143e6e /deepseek-ai-dsh-cli-account/use-this-package/runtime-context: en: e9152a589f09b94b zh: 04d192c2742bc2a8 diff --git a/packages/connector/cli-account/README.md b/packages/connector/cli-account/README.md index 2091d80599..b7605bb271 100644 --- a/packages/connector/cli-account/README.md +++ b/packages/connector/cli-account/README.md @@ -104,7 +104,7 @@ The returned handle serves the plugin outside an operation: `snapshot()` returns ### Prepare before a check -A plugin whose CLI or skills are downloaded after load registers `prepare: { phase, unprepared, ready, run }`. While `ready()` returns false, each `check` operation enters `phase`, awaits `run(signal)`, enters the Service's `checking` phase, and only then calls `perform`; the other operations call `perform` at once. When `run` throws, the account becomes `unprepared`, `perform` is not called, and the operation fails without a command in its result. The page can cancel `run` when `phase` is listed in `cancellable`: the signal aborts, the account becomes `unprepared`, and the operation ends as cancelled. `run` is not called while `ready()` returns true, and the next check calls it again after a failure, which makes the page's retry button the way to repeat a download. +A plugin whose CLI or skills are downloaded after load registers `prepare: { phase, unprepared, ready, run }`. While `ready()` returns false, each `check` operation enters `phase`, awaits `run(signal)`, enters the Service's `checking` phase, and only then calls `perform`; the other operations call `perform` at once. When `run` throws, the account becomes `unprepared`, `perform` is not called, and the operation fails without a command in its result. The page can cancel `run` when `phase` is listed in `cancellable`: the signal aborts, the account becomes `unprepared`, and the operation ends as cancelled. `run` is not called while `ready()` returns true, and the next check calls it again after a failure, which makes the page's retry button the way to repeat a download. A check that calls `perform` while the account is still the `unprepared` object first replaces it with the registration's `account`: once nothing is missing, a `perform` that fails without publishing leaves the first account, not `unprepared`. ### Runtime context diff --git a/packages/connector/cli-account/README.zh.md b/packages/connector/cli-account/README.zh.md index 8976e2be5d..58d7b4c3d6 100644 --- a/packages/connector/cli-account/README.zh.md +++ b/packages/connector/cli-account/README.zh.md @@ -104,7 +104,7 @@ export function apply(ctx: Context): void { ### 检查之前的准备 -CLI 或 skills 在加载之后才下载的插件注册 `prepare: { phase, unprepared, ready, run }`。`ready()` 返回 false 期间,每次 `check` 操作先进入 `phase`,等待 `run(signal)`,再进入 Service 的 `checking` 阶段,然后才调用 `perform`;其他操作直接调用 `perform`。`run` 抛出异常时,账号变为 `unprepared`,`perform` 不被调用,操作失败,结果中没有命令。`phase` 列在 `cancellable` 中时,插件页可以取消 `run`:signal 中止,账号变为 `unprepared`,操作以取消结束。`ready()` 返回 true 时不调用 `run`;失败之后的下一次检查会再次调用它,所以插件页的重试按钮就是重新下载的方式。 +CLI 或 skills 在加载之后才下载的插件注册 `prepare: { phase, unprepared, ready, run }`。`ready()` 返回 false 期间,每次 `check` 操作先进入 `phase`,等待 `run(signal)`,再进入 Service 的 `checking` 阶段,然后才调用 `perform`;其他操作直接调用 `perform`。`run` 抛出异常时,账号变为 `unprepared`,`perform` 不被调用,操作失败,结果中没有命令。`phase` 列在 `cancellable` 中时,插件页可以取消 `run`:signal 中止,账号变为 `unprepared`,操作以取消结束。`ready()` 返回 true 时不调用 `run`;失败之后的下一次检查会再次调用它,所以插件页的重试按钮就是重新下载的方式。账号仍是 `unprepared` 这个对象时,调用 `perform` 的检查会先把它换成注册的 `account`:什么都不缺之后,`perform` 没有发布就失败时,留下的是最初的账号,而不是 `unprepared`。 ### 运行时上下文 diff --git a/packages/connector/cli-account/src/index.ts b/packages/connector/cli-account/src/index.ts index 60145d0922..860b92342b 100644 --- a/packages/connector/cli-account/src/index.ts +++ b/packages/connector/cli-account/src/index.ts @@ -54,8 +54,9 @@ export default class CliAccounts extends Service { * Register the calling plugin's CLI and account: add the CLI's absolute path to required runtime context, run the * plugin's account operations one at a time, and show the account on the Plugins page while `connectorAccounts` is * loaded. With a `prepare` step, the path stays out of runtime context while the step reports that something is - * missing, and each check first runs the step. The registration belongs to the calling plugin: unloading that plugin - * withdraws it, after the active operation and the CLI processes it started have stopped. + * missing, and each check first runs the step; a check that starts with nothing missing replaces an account the + * step left `unprepared` with the registration's first account. The registration belongs to the calling plugin: + * unloading that plugin withdraws it, after the active operation and the CLI processes it started have stopped. * @param registration - the plugin's CLI, account operations, and Plugins page text. * @returns the handle for the plugin's own reads and updates of the account. * @throws when the runtime-context name `:cli` is already registered. @@ -73,15 +74,19 @@ export default class CliAccounts extends Service { cancellable: registration.cancellable, authorizationHosts: registration.authorizationHosts, perform: async (kind, control, signal) => { - if (kind === registration.check && prepare !== undefined && !prepare.ready()) { - control.stage(prepare.phase) - try { - await prepare.run(signal) - } catch (error) { - control.publish(prepare.unprepared) - throw error + if (kind === registration.check && prepare !== undefined) { + if (!prepare.ready()) { + control.stage(prepare.phase) + try { + await prepare.run(signal) + } catch (error) { + control.publish(prepare.unprepared) + throw error + } + control.stage('checking') } - control.stage('checking') + // Nothing is missing here, so `unprepared` from an earlier step must not outlast a check that publishes nothing. + if (runtime.snapshot().account === prepare.unprepared) control.publish(registration.account) } await registration.perform(kind, control, signal) }, diff --git a/packages/connector/cli-account/src/types.ts b/packages/connector/cli-account/src/types.ts index 2b7ba3c452..bdad898d10 100644 --- a/packages/connector/cli-account/src/types.ts +++ b/packages/connector/cli-account/src/types.ts @@ -86,7 +86,10 @@ export interface CliOperationControl { /** The plugin phase the operation is in while `run` runs; listed in `cancellable` when the page may cancel `run`. */ readonly phase: Phase - /** The account the view reports after `run` threw or was cancelled. */ + /** + * The account the view reports after `run` threw or was cancelled, until a check starts its `perform` with nothing + * missing: that check first replaces this object with the registration's `account`. + */ readonly unprepared: Account /** * Tell whether everything `run` puts in place is there; called before each `check` operation and each time required diff --git a/packages/connector/cli-account/tests/service.spec.ts b/packages/connector/cli-account/tests/service.spec.ts index c8dedd6788..9dcc0767ed 100644 --- a/packages/connector/cli-account/tests/service.spec.ts +++ b/packages/connector/cli-account/tests/service.spec.ts @@ -370,6 +370,32 @@ describe('prepare', () => { expect(subprocess.processes).toEqual([]) }) + it.each([ + ['its step succeeded', 2], + ['what was missing arrived without the step', 1], + ])('reports the first account again, not the unprepared one, when a later check fails after %s', async (_path, runs) => { + const { ctx, subprocess } = await host() + subprocess.respond = (process) => { process.reply({ exitCode: 3 }) } + let ready = false + const run = vi.fn<(signal: AbortSignal) => Promise>() + .mockRejectedValueOnce(new Error('download failed')) + .mockImplementationOnce(() => { + ready = true + return Promise.resolve() + }) + const prepare: Registration['prepare'] = { phase: 'downloading', unprepared: { state: 'not-installed' }, ready: () => ready, run } + const { handle } = await app(ctx, { ...REGISTRATION, prepare }) + const first = await ctx.connectorAccounts.start(PACKAGE, 'check') + await vi.waitFor(() => { expect(handle.snapshot()).toEqual({ account: { state: 'not-installed' }, result: { id: first, kind: 'check', outcome: 'failed' } }) }) + + if (runs === 1) ready = true + const id = await ctx.connectorAccounts.start(PACKAGE, 'check') + + await vi.waitFor(() => { expect(handle.snapshot().result).toMatchObject({ id, outcome: 'failed', failure: { command: 'status', exitCode: 3 } }) }) + expect(handle.snapshot().account).toEqual({ state: 'unchecked' }) + expect(run).toHaveBeenCalledTimes(runs) + }) + it('starts the other operations without the step', async () => { const { ctx, subprocess } = await host() subprocess.respond = (process) => { process.reply({ stdout: 'in\n' }) } diff --git a/packages/connector/dingtalk/README.i18n.yaml b/packages/connector/dingtalk/README.i18n.yaml index 449af7e6c2..2e85357568 100644 --- a/packages/connector/dingtalk/README.i18n.yaml +++ b/packages/connector/dingtalk/README.i18n.yaml @@ -24,8 +24,8 @@ en: 6ae1c6cfc0b6cd5d zh: 21ccf1e0f9312a4f /deepseek-ai-dsh-dingtalk/use-this-package/account-operations: - en: 265eb53ad3bce84f - zh: bbd01a50493bfa18 + en: 6afb429dd10f1d2d + zh: e56c3c3e11b6b13c /deepseek-ai-dsh-dingtalk/use-this-package/configure: en: f97716c608f5d992 zh: 97909644448a4523 diff --git a/packages/connector/dingtalk/README.md b/packages/connector/dingtalk/README.md index 3208d9d985..d3811981aa 100644 --- a/packages/connector/dingtalk/README.md +++ b/packages/connector/dingtalk/README.md @@ -56,7 +56,7 @@ The Plugins page drives these operations through the connector account registry, | `sign-out` | After the user confirms, runs `auth logout --profile :` for the account the last check found, which also signs it out of the user's own terminal, then checks again | | Cancel | Cancels a sign-in while it waits for authorization, or a check while it downloads, and waits for the command or download to stop; other steps are ignored | -A check runs `auth status --format json`, which refreshes an expired access token with the server and exits with code 0 whether or not a user is signed in. The account reads `connected`, with the user and organization names dws reports, when `authenticated` is true; `unverified` when it is false with one of the reasons dws reports as inconclusive (`local_state_requires_repair`, `local_state_unreadable`, `ciphertext_key_mismatch`, `dek_missing`, `keychain_unavailable`); and `signed-out` otherwise. A nonzero exit or output that is not the status JSON fails the check and keeps the previous account; a download that does not finish leaves `not-installed`. Sign-out requires both ids, so it never selects every account of an organization; accounts of other organizations stay signed in, and the next check shows the account dws then reports as current. The link that `auth login` prints alone on an indented stderr line is offered only when it is an HTTPS address on `login.dingtalk.com`. Results report succeeded, cancelled, or failed. Failures show the command and the observed exit code on the page and in the Host log; the CLI's output is omitted. The process running DSH needs access to `~/.dws` and the CLI's macOS keychain item; `DSH_HOME` does not relocate them. +A check runs `auth status --format json`, which refreshes an expired access token with the server and exits with code 0 whether or not a user is signed in. The account reads `connected`, with the user and organization names dws reports, when `authenticated` is true; `unverified` when it is false with one of the reasons dws reports as inconclusive (`local_state_requires_repair`, `local_state_unreadable`, `ciphertext_key_mismatch`, `dek_missing`, `keychain_unavailable`); and `signed-out` otherwise. A nonzero exit or output that is not the status JSON fails the check and keeps the previous account, except that `not-installed` becomes `unchecked` once the download is in place; a download that does not finish leaves `not-installed`. Sign-out requires both ids, so it never selects every account of an organization; accounts of other organizations stay signed in, and the next check shows the account dws then reports as current. The link that `auth login` prints alone on an indented stderr line is offered only when it is an HTTPS address on `login.dingtalk.com`. Results report succeeded, cancelled, or failed. Failures show the command and the observed exit code on the page and in the Host log; the CLI's output is omitted. The process running DSH needs access to `~/.dws` and the CLI's macOS keychain item; `DSH_HOME` does not relocate them. ### Configure diff --git a/packages/connector/dingtalk/README.zh.md b/packages/connector/dingtalk/README.zh.md index 481d7a9efe..5b878a0b9e 100644 --- a/packages/connector/dingtalk/README.zh.md +++ b/packages/connector/dingtalk/README.zh.md @@ -56,7 +56,7 @@ dsh plugin --profile web remove @deepseek-ai/dsh-dingtalk | `sign-out` | 用户确认后,对最近一次检查发现的账号运行 `auth logout --profile :`,这也会让用户自己的终端退出该账号,然后重新检查 | | 取消 | 在登录等待授权时取消它,或在检查下载时取消下载,并等待命令或下载停止;其他步骤会被忽略 | -检查运行 `auth status --format json`,它会向服务端刷新已过期的访问令牌,无论是否有用户登录,退出码都是 0。`authenticated` 为 true 时,账号为 `connected`,并带上 dws 报告的用户名和组织名;为 false 且原因属于 dws 报告为无法判断的几种(`local_state_requires_repair`、`local_state_unreadable`、`ciphertext_key_mismatch`、`dek_missing`、`keychain_unavailable`)时为 `unverified`;其余为 `signed-out`。退出码非零,或输出不是状态 JSON,会使检查失败并保留之前的账号状态;下载没有完成时为 `not-installed`。退出登录要求两个 id 都存在,因此不会选中一个组织的全部账号;其他组织的账号保持登录,下一次检查显示 dws 届时报告的当前账号。`auth login` 在 stderr 中单独一行、带缩进打印的链接,只有是 `login.dingtalk.com` 上的 HTTPS 地址时才会提供。结果分为成功、已取消和失败。失败时,页面和 Host 日志显示命令和观察到的退出码;CLI 的输出会被省略。运行 DSH 的进程需要能访问 `~/.dws` 和该 CLI 的 macOS 钥匙串项;`DSH_HOME` 不会改变它们的位置。 +检查运行 `auth status --format json`,它会向服务端刷新已过期的访问令牌,无论是否有用户登录,退出码都是 0。`authenticated` 为 true 时,账号为 `connected`,并带上 dws 报告的用户名和组织名;为 false 且原因属于 dws 报告为无法判断的几种(`local_state_requires_repair`、`local_state_unreadable`、`ciphertext_key_mismatch`、`dek_missing`、`keychain_unavailable`)时为 `unverified`;其余为 `signed-out`。退出码非零,或输出不是状态 JSON,会使检查失败并保留之前的账号状态,只是下载就位之后 `not-installed` 会换成 `unchecked`;下载没有完成时为 `not-installed`。退出登录要求两个 id 都存在,因此不会选中一个组织的全部账号;其他组织的账号保持登录,下一次检查显示 dws 届时报告的当前账号。`auth login` 在 stderr 中单独一行、带缩进打印的链接,只有是 `login.dingtalk.com` 上的 HTTPS 地址时才会提供。结果分为成功、已取消和失败。失败时,页面和 Host 日志显示命令和观察到的退出码;CLI 的输出会被省略。运行 DSH 的进程需要能访问 `~/.dws` 和该 CLI 的 macOS 钥匙串项;`DSH_HOME` 不会改变它们的位置。 ### 配置 diff --git a/packages/connector/feishu/README.i18n.yaml b/packages/connector/feishu/README.i18n.yaml index 895a82932e..4035e89377 100644 --- a/packages/connector/feishu/README.i18n.yaml +++ b/packages/connector/feishu/README.i18n.yaml @@ -21,8 +21,8 @@ en: 10bdd68f45f9dfe9 zh: 9ea8d884ae12690a /deepseek-ai-dsh-feishu/use-this-package/download-of-a-missing-cli: - en: f2a40b09d50c60b6 - zh: b91f83986c37eb4d + en: fbfb6ed23ce970cd + zh: ef94e59c8f37f4bf /deepseek-ai-dsh-feishu/use-this-package/what-you-get: en: 841b50c329791ac8 zh: 0ed710e724673e44 diff --git a/packages/connector/feishu/README.md b/packages/connector/feishu/README.md index 4fc5131c0f..f5814df546 100644 --- a/packages/connector/feishu/README.md +++ b/packages/connector/feishu/README.md @@ -39,7 +39,7 @@ pnpm blocks the `@larksuite/cli` install script, which downloads and verifies th ### Download of a missing CLI -When the `feishu` row loads without `binDir` and the `@larksuite/cli` package holds no executable `lark-cli`, the row starts one check, which first runs that package's install script with the Node that runs DSH. The script fetches the release archive for the computer's platform with `curl`, from GitHub and then from npm mirrors, for at most 120 seconds each, verifies its SHA-256 against the package's `checksums.txt`, and copies the binary into the package's `bin` directory. The runtime context gives no `lark-cli` path, and the catalog has no `feishu` skill, until the executable is in place. The download needs no browser; the Plugins page shows it as a step of the check, with **Cancel**. A download that does not finish leaves the account `not-installed`: the page says that the CLI could not be downloaded and offers **Retry**, and unless it was cancelled, the Host log has one warning with the script's exit code and error output. The next check downloads again. +When the `feishu` row loads without `binDir` and the `@larksuite/cli` package holds no executable `lark-cli`, the row starts one check, which first runs that package's install script with the Node that runs DSH. The script fetches the release archive for the computer's platform with `curl`, from GitHub and then from npm mirrors, for at most 120 seconds each, verifies its SHA-256 against the package's `checksums.txt`, and copies the binary into the package's `bin` directory. The runtime context gives no `lark-cli` path, and the catalog has no `feishu` skill, until the executable is in place. The download needs no browser; the Plugins page shows it as a step of the check, with **Cancel**. A download that does not finish leaves the account `not-installed`: the page says that the CLI could not be downloaded and offers **Retry**, and unless it was cancelled, the Host log has one warning with the script's exit code and error output. The next check downloads again. Once the executable is in place, a check that fails before it has read the account says that the sign-in state could not be confirmed, with **Retry**, and no longer names the download. ### What you get diff --git a/packages/connector/feishu/README.zh.md b/packages/connector/feishu/README.zh.md index 67466a27c2..f840aa6b3a 100644 --- a/packages/connector/feishu/README.zh.md +++ b/packages/connector/feishu/README.zh.md @@ -39,7 +39,7 @@ pnpm 会拦截 `@larksuite/cli` 的安装脚本,该脚本负责下载并校验 ### 下载缺失的 CLI -`feishu` 行加载时没有设置 `binDir`、且 `@larksuite/cli` 包中没有可执行的 `lark-cli` 时,该行会发起一次检查,检查先用运行 DSH 的 Node 运行该包的安装脚本。脚本用 `curl` 获取本机平台的发布压缩包,先从 GitHub、再从 npm 镜像,每个来源最多 120 秒,按包内 `checksums.txt` 校验 SHA-256,并把二进制复制到该包的 `bin` 目录。可执行文件就位之前,运行时上下文不给出 `lark-cli` 路径,目录中也没有 `feishu` skill。下载不需要浏览器;插件页把它显示为检查的一个步骤,并提供**取消**。没有完成的下载使账号处于 `not-installed`:页面提示没能下载 CLI 并提供**重试**;除非是被取消,Host 日志中有一条警告,带脚本的退出码和错误输出。下一次检查会重新下载。 +`feishu` 行加载时没有设置 `binDir`、且 `@larksuite/cli` 包中没有可执行的 `lark-cli` 时,该行会发起一次检查,检查先用运行 DSH 的 Node 运行该包的安装脚本。脚本用 `curl` 获取本机平台的发布压缩包,先从 GitHub、再从 npm 镜像,每个来源最多 120 秒,按包内 `checksums.txt` 校验 SHA-256,并把二进制复制到该包的 `bin` 目录。可执行文件就位之前,运行时上下文不给出 `lark-cli` 路径,目录中也没有 `feishu` skill。下载不需要浏览器;插件页把它显示为检查的一个步骤,并提供**取消**。没有完成的下载使账号处于 `not-installed`:页面提示没能下载 CLI 并提供**重试**;除非是被取消,Host 日志中有一条警告,带脚本的退出码和错误输出。下一次检查会重新下载。可执行文件就位之后,还没读到账号就失败的检查提示暂时无法确认登录状态,并提供**重试**,不再提下载。 ### 获得的能力 diff --git a/packages/connector/feishu/src/presentation.ts b/packages/connector/feishu/src/presentation.ts index af068c59fb..d7c5e17b1b 100644 --- a/packages/connector/feishu/src/presentation.ts +++ b/packages/connector/feishu/src/presentation.ts @@ -119,13 +119,16 @@ export function presentAccount(view: FeishuState, text: Text): ConnectorAccountD /* jscpd:ignore-end */ if (operation !== undefined) return presentOperation(operation, text) const failure = failureOf(view.result, text) + const unavailable = (detail: 'detail.missing' | 'detail.unavailable', notes: ConnectorAccountNote[]): ConnectorAccountDisplay => ({ + phase: 'unavailable', status: text('status.unavailable'), badge: text('badge.unavailable'), + buttons: [{ label: text('action.retry'), command: CHECK }], detail: text(detail), notes, ...failure, + }) switch (account.state) { - case 'unchecked': return { phase: 'checking', status: text('status.checking'), buttons: [], notes: [] } - case 'not-installed': - return { - phase: 'unavailable', status: text('status.unavailable'), badge: text('badge.unavailable'), - buttons: [{ label: text('action.retry'), command: CHECK }], detail: text('detail.missing'), notes: [], ...failure, - } + case 'unchecked': + return view.result?.outcome === 'failed' + ? unavailable('detail.unavailable', []) + : { phase: 'checking', status: text('status.checking'), buttons: [], notes: [] } + case 'not-installed': return unavailable('detail.missing', []) case 'unconfigured': return { phase: 'disconnected', status: text('status.disconnected'), badge: text('badge.disconnected'), @@ -138,11 +141,7 @@ export function presentAccount(view: FeishuState, text: Text): ConnectorAccountD buttons: [{ label: text('action.signIn'), command: SIGN_IN, variant: 'primary' }], connect: SIGN_IN, detail: text('detail.signed-out'), notes: appNotes(account.appId, text), ...failure, } - case 'unverified': - return { - phase: 'unavailable', status: text('status.unavailable'), badge: text('badge.unavailable'), - buttons: [{ label: text('action.retry'), command: CHECK }], detail: text('detail.unavailable'), notes: appNotes(account.appId, text), ...failure, - } + case 'unverified': return unavailable('detail.unavailable', appNotes(account.appId, text)) /* jscpd:ignore-start -- CLI app plugins that sign out offer the same confirmed sign-out button. */ case 'connected': return { diff --git a/packages/connector/feishu/tests/download.spec.ts b/packages/connector/feishu/tests/download.spec.ts index 9d2e0eda45..2a3f47f822 100644 --- a/packages/connector/feishu/tests/download.spec.ts +++ b/packages/connector/feishu/tests/download.spec.ts @@ -183,6 +183,33 @@ it('offers the skill at the retry after lark-cli was installed outside the plugi expect(await skills()).toEqual(['feishu']) }) +it.each([ + ['the retry downloaded lark-cli', false, [INSTALLER, INSTALLER, STATUS]], + ['lark-cli was installed outside the plugin\'s download', true, [INSTALLER, STATUS]], +])('stops reporting a missing download when `auth status` fails after %s', async (_path, outside, ran) => { + install = (process) => { process.reply({ exitCode: 1 }) } + status = (process) => { process.reply({ exitCode: 3 }) } + const page = await load() + const account = page.source + expect(await settled(account)).toMatchObject({ account: { state: 'not-installed' } }) + + present = outside + install = (process) => { + present = true + process.reply({}) + } + const retry = await account.start('check') + + const failure = { command: 'auth-status', exitCode: 3 } + await vi.waitFor(() => { expect(account.snapshot().result).toEqual({ id: retry, kind: 'check', outcome: 'failed', failure }) }) + expect(account.snapshot().account).toEqual({ state: 'unchecked' }) + expect(page.present(account.snapshot())).toMatchObject({ + phase: 'unavailable', status: say('status.unavailable'), detail: say('detail.unavailable'), + failure: { text: say('failed'), details: ['auth-status', 'exit 3'] }, buttons: [{ label: say('action.retry'), command: CHECK }], + }) + expect(commands()).toEqual(ran) +}) + it('stops the download when the plugin unloads', async () => { install = () => {} const fiber = await ctx.plugin(Feishu, {}) diff --git a/packages/connector/feishu/tests/presentation.spec.ts b/packages/connector/feishu/tests/presentation.spec.ts index 90216a628a..f8a8df111c 100644 --- a/packages/connector/feishu/tests/presentation.spec.ts +++ b/packages/connector/feishu/tests/presentation.spec.ts @@ -92,6 +92,18 @@ it('retries an unconfirmed sign-in by checking again', () => { expect(shown.buttons).toMatchObject([{ label: say('action.retry'), command: CHECK }]) }) +it('retries a check that failed before the account was ever read', () => { + const shown = presentAccount({ + account: { state: 'unchecked' }, + result: { id: OP, kind: 'check', outcome: 'failed', failure: { command: 'auth-status', exitCode: 3 } }, + }) + expect(shown).toMatchObject({ + phase: 'unavailable', status: say('status.unavailable'), badge: say('badge.unavailable'), detail: say('detail.unavailable'), + notes: [], failure: { text: say('failed'), details: ['auth-status', 'exit 3'] }, + }) + expect(shown.buttons).toMatchObject([{ label: say('action.retry'), command: CHECK }]) +}) + it('shows the download of a missing CLI with its cancel, and a retry after one that did not finish', () => { const UNCHECKED: FeishuState = { account: { state: 'unchecked' } } let shown = presentAccount({ ...UNCHECKED, operation: { id: OP, kind: 'check', phase: 'downloading', cancellable: true } }) diff --git a/packages/connector/tencent-meeting/README.i18n.yaml b/packages/connector/tencent-meeting/README.i18n.yaml index 3e75d008c4..59f33e782e 100644 --- a/packages/connector/tencent-meeting/README.i18n.yaml +++ b/packages/connector/tencent-meeting/README.i18n.yaml @@ -24,8 +24,8 @@ en: 57566f3951ed5a11 zh: 6d0ea243c0e19e9b /deepseek-ai-dsh-tencent-meeting/use-this-package/account-operations: - en: c282272dc744b8e3 - zh: 028635966af0ad38 + en: 9945c5f77441fe22 + zh: b7ac298014a28205 /deepseek-ai-dsh-tencent-meeting/use-this-package/configure: en: 1730401daedf703e zh: 5cd9e0bc2699efe8 diff --git a/packages/connector/tencent-meeting/README.md b/packages/connector/tencent-meeting/README.md index ba13f2d0d2..febc8d0b76 100644 --- a/packages/connector/tencent-meeting/README.md +++ b/packages/connector/tencent-meeting/README.md @@ -56,7 +56,7 @@ The Plugins page drives these operations through the connector account registry, | `sign-out` | After the user confirms, runs `auth logout`, which also signs out the user's own terminal, then checks again | | Cancel | Cancels a sign-in while it waits for authorization, or a check while it waits for the guide's download, and waits for the command or download to stop; other steps are ignored | -A check runs `auth status`, which in tmeet 1.0.18 prints plain text and exits with code 0 whether or not a user is signed in. The account reads `signed-out` for `Not logged in.`, for `Session has expired.`, or when `Logged in` comes with an expired refresh token; `connected`, with the user name, when `Logged in` comes with a `UserName:` line, which the CLI prints only after its user-info request to the server succeeds; and `unverified` for any other `Logged in`, for example when that request cannot reach the server. A nonzero exit or other output fails the check and keeps the previous account; a download that does not finish leaves `not-installed`. The link that `auth login` prints on its `authorize url:` stdout line is offered only when it is an HTTPS address on `meeting.tencent.com`. Results report succeeded, cancelled, or failed. Failures show the command and the observed exit code on the page and in the Host log; the CLI's output, which can carry the one-time authorization code, is omitted. The process running DSH needs access to the CLI configuration in `~/.tmeet`, the encrypted credentials in `~/Library/Application Support/tmeet`, and the macOS Keychain item that holds their key; `DSH_HOME` does not relocate them. +A check runs `auth status`, which in tmeet 1.0.18 prints plain text and exits with code 0 whether or not a user is signed in. The account reads `signed-out` for `Not logged in.`, for `Session has expired.`, or when `Logged in` comes with an expired refresh token; `connected`, with the user name, when `Logged in` comes with a `UserName:` line, which the CLI prints only after its user-info request to the server succeeds; and `unverified` for any other `Logged in`, for example when that request cannot reach the server. A nonzero exit or other output fails the check and keeps the previous account, except that `not-installed` becomes `unchecked` once the download is in place; a download that does not finish leaves `not-installed`. The link that `auth login` prints on its `authorize url:` stdout line is offered only when it is an HTTPS address on `meeting.tencent.com`. Results report succeeded, cancelled, or failed. Failures show the command and the observed exit code on the page and in the Host log; the CLI's output, which can carry the one-time authorization code, is omitted. The process running DSH needs access to the CLI configuration in `~/.tmeet`, the encrypted credentials in `~/Library/Application Support/tmeet`, and the macOS Keychain item that holds their key; `DSH_HOME` does not relocate them. ### Configure diff --git a/packages/connector/tencent-meeting/README.zh.md b/packages/connector/tencent-meeting/README.zh.md index 85b8128d62..45fb58b900 100644 --- a/packages/connector/tencent-meeting/README.zh.md +++ b/packages/connector/tencent-meeting/README.zh.md @@ -56,7 +56,7 @@ dsh plugin --profile web remove @deepseek-ai/dsh-tencent-meeting | `sign-out` | 用户确认后运行 `auth logout`,这也会退出用户自己终端里的登录,然后重新检查 | | 取消 | 在登录等待授权期间取消登录,或在检查等待子指南下载期间取消检查,并等待命令或下载停止;其他步骤会被忽略 | -检查运行 `auth status`。在 tmeet 1.0.18 中,它只输出纯文本,无论是否有用户登录,退出码都是 0。输出 `Not logged in.` 或 `Session has expired.`,或 `Logged in` 伴随已过期的 refresh token 时,账号为 `signed-out`;`Logged in` 伴随 `UserName:` 行时为 `connected` 并带用户名,CLI 只有在向服务端请求用户信息成功后才会打印这一行;其他 `Logged in` 为 `unverified`,例如该请求连不上服务端。退出码非零或其他输出会使检查失败,并保留之前的账号状态;没有完成的下载使状态成为 `not-installed`。`auth login` 在 stdout 的 `authorize url:` 行打印的链接,只有是 `meeting.tencent.com` 上的 HTTPS 地址时才会提供。结果分为成功、已取消和失败。失败时,页面和 Host 日志显示命令和观察到的退出码;CLI 的输出可能带有一次性授权码,因此会被省略。运行 DSH 的进程需要能访问 `~/.tmeet` 中的 CLI 配置、`~/Library/Application Support/tmeet` 中的加密凭据,以及保存其密钥的 macOS 钥匙串项;`DSH_HOME` 不会改变它们的位置。 +检查运行 `auth status`。在 tmeet 1.0.18 中,它只输出纯文本,无论是否有用户登录,退出码都是 0。输出 `Not logged in.` 或 `Session has expired.`,或 `Logged in` 伴随已过期的 refresh token 时,账号为 `signed-out`;`Logged in` 伴随 `UserName:` 行时为 `connected` 并带用户名,CLI 只有在向服务端请求用户信息成功后才会打印这一行;其他 `Logged in` 为 `unverified`,例如该请求连不上服务端。退出码非零或其他输出会使检查失败,并保留之前的账号状态,只是下载就位之后 `not-installed` 会换成 `unchecked`;没有完成的下载使状态成为 `not-installed`。`auth login` 在 stdout 的 `authorize url:` 行打印的链接,只有是 `meeting.tencent.com` 上的 HTTPS 地址时才会提供。结果分为成功、已取消和失败。失败时,页面和 Host 日志显示命令和观察到的退出码;CLI 的输出可能带有一次性授权码,因此会被省略。运行 DSH 的进程需要能访问 `~/.tmeet` 中的 CLI 配置、`~/Library/Application Support/tmeet` 中的加密凭据,以及保存其密钥的 macOS 钥匙串项;`DSH_HOME` 不会改变它们的位置。 ### 配置 diff --git a/packages/connector/wecom/README.i18n.yaml b/packages/connector/wecom/README.i18n.yaml index d10a02a84b..f66c90f39f 100644 --- a/packages/connector/wecom/README.i18n.yaml +++ b/packages/connector/wecom/README.i18n.yaml @@ -24,8 +24,8 @@ en: bb320b233ab74df2 zh: 337d1d1b213a8c60 /deepseek-ai-dsh-wecom/use-this-package/authorization-operations: - en: fb54bdc729deed65 - zh: b2ee5587d647007c + en: bd7599ee84d5e710 + zh: 479396e5e4385cc1 /deepseek-ai-dsh-wecom/use-this-package/configure: en: dfbcda32182eb7eb zh: 554086e7081a313a diff --git a/packages/connector/wecom/README.md b/packages/connector/wecom/README.md index e5314d1696..bc1e4a5b52 100644 --- a/packages/connector/wecom/README.md +++ b/packages/connector/wecom/README.md @@ -55,7 +55,7 @@ The Plugins page drives these operations through the connector account registry, | `connect` | Runs `auth init --noninteractive --no-browser`, waits for the user to scan the QR code, then checks that the CLI reports the bot authorized. The authorized section offers it again as changing the bot, after a confirmation, because the new binding replaces the one the terminal shares | | Cancel | Cancels the connection while it waits for the scan, or a check while it waits for the guides' download, and waits for the command or download to stop; other steps are ignored | -A check runs `auth show`. The authorization reads `authorized` or `unauthorized` from the CLI's `Status` line, and the bound bot's id from its `Bot ID` line, which the section shows when the CLI prints one; any other output or a nonzero exit fails the check and keeps the previous state; a download that does not finish leaves `not-installed`. Each link that `auth init` prints alone on a stdout line is offered only when it is an HTTPS address on `work.weixin.qq.com`. Results report succeeded, cancelled, or failed. Failures show the command and the observed exit code on the page and in the Host log; the CLI's output, which can carry the QR-code session, is omitted. `wecom-cli` has no command that revokes the authorization, so the plugin offers no disconnect. The process running DSH needs access to the CLI configuration; `DSH_HOME` does not relocate it. +A check runs `auth show`. The authorization reads `authorized` or `unauthorized` from the CLI's `Status` line, and the bound bot's id from its `Bot ID` line, which the section shows when the CLI prints one; any other output or a nonzero exit fails the check and keeps the previous state, except that `not-installed` becomes `unchecked` once the download is in place; a download that does not finish leaves `not-installed`. Each link that `auth init` prints alone on a stdout line is offered only when it is an HTTPS address on `work.weixin.qq.com`. Results report succeeded, cancelled, or failed. Failures show the command and the observed exit code on the page and in the Host log; the CLI's output, which can carry the QR-code session, is omitted. `wecom-cli` has no command that revokes the authorization, so the plugin offers no disconnect. The process running DSH needs access to the CLI configuration; `DSH_HOME` does not relocate it. ### Configure diff --git a/packages/connector/wecom/README.zh.md b/packages/connector/wecom/README.zh.md index e7a6712731..56317d171c 100644 --- a/packages/connector/wecom/README.zh.md +++ b/packages/connector/wecom/README.zh.md @@ -55,7 +55,7 @@ dsh plugin --profile web remove @deepseek-ai/dsh-wecom | `connect` | 运行 `auth init --noninteractive --no-browser`,等待用户扫码,然后确认 CLI 报告机器人已授权。已授权的区块以“更换机器人”再次提供它,需先确认,因为新绑定会替换终端共用的那一个 | | 取消 | 在等待扫码期间取消连接,或在检查等待子指南下载期间取消检查,并等待命令或下载停止;其他步骤会被忽略 | -检查运行 `auth show`。授权状态从 CLI 输出的 `Status` 行读作 `authorized` 或 `unauthorized`,CLI 打印 `Bot ID` 行时,从中读取已绑定机器人的 id 并显示在区块中;其他输出或非零退出码会使检查失败,并保留之前的状态;没有完成的下载使状态成为 `not-installed`。`auth init` 在 stdout 中单独一行打印的链接,只有是 `work.weixin.qq.com` 上的 HTTPS 地址时才会提供。结果分为成功、已取消和失败。失败时,页面和 Host 日志显示命令和观察到的退出码;CLI 的输出可能带有扫码会话,因此不保留。`wecom-cli` 没有撤销授权的命令,因此插件不提供断开连接。运行 DSH 的进程需要能访问 CLI 配置;`DSH_HOME` 不会迁移它。 +检查运行 `auth show`。授权状态从 CLI 输出的 `Status` 行读作 `authorized` 或 `unauthorized`,CLI 打印 `Bot ID` 行时,从中读取已绑定机器人的 id 并显示在区块中;其他输出或非零退出码会使检查失败,并保留之前的状态,只是下载就位之后 `not-installed` 会换成 `unchecked`;没有完成的下载使状态成为 `not-installed`。`auth init` 在 stdout 中单独一行打印的链接,只有是 `work.weixin.qq.com` 上的 HTTPS 地址时才会提供。结果分为成功、已取消和失败。失败时,页面和 Host 日志显示命令和观察到的退出码;CLI 的输出可能带有扫码会话,因此不保留。`wecom-cli` 没有撤销授权的命令,因此插件不提供断开连接。运行 DSH 的进程需要能访问 CLI 配置;`DSH_HOME` 不会迁移它。 ### 配置 diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 5dd6944cd9..737797830d 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -599,7 +599,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ methods: [ { signature: 'register( registration: CliAccountRegistration, ): CliAccountHandle', - description: 'Register the calling plugin\'s CLI and account: add the CLI\'s absolute path to required runtime context, run the plugin\'s account operations one at a time, and show the account on the Plugins page while `connectorAccounts` is loaded. With a `prepare` step, the path stays out of runtime context while the step reports that something is missing, and each check first runs the step. The registration belongs to the calling plugin: unloading that plugin withdraws it, after the active operation and the CLI processes it started have stopped.', + description: 'Register the calling plugin\'s CLI and account: add the CLI\'s absolute path to required runtime context, run the plugin\'s account operations one at a time, and show the account on the Plugins page while `connectorAccounts` is loaded. With a `prepare` step, the path stays out of runtime context while the step reports that something is missing, and each check first runs the step; a check that starts with nothing missing replaces an account the step left `unprepared` with the registration\'s first account. The registration belongs to the calling plugin: unloading that plugin withdraws it, after the active operation and the CLI processes it started have stopped.', parameters: [{ name: 'registration', description: 'the plugin\'s CLI, account operations, and Plugins page text.' }], returns: 'the handle for the plugin\'s own reads and updates of the account.', throws: ['when the runtime-context name `:cli` is already registered.'], From fcc3f10d89043ac8436f8f7bea305a1ccbe3cfc1 Mon Sep 17 00:00:00 2001 From: Yixiang Tu Date: Thu, 19 Nov 2026 19:20:08 +0800 Subject: [PATCH 4/8] =?UTF-8?q?fix(cua):=20name=20Computer=20Use=20?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E7=94=B5=E8=84=91=E6=93=8D=E4=BD=9C=20in=20C?= =?UTF-8?q?hinese=20UI=20copy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/web/tests/cua-optin.e2e.ts | 28 +++++++++---------- .../cua-permissions/default-mode.expected.md | 2 +- .../cua-permissions/enabling.expected.md | 2 +- .../cua-permissions/setup.expected.md | 6 ++-- .../experimental/cua-bundle/README.i18n.yaml | 2 +- packages/experimental/cua-bundle/README.zh.md | 2 +- .../experimental/cua-bundle/locale/zh.json | 2 +- .../experimental/cua-macos/locale/zh.json | 4 +-- .../cua-macos/src/permission-guide.ts | 2 +- .../cua-macos/tests/permission-guide.spec.ts | 2 +- .../tests/provider-lifecycle.spec.ts | 2 +- packages/experimental/cua-mcp/locale/zh.json | 4 +-- .../experimental/cua-windows/locale/zh.json | 4 +-- packages/experimental/cua/README.i18n.yaml | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/locale/zh.json | 4 +-- .../experimental/cua/src/client/locales.ts | 16 +++++------ packages/experimental/cua/src/locales.ts | 6 ++-- .../cua/tests/application-access.spec.ts | 2 +- 19 files changed, 47 insertions(+), 47 deletions(-) diff --git a/apps/web/tests/cua-optin.e2e.ts b/apps/web/tests/cua-optin.e2e.ts index 2b36d9f193..cc9f19620d 100644 --- a/apps/web/tests/cua-optin.e2e.ts +++ b/apps/web/tests/cua-optin.e2e.ts @@ -61,7 +61,7 @@ it.skipIf(process.platform !== 'darwin').each([ const listed = (await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === '@deepseek-ai/dsh-cua-bundle') expect(listed).toMatchObject({ availability: 'installation', optional: true, enabled: false, installed: false }) expect(listed).not.toHaveProperty('listedByDefault') - let toggle = card.getByRole('switch', { name: '启用 Computer Use', exact: true }) + let toggle = card.getByRole('switch', { name: '启用自动电脑操作', exact: true }) const originalAgent = scaffold.ctx.agents.list()[0]! const ptcAgent = (await scaffold.ctx.agents.create({ sessionId: brandString('cua-existing-ptc'), @@ -90,7 +90,7 @@ it.skipIf(process.platform !== 'darwin').each([ }) try { await toggle.click() - await card.getByRole('status').getByText('正在应用 Computer Use 的更改', { exact: true }).waitFor() + await card.getByRole('status').getByText('正在应用自动电脑操作的更改', { exact: true }).waitFor() await compareOrRefreshGolden(fileURLToPath(new URL('./expected/cua-permissions/enabling.expected.md', import.meta.url)), await captureStableAria(page, '[data-plugin-package="@deepseek-ai/dsh-cua-bundle"] [role="status"]', scaffold.workspaceCwd), webSnapshotMode()) } finally { @@ -100,10 +100,10 @@ it.skipIf(process.platform !== 'darwin').each([ } // Bundle transitions await native cleanup under the browser action deadline. await toggle.and(page.locator('[aria-checked="true"]')).waitFor({ state: 'visible' }) - await card.getByRole('status').getByText('正在应用 Computer Use 的更改', { exact: true }).waitFor({ state: 'hidden' }) - const setup = page.getByRole('dialog', { name: '使用 Computer Use 前需要设置', exact: true }) + await card.getByRole('status').getByText('正在应用自动电脑操作的更改', { exact: true }).waitFor({ state: 'hidden' }) + const setup = page.getByRole('dialog', { name: '使用自动电脑操作前需要设置', exact: true }) await setup.waitFor() - expect(await setup.getByText('Computer Use 插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) + expect(await setup.getByText('自动电脑操作插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) await compareOrRefreshGolden(fileURLToPath(new URL('./expected/cua-permissions/setup.expected.md', import.meta.url)), await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), webSnapshotMode()) expect(await setup.getByRole('button', { name: '设为 PTC', exact: true }).count()).toBe(0) @@ -116,7 +116,7 @@ it.skipIf(process.platform !== 'darwin').each([ expect(await card.textContent()).toContain('允许 agent 直接操作电脑上的应用程序。') expect(await card.textContent()).not.toContain('helper') expect(await card.textContent()).not.toContain('Swift') - const description = await card.getByRole('button', { name: '查看 Computer Use', exact: true }).evaluate((button) => { + const description = await card.getByRole('button', { name: '查看自动电脑操作', exact: true }).evaluate((button) => { const element = document.getElementById(button.getAttribute('aria-describedby')!)! const style = getComputedStyle(element) return { lines: style.webkitLineClamp, height: element.getBoundingClientRect().height, @@ -149,7 +149,7 @@ it.skipIf(process.platform !== 'darwin').each([ expect(runtimeFiber() === originalRuntimeFiber).toBe(true) expect(scaffold.ctx.ptcRuntime.programFormat).toBe(script ? 'script' : 'function-body') await setup.waitFor() - expect(await setup.getByText('Computer Use 插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) + expect(await setup.getByText('自动电脑操作插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) await setup.getByRole('button', { name: '稍后', exact: true }).click() await setup.waitFor({ state: 'hidden' }) let saved = await readFile(settingsPath, 'utf8') @@ -176,20 +176,20 @@ it.skipIf(process.platform !== 'darwin').each([ })).agent expect(scaffold.ctx.agentPresets.composedPreset(fresh.ctx)).toBe('ptc') expect(scaffold.ctx.tools.schemas(fresh).some(tool => tool.name === 'cua')).toBe(true) - await card.getByRole('button', { name: '查看 Computer Use', exact: true }).click() + await card.getByRole('button', { name: '查看自动电脑操作', exact: true }).click() const detail = plugins.locator('[data-detail-document]') await detail.getByRole('img', { name: '将会议要点填入备忘录的指令和输入结果' }).waitFor() const guidance = plugins.locator('[data-cua-guidance]') await guidance.getByText(/请谨慎在生产环境中使用/).waitFor() expect(await guidance.textContent()).not.toContain('helperPath') expect(await detail.textContent()).not.toContain('PTC') - toggle = page.locator('[data-plugin-panel]').getByRole('switch', { name: '启用 Computer Use', exact: true }) + toggle = page.locator('[data-plugin-panel]').getByRole('switch', { name: '启用自动电脑操作', exact: true }) const persistent = page.getByRole('group', { name: 'PTC 执行方式', exact: true }) if (!codingTools) { const panel = page.locator('[data-cua-settings]') await expect.poll(() => panel.getAttribute('aria-busy')).toBe('false') - expect(await panel.textContent()).toContain('标准、创造和 PTC 模式均可使用 Computer Use') - expect(await persistent.textContent()).toContain('其他模式始终单独保留 Computer Use 状态') + expect(await panel.textContent()).toContain('标准、创造和 PTC 模式均可使用自动电脑操作') + expect(await persistent.textContent()).toContain('其他模式始终单独保留自动电脑操作状态') for (const width of [1680, 390]) { await page.setViewportSize({ width, height: 1000 }) for (const colorScheme of ['light', 'dark'] as const) { @@ -239,11 +239,11 @@ it.skipIf(process.platform !== 'darwin').each([ await toggle.click() await toggle.and(page.locator('[aria-checked="true"]')).waitFor({ state: 'visible' }) await setup.waitFor() - expect(await setup.getByText('Computer Use 插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) + expect(await setup.getByText('自动电脑操作插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) expect(scaffold.ctx.agentPresets.defaultId).toBe(initialDefault) await setup.getByRole('button', { name: '前往设置', exact: true }).click() await setup.waitFor({ state: 'hidden' }) - await page.getByRole('region', { name: '给 Computer Use 授权', exact: true }).getByRole('alert').waitFor() + await page.getByRole('region', { name: '给自动电脑操作授权', exact: true }).getByRole('alert').waitFor() if (!codingTools) { expect(await readFile(settingsPath, 'utf8')).toBe(saved) expect(scaffold.ctx.settings.describe().find(row => row.ns === 'ui-settings')?.value).toMatchObject({ enabled: false }) @@ -278,7 +278,7 @@ it.skipIf(process.platform !== 'darwin').each([ await toggle.click() await toggle.and(page.locator('[aria-checked="true"]')).waitFor({ state: 'visible' }) await setup.waitFor() - expect(await setup.getByText('Computer Use 插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) + expect(await setup.getByText('自动电脑操作插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) expect(await setup.getByRole('button', { name: '设为 PTC', exact: true }).count()).toBe(0) expect(await readFile(settingsPath, 'utf8')).toBe(confirmedSettings) expect(scaffold.ctx.settings.describe().find(row => row.ns === 'ui-settings')?.value).toMatchObject({ enabled: codingTools }) diff --git a/apps/web/tests/expected/cua-permissions/default-mode.expected.md b/apps/web/tests/expected/cua-permissions/default-mode.expected.md index fba38356f3..589d3fddde 100644 --- a/apps/web/tests/expected/cua-permissions/default-mode.expected.md +++ b/apps/web/tests/expected/cua-permissions/default-mode.expected.md @@ -1,4 +1,4 @@ - group "新会话默认模式": - strong: 新会话默认模式 - - paragraph: 标准、创造和 PTC 模式均可使用 Computer Use。在此选择 PTC,可将其设为新会话的默认模式 + - paragraph: 标准、创造和 PTC 模式均可使用自动电脑操作。在此选择 PTC,可将其设为新会话的默认模式 - button "设为 PTC" diff --git a/apps/web/tests/expected/cua-permissions/enabling.expected.md b/apps/web/tests/expected/cua-permissions/enabling.expected.md index 44fc57e3e3..c4ebb5bca1 100644 --- a/apps/web/tests/expected/cua-permissions/enabling.expected.md +++ b/apps/web/tests/expected/cua-permissions/enabling.expected.md @@ -1 +1 @@ -- status: 正在应用 Computer Use 的更改 +- status: 正在应用自动电脑操作的更改 diff --git a/apps/web/tests/expected/cua-permissions/setup.expected.md b/apps/web/tests/expected/cua-permissions/setup.expected.md index 0ee5870bf3..f10e8f961c 100644 --- a/apps/web/tests/expected/cua-permissions/setup.expected.md +++ b/apps/web/tests/expected/cua-permissions/setup.expected.md @@ -1,6 +1,6 @@ -- dialog "使用 Computer Use 前需要设置": - - heading "使用 Computer Use 前需要设置" [level=2] +- dialog "使用自动电脑操作前需要设置": + - heading "使用自动电脑操作前需要设置" [level=2] - button "关闭" - - paragraph: Computer Use 插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。 + - paragraph: 自动电脑操作插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。 - button "稍后" - button "前往设置" diff --git a/packages/experimental/cua-bundle/README.i18n.yaml b/packages/experimental/cua-bundle/README.i18n.yaml index 0154449a45..3a5885ae46 100644 --- a/packages/experimental/cua-bundle/README.i18n.yaml +++ b/packages/experimental/cua-bundle/README.i18n.yaml @@ -16,7 +16,7 @@ zh: d0228da978238e05 /deepseek-ai-dsh-cua-bundle/use-this-package: en: ab8ae9608195104a - zh: 460911e6390612f2 + zh: 81c74f21275f64f8 /deepseek-ai-dsh-cua-bundle/understand-the-implementation: en: acb42fb7b181194b zh: 6961f4cb732560e9 diff --git a/packages/experimental/cua-bundle/README.zh.md b/packages/experimental/cua-bundle/README.zh.md index 4a7c792935..97e4d73d56 100644 --- a/packages/experimental/cua-bundle/README.zh.md +++ b/packages/experimental/cua-bundle/README.zh.md @@ -24,7 +24,7 @@ kind: "package-bundle" ## 使用本包 -在 macOS 或 Windows 上打开“插件 → 更多”,在实验性插件列表中开启 Computer Use。开启后组合包也会出现在插件主列表中,关闭后只留在实验性插件列表。启用后,详情页在配图下方、设置项上方显示使用建议,Windows 用户还可查看辅助程序的配置步骤。 +在 macOS 或 Windows 上打开“插件 → 更多”,在实验性插件列表中开启“自动电脑操作”。开启后组合包也会出现在插件主列表中,关闭后只留在实验性插件列表。启用后,详情页在配图下方、设置项上方显示使用建议,Windows 用户还可查看辅助程序的配置步骤。 在 macOS 上,组合包随 DSH 提供并随之升级,开启时无需下载。发布包包含已签名和公证的 helper,用户无需编译工具。源码 Web 和开发 Desktop 在开启时准备临时签名的 helper。请为 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。 diff --git a/packages/experimental/cua-bundle/locale/zh.json b/packages/experimental/cua-bundle/locale/zh.json index e729a5bb13..43bedfe779 100644 --- a/packages/experimental/cua-bundle/locale/zh.json +++ b/packages/experimental/cua-bundle/locale/zh.json @@ -1,6 +1,6 @@ { "meta": { - "title": "Computer Use", + "title": "自动电脑操作", "description": "允许 agent 直接操作电脑上的应用程序。", "detail": "docs/DETAIL.zh.md" } diff --git a/packages/experimental/cua-macos/locale/zh.json b/packages/experimental/cua-macos/locale/zh.json index ebfd9e1286..d4b9eac292 100644 --- a/packages/experimental/cua-macos/locale/zh.json +++ b/packages/experimental/cua-macos/locale/zh.json @@ -1,6 +1,6 @@ { "meta": { - "title": "macOS Computer Use 后端", - "description": "为共享 Computer Use 服务提供 macOS 原生应用与窗口对象。" + "title": "macOS 自动电脑操作后端", + "description": "为共享自动电脑操作服务提供 macOS 原生应用与窗口对象。" } } diff --git a/packages/experimental/cua-macos/src/permission-guide.ts b/packages/experimental/cua-macos/src/permission-guide.ts index 1074104351..a1effc11ea 100644 --- a/packages/experimental/cua-macos/src/permission-guide.ts +++ b/packages/experimental/cua-macos/src/permission-guide.ts @@ -24,7 +24,7 @@ const zh = { instruction: '将 {application} 拖入上方列表以允许{permission}', backLabel: '返回', finderLabel: '在 Finder 中显示', - unavailableMessage: '找不到此应用。请重新启用 Computer Use 后重试', + unavailableMessage: '找不到此应用。请重新启用自动电脑操作后重试', settingsMessage: '请手动打开系统设置 > 隐私与安全性 > {permission}', accessibility: '辅助功能', screenRecording: '屏幕录制', diff --git a/packages/experimental/cua-macos/tests/permission-guide.spec.ts b/packages/experimental/cua-macos/tests/permission-guide.spec.ts index 47a4c8a6f1..d005b77c13 100644 --- a/packages/experimental/cua-macos/tests/permission-guide.spec.ts +++ b/packages/experimental/cua-macos/tests/permission-guide.spec.ts @@ -29,7 +29,7 @@ it('matches language variants and falls back to English for unsupported language expect(parameters('requestPermission', 'accessibility', 'ZH-CN')).toEqual({ permission: 'accessibility', pollIntervalMs: 2000, instruction: '将 {application} 拖入上方列表以允许辅助功能', backLabel: '返回', finderLabel: '在 Finder 中显示', - unavailableMessage: '找不到此应用。请重新启用 Computer Use 后重试', + unavailableMessage: '找不到此应用。请重新启用自动电脑操作后重试', settingsMessage: '请手动打开系统设置 > 隐私与安全性 > 辅助功能', }) expect(parameters('requestPermission', 'screenRecording', 'it')).toEqual(parameters('requestPermission', 'screenRecording', 'en')) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 232a0f4751..c841c6b01d 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -1161,7 +1161,7 @@ it('routes permission actions through the macOS provider with the Client languag expect(native.request).toHaveBeenLastCalledWith('requestPermission', { permission: 'accessibility', pollIntervalMs: 1000, instruction: '将 {application} 拖入上方列表以允许辅助功能', backLabel: '返回', finderLabel: '在 Finder 中显示', - unavailableMessage: '找不到此应用。请重新启用 Computer Use 后重试', + unavailableMessage: '找不到此应用。请重新启用自动电脑操作后重试', settingsMessage: '请手动打开系统设置 > 隐私与安全性 > 辅助功能', }, expect.any(AbortSignal)) native.request.mockResolvedValueOnce({ opened: true }) diff --git a/packages/experimental/cua-mcp/locale/zh.json b/packages/experimental/cua-mcp/locale/zh.json index c7a6ef179f..00c44036da 100644 --- a/packages/experimental/cua-mcp/locale/zh.json +++ b/packages/experimental/cua-mcp/locale/zh.json @@ -1,6 +1,6 @@ { "meta": { - "title": "Computer Use MCP 服务器", - "description": "通过 cua-mcp profile 向 Codex、Claude Code 等 MCP 客户端提供 Computer Use:cua_run_code 对桌面应用运行持久程序,cua_reset 清空程序环境。" + "title": "自动电脑操作 MCP 服务器", + "description": "通过 cua-mcp profile 向 Codex、Claude Code 等 MCP 客户端提供自动电脑操作:cua_run_code 对桌面应用运行持久程序,cua_reset 清空程序环境。" } } diff --git a/packages/experimental/cua-windows/locale/zh.json b/packages/experimental/cua-windows/locale/zh.json index 69b2d02d65..10adf265dc 100644 --- a/packages/experimental/cua-windows/locale/zh.json +++ b/packages/experimental/cua-windows/locale/zh.json @@ -1,6 +1,6 @@ { "meta": { - "title": "Windows Computer Use 后端", - "description": "为共享 Computer Use 服务提供 Windows 原生应用与窗口对象。" + "title": "Windows 自动电脑操作后端", + "description": "为共享自动电脑操作服务提供 Windows 原生应用与窗口对象。" } } diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 5b7de75510..7131514011 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -19,7 +19,7 @@ zh: 5687bd20ba8be40b /deepseek-ai-dsh-cua/use-this-package/permission-controls: en: 3f638a4a76023fc5 - zh: 515aeb5de6ae5b33 + zh: 19a5e98109511ae7 /deepseek-ai-dsh-cua/understand-the-implementation: en: 7754a370ed7e54ff zh: a3fa369e265746ad diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index 1e9207d343..a990264391 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -67,7 +67,7 @@ kind: "package-reference" Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边框,区块间距为 32px。应用名称徽标保留 l1 边框。 -[Computer Use 组合](../cua-bundle/README.zh.md)将本页与原生 provider 一起挂载。在 macOS 上,“给 Computer Use 授权”把新会话默认模式、PTC 执行方式、辅助功能和屏幕录制放在同一个边框内。每条权限要求显示责任应用的名称和图标。“申请权限”将所选权限和当前界面语言交给 provider;原生拖动引导由 [macOS provider](../cua-macos/README.zh.md)负责。“已允许”描边按钮打开设置以撤销权限;未知状态使用“未确认”。应用访问授权保持独立分组。 +[Computer Use 组合](../cua-bundle/README.zh.md)将本页与原生 provider 一起挂载。在 macOS 上,“给自动电脑操作授权”把新会话默认模式、PTC 执行方式、辅助功能和屏幕录制放在同一个边框内。每条权限要求显示责任应用的名称和图标。“申请权限”将所选权限和当前界面语言交给 provider;原生拖动引导由 [macOS provider](../cua-macos/README.zh.md)负责。“已允许”描边按钮打开设置以撤销权限;未知状态使用“未确认”。应用访问授权保持独立分组。 启用组合包后,PTC 设置上方显示预览提示。Windows 页面还提供 npm 安装所需的辅助程序构建和配置步骤,macOS 页面提供辅助功能和屏幕录制授权操作。 diff --git a/packages/experimental/cua/locale/zh.json b/packages/experimental/cua/locale/zh.json index f47efff11b..7cc2da6bff 100644 --- a/packages/experimental/cua/locale/zh.json +++ b/packages/experimental/cua/locale/zh.json @@ -1,6 +1,6 @@ { "meta": { - "title": "Computer Use 服务", - "description": "管理 Computer Use 的应用对象、授权和带日志的工具执行。" + "title": "自动电脑操作服务", + "description": "管理自动电脑操作的应用对象、授权和带日志的工具执行。" } } diff --git a/packages/experimental/cua/src/client/locales.ts b/packages/experimental/cua/src/client/locales.ts index e66276a6c4..b1b4f97311 100644 --- a/packages/experimental/cua/src/client/locales.ts +++ b/packages/experimental/cua/src/client/locales.ts @@ -56,16 +56,16 @@ export const en = { export type CuaPermissionLocaleKey = keyof typeof en /** Chinese permission-page dictionary. */ export const zh: Record = { - previewNotice: 'Computer Use 是实验性预览功能。agent 可能点错按钮,或把内容输入错误的窗口,请谨慎在生产环境中使用。推荐使用原生 PTC 模式,agent 可以在同一段代码中操作应用并调用其他工具。', + previewNotice: '自动电脑操作是实验性预览功能。agent 可能点错按钮,或把内容输入错误的窗口,请谨慎在生产环境中使用。推荐使用原生 PTC 模式,agent 可以在同一段代码中操作应用并调用其他工具。', windowsHelperBuild: '通过 npm 安装 DSH 后,请使用对应版本的 DSH 源码构建 Windows 辅助程序。在 {directory} 中使用 .NET 10 SDK,按电脑架构运行 {x64} 或 {arm64}。', - providerLookupFailed: '无法识别 Computer Use 提供方:{message}', + providerLookupFailed: '无法识别自动电脑操作提供方:{message}', windowsHelperPath: '在当前 profile 的 {patch} 中,找到或添加 ID 为 {entry} 的条目,将其 {config} 下的 {path} 设为 {exe} 的绝对路径。', approvalRisks: '风险提示', - approvalRiskTitle: 'Computer Use 风险提示', + approvalRiskTitle: '自动电脑操作风险提示', approvalRiskNotice: '智能体只能访问你已授权的应用,并可在后台读取应用内容、操作应用。\n\n网络游戏、即时通讯等应用可能对自动化操作有所限制。违反相关规则可能导致你在该应用中的账号被暂停使用或封禁。\n\n请自行承担使用风险。如需停止自动化操作,可随时点击 DeepSeek Harness 中的停止按钮。', - title: '给 Computer Use 授权', applicationsTitle: '管理 Computer Use 可访问的应用', setupTitle: '使用 Computer Use 前需要设置', - setupBody: 'Computer Use 插件已开启。使用前请授予辅助功能和屏幕录制权限。请前往插件详情页完成设置。', - setupQueryFailed: 'Computer Use 插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', + title: '给自动电脑操作授权', applicationsTitle: '管理自动电脑操作可访问的应用', setupTitle: '使用自动电脑操作前需要设置', + setupBody: '自动电脑操作插件已开启。使用前请授予辅助功能和屏幕录制权限。请前往插件详情页完成设置。', + setupQueryFailed: '自动电脑操作插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', windowsSetupTitle: '检查 Windows 桌面访问状态', windowsSetupBody: '请解锁 Windows 桌面,然后重新检测。DSH 会在访问每个应用前询问授权。', windowsSessionUnknown: '尚未确认可交互的 Windows 桌面。请在已登录的桌面会话中运行 DSH,然后重新检测。', @@ -76,14 +76,14 @@ export const zh: Record = { windowsCapture: '窗口截图', available: '可用', unavailable: '不可用', locked: '已锁定或断开连接', elevated: '本机组件正以管理员权限运行。', standardPrivileges: '本机组件正以普通用户权限运行。', defaultTitle: '新会话默认模式', - defaultBody: '标准、创造和 PTC 模式均可使用 Computer Use。在此选择 PTC,可将其设为新会话的默认模式', + defaultBody: '标准、创造和 PTC 模式均可使用自动电脑操作。在此选择 PTC,可将其设为新会话的默认模式', defaultConfirm: '设为 PTC', defaultSet: '已设为 PTC', defaultUnavailable: '无法读取默认模式,请在设置中检查', defaultReadOnly: '默认模式设置为只读', defaultNotSaved: '默认模式未保存,请重试', defaultFailed: '无法切换默认模式:{message}', persistentTitle: 'PTC 执行方式', - persistentBody: '跨 PTC 工具调用保留变量和应用对象。切换会重启 PTC 运行时。其他模式始终单独保留 Computer Use 状态。', + persistentBody: '跨 PTC 工具调用保留变量和应用对象。切换会重启 PTC 运行时。其他模式始终单独保留自动电脑操作状态。', persistentConfirm: '设为持久化', persistentSet: '已设为持久化', persistentUnavailable: '无法读取 PTC 执行方式,请在设置中检查', persistentReadOnly: 'PTC 执行方式设置为只读', diff --git a/packages/experimental/cua/src/locales.ts b/packages/experimental/cua/src/locales.ts index 499ce34339..a6d6bb8668 100644 --- a/packages/experimental/cua/src/locales.ts +++ b/packages/experimental/cua/src/locales.ts @@ -9,7 +9,7 @@ export const en = { /** Chinese application-access messages. */ export const zh = { - question: '允许智能体通过 Computer Use 控制此应用吗?', + question: '允许智能体通过自动电脑操作控制此应用吗?', detail: '在插件页面管理所有会话的应用权限。', approve: '本会话允许', } satisfies Record @@ -84,7 +84,7 @@ export const applicationAccessDisplay = { /** Window consent never grants access to sibling windows or application launch. */ export const windowAccessQuestion = { en: 'Allow computer use to read, capture and control this window?', - zh: '允许电脑操作读取、截图并控制这个窗口吗?', + zh: '允许自动电脑操作读取、截图并控制这个窗口吗?', ja: 'このウィンドウの読み取り、撮影、操作を許可しますか?', es: '¿Permitir leer, capturar y controlar esta ventana?', fr: 'Autoriser la lecture, la capture et le contrôle de cette fenêtre ?', @@ -95,7 +95,7 @@ export const windowAccessQuestion = { /** Launch consent does not grant access to resulting windows. */ export const launchAccessQuestion = { en: 'Allow computer use to launch this entry? Window access is requested separately.', - zh: '允许电脑操作启动这个入口吗?窗口访问将单独请求授权。', + zh: '允许自动电脑操作启动这个入口吗?窗口访问将单独请求授权。', ja: 'この項目の起動を許可しますか?ウィンドウへのアクセスは別途確認します。', es: '¿Permitir iniciar esta entrada? El acceso a ventanas se solicita por separado.', fr: 'Autoriser le lancement de cette entrée ? L’accès aux fenêtres sera demandé séparément.', diff --git a/packages/experimental/cua/tests/application-access.spec.ts b/packages/experimental/cua/tests/application-access.spec.ts index 4ea6701b68..6c7c6479e1 100644 --- a/packages/experimental/cua/tests/application-access.spec.ts +++ b/packages/experimental/cua/tests/application-access.spec.ts @@ -114,7 +114,7 @@ it.each([ intent: { kind: 'approval', approve: 'Allow for this session', reject: 'Deny', subject: { name: 'Test application' }, display: { question: { en: 'Allow agent to control this application via computer use?', - zh: '允许智能体通过 Computer Use 控制此应用吗?', + zh: '允许智能体通过自动电脑操作控制此应用吗?', ja: 'エージェントが Computer Use でこのアプリを操作することを許可しますか?' }, detail: { en: 'Manage app permissions for all sessions on the plugin page.', zh: '在插件页面管理所有会话的应用权限。', From afa0120e4b81d4eb6c0a8286a54fc302901c99f6 Mon Sep 17 00:00:00 2001 From: Yixiang Tu Date: Fri, 20 Nov 2026 18:31:46 +0800 Subject: [PATCH 5/8] =?UTF-8?q?fix(cua):=20polish=20Chinese=20UI=20copy=20?= =?UTF-8?q?for=20=E8=87=AA=E5=8A=A8=E7=94=B5=E8=84=91=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/web/tests/cua-optin.e2e.ts | 30 +++++++++---------- .../cua-permissions/default-mode.expected.md | 2 +- .../cua-permissions/enabling.expected.md | 2 +- .../cua-permissions/setup.expected.md | 6 ++-- .../experimental/cua-bundle/locale/zh.json | 2 +- .../experimental/cua-macos/locale/zh.json | 2 +- .../cua-macos/src/permission-guide.ts | 2 +- .../cua-macos/tests/permission-guide.spec.ts | 2 +- .../tests/provider-lifecycle.spec.ts | 2 +- packages/experimental/cua-mcp/locale/zh.json | 2 +- .../experimental/cua-windows/locale/zh.json | 2 +- packages/experimental/cua/README.i18n.yaml | 2 +- packages/experimental/cua/README.zh.md | 2 +- .../experimental/cua/src/client/locales.ts | 14 ++++----- packages/experimental/cua/src/locales.ts | 6 ++-- .../cua/tests/application-access.spec.ts | 2 +- 16 files changed, 40 insertions(+), 40 deletions(-) diff --git a/apps/web/tests/cua-optin.e2e.ts b/apps/web/tests/cua-optin.e2e.ts index cc9f19620d..7c183efc57 100644 --- a/apps/web/tests/cua-optin.e2e.ts +++ b/apps/web/tests/cua-optin.e2e.ts @@ -61,7 +61,7 @@ it.skipIf(process.platform !== 'darwin').each([ const listed = (await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === '@deepseek-ai/dsh-cua-bundle') expect(listed).toMatchObject({ availability: 'installation', optional: true, enabled: false, installed: false }) expect(listed).not.toHaveProperty('listedByDefault') - let toggle = card.getByRole('switch', { name: '启用自动电脑操作', exact: true }) + let toggle = card.getByRole('switch', { name: '启用 自动电脑操作', exact: true }) const originalAgent = scaffold.ctx.agents.list()[0]! const ptcAgent = (await scaffold.ctx.agents.create({ sessionId: brandString('cua-existing-ptc'), @@ -90,7 +90,7 @@ it.skipIf(process.platform !== 'darwin').each([ }) try { await toggle.click() - await card.getByRole('status').getByText('正在应用自动电脑操作的更改', { exact: true }).waitFor() + await card.getByRole('status').getByText('正在应用 自动电脑操作 的更改', { exact: true }).waitFor() await compareOrRefreshGolden(fileURLToPath(new URL('./expected/cua-permissions/enabling.expected.md', import.meta.url)), await captureStableAria(page, '[data-plugin-package="@deepseek-ai/dsh-cua-bundle"] [role="status"]', scaffold.workspaceCwd), webSnapshotMode()) } finally { @@ -100,10 +100,10 @@ it.skipIf(process.platform !== 'darwin').each([ } // Bundle transitions await native cleanup under the browser action deadline. await toggle.and(page.locator('[aria-checked="true"]')).waitFor({ state: 'visible' }) - await card.getByRole('status').getByText('正在应用自动电脑操作的更改', { exact: true }).waitFor({ state: 'hidden' }) - const setup = page.getByRole('dialog', { name: '使用自动电脑操作前需要设置', exact: true }) + await card.getByRole('status').getByText('正在应用 自动电脑操作 的更改', { exact: true }).waitFor({ state: 'hidden' }) + const setup = page.getByRole('dialog', { name: '配置自动电脑操作', exact: true }) await setup.waitFor() - expect(await setup.getByText('自动电脑操作插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) + expect(await setup.getByText('“自动电脑操作”插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) await compareOrRefreshGolden(fileURLToPath(new URL('./expected/cua-permissions/setup.expected.md', import.meta.url)), await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), webSnapshotMode()) expect(await setup.getByRole('button', { name: '设为 PTC', exact: true }).count()).toBe(0) @@ -113,10 +113,10 @@ it.skipIf(process.platform !== 'darwin').each([ expect(await card.getByText('实验性', { exact: true }).count()).toBe(1) expect(await card.textContent()).not.toContain('将 PTC 模式改为可持久化') expect(await card.textContent()).not.toContain('请切换到 PTC 模式') - expect(await card.textContent()).toContain('允许 agent 直接操作电脑上的应用程序。') + expect(await card.textContent()).toContain('允许智能体直接操作电脑上的应用程序。') expect(await card.textContent()).not.toContain('helper') expect(await card.textContent()).not.toContain('Swift') - const description = await card.getByRole('button', { name: '查看自动电脑操作', exact: true }).evaluate((button) => { + const description = await card.getByRole('button', { name: '查看 自动电脑操作', exact: true }).evaluate((button) => { const element = document.getElementById(button.getAttribute('aria-describedby')!)! const style = getComputedStyle(element) return { lines: style.webkitLineClamp, height: element.getBoundingClientRect().height, @@ -149,7 +149,7 @@ it.skipIf(process.platform !== 'darwin').each([ expect(runtimeFiber() === originalRuntimeFiber).toBe(true) expect(scaffold.ctx.ptcRuntime.programFormat).toBe(script ? 'script' : 'function-body') await setup.waitFor() - expect(await setup.getByText('自动电脑操作插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) + expect(await setup.getByText('“自动电脑操作”插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) await setup.getByRole('button', { name: '稍后', exact: true }).click() await setup.waitFor({ state: 'hidden' }) let saved = await readFile(settingsPath, 'utf8') @@ -176,20 +176,20 @@ it.skipIf(process.platform !== 'darwin').each([ })).agent expect(scaffold.ctx.agentPresets.composedPreset(fresh.ctx)).toBe('ptc') expect(scaffold.ctx.tools.schemas(fresh).some(tool => tool.name === 'cua')).toBe(true) - await card.getByRole('button', { name: '查看自动电脑操作', exact: true }).click() + await card.getByRole('button', { name: '查看 自动电脑操作', exact: true }).click() const detail = plugins.locator('[data-detail-document]') await detail.getByRole('img', { name: '将会议要点填入备忘录的指令和输入结果' }).waitFor() const guidance = plugins.locator('[data-cua-guidance]') await guidance.getByText(/请谨慎在生产环境中使用/).waitFor() expect(await guidance.textContent()).not.toContain('helperPath') expect(await detail.textContent()).not.toContain('PTC') - toggle = page.locator('[data-plugin-panel]').getByRole('switch', { name: '启用自动电脑操作', exact: true }) + toggle = page.locator('[data-plugin-panel]').getByRole('switch', { name: '启用 自动电脑操作', exact: true }) const persistent = page.getByRole('group', { name: 'PTC 执行方式', exact: true }) if (!codingTools) { const panel = page.locator('[data-cua-settings]') await expect.poll(() => panel.getAttribute('aria-busy')).toBe('false') - expect(await panel.textContent()).toContain('标准、创造和 PTC 模式均可使用自动电脑操作') - expect(await persistent.textContent()).toContain('其他模式始终单独保留自动电脑操作状态') + expect(await panel.textContent()).toContain('标准、创造和 PTC 模式均支持自动电脑操作') + expect(await persistent.textContent()).toContain('其他模式始终各自独立保留自动电脑操作的运行状态') for (const width of [1680, 390]) { await page.setViewportSize({ width, height: 1000 }) for (const colorScheme of ['light', 'dark'] as const) { @@ -239,11 +239,11 @@ it.skipIf(process.platform !== 'darwin').each([ await toggle.click() await toggle.and(page.locator('[aria-checked="true"]')).waitFor({ state: 'visible' }) await setup.waitFor() - expect(await setup.getByText('自动电脑操作插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) + expect(await setup.getByText('“自动电脑操作”插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) expect(scaffold.ctx.agentPresets.defaultId).toBe(initialDefault) await setup.getByRole('button', { name: '前往设置', exact: true }).click() await setup.waitFor({ state: 'hidden' }) - await page.getByRole('region', { name: '给自动电脑操作授权', exact: true }).getByRole('alert').waitFor() + await page.getByRole('region', { name: '系统权限与设置', exact: true }).getByRole('alert').waitFor() if (!codingTools) { expect(await readFile(settingsPath, 'utf8')).toBe(saved) expect(scaffold.ctx.settings.describe().find(row => row.ns === 'ui-settings')?.value).toMatchObject({ enabled: false }) @@ -278,7 +278,7 @@ it.skipIf(process.platform !== 'darwin').each([ await toggle.click() await toggle.and(page.locator('[aria-checked="true"]')).waitFor({ state: 'visible' }) await setup.waitFor() - expect(await setup.getByText('自动电脑操作插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) + expect(await setup.getByText('“自动电脑操作”插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) expect(await setup.getByRole('button', { name: '设为 PTC', exact: true }).count()).toBe(0) expect(await readFile(settingsPath, 'utf8')).toBe(confirmedSettings) expect(scaffold.ctx.settings.describe().find(row => row.ns === 'ui-settings')?.value).toMatchObject({ enabled: codingTools }) diff --git a/apps/web/tests/expected/cua-permissions/default-mode.expected.md b/apps/web/tests/expected/cua-permissions/default-mode.expected.md index 589d3fddde..f986a34f24 100644 --- a/apps/web/tests/expected/cua-permissions/default-mode.expected.md +++ b/apps/web/tests/expected/cua-permissions/default-mode.expected.md @@ -1,4 +1,4 @@ - group "新会话默认模式": - strong: 新会话默认模式 - - paragraph: 标准、创造和 PTC 模式均可使用自动电脑操作。在此选择 PTC,可将其设为新会话的默认模式 + - paragraph: 标准、创造和 PTC 模式均支持自动电脑操作。在此选择 PTC,可将其设为新会话的默认模式。 - button "设为 PTC" diff --git a/apps/web/tests/expected/cua-permissions/enabling.expected.md b/apps/web/tests/expected/cua-permissions/enabling.expected.md index c4ebb5bca1..f034cdc2da 100644 --- a/apps/web/tests/expected/cua-permissions/enabling.expected.md +++ b/apps/web/tests/expected/cua-permissions/enabling.expected.md @@ -1 +1 @@ -- status: 正在应用自动电脑操作的更改 +- status: 正在应用 自动电脑操作 的更改 diff --git a/apps/web/tests/expected/cua-permissions/setup.expected.md b/apps/web/tests/expected/cua-permissions/setup.expected.md index f10e8f961c..1b918bf3f8 100644 --- a/apps/web/tests/expected/cua-permissions/setup.expected.md +++ b/apps/web/tests/expected/cua-permissions/setup.expected.md @@ -1,6 +1,6 @@ -- dialog "使用自动电脑操作前需要设置": - - heading "使用自动电脑操作前需要设置" [level=2] +- dialog "配置自动电脑操作": + - heading "配置自动电脑操作" [level=2] - button "关闭" - - paragraph: 自动电脑操作插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。 + - paragraph: “自动电脑操作”插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。 - button "稍后" - button "前往设置" diff --git a/packages/experimental/cua-bundle/locale/zh.json b/packages/experimental/cua-bundle/locale/zh.json index 43bedfe779..10d40c6376 100644 --- a/packages/experimental/cua-bundle/locale/zh.json +++ b/packages/experimental/cua-bundle/locale/zh.json @@ -1,7 +1,7 @@ { "meta": { "title": "自动电脑操作", - "description": "允许 agent 直接操作电脑上的应用程序。", + "description": "允许智能体直接操作电脑上的应用程序。", "detail": "docs/DETAIL.zh.md" } } diff --git a/packages/experimental/cua-macos/locale/zh.json b/packages/experimental/cua-macos/locale/zh.json index d4b9eac292..994fb548be 100644 --- a/packages/experimental/cua-macos/locale/zh.json +++ b/packages/experimental/cua-macos/locale/zh.json @@ -1,6 +1,6 @@ { "meta": { "title": "macOS 自动电脑操作后端", - "description": "为共享自动电脑操作服务提供 macOS 原生应用与窗口对象。" + "description": "为自动电脑操作服务提供 macOS 原生应用与窗口对象。" } } diff --git a/packages/experimental/cua-macos/src/permission-guide.ts b/packages/experimental/cua-macos/src/permission-guide.ts index a1effc11ea..7061f8df8c 100644 --- a/packages/experimental/cua-macos/src/permission-guide.ts +++ b/packages/experimental/cua-macos/src/permission-guide.ts @@ -24,7 +24,7 @@ const zh = { instruction: '将 {application} 拖入上方列表以允许{permission}', backLabel: '返回', finderLabel: '在 Finder 中显示', - unavailableMessage: '找不到此应用。请重新启用自动电脑操作后重试', + unavailableMessage: '找不到此应用。请重新启用“自动电脑操作”插件后重试', settingsMessage: '请手动打开系统设置 > 隐私与安全性 > {permission}', accessibility: '辅助功能', screenRecording: '屏幕录制', diff --git a/packages/experimental/cua-macos/tests/permission-guide.spec.ts b/packages/experimental/cua-macos/tests/permission-guide.spec.ts index d005b77c13..2ac82da48c 100644 --- a/packages/experimental/cua-macos/tests/permission-guide.spec.ts +++ b/packages/experimental/cua-macos/tests/permission-guide.spec.ts @@ -29,7 +29,7 @@ it('matches language variants and falls back to English for unsupported language expect(parameters('requestPermission', 'accessibility', 'ZH-CN')).toEqual({ permission: 'accessibility', pollIntervalMs: 2000, instruction: '将 {application} 拖入上方列表以允许辅助功能', backLabel: '返回', finderLabel: '在 Finder 中显示', - unavailableMessage: '找不到此应用。请重新启用自动电脑操作后重试', + unavailableMessage: '找不到此应用。请重新启用“自动电脑操作”插件后重试', settingsMessage: '请手动打开系统设置 > 隐私与安全性 > 辅助功能', }) expect(parameters('requestPermission', 'screenRecording', 'it')).toEqual(parameters('requestPermission', 'screenRecording', 'en')) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index c841c6b01d..fbdef26da0 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -1161,7 +1161,7 @@ it('routes permission actions through the macOS provider with the Client languag expect(native.request).toHaveBeenLastCalledWith('requestPermission', { permission: 'accessibility', pollIntervalMs: 1000, instruction: '将 {application} 拖入上方列表以允许辅助功能', backLabel: '返回', finderLabel: '在 Finder 中显示', - unavailableMessage: '找不到此应用。请重新启用自动电脑操作后重试', + unavailableMessage: '找不到此应用。请重新启用“自动电脑操作”插件后重试', settingsMessage: '请手动打开系统设置 > 隐私与安全性 > 辅助功能', }, expect.any(AbortSignal)) native.request.mockResolvedValueOnce({ opened: true }) diff --git a/packages/experimental/cua-mcp/locale/zh.json b/packages/experimental/cua-mcp/locale/zh.json index 00c44036da..85bfab3b99 100644 --- a/packages/experimental/cua-mcp/locale/zh.json +++ b/packages/experimental/cua-mcp/locale/zh.json @@ -1,6 +1,6 @@ { "meta": { "title": "自动电脑操作 MCP 服务器", - "description": "通过 cua-mcp profile 向 Codex、Claude Code 等 MCP 客户端提供自动电脑操作:cua_run_code 对桌面应用运行持久程序,cua_reset 清空程序环境。" + "description": "通过 cua-mcp profile 向 Codex、Claude Code 等 MCP 客户端提供自动电脑操作能力:cua_run_code 对桌面应用运行持久程序,cua_reset 清空程序环境。" } } diff --git a/packages/experimental/cua-windows/locale/zh.json b/packages/experimental/cua-windows/locale/zh.json index 10adf265dc..becd9e7db4 100644 --- a/packages/experimental/cua-windows/locale/zh.json +++ b/packages/experimental/cua-windows/locale/zh.json @@ -1,6 +1,6 @@ { "meta": { "title": "Windows 自动电脑操作后端", - "description": "为共享自动电脑操作服务提供 Windows 原生应用与窗口对象。" + "description": "为自动电脑操作服务提供 Windows 原生应用与窗口对象。" } } diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 7131514011..524f47ebd4 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -19,7 +19,7 @@ zh: 5687bd20ba8be40b /deepseek-ai-dsh-cua/use-this-package/permission-controls: en: 3f638a4a76023fc5 - zh: 19a5e98109511ae7 + zh: e693171d1bdea3a8 /deepseek-ai-dsh-cua/understand-the-implementation: en: 7754a370ed7e54ff zh: a3fa369e265746ad diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index a990264391..cdcbc6f125 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -67,7 +67,7 @@ kind: "package-reference" Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边框,区块间距为 32px。应用名称徽标保留 l1 边框。 -[Computer Use 组合](../cua-bundle/README.zh.md)将本页与原生 provider 一起挂载。在 macOS 上,“给自动电脑操作授权”把新会话默认模式、PTC 执行方式、辅助功能和屏幕录制放在同一个边框内。每条权限要求显示责任应用的名称和图标。“申请权限”将所选权限和当前界面语言交给 provider;原生拖动引导由 [macOS provider](../cua-macos/README.zh.md)负责。“已允许”描边按钮打开设置以撤销权限;未知状态使用“未确认”。应用访问授权保持独立分组。 +[Computer Use 组合](../cua-bundle/README.zh.md)将本页与原生 provider 一起挂载。在 macOS 上,“系统权限与设置”把新会话默认模式、PTC 执行方式、辅助功能和屏幕录制放在同一个边框内。每条权限要求显示责任应用的名称和图标。“申请权限”将所选权限和当前界面语言交给 provider;原生拖动引导由 [macOS provider](../cua-macos/README.zh.md)负责。“已允许”描边按钮打开设置以撤销权限;未知状态使用“未确认”。应用访问授权保持独立分组。 启用组合包后,PTC 设置上方显示预览提示。Windows 页面还提供 npm 安装所需的辅助程序构建和配置步骤,macOS 页面提供辅助功能和屏幕录制授权操作。 diff --git a/packages/experimental/cua/src/client/locales.ts b/packages/experimental/cua/src/client/locales.ts index b1b4f97311..63a368a7a0 100644 --- a/packages/experimental/cua/src/client/locales.ts +++ b/packages/experimental/cua/src/client/locales.ts @@ -56,16 +56,16 @@ export const en = { export type CuaPermissionLocaleKey = keyof typeof en /** Chinese permission-page dictionary. */ export const zh: Record = { - previewNotice: '自动电脑操作是实验性预览功能。agent 可能点错按钮,或把内容输入错误的窗口,请谨慎在生产环境中使用。推荐使用原生 PTC 模式,agent 可以在同一段代码中操作应用并调用其他工具。', + previewNotice: '自动电脑操作目前为实验性预览功能。智能体可能点错按钮,或把内容输入错误的窗口,请谨慎在生产环境中使用。推荐使用原生 PTC 模式,让智能体在同一段代码中操作应用并调用其他工具。', windowsHelperBuild: '通过 npm 安装 DSH 后,请使用对应版本的 DSH 源码构建 Windows 辅助程序。在 {directory} 中使用 .NET 10 SDK,按电脑架构运行 {x64} 或 {arm64}。', - providerLookupFailed: '无法识别自动电脑操作提供方:{message}', + providerLookupFailed: '无法识别自动电脑操作后端:{message}', windowsHelperPath: '在当前 profile 的 {patch} 中,找到或添加 ID 为 {entry} 的条目,将其 {config} 下的 {path} 设为 {exe} 的绝对路径。', approvalRisks: '风险提示', approvalRiskTitle: '自动电脑操作风险提示', approvalRiskNotice: '智能体只能访问你已授权的应用,并可在后台读取应用内容、操作应用。\n\n网络游戏、即时通讯等应用可能对自动化操作有所限制。违反相关规则可能导致你在该应用中的账号被暂停使用或封禁。\n\n请自行承担使用风险。如需停止自动化操作,可随时点击 DeepSeek Harness 中的停止按钮。', - title: '给自动电脑操作授权', applicationsTitle: '管理自动电脑操作可访问的应用', setupTitle: '使用自动电脑操作前需要设置', - setupBody: '自动电脑操作插件已开启。使用前请授予辅助功能和屏幕录制权限。请前往插件详情页完成设置。', - setupQueryFailed: '自动电脑操作插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', + title: '系统权限与设置', applicationsTitle: '管理可访问的应用', setupTitle: '配置自动电脑操作', + setupBody: '“自动电脑操作”插件已开启。使用前需授予辅助功能和屏幕录制权限,请前往插件详情页完成设置。', + setupQueryFailed: '“自动电脑操作”插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', windowsSetupTitle: '检查 Windows 桌面访问状态', windowsSetupBody: '请解锁 Windows 桌面,然后重新检测。DSH 会在访问每个应用前询问授权。', windowsSessionUnknown: '尚未确认可交互的 Windows 桌面。请在已登录的桌面会话中运行 DSH,然后重新检测。', @@ -76,14 +76,14 @@ export const zh: Record = { windowsCapture: '窗口截图', available: '可用', unavailable: '不可用', locked: '已锁定或断开连接', elevated: '本机组件正以管理员权限运行。', standardPrivileges: '本机组件正以普通用户权限运行。', defaultTitle: '新会话默认模式', - defaultBody: '标准、创造和 PTC 模式均可使用自动电脑操作。在此选择 PTC,可将其设为新会话的默认模式', + defaultBody: '标准、创造和 PTC 模式均支持自动电脑操作。在此选择 PTC,可将其设为新会话的默认模式。', defaultConfirm: '设为 PTC', defaultSet: '已设为 PTC', defaultUnavailable: '无法读取默认模式,请在设置中检查', defaultReadOnly: '默认模式设置为只读', defaultNotSaved: '默认模式未保存,请重试', defaultFailed: '无法切换默认模式:{message}', persistentTitle: 'PTC 执行方式', - persistentBody: '跨 PTC 工具调用保留变量和应用对象。切换会重启 PTC 运行时。其他模式始终单独保留自动电脑操作状态。', + persistentBody: '跨 PTC 工具调用保留变量和应用对象。切换会重启 PTC 运行时。其他模式始终各自独立保留自动电脑操作的运行状态。', persistentConfirm: '设为持久化', persistentSet: '已设为持久化', persistentUnavailable: '无法读取 PTC 执行方式,请在设置中检查', persistentReadOnly: 'PTC 执行方式设置为只读', diff --git a/packages/experimental/cua/src/locales.ts b/packages/experimental/cua/src/locales.ts index a6d6bb8668..319f5fa9c4 100644 --- a/packages/experimental/cua/src/locales.ts +++ b/packages/experimental/cua/src/locales.ts @@ -9,7 +9,7 @@ export const en = { /** Chinese application-access messages. */ export const zh = { - question: '允许智能体通过自动电脑操作控制此应用吗?', + question: '允许智能体自动操作此应用吗?', detail: '在插件页面管理所有会话的应用权限。', approve: '本会话允许', } satisfies Record @@ -84,7 +84,7 @@ export const applicationAccessDisplay = { /** Window consent never grants access to sibling windows or application launch. */ export const windowAccessQuestion = { en: 'Allow computer use to read, capture and control this window?', - zh: '允许自动电脑操作读取、截图并控制这个窗口吗?', + zh: '允许智能体读取、截图并操作此窗口吗?', ja: 'このウィンドウの読み取り、撮影、操作を許可しますか?', es: '¿Permitir leer, capturar y controlar esta ventana?', fr: 'Autoriser la lecture, la capture et le contrôle de cette fenêtre ?', @@ -95,7 +95,7 @@ export const windowAccessQuestion = { /** Launch consent does not grant access to resulting windows. */ export const launchAccessQuestion = { en: 'Allow computer use to launch this entry? Window access is requested separately.', - zh: '允许自动电脑操作启动这个入口吗?窗口访问将单独请求授权。', + zh: '允许启动此项吗?窗口访问将单独请求授权。', ja: 'この項目の起動を許可しますか?ウィンドウへのアクセスは別途確認します。', es: '¿Permitir iniciar esta entrada? El acceso a ventanas se solicita por separado.', fr: 'Autoriser le lancement de cette entrée ? L’accès aux fenêtres sera demandé séparément.', diff --git a/packages/experimental/cua/tests/application-access.spec.ts b/packages/experimental/cua/tests/application-access.spec.ts index 6c7c6479e1..0290217523 100644 --- a/packages/experimental/cua/tests/application-access.spec.ts +++ b/packages/experimental/cua/tests/application-access.spec.ts @@ -114,7 +114,7 @@ it.each([ intent: { kind: 'approval', approve: 'Allow for this session', reject: 'Deny', subject: { name: 'Test application' }, display: { question: { en: 'Allow agent to control this application via computer use?', - zh: '允许智能体通过自动电脑操作控制此应用吗?', + zh: '允许智能体自动操作此应用吗?', ja: 'エージェントが Computer Use でこのアプリを操作することを許可しますか?' }, detail: { en: 'Manage app permissions for all sessions on the plugin page.', zh: '在插件页面管理所有会话的应用权限。', From a0d57ee4ebf1cf1fb574ed6e9612012cef240f9e Mon Sep 17 00:00:00 2001 From: Yixiang Tu Date: Fri, 20 Nov 2026 20:37:36 +0800 Subject: [PATCH 6/8] feat(cua-bundle): redesign feature preview SVGs with platform-agnostic multi-window layout --- apps/web/tests/cua-optin.e2e.ts | 2 +- .../experimental/cua-bundle/docs/DETAIL.md | 2 +- .../experimental/cua-bundle/docs/DETAIL.zh.md | 2 +- .../experimental/cua-bundle/docs/preview.svg | 239 +++++++++++++++--- .../cua-bundle/docs/preview.zh.svg | 239 +++++++++++++++--- 5 files changed, 419 insertions(+), 65 deletions(-) diff --git a/apps/web/tests/cua-optin.e2e.ts b/apps/web/tests/cua-optin.e2e.ts index 7c183efc57..c97b2701ca 100644 --- a/apps/web/tests/cua-optin.e2e.ts +++ b/apps/web/tests/cua-optin.e2e.ts @@ -178,7 +178,7 @@ it.skipIf(process.platform !== 'darwin').each([ expect(scaffold.ctx.tools.schemas(fresh).some(tool => tool.name === 'cua')).toBe(true) await card.getByRole('button', { name: '查看 自动电脑操作', exact: true }).click() const detail = plugins.locator('[data-detail-document]') - await detail.getByRole('img', { name: '将会议要点填入备忘录的指令和输入结果' }).waitFor() + await detail.getByRole('img', { name: '在多窗口桌面中自动操作选定任务看板窗口的示意图' }).waitFor() const guidance = plugins.locator('[data-cua-guidance]') await guidance.getByText(/请谨慎在生产环境中使用/).waitFor() expect(await guidance.textContent()).not.toContain('helperPath') diff --git a/packages/experimental/cua-bundle/docs/DETAIL.md b/packages/experimental/cua-bundle/docs/DETAIL.md index 2b7ab76d62..e86ecc3b08 100644 --- a/packages/experimental/cua-bundle/docs/DETAIL.md +++ b/packages/experimental/cua-bundle/docs/DETAIL.md @@ -1 +1 @@ -![A request to add meeting notes and the resulting text in Notes](preview.svg) +![An automated cursor operating a selected task window amid other desktop windows](preview.svg) diff --git a/packages/experimental/cua-bundle/docs/DETAIL.zh.md b/packages/experimental/cua-bundle/docs/DETAIL.zh.md index 3f8a908892..3646dbb575 100644 --- a/packages/experimental/cua-bundle/docs/DETAIL.zh.md +++ b/packages/experimental/cua-bundle/docs/DETAIL.zh.md @@ -1 +1 @@ -![将会议要点填入备忘录的指令和输入结果](preview.zh.svg) +![在多窗口桌面中自动操作选定任务看板窗口的示意图](preview.zh.svg) diff --git a/packages/experimental/cua-bundle/docs/preview.svg b/packages/experimental/cua-bundle/docs/preview.svg index 4abf3d57c3..d2ab1eaa8d 100644 --- a/packages/experimental/cua-bundle/docs/preview.svg +++ b/packages/experimental/cua-bundle/docs/preview.svg @@ -1,33 +1,210 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/experimental/cua-bundle/docs/preview.zh.svg b/packages/experimental/cua-bundle/docs/preview.zh.svg index 5b02060a56..7996a7cb07 100644 --- a/packages/experimental/cua-bundle/docs/preview.zh.svg +++ b/packages/experimental/cua-bundle/docs/preview.zh.svg @@ -1,33 +1,210 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 0168b0f88dc98002b48ade2b199a100ec1155bcf Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 23 Nov 2026 13:39:06 +0800 Subject: [PATCH 7/8] feat(sdk): expose cordis_inspect in the SDK profile Mount the Cordis inspection registry, the Host inspect providers, and the `cordis_inspect` tool in the sdk-app bundle so the SDK model receives the same runtime inspection tool as the Desktop standard and Creator presets. The SDK serves no browser, so its directory lists Host providers only. Remove the standard-mode parity exception, record the SDK-only PTC difference, keep pre-desktop SDK and Python compositions pinned, refresh the affected SDK snapshots, and document the change. --- .../tests/profiles/sdk/keyless-smoke.e2e.ts | 66 ++++++++++++++++ apps/cli/tests/profiles/sdk/tool-parity.ts | 4 +- docs/tool-catalog.i18n.yaml | 8 +- docs/tool-catalog.md | 4 +- docs/tool-catalog.zh.md | 4 +- .../sdk-cordis-inspect/guide.i18n.yaml | 16 ++++ .../sdk-cordis-inspect/guide.md | 24 ++++++ .../sdk-cordis-inspect/guide.zh.md | 24 ++++++ packages/bundle/sdk-app/README.i18n.yaml | 8 +- packages/bundle/sdk-app/README.md | 4 +- packages/bundle/sdk-app/README.zh.md | 4 +- packages/bundle/sdk-app/cordis.patch.yml | 13 ++++ packages/bundle/sdk-app/package.json | 4 +- .../extensions/tool-cordis/README.i18n.yaml | 12 +-- packages/extensions/tool-cordis/README.md | 6 +- packages/extensions/tool-cordis/README.zh.md | 6 +- pnpm-lock.yaml | 6 ++ scripts/gen-tool-catalog.ts | 2 +- scripts/smoke-python-runtime.py | 1 + .../dynamic-tools/tool-history.json | 3 + .../tool-schemas.expected.json | 39 ++++++++++ .../tool-schemas.expected.json | 39 ++++++++++ .../cua-run-code/tool-schemas.expected.json | 39 ++++++++++ .../tool-schemas.expected.json | 39 ++++++++++ .../system-prompt.expected.md | 14 ++++ .../system-prompt.expected.md | 14 ++++ snapshots/sdk/legacy-context.patch.yml | 3 + .../manual-compact/tool-schemas.expected.json | 78 +++++++++++++++++++ snapshots/sdk/plan-review/session.v4.jsonl | 4 +- .../plan-review/tool-schemas.expected.json | 78 +++++++++++++++++++ .../tool-schemas.1.expected.json | 39 ++++++++++ .../tool-schemas.expected.json | 39 ++++++++++ 32 files changed, 610 insertions(+), 34 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.md create mode 100644 docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.zh.md diff --git a/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts b/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts index 97d31bf34f..518e223dc3 100644 --- a/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts +++ b/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts @@ -797,3 +797,69 @@ it.each(['standard', 'ptc'] as const)('lists and loads the packaged dsh-doc skil const exit = await child expect(exit.exitCode, stderr).toBe(0) }) + +it('inspects the Host runtime through cordis_inspect in the SDK profile', async () => { + const root = await mkdtemp(join(tmpdir(), 'sdk-cordis-inspect-')) + onTestFinished(() => rm(root, { recursive: true, force: true })) + const requests: { messages: { content: { type: string; tool_use_id?: string; content?: unknown; is_error?: boolean }[] }[] }[] = [] + const toolUses = [ + { type: 'tool_use', id: 'inspect-directory', name: 'cordis_inspect', input: {} }, + { type: 'tool_use', id: 'inspect-version', name: 'cordis_inspect', input: { query: { platform: 'host', provider: 'Runtime', method: 'getVersion' } } }, + ] as const + const server = createServer((request, response) => { + let body = '' + request.setEncoding('utf8').on('data', (chunk: string) => { body += chunk }) + request.on('end', () => { + requests.push(JSON.parse(body) as typeof requests[number]) + const toolUse = toolUses[requests.length - 1] + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.end(toolUse === undefined ? messagesResponse({ type: 'text', text: 'done' }, 'end_turn') : messagesResponse(toolUse, 'tool_use')) + }) + }) + onTestFinished(() => new Promise((resolve) => { server.close(() => { resolve() }) })) + await new Promise((resolve) => { server.listen(0, '127.0.0.1', resolve) }) + const address = server.address() + if (address === null || typeof address === 'string') throw new Error('model fixture did not bind') + const launch = resolveExampleLaunch({ + srcBin: fileURLToPath(new URL('../../../src/bin.ts', import.meta.url)), mode: 'lib', + configArgs: ['--profile', 'sdk'], + env: { DSH_HOME: join(root, 'home'), DSH_PRIMARY_RUNTIME: '', DSH_PERMISSION_MODE: 'danger-full-access', DSH_TELEMETRY_DISABLED: '1', + DEEPSEEK_API_KEY: 'local-fixture', DEEPSEEK_BASE_URL: `http://127.0.0.1:${address.port}` }, + }) + const child = execa(launch.command, launch.args, { cwd: repoRoot, env: launch.env, timeout: 60_000, reject: false }) + onTestFinished(async () => { child.kill('SIGKILL'); await child }) + let buffer = '', stderr = '' + const lines: string[] = [] + child.stdout.on('data', (chunk: Buffer) => { + buffer += chunk.toString() + const parts = buffer.split('\n') + buffer = parts.pop() ?? '' + lines.push(...parts) + }) + child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString() }) + const send = (id: number, method: string, params?: object) => { + child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`) + return waitForLine(lines, value => value.id === id, () => stderr) + } + expect(await send(1, 'initialize', { cwd: root, provider: 'deepseek-official', model: 'deepseek-v4-pro' })).toHaveProperty('result') + await send(2, 'session/prompt', { sessionId: 'cordis-inspect', contentBlocks: [{ type: 'text', text: 'Which DSH version is running?' }] }) + await waitForLine(lines, (value) => { + const params = value.params as { sessionId?: string; event?: { type?: string } } | undefined + return value.method === 'session.event' && params?.sessionId === 'cordis-inspect' && params.event?.type === 'turn/end' + }, () => stderr) + expect(requests).toHaveLength(toolUses.length + 1) + const results = requests.at(-1)!.messages.flatMap(message => message.content).filter(block => block.type === 'tool_result') + const result = (id: string) => { + const block = results.find(candidate => candidate.tool_use_id === id) + expect(block?.is_error, JSON.stringify(block)).not.toBe(true) + return JSON.stringify(block?.content) + } + const directory = result('inspect-directory') + for (const provider of ['Service', 'Event', 'Config', 'Runtime', 'Tool']) expect(directory).toContain(provider) + expect(directory).not.toContain('Slots') + const { version } = JSON.parse(await readFile(join(repoRoot, 'packages/boot/app-boot/package.json'), 'utf8')) as { version: string } + expect(result('inspect-version')).toContain(version) + await send(3, 'shutdown') + const exit = await child + expect(exit.exitCode, stderr).toBe(0) +}) diff --git a/apps/cli/tests/profiles/sdk/tool-parity.ts b/apps/cli/tests/profiles/sdk/tool-parity.ts index a74e51d6fb..f4b2ed9014 100644 --- a/apps/cli/tests/profiles/sdk/tool-parity.ts +++ b/apps/cli/tests/profiles/sdk/tool-parity.ts @@ -12,12 +12,12 @@ export const toolParityExceptions: Record = { standard: [ { tool: 'list_subagent_models', side: 'desktop', reason: 'Desktop enables subagent model discovery; SDK delegation inherits the caller model by default.' }, - { tool: 'cordis_inspect', side: 'desktop', - reason: 'Web exposes inspection of its Host and connected Client runtime; the SDK profile does not compose the Cordis inspection providers.' }, ], ptc: [ { tool: 'list_subagent_models', side: 'desktop', reason: 'Desktop enables subagent model discovery; SDK delegation inherits the caller model by default.' }, + { tool: 'cordis_inspect', side: 'sdk', + reason: 'The SDK profile composes runtime inspection for both executors; the Desktop PTC preset omits it.' }, { tool: 'workflow', side: 'sdk', reason: 'The SDK PTC overlay changes only the executor so existing base workflow callers keep working; Desktop PTC uses run_code orchestration and omits the separate workflow surface.' }, ], diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index 679756eb45..3cc55f7b70 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -9,8 +9,8 @@ en: 6cc2cd9ced70bb09 zh: 1c0e6cb4ba2ed637 /tool-schema-catalog/tool-package-map: - en: 30abd845c15aab11 - zh: 584288adf33e54ac + en: 8eb7039496b00847 + zh: 7d115fbbd23e2084 /tool-schema-catalog/deepseek-ai-dsh-tool-session-control: en: 79ab575ea6da86e2 zh: 79ab575ea6da86e2 @@ -114,8 +114,8 @@ en: 76c7c62f9029b6f5 zh: 76c7c62f9029b6f5 /tool-schema-catalog/deepseek-ai-dsh-tool-cordis/cordis-inspect: - en: f804c4e7fccc1c45 - zh: 7538d8201ef16ed9 + en: b00bf7275e14730e + zh: 61eb02e91ec980cf /tool-schema-catalog/deepseek-ai-dsh-tool-bash-persistent: en: bdd9e88c49029e05 zh: bdd9e88c49029e05 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index 7538893da3..b2efdb8375 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -27,7 +27,7 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tool-office` | `office_convert`, `office_recalculate`, `office_render` | `ctx.workingDirectory`, `ctx.tools`, `ctx.fs`, `ctx.agents`, `ctx.officeKit`, `ctx.attachments and ctx.llm for office_render` | `tool/call`, `tool/result with rendered image attachments`, `temporary converted files in the Office kit output store` | - | Declared to an Agent from the step after it successfully loads an Office skill, and kept while the previous request header declares an Office tool. Admitted calls fail with the Office service's unavailable error when LibreOffice Kit is not installed. | | `@deepseek-ai/dsh-tool-present` | `present` | `ctx.workingDirectory`, `ctx.tools`, `ctx.fs`, `ctx.agents` | `tool/call`, `deliverables/presented after a successful final result`, `tool/result` | - | Deliveries belong to the calling Session; Web ui-deliverables supplies source-file opening and cards. | | `@deepseek-ai/dsh-tool-pwsh` | `pwsh` | `ctx.workingDirectory`, `ctx.tools`, `ctx.shell`, `ctx.systemPrompt`, `ctx.shellEnv`, `ctx.jobs for run_in_background and the job-backed foreground path` | `tool/call`, `tool/result` | - | The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.shell`); it mirrors the bash tool call-for-call minus sandbox controls — `run_in_background` runs register with the generic `ctx.jobs` runtime and are collected/stopped through the `job_*` tools, and the managed `DSH_*` environment comes from `@deepseek-ai/dsh-shell-env`. Each call runs in a fresh process (no persistent PTY session), with native `C:\...` paths and `$env:NAME` variables. | -| `@deepseek-ai/dsh-tool-cordis` | `cordis_inspect` | `ctx.tools`, `ctx.cordisInspect` | `tool/call`, `tool/result` | - | Standard and Creator modes provide one read-only runtime inspection tool. Omit query for the provider directory; pass query to inspect a declared method. The Cordis host runner supplies the inspection registry; Client queries require a connected page. Author persistent changes as bundles and install them with plugin_manager. | +| `@deepseek-ai/dsh-tool-cordis` | `cordis_inspect` | `ctx.tools`, `ctx.cordisInspect` | `tool/call`, `tool/result` | - | The Desktop Standard and Creator modes and the SDK profile provide one read-only runtime inspection tool. Omit query for the provider directory; pass query to inspect a declared method. The Cordis host runner supplies the inspection registry; Client queries require a connected page. Author persistent changes as bundles and install them with plugin_manager. | | `@deepseek-ai/dsh-tool-bash-persistent` | `bash` | `ctx.workingDirectory`, `ctx.tools`, `ctx.terminals`, `an owning Agent at execution time` | `tool/call`, `PTY shell state`, `tool/result` | - | One owner-isolated persistent bash tool; deployment composition supplies the PTY backend and may override the model-facing environment description. | | `@deepseek-ai/dsh-tool-pwsh-persistent` | `pwsh` | `ctx.workingDirectory`, `ctx.tools`, `ctx.terminals`, `an owning Agent at execution time` | `tool/call`, `PTY shell state`, `tool/result` | - | One owner-isolated persistent pwsh tool, the Windows counterpart of the persistent bash tool; deployment composition supplies a pwsh-dialect PTY backend and may override the model-facing environment description. | | `@deepseek-ai/dsh-tool-str-replace-editor` | `str_replace_editor` | `ctx.tools`, `ctx.fs` | `tool/call`, `fs/observed after view presence/absence, edit absence, or successful mutation`, `tool/result` | - | Standalone view/create/unique literal replace/line insert tool over the filesystem seam; it composes with any shell or terminal API. | @@ -978,7 +978,7 @@ Inspect runtime APIs before writing or configuring plugins. Omit query to discov Source: [`packages/extensions/tool-cordis/src/index.ts`](../packages/extensions/tool-cordis/src/index.ts) -Standard and Creator modes provide one read-only runtime inspection tool. Omit query for the provider directory; pass query to inspect a declared method. The Cordis host runner supplies the inspection registry; Client queries require a connected page. Author persistent changes as bundles and install them with plugin_manager. +The Desktop Standard and Creator modes and the SDK profile provide one read-only runtime inspection tool. Omit query for the provider directory; pass query to inspect a declared method. The Cordis host runner supplies the inspection registry; Client queries require a connected page. Author persistent changes as bundles and install them with plugin_manager. diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index 8753f7952d..e41b6203b9 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -31,7 +31,7 @@ | `@deepseek-ai/dsh-tool-office` | `office_convert`、`office_recalculate`、`office_render` | `ctx.workingDirectory`、`ctx.tools`、`ctx.fs`、`ctx.agents`、`ctx.officeKit`、`ctx.attachments and ctx.llm for office_render` | `tool/call`、`tool/result with rendered image attachments`、`temporary converted files in the Office kit output store` | - | Agent 成功加载 Office 技能后,从下一步起向其声明这些工具;上一次请求头已声明 Office 工具时继续保留。未安装 LibreOffice Kit 时,已声明工具的调用以 Office 服务的 unavailable 错误失败。 | | `@deepseek-ai/dsh-tool-present` | `present` | `ctx.workingDirectory`、`ctx.tools`, `ctx.fs`, `ctx.agents` | `tool/call`, `deliverables/presented 在成功的最终结果之后`, `tool/result` | - | 交付归调用方 Session 所有;Web ui-deliverables 提供源文件打开与卡片。 | | `@deepseek-ai/dsh-tool-pwsh` | `pwsh` | `ctx.workingDirectory`、`ctx.tools`、`ctx.shell`、`ctx.systemPrompt`、`ctx.shellEnv`、`ctx.jobs for run_in_background and the job-backed foreground path` | `tool/call`、`tool/result` | - | pwsh 工具是 Windows 组合中 bash 执行器 seam 的 PowerShell 方言消费方(由 `@deepseek-ai/dsh-pwsh-local` 等 PowerShell 执行器为 `ctx.shell` 提供后端);除沙箱接口外,它逐项对应 bash 工具调用。使用 `run_in_background` 的运行会注册到通用 `ctx.jobs` 运行时,并通过 `job_*` 工具收集/停止;托管的 `DSH_*` 环境来自 `@deepseek-ai/dsh-shell-env`。每次调用都在新进程中运行,不使用持久 PTY 会话。路径采用原生 `C:\...` 形式,变量采用 `$env:NAME`。 | -| `@deepseek-ai/dsh-tool-cordis` | `cordis_inspect` | `ctx.tools`, `ctx.cordisInspect` | `tool/call`, `tool/result` | - | 标准模式和创造模式提供一个只读运行时检查工具。省略 query 获取 provider 目录;传入 query 查询已声明的方法。Cordis host runner 提供检查注册表;Client 查询需要已连接页面。持久化变更编写为组合包,再通过 plugin_manager 安装。 | +| `@deepseek-ai/dsh-tool-cordis` | `cordis_inspect` | `ctx.tools`, `ctx.cordisInspect` | `tool/call`, `tool/result` | - | Desktop 标准模式、创造模式和 SDK profile 提供一个只读运行时检查工具。省略 query 获取 provider 目录;传入 query 查询已声明的方法。Cordis host runner 提供检查注册表;Client 查询需要已连接页面。持久化变更编写为组合包,再通过 plugin_manager 安装。 | | `@deepseek-ai/dsh-tool-bash-persistent` | `bash` | `ctx.workingDirectory`、`ctx.tools`、`ctx.terminals`、`an owning Agent at execution time` | `tool/call`、`PTY shell state`、`tool/result` | - | 一个按所有者隔离的持久 bash 工具;部署组合提供 PTY 后端,并可覆盖面向模型的环境描述。 | | `@deepseek-ai/dsh-tool-pwsh-persistent` | `pwsh` | `ctx.workingDirectory`、`ctx.tools`、`ctx.terminals`、`an owning Agent at execution time` | `tool/call`、`PTY shell state`、`tool/result` | - | 一个按所有者隔离的持久 pwsh 工具,持久 bash 工具的 Windows 对应物;部署组合提供 pwsh 方言的 PTY 后端,并可覆盖面向模型的环境描述。 | | `@deepseek-ai/dsh-tool-str-replace-editor` | `str_replace_editor` | `ctx.tools`、`ctx.fs` | `tool/call`、`fs/observed after view presence/absence, edit absence, or successful mutation`、`tool/result` | - | 基于文件系统 seam 的独立查看/创建/唯一字面量替换/按行插入工具;可与任何 shell 或终端接口组合。 | @@ -982,7 +982,7 @@ pwsh 工具是 Windows 组合中 bash 执行器 seam 的 PowerShell 方言消费 来源: [`packages/extensions/tool-cordis/src/index.ts`](../packages/extensions/tool-cordis/src/index.ts) -标准模式和创造模式提供一个只读运行时检查工具。省略 query 获取 provider 目录;传入 query 查询已声明的方法。Cordis host runner 提供检查注册表;Client 查询需要已连接页面。持久化变更编写为组合包,再通过 plugin_manager 安装。 +Desktop 标准模式、创造模式和 SDK profile 提供一个只读运行时检查工具。省略 query 获取 provider 目录;传入 query 查询已声明的方法。Cordis host runner 提供检查注册表;Client 查询需要已连接页面。持久化变更编写为组合包,再通过 plugin_manager 安装。 diff --git a/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.i18n.yaml b/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.i18n.yaml new file mode 100644 index 0000000000..fb761f368e --- /dev/null +++ b/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.md +/: + en: 895270534c3c0211 + zh: 5da3b94c9350547c +/sdk-runtime-inspection-tool: + en: 750dcdacf1b45f1a + zh: b94ccea9590bfc90 +/sdk-runtime-inspection-tool/change: + en: e05bc467d0ce54f1 + zh: dae859bf19c5b707 +/sdk-runtime-inspection-tool/migration: + en: ec1bf74ca8b0ad38 + zh: ee38ed5a5c00f160 diff --git a/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.md b/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.md new file mode 100644 index 0000000000..c997391d7a --- /dev/null +++ b/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.md @@ -0,0 +1,24 @@ +--- +kind: upgrade-guide +description: The SDK profile adds the cordis_inspect runtime inspection tool. +--- + +# SDK runtime inspection tool + +English | [中文](guide.zh.md) + +## Change + +The `sdk` profile now mounts `cordis-host-runner`, `cordis-inspect-providers`, and `tool-cordis`, so the model receives `cordis_inspect` as the Desktop standard and Creator presets provide it. Host queries read Service, Event, Config, Runtime, and Tool data; the directory lists no Client providers because the SDK serves no browser. `sdk-minimal` is unchanged. + +## Migration + +1. Review pinned prompts, tool schemas, and tool-name allowlists for the added `cordis_inspect` definition. +2. To keep the previous tool roster, disable the `tool-cordis` row in a profile patch: + + ```yaml + - id: tool-cordis + disabled: true + ``` + +3. Run a task and confirm that the first model request lists `cordis_inspect` exactly when the row is enabled. diff --git a/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.zh.md b/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.zh.md new file mode 100644 index 0000000000..d4aeec18ef --- /dev/null +++ b/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.zh.md @@ -0,0 +1,24 @@ +--- +kind: upgrade-guide +description: SDK profile 新增 cordis_inspect 运行时检查工具。 +--- + +# SDK 运行时检查工具 + +[English](guide.md) | 中文 + +## 变更 + +`sdk` profile 现在挂载 `cordis-host-runner`、`cordis-inspect-providers` 和 `tool-cordis`,模型像在 Desktop 标准模式和创造模式中一样收到 `cordis_inspect`。Host 查询读取 Service、Event、Config、Runtime 和 Tool 数据;SDK 不提供浏览器,因此目录不列出 Client provider。`sdk-minimal` 保持不变。 + +## 迁移 + +1. 检查固定的提示词、工具 schema 和工具名允许列表,确认新增的 `cordis_inspect` 定义。 +2. 如需保持原来的工具集合,在 profile patch 中禁用 `tool-cordis` 行: + + ```yaml + - id: tool-cordis + disabled: true + ``` + +3. 运行一个任务,确认首个模型请求只在该行启用时列出 `cordis_inspect`。 diff --git a/packages/bundle/sdk-app/README.i18n.yaml b/packages/bundle/sdk-app/README.i18n.yaml index 4e63cce002..3ec85e7fb6 100644 --- a/packages/bundle/sdk-app/README.i18n.yaml +++ b/packages/bundle/sdk-app/README.i18n.yaml @@ -24,11 +24,11 @@ en: 4f88e647c6df4f42 zh: 2bd3e4b0bdfe9412 /deepseek-ai-dsh-sdk-app/model-experience/sdk-model-context/what-the-model-sees: - en: 2c54cdab827df6dc - zh: 575a00d86ecea5aa + en: 146ac8b6243a3d82 + zh: 367ac396c4a719ad /deepseek-ai-dsh-sdk-app/model-experience/sdk-model-context/token-effect: - en: 7bb67dfbf1621d73 - zh: 71414a307ccf3f7b + en: 6d7e69d35ddf1de8 + zh: f8f95ffc54547b8e /deepseek-ai-dsh-sdk-app/model-experience/sdk-model-context/kv-cache-effect: en: ccce9395f246ba39 zh: d758f8a78f03878d diff --git a/packages/bundle/sdk-app/README.md b/packages/bundle/sdk-app/README.md index 45383dd4bd..9b7ca385d7 100644 --- a/packages/bundle/sdk-app/README.md +++ b/packages/bundle/sdk-app/README.md @@ -50,11 +50,11 @@ The standard SDK profile lists `official-plugins` and `personalized-pages` by de #### What the model sees -The profile inherits the base system prompt, including the `You are an AI agent powered by DeepSeek Harness.` identity, and adds the same model-interpolated coding persona as the Web and headless profiles. Each Session receives its current directory in required user-role context from [`dsh-working-directory`](../../session/working-directory/README.md). Default file tool schemas include `read`, `write`, and `edit`; they omit `str_replace_editor`. The model also receives `present`, `ask_user_question`, `plugin_manager`, schedule tools, shared file-reference guidance, and time context. Child agents cannot use schedule tools. The [`time-context`](../../context/time-context/README.md) row accepts a fallback time zone. Each ordinary prompt reports its zone like a Web prompt: the client's `timeZone` (`time_zone` in Python) when given, otherwise the runtime process zone sampled for that prompt, so the model sees `Browser time zone for this request: . Interpret otherwise-unqualified dates and times in this zone.` A process zone that is not UTC or an IANA Area/Location name, such as the `+00:00` that `TZ=GMT` produces, reports `unavailable`. The skill catalog always lists the Office skills; their Python environment section names `load_workspace_dependencies` with an authoring payload and the user's existing Python without one. The catalog also lists `dsh-doc`, the DSH documentation skill that the Desktop standard, PTC, and Creator presets list; see the [Web app](../web-app/README.md#model-experience) for what it guides. +The profile inherits the base system prompt, including the `You are an AI agent powered by DeepSeek Harness.` identity, and adds the same model-interpolated coding persona as the Web and headless profiles. Each Session receives its current directory in required user-role context from [`dsh-working-directory`](../../session/working-directory/README.md). Default file tool schemas include `read`, `write`, and `edit`; they omit `str_replace_editor`. The model also receives `present`, `ask_user_question`, `plugin_manager`, `cordis_inspect`, schedule tools, shared file-reference guidance, and time context. `cordis_inspect` reads Host runtime APIs as the Desktop standard and Creator presets do; its directory lists no Client providers because the SDK serves no browser. Child agents cannot use schedule tools. The [`time-context`](../../context/time-context/README.md) row accepts a fallback time zone. Each ordinary prompt reports its zone like a Web prompt: the client's `timeZone` (`time_zone` in Python) when given, otherwise the runtime process zone sampled for that prompt, so the model sees `Browser time zone for this request: . Interpret otherwise-unqualified dates and times in this zone.` A process zone that is not UTC or an IANA Area/Location name, such as the `+00:00` that `TZ=GMT` produces, reports `unavailable`. The skill catalog always lists the Office skills; their Python environment section names `load_workspace_dependencies` with an authoring payload and the user's existing Python without one. The catalog also lists `dsh-doc`, the DSH documentation skill that the Desktop standard, PTC, and Creator presets list; see the [Web app](../web-app/README.md#model-experience) for what it guides. #### Token effect -The profile adds a coding-persona sentence, the mounted tool definitions and guidance, and logged runtime-context and time messages. The `plugin_manager` description and parameter schema add input tokens even when an operation cannot be approved; an embedding that does not use plugin management can disable its row. The `dsh-doc` catalog entry adds about 125 heuristic tokens to the first request; its instructions and references enter context only when the model loads the skill. +The profile adds a coding-persona sentence, the mounted tool definitions and guidance, and logged runtime-context and time messages. The `plugin_manager` description and parameter schema add input tokens even when an operation cannot be approved; an embedding that does not use plugin management can disable its row. The `cordis_inspect` schema adds one tool definition; query results enter the transcript only when the model calls it. The `dsh-doc` catalog entry adds about 125 heuristic tokens to the first request; its instructions and references enter context only when the model loads the skill. #### KV Cache effect diff --git a/packages/bundle/sdk-app/README.zh.md b/packages/bundle/sdk-app/README.zh.md index c3260b7372..c49e788615 100644 --- a/packages/bundle/sdk-app/README.zh.md +++ b/packages/bundle/sdk-app/README.zh.md @@ -50,11 +50,11 @@ Python 运行时向本 profile 提供显式下载的创作资源和 Office sidec #### 模型看到什么 -profile 继承 base 系统提示词,包括 `You are an AI agent powered by DeepSeek Harness.` 身份说明,并添加与 Web 和 headless profile 相同、按当前模型插值的 coding persona。每个 Session 通过 [`dsh-working-directory`](../../session/working-directory/README.zh.md) 提供的必需 user-role 上下文接收当前目录。默认文件工具 schema 包含 `read`、`write` 和 `edit`,不包含 `str_replace_editor`。模型还会收到 `present`、`ask_user_question`、`plugin_manager`、定时任务工具、共用文件引用说明和时间上下文。子 agent 不能使用定时任务工具。[`time-context`](../../context/time-context/README.zh.md) 配置项接受回退时区。每条普通 prompt 像 Web prompt 一样上报时区:传入了客户端的 `timeZone`(Python 中为 `time_zone`)时用它,否则用运行时为这条 prompt 采样的进程时区,因此模型看到 `Browser time zone for this request: . Interpret otherwise-unqualified dates and times in this zone.`。进程时区既不是 UTC 也不是 IANA Area/Location 名称时(例如 `TZ=GMT` 产生的 `+00:00`),上报 `unavailable`。技能目录总是列出 Office skills;有创作载荷时其 Python 环境说明指向 `load_workspace_dependencies`,没有时指向用户已有的 Python。技能目录还列出 `dsh-doc`,即 Desktop 标准模式、PTC 模式和创造模式列出的 DSH 文档 skill;其用途参见 [Web app](../web-app/README.zh.md#model-experience)。 +profile 继承 base 系统提示词,包括 `You are an AI agent powered by DeepSeek Harness.` 身份说明,并添加与 Web 和 headless profile 相同、按当前模型插值的 coding persona。每个 Session 通过 [`dsh-working-directory`](../../session/working-directory/README.zh.md) 提供的必需 user-role 上下文接收当前目录。默认文件工具 schema 包含 `read`、`write` 和 `edit`,不包含 `str_replace_editor`。模型还会收到 `present`、`ask_user_question`、`plugin_manager`、`cordis_inspect`、定时任务工具、共用文件引用说明和时间上下文。`cordis_inspect` 与 Desktop 标准模式和创造模式一样读取 Host 运行时 API;SDK 不提供浏览器,因此它的目录不列出 Client provider。子 agent 不能使用定时任务工具。[`time-context`](../../context/time-context/README.zh.md) 配置项接受回退时区。每条普通 prompt 像 Web prompt 一样上报时区:传入了客户端的 `timeZone`(Python 中为 `time_zone`)时用它,否则用运行时为这条 prompt 采样的进程时区,因此模型看到 `Browser time zone for this request: . Interpret otherwise-unqualified dates and times in this zone.`。进程时区既不是 UTC 也不是 IANA Area/Location 名称时(例如 `TZ=GMT` 产生的 `+00:00`),上报 `unavailable`。技能目录总是列出 Office skills;有创作载荷时其 Python 环境说明指向 `load_workspace_dependencies`,没有时指向用户已有的 Python。技能目录还列出 `dsh-doc`,即 Desktop 标准模式、PTC 模式和创造模式列出的 DSH 文档 skill;其用途参见 [Web app](../web-app/README.zh.md#model-experience)。 #### Token 影响 -此 profile 添加一句 coding persona、所挂载的工具定义与说明,以及记录在日志中的运行时上下文和时间消息。 即使操作无法获批,`plugin_manager` 的描述和参数 schema 仍增加输入 token;不使用插件管理的嵌入方可禁用该条目。`dsh-doc` 目录项使首个请求增加约 125 个启发式估算 token;其指令和参考资料仅在模型加载该 skill 时进入上下文。 +此 profile 添加一句 coding persona、所挂载的工具定义与说明,以及记录在日志中的运行时上下文和时间消息。 即使操作无法获批,`plugin_manager` 的描述和参数 schema 仍增加输入 token;不使用插件管理的嵌入方可禁用该条目。`cordis_inspect` 的 schema 增加一个工具定义;查询结果仅在模型调用它时进入转录。`dsh-doc` 目录项使首个请求增加约 125 个启发式估算 token;其指令和参考资料仅在模型加载该 skill 时进入上下文。 #### KV Cache 影响 diff --git a/packages/bundle/sdk-app/cordis.patch.yml b/packages/bundle/sdk-app/cordis.patch.yml index 4cbb999d5f..e51280fdf3 100644 --- a/packages/bundle/sdk-app/cordis.patch.yml +++ b/packages/bundle/sdk-app/cordis.patch.yml @@ -104,3 +104,16 @@ - id: deliverable-file-references name: '@deepseek-ai/dsh-deliverable-file-references' + +# Runtime inspection, as the Desktop standard and Creator presets expose it. +# The registry and Host providers mount once per process; the directory lists +# no Client providers because the SDK serves no browser. +- insert: + - id: cordis-host-runner + name: '@deepseek-ai/dsh-cordis-host-runner' + + - id: cordis-inspect-providers + name: '@deepseek-ai/dsh-tool-cordis/host' + + - id: tool-cordis + name: '@deepseek-ai/dsh-tool-cordis' diff --git a/packages/bundle/sdk-app/package.json b/packages/bundle/sdk-app/package.json index 9c22b7d27b..4134267165 100644 --- a/packages/bundle/sdk-app/package.json +++ b/packages/bundle/sdk-app/package.json @@ -60,7 +60,9 @@ "@deepseek-ai/dsh-tool-ask-user": "workspace:*", "@deepseek-ai/dsh-tool-present": "workspace:*", "@deepseek-ai/dsh-file-reference-local": "workspace:*", - "@deepseek-ai/dsh-deliverable-file-references": "workspace:*" + "@deepseek-ai/dsh-deliverable-file-references": "workspace:*", + "@deepseek-ai/dsh-cordis-host-runner": "workspace:*", + "@deepseek-ai/dsh-tool-cordis": "workspace:*" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~" diff --git a/packages/extensions/tool-cordis/README.i18n.yaml b/packages/extensions/tool-cordis/README.i18n.yaml index f53652026b..6983a97a8d 100644 --- a/packages/extensions/tool-cordis/README.i18n.yaml +++ b/packages/extensions/tool-cordis/README.i18n.yaml @@ -9,14 +9,14 @@ en: ea2c0ac7e7932a08 zh: 5562e6f26d700b64 /deepseek-ai-dsh-tool-cordis/summary: - en: a4b0f81d92c4fb57 - zh: 2b548fd55ac6f1bf + en: 61866a9ad60c6492 + zh: f535ac43453fbf45 /deepseek-ai-dsh-tool-cordis/table-of-contents: en: d152484eb41ac6b4 zh: 3a2f21ff0dc3420d /deepseek-ai-dsh-tool-cordis/use-this-package: - en: 6a03f434a773ec43 - zh: d2d7c48df1a29e0b + en: 44c28af9651b98be + zh: dc52ac59ebce55e3 /deepseek-ai-dsh-tool-cordis/understand-the-implementation: en: c4d39015cdf9a6b6 zh: 9ca8a882bdea7529 @@ -33,8 +33,8 @@ en: 63d8b2a3ac2c6bc9 zh: 2ada02dd993f3d4f /deepseek-ai-dsh-tool-cordis/model-experience/runtime-inspection/token-effect: - en: b393ba67aaa0a600 - zh: 89a899e2401e9a34 + en: 8bfecb93d302d53d + zh: fd4494be2cf32a75 /deepseek-ai-dsh-tool-cordis/model-experience/runtime-inspection/kv-cache-effect: en: f57a20cd4e76d13c zh: 7b673116422bee87 diff --git a/packages/extensions/tool-cordis/README.md b/packages/extensions/tool-cordis/README.md index d672f52bb9..a75b4d642e 100644 --- a/packages/extensions/tool-cordis/README.md +++ b/packages/extensions/tool-cordis/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Inspect Host and Client runtime APIs before writing plugin code. Standard and Creator modes provide this read-only tool alongside Plugin Manager, which owns persistent profile changes. The inspection registry is supplied by the Cordis host runner; browser queries need a connected page. +Inspect Host and Client runtime APIs before writing plugin code. The Desktop Standard and Creator modes and the SDK profile provide this read-only tool alongside Plugin Manager, which owns persistent profile changes. The inspection registry is supplied by the Cordis host runner; browser queries need a connected page. ## Table of Contents @@ -25,7 +25,7 @@ Inspect Host and Client runtime APIs before writing plugin code. Standard and Cr ## Use this package -Standard and Creator modes include this tool. Other compositions mount `@deepseek-ai/dsh-tool-cordis/host` once in the host composition beside the host runner that provides `cordisInspect`, and `@deepseek-ai/dsh-tool-cordis` in each agent preset that exposes the tool; a preset row alone registers no Host providers. Call `cordis_inspect` without `query` to discover providers, then pass a `query` object with `platform`, `provider`, `method`, and optional `input` to read a provider's exact methods and types. The Host `Config` provider lists live Loader entries in pages (`offset`, `limit` up to 100, optional exact plugin `name`; `total` and `nextOffset` bound the walk) with each entry's Loader id, the tree-local id patches address, and its Config status (`schema`, `absent`, `unsupported`, `tree` for group and include carriers, `inactive` for disabled, never imported, or disposed entries), and projects one entry's native Config into a self-contained JSON Schema document beside the entry's `packageDir`, the resolved directory holding the package README and built `lib/`, when the profile package lookup resolves it. The Host `Runtime` provider's `getVersion` returns `{ version }`, the exact running DSH version that plugin `engines.dsh` ranges and DSH peer dependencies are checked against. A call without an Agent, or a `Config` query on a Host without a Loader, fails with `ToolContextUnavailableError`; a malformed `Config` paging field fails with `ToolArgsError`; and an unknown entry id fails with `InspectError` `INSPECT_TARGET_NOT_FOUND`. Use [Plugin Manager](../../boot/plugin-manager/README.md) to install bundles containing plugin code or MCP configuration. +The Desktop Standard and Creator modes and the SDK profile include this tool. Other compositions mount `@deepseek-ai/dsh-tool-cordis/host` once in the host composition beside the host runner that provides `cordisInspect`, and `@deepseek-ai/dsh-tool-cordis` in each agent preset that exposes the tool; a preset row alone registers no Host providers. Call `cordis_inspect` without `query` to discover providers, then pass a `query` object with `platform`, `provider`, `method`, and optional `input` to read a provider's exact methods and types. The Host `Config` provider lists live Loader entries in pages (`offset`, `limit` up to 100, optional exact plugin `name`; `total` and `nextOffset` bound the walk) with each entry's Loader id, the tree-local id patches address, and its Config status (`schema`, `absent`, `unsupported`, `tree` for group and include carriers, `inactive` for disabled, never imported, or disposed entries), and projects one entry's native Config into a self-contained JSON Schema document beside the entry's `packageDir`, the resolved directory holding the package README and built `lib/`, when the profile package lookup resolves it. The Host `Runtime` provider's `getVersion` returns `{ version }`, the exact running DSH version that plugin `engines.dsh` ranges and DSH peer dependencies are checked against. A call without an Agent, or a `Config` query on a Host without a Loader, fails with `ToolContextUnavailableError`; a malformed `Config` paging field fails with `ToolArgsError`; and an unknown entry id fails with `InspectError` `INSPECT_TARGET_NOT_FOUND`. Use [Plugin Manager](../../boot/plugin-manager/README.md) to install bundles containing plugin code or MCP configuration. ----- @@ -58,7 +58,7 @@ The [tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-tool-cordis) des #### Token effect -In the shipped Standard and Creator modes, this plugin contributes one tool schema to each model request. Query results append to the transcript; exact queries avoid loading unrelated declarations. +In the shipped Desktop Standard and Creator modes and the SDK profile, this plugin contributes one tool schema to each model request. Query results append to the transcript; exact queries avoid loading unrelated declarations. #### KV Cache effect diff --git a/packages/extensions/tool-cordis/README.zh.md b/packages/extensions/tool-cordis/README.zh.md index e118bc222e..8c1666acff 100644 --- a/packages/extensions/tool-cordis/README.zh.md +++ b/packages/extensions/tool-cordis/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -编写插件代码前查询 Host 和 Client 的运行时 API。标准模式和创造模式同时提供这个只读工具与 Plugin Manager,后者负责持久化 profile 变更。检查注册表由 Cordis host runner 提供;浏览器查询需要已连接的页面。 +编写插件代码前查询 Host 和 Client 的运行时 API。Desktop 标准模式、创造模式和 SDK profile 同时提供这个只读工具与 Plugin Manager,后者负责持久化 profile 变更。检查注册表由 Cordis host runner 提供;浏览器查询需要已连接的页面。 ## 目录 @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -标准模式和创造模式包含这个工具。其他组合需要在宿主组合里、提供 `cordisInspect` 的 host runner 旁挂载一次 `@deepseek-ai/dsh-tool-cordis/host`,并在每个要暴露这个工具的 agent preset 里挂载 `@deepseek-ai/dsh-tool-cordis`;仅有 preset 行不会注册任何 Host provider。调用 `cordis_inspect` 时省略 `query` 以发现 provider,再传入包含 `platform`、`provider`、`method` 及可选 `input` 的 `query` 对象,读取 provider 的具体方法和类型。Host 的 `Config` provider 分页列出运行中的 Loader entry(`offset`、最多 100 的 `limit`、可选的精确插件 `name`;`total` 与 `nextOffset` 界定遍历),每个 entry 带 Loader id、patch 所寻址的树内 id 及其 Config 状态(`schema`、`absent`、`unsupported`、group 与 include 载体为 `tree`、禁用、未导入或已销毁的 entry 为 `inactive`),并把单个 entry 的原生 Config 投影为自包含的 JSON Schema 文档,同时在 profile 包查找能解析时给出该 entry 的 `packageDir`,即包 README 与构建产物 `lib/` 所在目录。Host 的 `Runtime` provider 的 `getVersion` 返回 `{ version }`,即插件 `engines.dsh` 范围和 DSH peer 依赖所比对的当前运行 DSH 的精确版本。没有 Agent 的调用,或在没有 Loader 的 Host 上的 `Config` 查询,以 `ToolContextUnavailableError` 失败;`Config` 分页字段格式错误时以 `ToolArgsError` 失败;未知 entry id 以 `InspectError` `INSPECT_TARGET_NOT_FOUND` 失败。通过 [Plugin Manager](../../boot/plugin-manager/README.zh.md) 安装包含插件代码或 MCP 配置的组合包。 +Desktop 标准模式、创造模式和 SDK profile 包含这个工具。其他组合需要在宿主组合里、提供 `cordisInspect` 的 host runner 旁挂载一次 `@deepseek-ai/dsh-tool-cordis/host`,并在每个要暴露这个工具的 agent preset 里挂载 `@deepseek-ai/dsh-tool-cordis`;仅有 preset 行不会注册任何 Host provider。调用 `cordis_inspect` 时省略 `query` 以发现 provider,再传入包含 `platform`、`provider`、`method` 及可选 `input` 的 `query` 对象,读取 provider 的具体方法和类型。Host 的 `Config` provider 分页列出运行中的 Loader entry(`offset`、最多 100 的 `limit`、可选的精确插件 `name`;`total` 与 `nextOffset` 界定遍历),每个 entry 带 Loader id、patch 所寻址的树内 id 及其 Config 状态(`schema`、`absent`、`unsupported`、group 与 include 载体为 `tree`、禁用、未导入或已销毁的 entry 为 `inactive`),并把单个 entry 的原生 Config 投影为自包含的 JSON Schema 文档,同时在 profile 包查找能解析时给出该 entry 的 `packageDir`,即包 README 与构建产物 `lib/` 所在目录。Host 的 `Runtime` provider 的 `getVersion` 返回 `{ version }`,即插件 `engines.dsh` 范围和 DSH peer 依赖所比对的当前运行 DSH 的精确版本。没有 Agent 的调用,或在没有 Loader 的 Host 上的 `Config` 查询,以 `ToolContextUnavailableError` 失败;`Config` 分页字段格式错误时以 `ToolArgsError` 失败;未知 entry id 以 `InspectError` `INSPECT_TARGET_NOT_FOUND` 失败。通过 [Plugin Manager](../../boot/plugin-manager/README.zh.md) 安装包含插件代码或 MCP 配置的组合包。 ----- @@ -58,7 +58,7 @@ Host provider 结合生成的 Service/Event 目录、经 app-boot Config 投影 #### Token 影响 -在随发行版提供的标准模式和创造模式中,此插件向每次模型请求提供一个工具 schema。查询结果追加到转录中;精确查询避免加载无关声明。 +在随发行版提供的 Desktop 标准模式、创造模式和 SDK profile 中,此插件向每次模型请求提供一个工具 schema。查询结果追加到转录中;精确查询避免加载无关声明。 #### KV Cache 影响 diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c8aea99658..5b493af3be 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2976,6 +2976,9 @@ importers: '@deepseek-ai/dsh-cmdline': specifier: workspace:* version: link:../../boot/cmdline + '@deepseek-ai/dsh-cordis-host-runner': + specifier: workspace:* + version: link:../../extensions/cordis-host-runner '@deepseek-ai/dsh-creation-recommendations': specifier: workspace:* version: link:../../extensions/creation-recommendations @@ -3006,6 +3009,9 @@ importers: '@deepseek-ai/dsh-tool-ask-user': specifier: workspace:* version: link:../../interaction/tool-ask-user + '@deepseek-ai/dsh-tool-cordis': + specifier: workspace:* + version: link:../../extensions/tool-cordis '@deepseek-ai/dsh-tool-office': specifier: workspace:* version: link:../../document/tool-office diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index 99086f9f07..03a942a914 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -399,7 +399,7 @@ const TOOL_PACKAGES: ToolPackage[] = [ await ctx.plugin(ToolCordis) }, note: - 'Standard and Creator modes provide one read-only runtime inspection tool. Omit query for the provider directory; pass query to inspect a declared method. The Cordis host runner supplies the inspection registry; Client queries require a connected page. Author persistent changes as bundles and install them with plugin_manager.', + 'The Desktop Standard and Creator modes and the SDK profile provide one read-only runtime inspection tool. Omit query for the provider directory; pass query to inspect a declared method. The Cordis host runner supplies the inspection registry; Client queries require a connected page. Author persistent changes as bundles and install them with plugin_manager.', }, { pkg: '@deepseek-ai/dsh-tool-bash-persistent', diff --git a/scripts/smoke-python-runtime.py b/scripts/smoke-python-runtime.py index d3195fe73a..e25343436c 100644 --- a/scripts/smoke-python-runtime.py +++ b/scripts/smoke-python-runtime.py @@ -90,6 +90,7 @@ LEGACY_CUSTOM_DISABLED_ROWS = ( "workspace-dependencies", "time-context", "tool-ask-user", + "tool-cordis", "tool-fs", "tool-fs-search", "tool-goal", diff --git a/scripts/snapshots/python-sdk-single-exe/dynamic-tools/tool-history.json b/scripts/snapshots/python-sdk-single-exe/dynamic-tools/tool-history.json index 9d80c7d279..b9a01c73a9 100644 --- a/scripts/snapshots/python-sdk-single-exe/dynamic-tools/tool-history.json +++ b/scripts/snapshots/python-sdk-single-exe/dynamic-tools/tool-history.json @@ -47,6 +47,7 @@ "tools": [ "apply_patch", "ask_user_question", + "cordis_inspect", "create_goal", "edit", "get_goal", @@ -109,6 +110,7 @@ "tools": [ "apply_patch", "ask_user_question", + "cordis_inspect", "create_goal", "edit", "get_goal", @@ -186,6 +188,7 @@ "tools": [ "apply_patch", "ask_user_question", + "cordis_inspect", "create_goal", "edit", "get_goal", diff --git a/snapshots/sdk/background-wait-steer/tool-schemas.expected.json b/snapshots/sdk/background-wait-steer/tool-schemas.expected.json index 13611d9fad..3982fedb9d 100644 --- a/snapshots/sdk/background-wait-steer/tool-schemas.expected.json +++ b/snapshots/sdk/background-wait-steer/tool-schemas.expected.json @@ -136,6 +136,45 @@ ] } }, + { + "name": "cordis_inspect", + "description": "Inspect runtime APIs before writing or configuring plugins. Omit query to discover providers, methods, and input schemas; then query an exact entry from that directory. Read-only: cannot invoke business Service methods or modify the runtime. Client queries require a connected page.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "platform": { + "type": "string", + "description": "Provider platform.", + "enum": [ + "host", + "client" + ] + }, + "provider": { + "type": "string", + "description": "Provider ID from the directory." + }, + "method": { + "type": "string", + "description": "Method name from the directory." + }, + "input": { + "description": "Arguments matching the method's input schema." + } + }, + "required": [ + "platform", + "provider", + "method" + ] + } + } + } + }, { "name": "create_goal", "description": "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.", diff --git a/snapshots/sdk/command-attachments/tool-schemas.expected.json b/snapshots/sdk/command-attachments/tool-schemas.expected.json index 262bf12a5f..ea7c203ff4 100644 --- a/snapshots/sdk/command-attachments/tool-schemas.expected.json +++ b/snapshots/sdk/command-attachments/tool-schemas.expected.json @@ -136,6 +136,45 @@ ] } }, + { + "name": "cordis_inspect", + "description": "Inspect runtime APIs before writing or configuring plugins. Omit query to discover providers, methods, and input schemas; then query an exact entry from that directory. Read-only: cannot invoke business Service methods or modify the runtime. Client queries require a connected page.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "platform": { + "type": "string", + "description": "Provider platform.", + "enum": [ + "host", + "client" + ] + }, + "provider": { + "type": "string", + "description": "Provider ID from the directory." + }, + "method": { + "type": "string", + "description": "Method name from the directory." + }, + "input": { + "description": "Arguments matching the method's input schema." + } + }, + "required": [ + "platform", + "provider", + "method" + ] + } + } + } + }, { "name": "create_goal", "description": "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.", diff --git a/snapshots/sdk/cua-run-code/tool-schemas.expected.json b/snapshots/sdk/cua-run-code/tool-schemas.expected.json index d251bd81c2..ac0a023477 100644 --- a/snapshots/sdk/cua-run-code/tool-schemas.expected.json +++ b/snapshots/sdk/cua-run-code/tool-schemas.expected.json @@ -136,6 +136,45 @@ ] } }, + { + "name": "cordis_inspect", + "description": "Inspect runtime APIs before writing or configuring plugins. Omit query to discover providers, methods, and input schemas; then query an exact entry from that directory. Read-only: cannot invoke business Service methods or modify the runtime. Client queries require a connected page.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "platform": { + "type": "string", + "description": "Provider platform.", + "enum": [ + "host", + "client" + ] + }, + "provider": { + "type": "string", + "description": "Provider ID from the directory." + }, + "method": { + "type": "string", + "description": "Method name from the directory." + }, + "input": { + "description": "Arguments matching the method's input schema." + } + }, + "required": [ + "platform", + "provider", + "method" + ] + } + } + } + }, { "name": "create_goal", "description": "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.", diff --git a/snapshots/sdk/desktop-context/tool-schemas.expected.json b/snapshots/sdk/desktop-context/tool-schemas.expected.json index be187a3abb..0a8f3b4adb 100644 --- a/snapshots/sdk/desktop-context/tool-schemas.expected.json +++ b/snapshots/sdk/desktop-context/tool-schemas.expected.json @@ -136,6 +136,45 @@ ] } }, + { + "name": "cordis_inspect", + "description": "Inspect runtime APIs before writing or configuring plugins. Omit query to discover providers, methods, and input schemas; then query an exact entry from that directory. Read-only: cannot invoke business Service methods or modify the runtime. Client queries require a connected page.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "platform": { + "type": "string", + "description": "Provider platform.", + "enum": [ + "host", + "client" + ] + }, + "provider": { + "type": "string", + "description": "Provider ID from the directory." + }, + "method": { + "type": "string", + "description": "Method name from the directory." + }, + "input": { + "description": "Arguments matching the method's input schema." + } + }, + "required": [ + "platform", + "provider", + "method" + ] + } + } + } + }, { "name": "create_goal", "description": "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.", diff --git a/snapshots/sdk/desktop-ptc-context-scoped/system-prompt.expected.md b/snapshots/sdk/desktop-ptc-context-scoped/system-prompt.expected.md index de9d3d4aab..f7c63027fa 100644 --- a/snapshots/sdk/desktop-ptc-context-scoped/system-prompt.expected.md +++ b/snapshots/sdk/desktop-ptc-context-scoped/system-prompt.expected.md @@ -106,6 +106,19 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access. Use the language of the user’s current request. */ justification?: string; } & Record; + /** Inspect runtime APIs before writing or configuring plugins. Omit query to discover providers, methods, and input schemas; then query an exact entry from that directory. Read-only: cannot invoke business Service methods or modify the runtime. Client queries require a connected page. */ + cordis_inspect: { + query?: { + /** Provider platform. */ + platform: "host" | "client"; + /** Provider ID from the directory. */ + provider: string; + /** Method name from the directory. */ + method: string; + /** Arguments matching the method's input schema. */ + input?: JsonValue; + }; + } & Record; /** Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say "goal"; not for single-turn work. */ create_goal: { /** The concrete completion objective inferred from the direct human request. */ @@ -432,6 +445,7 @@ interface ToolOutputMap { runnerFailed?: boolean; }; }; + cordis_inspect: JsonValue; create_goal: { goal: null; } | { diff --git a/snapshots/sdk/desktop-ptc-context/system-prompt.expected.md b/snapshots/sdk/desktop-ptc-context/system-prompt.expected.md index f85367d44c..c4ebe80835 100644 --- a/snapshots/sdk/desktop-ptc-context/system-prompt.expected.md +++ b/snapshots/sdk/desktop-ptc-context/system-prompt.expected.md @@ -106,6 +106,19 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access. Use the language of the user’s current request. */ justification?: string; } & Record; + /** Inspect runtime APIs before writing or configuring plugins. Omit query to discover providers, methods, and input schemas; then query an exact entry from that directory. Read-only: cannot invoke business Service methods or modify the runtime. Client queries require a connected page. */ + cordis_inspect: { + query?: { + /** Provider platform. */ + platform: "host" | "client"; + /** Provider ID from the directory. */ + provider: string; + /** Method name from the directory. */ + method: string; + /** Arguments matching the method's input schema. */ + input?: JsonValue; + }; + } & Record; /** Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say "goal"; not for single-turn work. */ create_goal: { /** The concrete completion objective inferred from the direct human request. */ @@ -432,6 +445,7 @@ interface ToolOutputMap { runnerFailed?: boolean; }; }; + cordis_inspect: JsonValue; create_goal: { goal: null; } | { diff --git a/snapshots/sdk/legacy-context.patch.yml b/snapshots/sdk/legacy-context.patch.yml index ea0b46ea86..0775a0fee5 100644 --- a/snapshots/sdk/legacy-context.patch.yml +++ b/snapshots/sdk/legacy-context.patch.yml @@ -25,6 +25,9 @@ - id: tool-office disabled: true +- id: tool-cordis + disabled: true + # The recorded tool catalog includes the optional patch tool. - id: tool-fs config: diff --git a/snapshots/sdk/manual-compact/tool-schemas.expected.json b/snapshots/sdk/manual-compact/tool-schemas.expected.json index 263b09efac..6175a87da0 100644 --- a/snapshots/sdk/manual-compact/tool-schemas.expected.json +++ b/snapshots/sdk/manual-compact/tool-schemas.expected.json @@ -136,6 +136,45 @@ ] } }, + { + "name": "cordis_inspect", + "description": "Inspect runtime APIs before writing or configuring plugins. Omit query to discover providers, methods, and input schemas; then query an exact entry from that directory. Read-only: cannot invoke business Service methods or modify the runtime. Client queries require a connected page.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "platform": { + "type": "string", + "description": "Provider platform.", + "enum": [ + "host", + "client" + ] + }, + "provider": { + "type": "string", + "description": "Provider ID from the directory." + }, + "method": { + "type": "string", + "description": "Method name from the directory." + }, + "input": { + "description": "Arguments matching the method's input schema." + } + }, + "required": [ + "platform", + "provider", + "method" + ] + } + } + } + }, { "name": "create_goal", "description": "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.", @@ -1040,6 +1079,45 @@ ] } }, + { + "name": "cordis_inspect", + "description": "Inspect runtime APIs before writing or configuring plugins. Omit query to discover providers, methods, and input schemas; then query an exact entry from that directory. Read-only: cannot invoke business Service methods or modify the runtime. Client queries require a connected page.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "platform": { + "type": "string", + "description": "Provider platform.", + "enum": [ + "host", + "client" + ] + }, + "provider": { + "type": "string", + "description": "Provider ID from the directory." + }, + "method": { + "type": "string", + "description": "Method name from the directory." + }, + "input": { + "description": "Arguments matching the method's input schema." + } + }, + "required": [ + "platform", + "provider", + "method" + ] + } + } + } + }, { "name": "create_goal", "description": "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.", diff --git a/snapshots/sdk/plan-review/session.v4.jsonl b/snapshots/sdk/plan-review/session.v4.jsonl index ab9e5d79e0..4899b549b1 100644 --- a/snapshots/sdk/plan-review/session.v4.jsonl +++ b/snapshots/sdk/plan-review/session.v4.jsonl @@ -11,7 +11,7 @@ {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, read, edit, and validate Word, PowerPoint, and Excel files; render Office files and PDFs; convert or recalculate. Load first to enable office_render, office_convert, and office_recalculate.\n- `official-plugins`: Check DSH’s optional plugins when the user asks how to do or use something in this app, whether it can, or says a capability is missing or should change: tools, input, thinking or title display, session search, terminals, worktrees, agent teams, desktop control, automation, access, approvals, badges or signatures, plugins or plugin sources. Not a request to develop DSH, even in its own repository: load before reading files or source. Not for ordinary tasks, quoted wishes or declined offers.\n- `personalized-pages`: Plan an optional page or small tool when the user asks for a page, tab, panel, tool or interface in this app (even for one-off use), wants something to keep, revisit or update later, will keep changing data in your answer, or wants a live view of this app’s own data (Sessions, tasks, logs, workspace). Load this before reading any files or source; it says how to submit the proposal. Not for requested files or code, ordinary answers, existing-feature questions, quoted wishes or declined offers.\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create, read, edit, and validate Word, PowerPoint, and Excel files; render Office files and PDFs; convert or recalculate. Load first to enable office_render, office_convert, and office_recalculate."},{"name":"official-plugins","description":"Check DSH’s optional plugins when the user asks how to do or use something in this app, whether it can, or says a capability is missing or should change: tools, input, thinking or title display, session search, terminals, worktrees, agent teams, desktop control, automation, access, approvals, badges or signatures, plugins or plugin sources. Not a request to develop DSH, even in its own repository: load before reading files or source. Not for ordinary tasks, quoted wishes or declined offers."},{"name":"personalized-pages","description":"Plan an optional page or small tool when the user asks for a page, tab, panel, tool or interface in this app (even for one-off use), wants something to keep, revisit or update later, will keep changing data in your answer, or wants a live view of this app’s own data (Sessions, tasks, logs, workspace). Load this before reading any files or source; it says how to submit the proposal. Not for requested files or code, ordinary answers, existing-feature questions, quoted wishes or declined offers."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: UTC. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: unavailable."}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: UTC. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: unavailable."}]},"role":"user","id":"{{message:5}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","cordis_inspect","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply SDK_PLAN_INITIAL without tools.","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":14}} @@ -29,7 +29,7 @@ {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"plan:policy","order":500,"state":"active","contentIndex":0},{"name":"plan:status","order":501,"state":"active","contentIndex":1}]},"id":"{{message:9}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"The user switched this session to plan mode."}],"source":{"kind":"plan-mode","form":"notice","summary":"The user switched this session to plan mode."},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Prepare a plan through exit_plan_mode; revise after feedback and acknowledge approval."}],"source":{"kind":"user"},"role":"user","id":"{{message:8}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","cordis_inspect","create_goal","edit","exit_plan_mode","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"exit_plan_mode"}],"role":"developer","id":"{{message:10}}"},"headerSeq":30},"surfaceOp":"append"} {"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":31}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"commands-tool-1","name":"exit_plan_mode","arguments":"{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"tool-call"}]}},"id":"{{message:11}}"},"usage":{"inputTokens":10000,"outputTokens":32,"totalTokens":10032},"stream":[{"type":"chunk","time":1792108800000,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1792108800000,"index":0,"dt":[],"id":"commands-tool-1","name":"exit_plan_mode","args":[""]},{"type":"tool-call-chunks","time0":1792108800000,"index":0,"dt":[],"id":"commands-tool-1","args":["{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"]},{"type":"chunk","time":1792108800000,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"commands-tool-1","name":"exit_plan_mode","arguments":"{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"usage","usage":{"inputTokens":10000,"outputTokens":32,"totalTokens":10032}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"finish","reason":{"kind":"tool-calls"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"tool-call"}]}}}]},"surfaceOp":"append"} diff --git a/snapshots/sdk/plan-review/tool-schemas.expected.json b/snapshots/sdk/plan-review/tool-schemas.expected.json index 71e14844b3..bc146c56cf 100644 --- a/snapshots/sdk/plan-review/tool-schemas.expected.json +++ b/snapshots/sdk/plan-review/tool-schemas.expected.json @@ -136,6 +136,45 @@ ] } }, + { + "name": "cordis_inspect", + "description": "Inspect runtime APIs before writing or configuring plugins. Omit query to discover providers, methods, and input schemas; then query an exact entry from that directory. Read-only: cannot invoke business Service methods or modify the runtime. Client queries require a connected page.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "platform": { + "type": "string", + "description": "Provider platform.", + "enum": [ + "host", + "client" + ] + }, + "provider": { + "type": "string", + "description": "Provider ID from the directory." + }, + "method": { + "type": "string", + "description": "Method name from the directory." + }, + "input": { + "description": "Arguments matching the method's input schema." + } + }, + "required": [ + "platform", + "provider", + "method" + ] + } + } + } + }, { "name": "create_goal", "description": "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.", @@ -1040,6 +1079,45 @@ ] } }, + { + "name": "cordis_inspect", + "description": "Inspect runtime APIs before writing or configuring plugins. Omit query to discover providers, methods, and input schemas; then query an exact entry from that directory. Read-only: cannot invoke business Service methods or modify the runtime. Client queries require a connected page.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "platform": { + "type": "string", + "description": "Provider platform.", + "enum": [ + "host", + "client" + ] + }, + "provider": { + "type": "string", + "description": "Provider ID from the directory." + }, + "method": { + "type": "string", + "description": "Method name from the directory." + }, + "input": { + "description": "Arguments matching the method's input schema." + } + }, + "required": [ + "platform", + "provider", + "method" + ] + } + } + } + }, { "name": "create_goal", "description": "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.", diff --git a/snapshots/sdk/team-default-enabled/tool-schemas.1.expected.json b/snapshots/sdk/team-default-enabled/tool-schemas.1.expected.json index 125b25eeaa..8730f8b10f 100644 --- a/snapshots/sdk/team-default-enabled/tool-schemas.1.expected.json +++ b/snapshots/sdk/team-default-enabled/tool-schemas.1.expected.json @@ -108,6 +108,45 @@ ] } }, + { + "name": "cordis_inspect", + "description": "Inspect runtime APIs before writing or configuring plugins. Omit query to discover providers, methods, and input schemas; then query an exact entry from that directory. Read-only: cannot invoke business Service methods or modify the runtime. Client queries require a connected page.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "platform": { + "type": "string", + "description": "Provider platform.", + "enum": [ + "host", + "client" + ] + }, + "provider": { + "type": "string", + "description": "Provider ID from the directory." + }, + "method": { + "type": "string", + "description": "Method name from the directory." + }, + "input": { + "description": "Arguments matching the method's input schema." + } + }, + "required": [ + "platform", + "provider", + "method" + ] + } + } + } + }, { "name": "create_goal", "description": "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.", diff --git a/snapshots/sdk/team-default-enabled/tool-schemas.expected.json b/snapshots/sdk/team-default-enabled/tool-schemas.expected.json index 125b25eeaa..8730f8b10f 100644 --- a/snapshots/sdk/team-default-enabled/tool-schemas.expected.json +++ b/snapshots/sdk/team-default-enabled/tool-schemas.expected.json @@ -108,6 +108,45 @@ ] } }, + { + "name": "cordis_inspect", + "description": "Inspect runtime APIs before writing or configuring plugins. Omit query to discover providers, methods, and input schemas; then query an exact entry from that directory. Read-only: cannot invoke business Service methods or modify the runtime. Client queries require a connected page.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "platform": { + "type": "string", + "description": "Provider platform.", + "enum": [ + "host", + "client" + ] + }, + "provider": { + "type": "string", + "description": "Provider ID from the directory." + }, + "method": { + "type": "string", + "description": "Method name from the directory." + }, + "input": { + "description": "Arguments matching the method's input schema." + } + }, + "required": [ + "platform", + "provider", + "method" + ] + } + } + } + }, { "name": "create_goal", "description": "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.", From 5f20c2f19d8e5c0242d271942b6499ddd168bd6e Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 23 Nov 2026 13:54:23 +0800 Subject: [PATCH 8/8] fix(sdk): let the Python advanced patch reuse the bundle's Cordis rows The sdk-app bundle now mounts cordis-host-runner and tool-cordis, so the Python smoke's advanced patch no longer inserts its own copies. The composition keeps one row per id and the recorded tool set unchanged. The upgrade guide also names the rows that remove the inspection services along with the tool. --- .../v0.2.3-alpha.2/sdk-cordis-inspect/guide.i18n.yaml | 4 ++-- docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.md | 2 ++ .../v0.2.3-alpha.2/sdk-cordis-inspect/guide.zh.md | 2 ++ scripts/smoke-python-runtime.py | 3 --- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.i18n.yaml b/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.i18n.yaml index fb761f368e..573994974e 100644 --- a/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.i18n.yaml @@ -12,5 +12,5 @@ en: e05bc467d0ce54f1 zh: dae859bf19c5b707 /sdk-runtime-inspection-tool/migration: - en: ec1bf74ca8b0ad38 - zh: ee38ed5a5c00f160 + en: 6be51f2b5530a939 + zh: 746ab19a6d514fb6 diff --git a/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.md b/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.md index c997391d7a..a4edb5162a 100644 --- a/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.md +++ b/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.md @@ -21,4 +21,6 @@ The `sdk` profile now mounts `cordis-host-runner`, `cordis-inspect-providers`, a disabled: true ``` + This removes only the tool. To also remove the inspection registry and Host providers from the process, disable the `cordis-inspect-providers` and `cordis-host-runner` rows as well. + 3. Run a task and confirm that the first model request lists `cordis_inspect` exactly when the row is enabled. diff --git a/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.zh.md b/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.zh.md index d4aeec18ef..8a1ae74c1b 100644 --- a/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.zh.md +++ b/docs/upgrade-guide/v0.2.3-alpha.2/sdk-cordis-inspect/guide.zh.md @@ -21,4 +21,6 @@ description: SDK profile 新增 cordis_inspect 运行时检查工具。 disabled: true ``` + 这样只移除工具。如需同时从进程中移除检查注册表和 Host provider,还要禁用 `cordis-inspect-providers` 和 `cordis-host-runner` 行。 + 3. 运行一个任务,确认首个模型请求只在该行启用时列出 `cordis_inspect`。 diff --git a/scripts/smoke-python-runtime.py b/scripts/smoke-python-runtime.py index e25343436c..74b2b1dddf 100644 --- a/scripts/smoke-python-runtime.py +++ b/scripts/smoke-python-runtime.py @@ -90,7 +90,6 @@ LEGACY_CUSTOM_DISABLED_ROWS = ( "workspace-dependencies", "time-context", "tool-ask-user", - "tool-cordis", "tool-fs", "tool-fs-search", "tool-goal", @@ -285,8 +284,6 @@ def write_advanced_profile_patch( }, {"insert": [ {"id": "ptc-runtime", "name": "@deepseek-ai/dsh-ptc-runtime-node"}, - {"id": "cordis-host-runner", "name": "@deepseek-ai/dsh-cordis-host-runner"}, - {"id": "cordis-tool", "name": "@deepseek-ai/dsh-tool-cordis"}, ]}, ])