From dccf989cd8b276f1a2ce082f1fd49911d6297ef7 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 22 Sep 2026 12:35:37 +0800 Subject: [PATCH 01/19] feat(plugin-manager): prefer the mainland mirror for CN network exits --- .../country-default.expected.md | 10 ++ apps/web/tests/plugin-install-registry.e2e.ts | 32 +++++- apps/web/tests/scaffold.ts | 1 + docs/capability-seams.i18n.yaml | 4 +- docs/capability-seams.md | 5 + docs/capability-seams.zh.md | 5 + docs/config-catalog.i18n.yaml | 4 +- docs/config-catalog.md | 24 ++++- docs/config-catalog.zh.md | 24 ++++- docs/subsystems/boot.i18n.yaml | 4 +- docs/subsystems/boot.md | 17 +++ docs/subsystems/boot.zh.md | 17 +++ packages/api/remotes/README.i18n.yaml | 4 +- packages/api/remotes/README.md | 2 +- packages/api/remotes/README.zh.md | 2 +- packages/api/remotes/package.json | 1 + packages/api/remotes/src/client/index.ts | 5 +- .../client/ui-plugin-manager/README.i18n.yaml | 4 +- packages/client/ui-plugin-manager/README.md | 14 ++- .../client/ui-plugin-manager/README.zh.md | 14 ++- .../client/ui-plugin-manager/package.json | 25 ++++- .../ui-plugin-manager/src/client/index.ts | 2 +- .../src/client/manager-store.ts | 59 ++++++++-- .../client/ui-plugin-manager/src/index.ts | 83 +++++++++++++- .../tests/browser-plugin.client.spec.tsx | 8 +- .../tests/location.host.spec.ts | 71 ++++++++++++ .../tests/manager-store.client.spec.ts | 102 +++++++++++++++++- .../ui-plugin-manager/tsconfig.client.json | 56 ++++++++++ .../ui-plugin-manager/tsconfig.host.json | 28 +++++ .../client/ui-plugin-manager/tsconfig.json | 49 +-------- .../client/ui-plugin-manager/tsdown.config.ts | 2 +- .../ui-settings-agent-loop/tsconfig.json | 2 +- .../client/ui-settings-shell/tsconfig.json | 2 +- .../client/ui-settings-subagent/tsconfig.json | 2 +- .../ui-settings-web-search/tsconfig.json | 2 +- .../client-ui-voice-input/tsconfig.json | 2 +- .../extensions/tool-cordis/src/api-catalog.ts | 13 +++ .../references/packages.md | 2 +- packages/util/README.i18n.yaml | 4 +- packages/util/README.md | 1 + packages/util/README.zh.md | 1 + packages/util/ip-geolocation/README.i18n.yaml | 6 ++ packages/util/ip-geolocation/README.md | 80 ++++++++++++++ packages/util/ip-geolocation/README.zh.md | 80 ++++++++++++++ packages/util/ip-geolocation/package.json | 36 +++++++ packages/util/ip-geolocation/src/index.ts | 55 ++++++++++ .../util/ip-geolocation/tests/country.spec.ts | 68 ++++++++++++ .../util/ip-geolocation/tests/egress.spec.ts | 34 ++++++ packages/util/ip-geolocation/tsconfig.json | 11 ++ pnpm-lock.yaml | 28 +++++ scripts/doc-standard.spec.ts | 1 + scripts/gen-cordis-catalog.ts | 1 + scripts/gen-doc-graphs.ts | 8 ++ scripts/package-dependency-policy.ts | 1 + scripts/verify-package-dependencies.spec.ts | 1 + .../verify-package-readme-model-experience.ts | 1 + tsconfig.base.json | 1 + tsconfig.client.json | 2 +- tsconfig.host.json | 2 + 59 files changed, 1020 insertions(+), 105 deletions(-) create mode 100644 apps/web/tests/expected/plugin-install-registry/country-default.expected.md create mode 100644 packages/client/ui-plugin-manager/tests/location.host.spec.ts create mode 100644 packages/client/ui-plugin-manager/tsconfig.client.json create mode 100644 packages/client/ui-plugin-manager/tsconfig.host.json create mode 100644 packages/util/ip-geolocation/README.i18n.yaml create mode 100644 packages/util/ip-geolocation/README.md create mode 100644 packages/util/ip-geolocation/README.zh.md create mode 100644 packages/util/ip-geolocation/package.json create mode 100644 packages/util/ip-geolocation/src/index.ts create mode 100644 packages/util/ip-geolocation/tests/country.spec.ts create mode 100644 packages/util/ip-geolocation/tests/egress.spec.ts create mode 100644 packages/util/ip-geolocation/tsconfig.json diff --git a/apps/web/tests/expected/plugin-install-registry/country-default.expected.md b/apps/web/tests/expected/plugin-install-registry/country-default.expected.md new file mode 100644 index 0000000000..c83912b6b8 --- /dev/null +++ b/apps/web/tests/expected/plugin-install-registry/country-default.expected.md @@ -0,0 +1,10 @@ +- group "从哪个 npm 源下载插件": + - radio "默认安装源(registry.npmjs.org)" + - text: 默认安装源(registry.npmjs.org) + - radio "中国大陆镜像源(registry.npmmirror.com)" [checked] + - text: 中国大陆镜像源(registry.npmmirror.com) + - radio "自定义地址" + - text: 自定义地址 + - textbox "自定义地址" [disabled]: + - /placeholder: https://npm.example.com/ + - text: 公司内网或私有 npm 源;需要登录的源,把凭据放在本机的 ~/.npmrc 里 diff --git a/apps/web/tests/plugin-install-registry.e2e.ts b/apps/web/tests/plugin-install-registry.e2e.ts index 3599b0b60c..e7157d0e43 100644 --- a/apps/web/tests/plugin-install-registry.e2e.ts +++ b/apps/web/tests/plugin-install-registry.e2e.ts @@ -5,17 +5,30 @@ import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' +import { createServer } from 'node:http' import { chromium } from 'playwright' -import { expect, it } from 'vitest' +import { expect, it, onTestFinished } from 'vitest' import { launchWebScaffold, captureStableAria, compareOrRefreshGolden, webSnapshotMode, watchConsole, type WebScaffold } from './scaffold.ts' import { ZH_BROWSER_LOCALE } from './support.ts' const MIRROR = 'https://registry.npmmirror.com/' -it('offers the registries, remembers the one picked, and moves an install on to the next when a run loses its registry', async () => { +it.each([null, 'CN'])('selects an installation source for Host country %s, remembers it, and falls back after a registry failure', async (country) => { const scratch = await mkdtemp(join(tmpdir(), 'dsh-install-registry-')) const overlay = join(scratch, 'cordis.patch.yml') - await writeFile(overlay, `- id: plugin-manager\n config: ${JSON.stringify({ pnpmCommand: process.execPath })}\n`) + const countryServer = createServer((_request, response) => { + response.writeHead(200, { 'content-type': 'application/json' }) + response.end(JSON.stringify({ country })) + }) + await new Promise((resolve) => { countryServer.listen(0, '127.0.0.1', resolve) }) + onTestFinished(() => new Promise((resolve, reject) => { + countryServer.close((error) => { if (error === undefined) resolve(); else reject(error) }) + countryServer.closeAllConnections() + })) + const address = countryServer.address() + if (address === null || typeof address === 'string') throw new Error('Expected a TCP listener') + await writeFile(overlay, `- id: plugin-manager\n config: ${JSON.stringify({ pnpmCommand: process.execPath })}\n` + + `- id: ui-plugin-manager\n config: ${JSON.stringify({ countryLookupEnabled: true, countryEndpoint: `http://127.0.0.1:${address.port}/` })}\n`) let scaffold: WebScaffold | undefined try { scaffold = await launchWebScaffold({ profile: { packages: [] }, extraOverlayPath: overlay }) @@ -29,6 +42,7 @@ it('offers the registries, remembers the one picked, and moves an install on to // it is asked, naming the registry, and installs the package on the next; the Host moves it on to the next registry. await writeFile(join(profile, 'config'), 'console.log("https://registry.npmjs.org/")\n') await writeFile(join(profile, 'view'), ` + require('node:fs').appendFileSync('.registry-lookups', JSON.stringify(process.argv) + '\\n'); if (!process.argv.includes('--registry=${MIRROR}')) { console.log(JSON.stringify({ error: { code: 'ERR_PNPM_META_FETCH_FAIL', message: 'GET https://registry.npmjs.org/mirrored-package: request timed out (ETIMEDOUT)' } })); process.exitCode = 1; @@ -63,12 +77,17 @@ it('offers the registries, remembers the one picked, and moves an install on to const dialog = page.getByRole('dialog') // Folded, the registry control names pnpm's own registry; unfolded, its options float from it and offer the configured // mirror and a typed address. - const registryToggle = dialog.getByRole('button', { name: '安装源 默认安装源', exact: true }) + const registryToggle = dialog.getByRole('button', { name: country === 'CN' ? '安装源 中国大陆镜像源' : '安装源 默认安装源', exact: true }) await registryToggle.waitFor() expect(await page.getByRole('radio').count()).toBe(0) await registryToggle.click() const options = page.getByRole('group', { name: '从哪个 npm 源下载插件', exact: true }) - await options.getByRole('radio', { name: '中国大陆镜像源(registry.npmmirror.com)', exact: true }).click() + const mirror = options.getByRole('radio', { name: '中国大陆镜像源(registry.npmmirror.com)', exact: true }) + if (country === 'CN') { + expect(await mirror.isChecked()).toBe(true) + await compareOrRefreshGolden(fileURLToPath(new URL('./expected/plugin-install-registry/country-default.expected.md', import.meta.url)), + await captureStableAria(page, '[data-install-registry]', scaffold.workspaceCwd), webSnapshotMode()) + } else await mirror.click() expect(await options.getByRole('radio').count()).toBe(3) await dialog.getByRole('button', { name: '安装源 中国大陆镜像源', exact: true }).waitFor() await dialog.getByRole('textbox', { name: '包名或地址' }).fill('mirrored-package') @@ -86,6 +105,9 @@ it('offers the registries, remembers the one picked, and moves an install on to // the registry after it, which finished it. Each run shows behind the details with the registry it asked. await dialog.getByRole('button', { name: '立即启用', exact: true }).waitFor({ timeout: 20_000 }) await dialog.getByText('版本 2.0.0', { exact: true }).waitFor() + const lookups = (await readFile(join(profile, '.registry-lookups'), 'utf8')).trim().split('\n') + expect(lookups).toHaveLength(1) + expect(JSON.parse(lookups[0]!)).toContain('--registry=' + MIRROR) await dialog.getByRole('button', { name: '查看安装详情', exact: true }).click() await dialog.getByText('Installed from the registry pnpm names', { exact: true }).waitFor() await dialog.getByText('第 1 次 · 中国大陆镜像源', { exact: true }).waitFor() diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index c3a18d7ee9..fa951f669b 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -565,6 +565,7 @@ export async function launchWebScaffold(options: LaunchOptions = {}): PromiseSerialized module and configuration reloads"] pkg_app_boot["app-boot"] + pkg_client_ui_plugin_manager["client-ui-plugin-manager"] + svc_pluginInstallLocation["ctx.pluginInstallLocation
Host exit country for plugin installation"] pkg_plugin_manager["plugin-manager"] svc_pluginManager["ctx.pluginManager
Current-profile plugin and bundle management"] pkg_ui_settings_plugin_inventory["ui-settings-plugin-inventory"] @@ -293,6 +295,7 @@ flowchart LR pkg_client_connection --> svc_connection pkg_client_file_upload --> svc_fileUploads pkg_client_modules --> svc_clientModules + pkg_client_ui_plugin_manager --> svc_pluginInstallLocation pkg_command_feedback --> svc_sessionFeedback pkg_commands --> svc_commands pkg_compaction --> svc_compaction @@ -468,6 +471,7 @@ flowchart LR svc_lsp --> pkg_tool_lsp svc_mcpResources --> pkg_mcp_resources svc_officeToPdf --> pkg_client_ui_sidebar_documentpreview + svc_pluginInstallLocation --> pkg_client_ui_plugin_manager svc_pluginManager --> pkg_plugin_manager svc_pluginManager --> pkg_ui_settings_plugin_inventory svc_profileContext --> pkg_plugin_manager @@ -564,6 +568,7 @@ flowchart LR | ctx key | Role | Owner | Implementations | Direct consumers | Companion plugins | Note | | --- | --- | --- | --- | --- | --- | --- | | `ctx.hmr` | `core` | [`hmr`](../packages/boot/hmr) | - | [`app-boot`](../packages/boot/app-boot) | - | Owns module and exact configuration watchers; application mutations share its queue and automatic reloads await the application file lock. | +| `ctx.pluginInstallLocation` | `core` | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | Shares a bounded country lookup across dialogs; the Client owns the initial registry recommendation. | | `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager), `ui-settings-plugin-inventory` | - | Shares profile package operations with the CLI and reports persisted and running state to Web and agent callers. | | `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | The dsh launcher supplies data-only profile locations and composition inputs; reload scheduling belongs to dsh-hmr. | | `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | Owns browser authentication and shared HTTP request dispatch; API adapters register endpoints and streams. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index f0e584f926..46c7b44b1a 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -12,6 +12,8 @@ flowchart LR pkg_hmr["hmr"] svc_hmr["ctx.hmr
Serialized module and configuration reloads"] pkg_app_boot["app-boot"] + pkg_client_ui_plugin_manager["client-ui-plugin-manager"] + svc_pluginInstallLocation["ctx.pluginInstallLocation
Host exit country for plugin installation"] pkg_plugin_manager["plugin-manager"] svc_pluginManager["ctx.pluginManager
Current-profile plugin and bundle management"] pkg_ui_settings_plugin_inventory["ui-settings-plugin-inventory"] @@ -295,6 +297,7 @@ flowchart LR pkg_client_connection --> svc_connection pkg_client_file_upload --> svc_fileUploads pkg_client_modules --> svc_clientModules + pkg_client_ui_plugin_manager --> svc_pluginInstallLocation pkg_command_feedback --> svc_sessionFeedback pkg_commands --> svc_commands pkg_compaction --> svc_compaction @@ -470,6 +473,7 @@ flowchart LR svc_lsp --> pkg_tool_lsp svc_mcpResources --> pkg_mcp_resources svc_officeToPdf --> pkg_client_ui_sidebar_documentpreview + svc_pluginInstallLocation --> pkg_client_ui_plugin_manager svc_pluginManager --> pkg_plugin_manager svc_pluginManager --> pkg_ui_settings_plugin_inventory svc_profileContext --> pkg_plugin_manager @@ -566,6 +570,7 @@ flowchart LR | ctx 键 | 角色 | 所属包 | 实现 | 直接消费方 | 配套插件 | 说明 | | --- | --- | --- | --- | --- | --- | --- | | `ctx.hmr` | `core` | [`hmr`](../packages/boot/hmr) | - | [`app-boot`](../packages/boot/app-boot) | - | 负责模块和精确配置监听;应用修改共用其队列,自动重载等待应用文件锁。 | +| `ctx.pluginInstallLocation` | `core` | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | 在对话框之间共享有时限的国家查询;初始安装源推荐由 Client 负责。 | | `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager), `ui-settings-plugin-inventory` | - | 与 CLI 共享 profile 包操作,并向 Web 和 Agent 调用方分别报告持久状态与运行状态。 | | `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | dsh launcher 提供纯数据形式的 profile 位置与组合输入;重载调度由 dsh-hmr 负责。 | | `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | 负责浏览器认证与共享 HTTP 请求分发;API 适配器注册端点和流。 | diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index 29fa75561d..8c44515ac7 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: 573d16f37b9ce3c123c55c366d8ee6424feb3d64 -config-catalog.zh.md: 9d827a4c65ec198239d7d1ef29735747a39838b9 +config-catalog.md: e222db1d6abfefeed9e9263841db1fcc25828a22 +config-catalog.zh.md: b433333798acf497b7160af57b807756d87896a6 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 573d16f37b..e222db1d6a 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -481,6 +481,28 @@ export interface Config { Source: [`packages/client/hmr/src/index.ts:30`](../packages/client/hmr/src/index.ts) + + +## `@deepseek-ai/dsh-client-ui-plugin-manager` + +```ts config-catalog +/** Country lookup endpoint, request bounds, and process-local cache policy. */ +export interface Config { + /** Whether the dialog can query the Host network country. */ + countryLookupEnabled: boolean + /** HTTP(S) endpoint returning a two-letter `country` field. */ + countryEndpoint: string + /** Deadline for one lookup, including its body. */ + countryTimeoutMs: number + /** Maximum country lookup response-body bytes. */ + countryMaxResponseBytes: number + /** Lifetime of a known or unavailable country reading. */ + countryCacheTtlMs: number +} +``` + +Source: [`packages/client/ui-plugin-manager/src/index.ts:16`](../packages/client/ui-plugin-manager/src/index.ts) + ## `@deepseek-ai/dsh-client-ui-settings-account` @@ -4114,7 +4136,6 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co - `@deepseek-ai/dsh-client-ui-open-in-app` ([`packages/client/ui-open-in-app/src/index.ts`](../packages/client/ui-open-in-app/src/index.ts)) - `@deepseek-ai/dsh-client-ui-permission-presets` ([`packages/client/ui-permission-presets/src/index.ts`](../packages/client/ui-permission-presets/src/index.ts)) - `@deepseek-ai/dsh-client-ui-plan` ([`packages/client/ui-plan/src/index.ts`](../packages/client/ui-plan/src/index.ts)) -- `@deepseek-ai/dsh-client-ui-plugin-manager` ([`packages/client/ui-plugin-manager/src/index.ts`](../packages/client/ui-plugin-manager/src/index.ts)) - `@deepseek-ai/dsh-client-ui-reference` ([`packages/client/ui-reference/src/index.ts`](../packages/client/ui-reference/src/index.ts)) - `@deepseek-ai/dsh-client-ui-renderer` ([`packages/client/ui-renderer/src/index.ts`](../packages/client/ui-renderer/src/index.ts)) - `@deepseek-ai/dsh-client-ui-schedule` ([`packages/client/ui-schedule/src/index.ts`](../packages/client/ui-schedule/src/index.ts)) @@ -4230,6 +4251,7 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them. - `@deepseek-ai/dsh-home-paths` ([`packages/util/home-paths/src/index.ts`](../packages/util/home-paths/src/index.ts)) - `@deepseek-ai/dsh-hook-protocol` ([`packages/hooks/hook-protocol/src/index.ts`](../packages/hooks/hook-protocol/src/index.ts)) - `@deepseek-ai/dsh-http-proxy` ([`packages/util/http-proxy/src/index.ts`](../packages/util/http-proxy/src/index.ts)) +- `@deepseek-ai/dsh-ip-geolocation` ([`packages/util/ip-geolocation/src/index.ts`](../packages/util/ip-geolocation/src/index.ts)) - `@deepseek-ai/dsh-launch-environment` ([`packages/util/launch-environment/src/index.ts`](../packages/util/launch-environment/src/index.ts)) - `@deepseek-ai/dsh-lazy-require` ([`packages/util/lazy-require/src/index.ts`](../packages/util/lazy-require/src/index.ts)) - `@deepseek-ai/dsh-llm-mock-server` ([`packages/test-support/llm-mock-server/src/index.ts`](../packages/test-support/llm-mock-server/src/index.ts)) diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 9d827a4c65..b433333798 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -483,6 +483,28 @@ export interface Config { 来源: [`packages/client/hmr/src/index.ts:30`](../packages/client/hmr/src/index.ts) + + +## `@deepseek-ai/dsh-client-ui-plugin-manager` + +```ts config-catalog +/** Country lookup endpoint, request bounds, and process-local cache policy. */ +export interface Config { + /** Whether the dialog can query the Host network country. */ + countryLookupEnabled: boolean + /** HTTP(S) endpoint returning a two-letter `country` field. */ + countryEndpoint: string + /** Deadline for one lookup, including its body. */ + countryTimeoutMs: number + /** Maximum country lookup response-body bytes. */ + countryMaxResponseBytes: number + /** Lifetime of a known or unavailable country reading. */ + countryCacheTtlMs: number +} +``` + +来源: [`packages/client/ui-plugin-manager/src/index.ts:16`](../packages/client/ui-plugin-manager/src/index.ts) + ## `@deepseek-ai/dsh-client-ui-settings-account` @@ -4116,7 +4138,6 @@ export interface Config { - `@deepseek-ai/dsh-client-ui-open-in-app`([`packages/client/ui-open-in-app/src/index.ts`](../packages/client/ui-open-in-app/src/index.ts)) - `@deepseek-ai/dsh-client-ui-permission-presets`([`packages/client/ui-permission-presets/src/index.ts`](../packages/client/ui-permission-presets/src/index.ts)) - `@deepseek-ai/dsh-client-ui-plan`([`packages/client/ui-plan/src/index.ts`](../packages/client/ui-plan/src/index.ts)) -- `@deepseek-ai/dsh-client-ui-plugin-manager`([`packages/client/ui-plugin-manager/src/index.ts`](../packages/client/ui-plugin-manager/src/index.ts)) - `@deepseek-ai/dsh-client-ui-reference`([`packages/client/ui-reference/src/index.ts`](../packages/client/ui-reference/src/index.ts)) - `@deepseek-ai/dsh-client-ui-renderer`([`packages/client/ui-renderer/src/index.ts`](../packages/client/ui-renderer/src/index.ts)) - `@deepseek-ai/dsh-client-ui-schedule`([`packages/client/ui-schedule/src/index.ts`](../packages/client/ui-schedule/src/index.ts)) @@ -4232,6 +4253,7 @@ export interface Config { - `@deepseek-ai/dsh-home-paths`([`packages/util/home-paths/src/index.ts`](../packages/util/home-paths/src/index.ts)) - `@deepseek-ai/dsh-hook-protocol`([`packages/hooks/hook-protocol/src/index.ts`](../packages/hooks/hook-protocol/src/index.ts)) - `@deepseek-ai/dsh-http-proxy`([`packages/util/http-proxy/src/index.ts`](../packages/util/http-proxy/src/index.ts)) +- `@deepseek-ai/dsh-ip-geolocation`([`packages/util/ip-geolocation/src/index.ts`](../packages/util/ip-geolocation/src/index.ts)) - `@deepseek-ai/dsh-launch-environment`([`packages/util/launch-environment/src/index.ts`](../packages/util/launch-environment/src/index.ts)) - `@deepseek-ai/dsh-lazy-require`([`packages/util/lazy-require/src/index.ts`](../packages/util/lazy-require/src/index.ts)) - `@deepseek-ai/dsh-llm-mock-server`([`packages/test-support/llm-mock-server/src/index.ts`](../packages/test-support/llm-mock-server/src/index.ts)) diff --git a/docs/subsystems/boot.i18n.yaml b/docs/subsystems/boot.i18n.yaml index c5d46dd2cb..da42c058a9 100644 --- a/docs/subsystems/boot.i18n.yaml +++ b/docs/subsystems/boot.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/boot.md -boot.md: a52c362aef1c61f9087da7c1abfce8d4671d9e92 -boot.zh.md: 5933e206127bd5ca4aa0b8888cf81f0e1aeb9eb7 +boot.md: 4e34b13981c7601a5d20efc7508a023c54cb0ccd +boot.zh.md: 0b7e57910a72c784a527a84ac7876297a0980b3d diff --git a/docs/subsystems/boot.md b/docs/subsystems/boot.md index a52c362aef..4e34b13981 100644 --- a/docs/subsystems/boot.md +++ b/docs/subsystems/boot.md @@ -82,6 +82,23 @@ async getLinked(url: string): Promise Source: [`packages/boot/hmr/src/index.ts`](../../packages/boot/hmr/src/index.ts) + + +### `ctx.pluginInstallLocation` — `PluginInstallLocation` + +Shares a bounded Host lookup across installation dialogs; source-selection policy belongs to the Client. + +```ts cordis-catalog +/** + * Read the Host's exit country through its configured outbound fetch transport. + * Concurrent callers share one lookup; caller disconnects do not cancel other readers. + * @returns country code, or null when disabled, unavailable, or the lookup fails; both outcomes are cached. + */ +@Remote country(): Promise +``` + +Source: [`packages/client/ui-plugin-manager/src/index.ts`](../../packages/client/ui-plugin-manager/src/index.ts) + ### `ctx.pluginManager` — `PluginManager` diff --git a/docs/subsystems/boot.zh.md b/docs/subsystems/boot.zh.md index 5933e20612..0b7e57910a 100644 --- a/docs/subsystems/boot.zh.md +++ b/docs/subsystems/boot.zh.md @@ -82,6 +82,23 @@ async getLinked(url: string): Promise Source: [`packages/boot/hmr/src/index.ts`](../../packages/boot/hmr/src/index.ts) + + +### `ctx.pluginInstallLocation` — `PluginInstallLocation` + +Shares a bounded Host lookup across installation dialogs; source-selection policy belongs to the Client. + +```ts cordis-catalog +/** + * Read the Host's exit country through its configured outbound fetch transport. + * Concurrent callers share one lookup; caller disconnects do not cancel other readers. + * @returns country code, or null when disabled, unavailable, or the lookup fails; both outcomes are cached. + */ +@Remote country(): Promise +``` + +Source: [`packages/client/ui-plugin-manager/src/index.ts`](../../packages/client/ui-plugin-manager/src/index.ts) + ### `ctx.pluginManager` — `PluginManager` diff --git a/packages/api/remotes/README.i18n.yaml b/packages/api/remotes/README.i18n.yaml index 0456102db4..fbc48fa767 100644 --- a/packages/api/remotes/README.i18n.yaml +++ b/packages/api/remotes/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/api/remotes/README.md -README.md: 74e1595bfbe852605e5d5a7c6930c113e63a92bd -README.zh.md: b8974b0987d5be4ebee2a2886d3cbce321638d4d +README.md: f59b85434efb120e60f067eb1c4652cbada09678 +README.zh.md: 9739f3dc0461765a35fb467bfd6306bcf7d940a7 diff --git a/packages/api/remotes/README.md b/packages/api/remotes/README.md index 74e1595bfb..f59b85434e 100644 --- a/packages/api/remotes/README.md +++ b/packages/api/remotes/README.md @@ -27,7 +27,7 @@ Two-sided BFF for Host Remote capabilities selected by this application. The Hos [`@deepseek-ai/dsh-api-session-controller`](../session-controller/README.md) owns Agent and Session identity policy, including the Typert lookup resolvers used by other namespaces. This package only selects and mounts that generated Session contribution; it does not duplicate activation policy. -The Client assembly mounts Office conversion, Commands, credentials, settings, Goal, dynamic Cordis, file and Session references, read-only Host plugin inventory, message feedback, permission presets, Session Controller, subagents, and Workspace Controller contributions. The `permissionPresets` namespace returns the complete process-level catalog used by current-session controls. Cordis effect ownership withdraws every contribution when this assembly unloads, while `@deepseek-ai/dsh-api-gateway/client` owns descriptor validation, traced namespace Services, direct and scoped methods, invocation, streams, and cancellation. The Client entry consumes the shared `TypertClientRemote` interface through Cordis and does not import the concrete Gateway. It re-exports the Gateway Client face's declaration merges type-only, so a consumer reaching the forwarded-event vocabulary through this facade gains no runtime edge to the Gateway implementation. +The Client assembly mounts Office conversion, Commands, credentials, settings, Goal, dynamic Cordis, file and Session references, read-only Host plugin inventory, plugin-installation exit country, message feedback, permission presets, Session Controller, subagents, and Workspace Controller contributions. The `permissionPresets` namespace returns the complete process-level catalog used by current-session controls. Cordis effect ownership withdraws every contribution when this assembly unloads, while `@deepseek-ai/dsh-api-gateway/client` owns descriptor validation, traced namespace Services, direct and scoped methods, invocation, streams, and cancellation. The Client entry consumes the shared `TypertClientRemote` interface through Cordis and does not import the concrete Gateway. It re-exports the Gateway Client face's declaration merges type-only, so a consumer reaching the forwarded-event vocabulary through this facade gains no runtime edge to the Gateway implementation. This facade is also the front door for the wire type vocabulary a Client package names. It re-exports, type-only, the Remote failure vocabulary (`RemoteResult`, `RemoteFailure`, `RemoteErrorCode`, `RemoteErrorDetailsMap`), the Host facts (`RemoteHostFacts`), and each selected domain's client-safe payload types, so a Client feature package imports one specifier instead of reaching into `dsh-typert-protocol`, the Gateway, or an owner's Host entry. Two kinds of package deliberately skip this door: the API-layer packages this assembly itself selects — importing it back would close a dependency cycle — and their tests, which take the failure vocabulary from `dsh-typert-protocol` directly. A UI package's tests instead take the `RemoteError` constructor from [`dsh-client-test-runtime`](../../test-support/client-runtime/README.md). diff --git a/packages/api/remotes/README.zh.md b/packages/api/remotes/README.zh.md index b8974b0987..9739f3dc04 100644 --- a/packages/api/remotes/README.zh.md +++ b/packages/api/remotes/README.zh.md @@ -27,7 +27,7 @@ kind: "package-reference" [`@deepseek-ai/dsh-api-session-controller`](../session-controller/README.zh.md) 拥有 agent(智能体)与会话身份策略,包括供其他 namespace 使用的 Typert lookup 解析器。本包只选择并挂载生成的会话 contribution,不复制激活策略。 -Client 组合挂载 Office 转换、Commands、凭据、settings、Goal、动态 Cordis、文件与会话引用、只读 Host 插件清单、消息反馈、权限预设、会话控制器、subagents 和 Workspace 控制器 contribution。`permissionPresets` namespace 返回 current-session 控件使用的完整进程级目录。该组合卸载时,Cordis effect 的所有权机制会撤回所有贡献;`@deepseek-ai/dsh-api-gateway/client` 负责描述符校验、可追踪的 namespace 服务、直接与作用域方法、调用、流与取消。Client 入口通过 Cordis 消费共享的 `TypertClientRemote` 接口,不导入具体 Gateway;它只以 type-only 形式重新导出 Gateway Client face 的声明合并,因此消费端经由本外观取到转发事件词汇时,运行时不会多出一条通往 Gateway 实现的边。 +Client 组合挂载 Office 转换、Commands、凭据、settings、Goal、动态 Cordis、文件与会话引用、只读 Host 插件清单、插件安装出口国家、消息反馈、权限预设、会话控制器、subagents 和 Workspace 控制器 contribution。`permissionPresets` namespace 返回 current-session 控件使用的完整进程级目录。该组合卸载时,Cordis effect 的所有权机制会撤回所有贡献;`@deepseek-ai/dsh-api-gateway/client` 负责描述符校验、可追踪的 namespace 服务、直接与作用域方法、调用、流与取消。Client 入口通过 Cordis 消费共享的 `TypertClientRemote` 接口,不导入具体 Gateway;它只以 type-only 形式重新导出 Gateway Client face 的声明合并,因此消费端经由本外观取到转发事件词汇时,运行时不会多出一条通往 Gateway 实现的边。 本 facade 同时是 Client 包指称 wire 类型词汇的正门。它以 type-only 方式转出 Remote 失败词汇(`RemoteResult`、`RemoteFailure`、`RemoteErrorCode`、`RemoteErrorDetailsMap`)、Host 事实(`RemoteHostFacts`),以及各已选领域对 Client 安全的载荷类型,因此 Client 功能包只 import 一个 specifier,不必伸手进 `dsh-typert-protocol`、Gateway 或某个拥有方的 Host 入口。有两类包刻意不走这道门:本装配自己选中的 API 层包——反向 import 会形成依赖环——以及它们的测试,后者直接从 `dsh-typert-protocol` 取失败词汇。UI 包的测试则从 [`dsh-client-test-runtime`](../../test-support/client-runtime/README.zh.md) 取 `RemoteError` 构造器。 diff --git a/packages/api/remotes/package.json b/packages/api/remotes/package.json index 53ad17d4f2..5b423ce0cf 100644 --- a/packages/api/remotes/package.json +++ b/packages/api/remotes/package.json @@ -95,6 +95,7 @@ "@deepseek-ai/dsh-command-feedback": "workspace:^", "@deepseek-ai/dsh-api-terminal-controller": "workspace:^", "@deepseek-ai/dsh-plugin-manager": "workspace:^", + "@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:^", "@deepseek-ai/dsh-office-to-pdf": "workspace:^", "@deepseek-ai/dsh-api-account-controller": "workspace:^" } diff --git a/packages/api/remotes/src/client/index.ts b/packages/api/remotes/src/client/index.ts index 39f2706fe0..f299a6214a 100644 --- a/packages/api/remotes/src/client/index.ts +++ b/packages/api/remotes/src/client/index.ts @@ -10,6 +10,7 @@ import goalsRemote from '@deepseek-ai/dsh-goal/remote' import llmRemote from '@deepseek-ai/dsh-llm/remote' import dynamicRemote from '@deepseek-ai/dsh-cordis-host-runner/remote' import pluginManagerRemote from '@deepseek-ai/dsh-plugin-manager/remote' +import pluginInstallLocationRemote from '@deepseek-ai/dsh-client-ui-plugin-manager/remote' import pluginInventoryRemote from '@deepseek-ai/dsh-host-plugin-inventory/remote' import messageFeedbackRemote from '@deepseek-ai/dsh-message-feedback/remote' import permissionPresetsRemote from '@deepseek-ai/dsh-permission-presets/remote' @@ -31,6 +32,7 @@ export type { PluginInstallLogChunk, PluginInstallProgress, PluginInstallRequestId, PluginRegistries, PluginSpecInspection, ReadOnlyReason, Registry, } from '@deepseek-ai/dsh-plugin-manager/types' export type {} from '@deepseek-ai/dsh-plugin-manager/remote' +export type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/remote' export type { PluginInventorySnapshot } from '@deepseek-ai/dsh-host-plugin-inventory/types' export type {} from '@deepseek-ai/dsh-agent-preset-registry/remote' export type {} from '@deepseek-ai/dsh-commands/remote' @@ -171,7 +173,8 @@ export async function apply(ctx: Context): Promise<() => Promise> { try { for (const contribution of [ agentPresetsRemote, commandsRemote, settingsControllerRemote, accountRemote, goalsRemote, llmRemote, dynamicRemote, - pluginInventoryRemote, pluginManagerRemote, messageFeedbackRemote, sessionFeedbackRemote, fileUploadsRemote, sessionReferencesRemote, + pluginInventoryRemote, pluginManagerRemote, pluginInstallLocationRemote, messageFeedbackRemote, sessionFeedbackRemote, + fileUploadsRemote, sessionReferencesRemote, permissionPresetsRemote, subagentsRemote, sessionRemote, jobRemote, workspaceRemote, workspaceFilesRemote, terminalRemote, officeToPdfRemote, ]) { diff --git a/packages/client/ui-plugin-manager/README.i18n.yaml b/packages/client/ui-plugin-manager/README.i18n.yaml index 12964e8b98..362a93b151 100644 --- a/packages/client/ui-plugin-manager/README.i18n.yaml +++ b/packages/client/ui-plugin-manager/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-plugin-manager/README.md -README.md: a281f00df4544564a324b4e7da10a1bc59debf10 -README.zh.md: 0287090cd70f2a95c058cc14197769b6f8ad8bd8 +README.md: 0210adad01be438f8a40aaec52fb15793ee7ae74 +README.zh.md: 75def34b121fcc1775b19159222b217dab5f2765 diff --git a/packages/client/ui-plugin-manager/README.md b/packages/client/ui-plugin-manager/README.md index a281f00df4..0210adad01 100644 --- a/packages/client/ui-plugin-manager/README.md +++ b/packages/client/ui-plugin-manager/README.md @@ -31,7 +31,11 @@ Installed bundles and their plugin rows display their own title and description ### Installing a bundle -**Add plugin** takes a package name with an optional version, a Git address, a tarball, or an absolute local path; the dialog says a package name is what follows `dsh plugin add` in a README. **Install guide and examples** under the field opens a guide that shows the three common forms with an example each; **Use example** drops one into the field. **Registry** beside it names the registry the install asks first and unfolds the choice: the default registry, pnpm's own, titled with the host the machine's pnpm configuration names; each mirror the Host configured (`pluginManager.registries`), npmmirror as the mainland China mirror; and a typed http(s) address. The options float over the dialog from the control, so unfolding them never lengthens the card, and the card's content scrolls when the guide makes it taller than the viewport. The registry the Host asks first is the choice until one is remembered; the choice is then remembered in this browser (`localStorage`) and starts the next dialog, and a remembered address the Host no longer offers stays as a typed one. **Install** first asks the Host to read what the spec names (`pluginManager.inspect`) at the chosen registry: a name the list already shows, a name no registry has, a path without a package, a package without a bundle patch, or a spec pnpm would refuse comes back under the field as one sentence, with the spec kept for editing; when no registry could be reached, the sentence names every one asked. The install then starts at the registry that answered. An accepted spec opens the installing screen, which shows the package's name, one-liner, and version as the Host read them and folds pnpm's command and output behind **Show install details**. A finished install offers **Enable now**, which switches the new bundle on, closes the dialog, and scrolls the list to it; closing instead leaves it installed and off. While the Host moves on to another registry, the installing screen says which registry could not serve the package and which is asked now, and each pnpm run behind the details carries a badge naming its registry. A failed install says what went wrong in one line, as the Host attributed it — no registry could be reached, naming every one asked; the host a GitHub address or a tarball link is fetched from could not be reached, which no registry helps; the package was not found, the disk is full, the profile is not writable, pnpm blocked a build script — with pnpm's output behind the details and **Retry** at hand, and **Change registry** beside it when the Host laid the failure at the registry it asked, which returns to the spec with the registry options open; the Host has already put the profile files back. When pnpm blocked a dependency's install scripts, the failed screen lists the packages whose scripts wait for permission and offers **Allow these scripts and retry** in place of **Retry**; the Host saves the permission in the profile's `pnpm-workspace.yaml`, which a failed run leaves as pnpm wrote it, then runs pnpm again, and the installed screen names what was allowed. A successful installation does not certify that a module can activate. +On first use, an unconfigured official npm registry is replaced by the offered npmmirror mirror when the Host exit country is `CN`. The dialog preserves remembered choices, manual selections, explicit manager configuration, and custom or unknown pnpm registries. An install clicked during initial detection waits for that bounded lookup; a late result cannot overwrite a manual choice or reopen a closed dialog. + +The Host queries `https://get.geojs.io/v1/ip/country.json` on demand through its normal fetch proxy, with a 1500 ms deadline, a 4096-byte response limit, and a five-minute cache for known and unavailable results. Configure `countryEndpoint`, `countryTimeoutMs`, `countryMaxResponseBytes`, and `countryCacheTtlMs` on `ui-plugin-manager`; `countryLookupEnabled: false` disables detection. Network and parsing failures retain the existing default. The lookup returns only a country code to the Client and sends no Session content. + +**Add plugin** takes a package name with an optional version, a Git address, a tarball, or an absolute local path; the dialog says a package name is what follows `dsh plugin add` in a README. **Install guide and examples** under the field opens a guide that shows the three common forms with an example each; **Use example** drops one into the field. **Registry** beside it names the registry the install asks first and unfolds the choice: the default registry, pnpm's own, titled with the host the machine's pnpm configuration names; each mirror the Host configured (`pluginManager.registries`), npmmirror as the mainland China mirror; and a typed http(s) address. The options float over the dialog from the control, so unfolding them never lengthens the card, and the card's content scrolls when the guide makes it taller than the viewport. The initial choice follows the country recommendation above; the choice is then remembered in this browser (`localStorage`) and starts the next dialog, and a remembered address the Host no longer offers stays as a typed one. **Install** first asks the Host to read what the spec names (`pluginManager.inspect`) at the chosen registry: a name the list already shows, a name no registry has, a path without a package, a package without a bundle patch, or a spec pnpm would refuse comes back under the field as one sentence, with the spec kept for editing; when no registry could be reached, the sentence names every one asked. The install then starts at the registry that answered. An accepted spec opens the installing screen, which shows the package's name, one-liner, and version as the Host read them and folds pnpm's command and output behind **Show install details**. A finished install offers **Enable now**, which switches the new bundle on, closes the dialog, and scrolls the list to it; closing instead leaves it installed and off. While the Host moves on to another registry, the installing screen says which registry could not serve the package and which is asked now, and each pnpm run behind the details carries a badge naming its registry. A failed install says what went wrong in one line, as the Host attributed it — no registry could be reached, naming every one asked; the host a GitHub address or a tarball link is fetched from could not be reached, which no registry helps; the package was not found, the disk is full, the profile is not writable, pnpm blocked a build script — with pnpm's output behind the details and **Retry** at hand, and **Change registry** beside it when the Host laid the failure at the registry it asked, which returns to the spec with the registry options open; the Host has already put the profile files back. When pnpm blocked a dependency's install scripts, the failed screen lists the packages whose scripts wait for permission and offers **Allow these scripts and retry** in place of **Retry**; the Host saves the permission in the profile's `pnpm-workspace.yaml`, which a failed run leaves as pnpm wrote it, then runs pnpm again, and the installed screen names what was allowed. A successful installation does not certify that a module can activate. During preparation and download, **Cancel install** asks the Host to stop the run and waits for confirmation. Loading the bundle cannot be cancelled. Closing with ×, Escape, or the backdrop hides the dialog immediately and requests cancellation when possible. **View installation** reopens the same task with its output; another installation cannot start while its outcome is pending or unconfirmed. Confirmed cancellation returns to the spec and shows a toast; the manifest and lockfile are restored, while downloaded files can remain. A lost installation response triggers a request to recover the result; **Check installation status** and reconnect retry that request. If the Host has no active request, **Installation result unavailable** allows returning to editing after checking the plugin list. A cancellation sent before acceptance waits and retries automatically; a failed cancellation can be retried manually. Hidden tasks report their outcome through toasts without reopening the dialog. @@ -83,6 +87,8 @@ Package management uses the profile's dependency records: installed bundles can ### Registration +The Host entry exposes `pluginInstallLocation.country()` through the generated Remote interface, using [ip-geolocation](../../util/ip-geolocation/README.md) for transport and response validation. It shares pending lookups, expires cached readings, and aborts and awaits an outstanding lookup on unload. + The browser plugin registers the `plugins` sidebar entry and its `main` panel through `ctx.slots.inject()`, so both follow late slot declaration, locale changes and teardown. The page is global and belongs to no Session. Display text comes from package metadata and the page's dictionary. ### The store @@ -124,6 +130,8 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work +- Country detection observes the Host fetch exit. Remote Web users may be elsewhere, and pnpm-specific proxy settings can use a different route; users can always choose the registry manually. + @@ -134,7 +142,7 @@ These limits define the reach of the management view; they are current package c - **Rows show a phase, not a reason** — a failed row reads as failed without the Host's error text; the Host log has it. - **One install at a time** — the dialog runs one pnpm command; a second spec waits for the first to finish. - **No version picker** — the spec is typed as pnpm accepts it; the page neither lists registry versions nor offers upgrades. -- **The registry choice is this browser's** — it lives in `localStorage`, so another browser, the `dsh plugin` command, and the agent tool start from the Host's configured registry. +- **The registry choice is this browser's** — it lives in `localStorage`, so another browser computes its own initial recommendation; the `dsh plugin` command and the agent tool use the Host's configured registry. - **Every registry read runs pnpm** — opening the dialog, the check, and the install each ask pnpm what its own configuration names; a machine without pnpm reads it as unknown and is offered no fallback. @@ -147,4 +155,4 @@ None. -**Runtime invariant:** No companion is published. This package owns a sidebar panel over Host-owned facts. +**Runtime invariant:** No companion is published. The panel reads Host-owned facts, and the country cache stores one query result without an independently maintained projection. diff --git a/packages/client/ui-plugin-manager/README.zh.md b/packages/client/ui-plugin-manager/README.zh.md index 0287090cd7..75def34b12 100644 --- a/packages/client/ui-plugin-manager/README.zh.md +++ b/packages/client/ui-plugin-manager/README.zh.md @@ -31,7 +31,11 @@ kind: "package-reference" ### 安装一个组合包 -**添加插件**接受包名(可带版本)、Git 地址、压缩包或本地绝对路径;对话框说明包名就是 README 里 `dsh plugin add` 后面的那一段。输入框下方的**插件安装引导和示例**展开一段引导,给出三种常见形式各一个示例;**填入示例**把示例填进输入框。旁边的**安装源**写着安装首先询问的注册表,展开后可选:默认安装源,即 pnpm 自身的注册表,标题带上本机 pnpm 配置指向的主机名;Host 配置的每个镜像(`pluginManager.registries`),npmmirror 显示为中国大陆镜像源;以及手动输入的 http(s) 地址。选项从控件上浮在对话框之上,展开不会拉长卡片;引导使卡片高过视口时,卡片内容可以滚动。Host 首先询问的注册表在记住选择之前就是当前选择;之后选择记在本浏览器(`localStorage`)里,下次打开对话框从它开始,Host 不再提供的已记住地址保留为手动输入的地址。**安装**先让 Host 在所选注册表读出 spec 指向什么(`pluginManager.inspect`):列表中已有的名字、所有注册表都没有的名字、没有包的路径、没有组合包 patch 的包,或 pnpm 会拒绝的 spec,都以一句话回到输入框下方,spec 保留可继续编辑;所有注册表都连不上时,这句话列出问过的每一个。随后安装从作答的那个注册表开始。通过检查的 spec 打开安装中界面,展示 Host 读到的包名、一句话简介和版本,pnpm 的命令与输出折叠在**查看安装详情**之后。安装完成后提供**立即启用**:启用新组合包、关闭对话框并把列表滚动到它;直接关闭则让它保持已安装但关闭。Host 改问另一个注册表时,安装中界面会说明哪个源没能提供这个包、现在改问哪个,详情里每次 pnpm 运行都带一个写明所用源的标记。安装失败时按 Host 的归因用一行话说明原因——所有安装源都连不上,并列出问过的每一个;GitHub 地址或压缩包链接自身的主机连不上,换源无济于事;包不存在、磁盘已满、profile 不可写、pnpm 拦下了构建脚本——pnpm 输出在详情里,**重试**就在手边,Host 把失败归于所问注册表时还在旁边提供**更换安装源**,回到 spec 输入界面并展开安装源选项;Host 已经把 profile 文件放回原样。pnpm 拦下依赖的安装脚本时,失败界面列出等待允许的包,并以**允许这些脚本并重试**取代**重试**;Host 把授权写进 profile 的 `pnpm-workspace.yaml`(失败的运行保留 pnpm 写入的这个文件)再运行 pnpm,安装完成界面会说明允许了哪些脚本。安装成功不代表模块一定能够激活。 +首次使用时,如果未显式配置安装源、pnpm 使用官方 npm 源,且 Host 出口国家为 `CN`,对话框会默认选中列表中的 npmmirror 镜像。已记住的选择、用户手选、管理器显式配置,以及自定义或未知的 pnpm 源均保留。在初次检测期间点击安装会等待这次有时限的查询;迟到结果不会覆盖手选或重新打开已关闭的对话框。 + +Host 按需通过普通 fetch 代理查询 `https://get.geojs.io/v1/ip/country.json`,默认时限为 1500 毫秒、响应上限为 4096 字节,已知与未知结果均缓存五分钟。在 `ui-plugin-manager` 上配置 `countryEndpoint`、`countryTimeoutMs`、`countryMaxResponseBytes` 和 `countryCacheTtlMs`;`countryLookupEnabled: false` 关闭检测。网络或解析失败保留现有默认源。查询只向 Client 返回国家代码,不发送 Session 内容。 + +**添加插件**接受包名(可带版本)、Git 地址、压缩包或本地绝对路径;对话框说明包名就是 README 里 `dsh plugin add` 后面的那一段。输入框下方的**插件安装引导和示例**展开一段引导,给出三种常见形式各一个示例;**填入示例**把示例填进输入框。旁边的**安装源**写着安装首先询问的注册表,展开后可选:默认安装源,即 pnpm 自身的注册表,标题带上本机 pnpm 配置指向的主机名;Host 配置的每个镜像(`pluginManager.registries`),npmmirror 显示为中国大陆镜像源;以及手动输入的 http(s) 地址。选项从控件上浮在对话框之上,展开不会拉长卡片;引导使卡片高过视口时,卡片内容可以滚动。初始选择遵循上文的国家推荐规则;之后选择记在本浏览器(`localStorage`)里,下次打开对话框从它开始,Host 不再提供的已记住地址保留为手动输入的地址。**安装**先让 Host 在所选注册表读出 spec 指向什么(`pluginManager.inspect`):列表中已有的名字、所有注册表都没有的名字、没有包的路径、没有组合包 patch 的包,或 pnpm 会拒绝的 spec,都以一句话回到输入框下方,spec 保留可继续编辑;所有注册表都连不上时,这句话列出问过的每一个。随后安装从作答的那个注册表开始。通过检查的 spec 打开安装中界面,展示 Host 读到的包名、一句话简介和版本,pnpm 的命令与输出折叠在**查看安装详情**之后。安装完成后提供**立即启用**:启用新组合包、关闭对话框并把列表滚动到它;直接关闭则让它保持已安装但关闭。Host 改问另一个注册表时,安装中界面会说明哪个源没能提供这个包、现在改问哪个,详情里每次 pnpm 运行都带一个写明所用源的标记。安装失败时按 Host 的归因用一行话说明原因——所有安装源都连不上,并列出问过的每一个;GitHub 地址或压缩包链接自身的主机连不上,换源无济于事;包不存在、磁盘已满、profile 不可写、pnpm 拦下了构建脚本——pnpm 输出在详情里,**重试**就在手边,Host 把失败归于所问注册表时还在旁边提供**更换安装源**,回到 spec 输入界面并展开安装源选项;Host 已经把 profile 文件放回原样。pnpm 拦下依赖的安装脚本时,失败界面列出等待允许的包,并以**允许这些脚本并重试**取代**重试**;Host 把授权写进 profile 的 `pnpm-workspace.yaml`(失败的运行保留 pnpm 写入的这个文件)再运行 pnpm,安装完成界面会说明允许了哪些脚本。安装成功不代表模块一定能够激活。 准备和下载期间,**取消安装**会请求 Host 停止运行并等待确认。加载组合包的阶段不可取消。点击 ×、按 Escape 或点击遮罩会立即隐藏对话框,并在可以取消时请求取消。**查看安装任务**会重新打开同一任务并保留输出;结果待定或尚未确认时不能发起另一项安装。确认取消后回到 spec 输入界面并显示 toast;manifest 与 lockfile 已恢复,已下载文件可能保留。安装响应丢失后会请求恢复结果;**核对安装状态**和重连会重试该请求。Host 已无活动请求时,**未能获取安装结果**允许检查插件列表后返回编辑。早于接收确认的取消请求会等待并自动重试;取消失败可手动重试。隐藏的任务通过 toast 通知结果,不会重新弹出对话框。 @@ -83,6 +87,8 @@ ctx.slots.inject('plugins.detail.section', () => ctx.slots.register({ ### 注册 +Host 入口通过生成的 Remote 接口暴露 `pluginInstallLocation.country()`,使用 [ip-geolocation](../../util/ip-geolocation/README.zh.md) 处理传输和响应校验。它共享进行中的查询、让缓存按时过期,并在卸载时中止和等待未完成查询。 + 浏览器插件通过 `ctx.slots.inject()` 注册 `plugins` 侧栏入口与它的 `main` 面板,使两者跟随 slot 延迟声明、本地化变化与销毁。页面为全局页面,不属于任何 Session。显示文本来自包元信息与页面字典。 ### store @@ -124,6 +130,8 @@ ctx.slots.inject('plugins.detail.section', () => ctx.slots.register({ ## 已知限制与延期工作 +- 国家检测观察 Host fetch 的出口。远程 Web 用户可能身处其他地区,pnpm 专用代理设置也可能使用不同路径;用户始终可以手动选择安装源。 + @@ -134,7 +142,7 @@ ctx.slots.inject('plugins.detail.section', () => ctx.slots.register({ - **行只显示阶段,不显示原因**——失败的行只显示为失败,没有 Host 的错误文本;Host 日志里有。 - **一次只能安装一个**——对话框一次运行一个 pnpm 命令;第二个 spec 要等前一个完成。 - **没有版本选择器**——spec 按 pnpm 接受的写法输入;页面不列出注册表版本,也不提供升级。 -- **安装源选择只属于本浏览器**——它存在 `localStorage` 里,所以另一个浏览器、`dsh plugin` 命令和 agent 工具都从 Host 配置的注册表开始。 +- **安装源选择只属于本浏览器**——它存在 `localStorage` 里,所以另一个浏览器会独立计算初始推荐;`dsh plugin` 命令和 agent 工具使用 Host 配置的注册表。 - **每次读注册表都要运行 pnpm**——打开对话框、检查、安装各问一次 pnpm 自身配置指向哪里;没有 pnpm 的机器读作未知,不提供备选。 @@ -147,4 +155,4 @@ ctx.slots.inject('plugins.detail.section', () => ctx.slots.register({ -**运行时不变式:** 不发布伴生检查。本包只拥有一个基于 Host 事实的侧栏面板。 +**运行时不变式:** 不发布伴生检查。面板读取 Host 事实,国家缓存只保存一次查询结果,没有独立维护的投影。 diff --git a/packages/client/ui-plugin-manager/package.json b/packages/client/ui-plugin-manager/package.json index bc375c0b9f..cc68cc190b 100644 --- a/packages/client/ui-plugin-manager/package.json +++ b/packages/client/ui-plugin-manager/package.json @@ -23,7 +23,15 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./typert": { + "types": "./lib/typert.host.d.ts", + "default": "./lib/typert.host.js" + }, + "./remote": { + "types": "./lib/typert.remote-client.d.ts", + "default": "./lib/typert.remote-client.js" + } }, "dsh": { "client": { @@ -69,6 +77,17 @@ "files": [ "lib/index.js", "lib/client.js", - "lib/types/**/*.d.ts" - ] + "lib/types/**/*.d.ts", + "lib/typert.host.js", + "lib/typert.host.d.ts", + "lib/typert.remote-client.js", + "lib/typert.remote-client.d.ts" + ], + "dependencies": { + "@deepseek-ai/dsh-ip-geolocation": "workspace:^", + "@deepseek-ai/dsh-timeout": "workspace:^", + "@deepseek-ai/schemastery": "workspace:^", + "zod": "^4.4.3", + "@deepseek-ai/dsh-typert-protocol": "workspace:^" + } } diff --git a/packages/client/ui-plugin-manager/src/client/index.ts b/packages/client/ui-plugin-manager/src/client/index.ts index 7351ee4388..867d158fb7 100644 --- a/packages/client/ui-plugin-manager/src/client/index.ts +++ b/packages/client/ui-plugin-manager/src/client/index.ts @@ -49,7 +49,7 @@ export const NS = 'pluginManager' export const PANEL_ID = 'plugins' as MainPanelId /** Services required by the sidebar registration and the Remote methods; the inventory says whether the Host manages a profile. */ -export const inject = ['slots', 'locale', 'remote', 'remote.pluginManager', 'remote.pluginInventory', 'configForms'] +export const inject = ['slots', 'locale', 'remote', 'remote.pluginManager', 'remote.pluginInventory', 'remote.pluginInstallLocation', 'configForms'] /** * Contribute the Plugins entry to the sidebar with the management page it diff --git a/packages/client/ui-plugin-manager/src/client/manager-store.ts b/packages/client/ui-plugin-manager/src/client/manager-store.ts index 93ede95a02..5c176082af 100644 --- a/packages/client/ui-plugin-manager/src/client/manager-store.ts +++ b/packages/client/ui-plugin-manager/src/client/manager-store.ts @@ -24,7 +24,7 @@ import type { ReadOnlyReason, Registry, } from '@deepseek-ai/dsh-api-remotes/client' -import { REGISTRY_URL } from '@deepseek-ai/dsh-plugin-manager/registry' +import { normalizeRegistry, OFFICIAL_NPM_REGISTRY, REGISTRY_URL } from '@deepseek-ai/dsh-plugin-manager/registry' import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' import type { LocalizedText, PluginLocalizedMeta } from '@deepseek-ai/dsh-package-manifest' @@ -389,6 +389,25 @@ function reconciled(remembered: RegistryChoice | null, registries: PluginRegistr : remembered } +interface RegistryRead { + /** Last automatically assigned choice; a different object belongs to a manual selection. */ + choice: RegistryChoice + done?: Promise +} + +/** Only the shipped public mirror can replace an unconfigured official npm default. */ +function mainlandMirror(registries: PluginRegistries): string | undefined { + if (registries.registry !== null || registries.resolved === null) return undefined + let resolved: string + try { resolved = normalizeRegistry(registries.resolved) } + catch (_error) { + // An invalid pnpm registry cannot receive a public mirror recommendation. + return undefined + } + if (resolved !== OFFICIAL_NPM_REGISTRY) return undefined + return registries.fallbackRegistries.find(registry => registry === 'https://registry.npmmirror.com/') +} + /** One installation owns acceptance, response recovery, and every cancellation attempt. */ interface InstallRequest { readonly requestId: PluginInstallRequestId @@ -410,6 +429,7 @@ export class PluginManagerController { private inspectAbort: AbortController | undefined private request: InstallRequest | undefined private noticeSeq = 0 + private registryRead: RegistryRead | undefined /** The registry last used from this browser, kept across dialogs and page loads; null until one was used. */ private readonly registryMemory: SnapshotStore = createSnapshotStore(null, { persist: { name: 'dsh.plugin-manager.install-registry' }, @@ -438,6 +458,7 @@ export class PluginManagerController { /** Stop publishing and drop every late settlement. */ dispose(): void { this.disposed = true + this.registryRead = undefined this.request = undefined this.generation += 1 } @@ -460,7 +481,9 @@ export class PluginManagerController { if (install.requestId === undefined) { // A new dialog starts from the registry last used here and reads what the Host offers; a hidden install reopens as it is. this.patch({ install: { ...IDLE_INSTALL, open: true, registry: this.registryMemory.getSnapshot() ?? OFFICIAL_REGISTRY } }) - void this.readRegistries() + const read: RegistryRead = { choice: this.getSnapshot().install.registry } + this.registryRead = read + read.done = this.readRegistries(read).finally(() => { delete read.done }) } else { this.patchInstall({ open: true }) } @@ -473,6 +496,7 @@ export class PluginManagerController { return } this.abortInspect() + this.registryRead = undefined this.patch({ install: IDLE_INSTALL }) }, editInstallSpec: (text) => { @@ -543,12 +567,27 @@ export class PluginManagerController { }) } + private currentRegistryRead(read: RegistryRead): boolean { + return !this.disposed && this.registryRead === read + } + /** Read the registries the Host offers, for the dialog just opened; a refused read leaves pnpm's own and a typed one. */ - private async readRegistries(): Promise { + private async readRegistries(read: RegistryRead): Promise { const answer = await this.ctx.remote.pluginManager.registries() const install = this.getSnapshot().install - if (this.disposed || !install.open || !answer.ok) return - this.patchInstall({ registries: answer.value, registry: reconciled(this.registryMemory.getSnapshot(), answer.value) }) + if (!this.currentRegistryRead(read) || !install.open || !answer.ok) return + const remembered = this.registryMemory.getSnapshot() + const untouched = install.registry === read.choice && (install.phase === 'idle' || install.phase === 'checking') + if (untouched) read.choice = reconciled(remembered, answer.value) + this.patchInstall({ registries: answer.value, ...untouched ? { registry: read.choice } : {} }) + const mirror = mainlandMirror(answer.value) + if (!untouched || remembered !== null || mirror === undefined) return + const country = await this.ctx.remote.pluginInstallLocation.country() + const current = this.getSnapshot().install + if (!this.currentRegistryRead(read) || !current.open || (current.phase !== 'idle' && current.phase !== 'checking') + || current.registry !== read.choice || !country.ok || country.value !== 'CN') return + read.choice = { kind: 'offered', registry: mirror } + this.patchInstall({ registry: read.choice }) } /** @@ -669,8 +708,6 @@ export class PluginManagerController { this.patchInstall({ phase: 'idle', registryError: true }) return } - const registry: Registry = typed ?? (choice as Extract).registry - this.registryMemory.set(typed === undefined ? choice : { kind: 'custom', url: typed }) this.abortInspect() const controller = new AbortController() this.inspectAbort = controller @@ -678,6 +715,14 @@ export class PluginManagerController { phase: 'checking', inputError: null, subject: null, runs: [], detailsOpen: false, attempts: null, registryOpen: false, installed: null, restartRequired: false, failure: null, approvedBuilds: [], }) + const read = this.registryRead + if (read !== undefined && choice === read.choice && read.done !== undefined) { + await read.done + if (this.gone(controller.signal) || this.registryRead !== read) return + } + const selected = this.getSnapshot().install.registry + const registry: Registry = typed ?? (selected as Extract).registry + this.registryMemory.set(typed === undefined ? selected : { kind: 'custom', url: typed }) const inspected = await this.ctx.remote.pluginManager.inspect(spec, { registry }, controller.signal) if (this.gone(controller.signal)) return this.inspectAbort = undefined diff --git a/packages/client/ui-plugin-manager/src/index.ts b/packages/client/ui-plugin-manager/src/index.ts index bcfd623c2a..f1832ea2ce 100644 --- a/packages/client/ui-plugin-manager/src/index.ts +++ b/packages/client/ui-plugin-manager/src/index.ts @@ -1,4 +1,81 @@ -/** Host loader entry for the plugin-manager tab's browser implementation exported from `./client`. */ +/** Host network-country lookup for the plugin installation dialog. */ -/** Host plugin body — no host-side behavior for the plugin manager tab. */ -export function apply(): void {} +import type { Context } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' +import { lookupIpCountry } from '@deepseek-ai/dsh-ip-geolocation' +import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' +import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' + +declare module '@deepseek-ai/cordis' { + interface Context { + pluginInstallLocation: PluginInstallLocation + } +} + +/** Country lookup endpoint, request bounds, and process-local cache policy. */ +export interface Config { + /** Whether the dialog can query the Host network country. */ + countryLookupEnabled: boolean + /** HTTP(S) endpoint returning a two-letter `country` field. */ + countryEndpoint: string + /** Deadline for one lookup, including its body. */ + countryTimeoutMs: number + /** Maximum country lookup response-body bytes. */ + countryMaxResponseBytes: number + /** Lifetime of a known or unavailable country reading. */ + countryCacheTtlMs: number +} + +/** Shares a bounded Host lookup across installation dialogs; source-selection policy belongs to the Client. */ +export default class PluginInstallLocation extends TypertRemoteService { + static Config: z, Config> = z.object({ + countryLookupEnabled: z.boolean().default(true), + countryEndpoint: z.string().default('https://get.geojs.io/v1/ip/country.json'), + countryTimeoutMs: z.natural().min(1).max(MAX_TIMER_DELAY_MS).default(1500), + countryMaxResponseBytes: z.natural().min(1).default(4096), + countryCacheTtlMs: z.natural().default(300000), + }) + + private readonly lifetime = new AbortController() + private pending: Promise | undefined + private cached: { country: string | null; expiresAt: number } | undefined + + constructor(ctx: Context, private readonly config: Config) { + super(ctx, 'pluginInstallLocation') + const url = new URL(config.countryEndpoint) + if (!['http:', 'https:'].includes(url.protocol) || url.username !== '' || url.password !== '') { + throw new TypeError('countryEndpoint must be an HTTP(S) URL without credentials') + } + ctx.effect(() => async () => { + this.lifetime.abort() + await this.pending + }) + } + + /** + * Read the Host's exit country through its configured outbound fetch transport. + * Concurrent callers share one lookup; caller disconnects do not cancel other readers. + * @returns country code, or null when disabled, unavailable, or the lookup fails; both outcomes are cached. + */ + @Remote + country(): Promise { + this.lifetime.signal.throwIfAborted() + if (!this.config.countryLookupEnabled) return Promise.resolve(null) + if (this.cached !== undefined && this.cached.expiresAt > Date.now()) return Promise.resolve(this.cached.country) + this.pending ??= this.lookup(this.config.countryEndpoint).finally(() => { this.pending = undefined }) + return this.pending + } + + private async lookup(endpoint: string): Promise { + const signal = AbortSignal.any([this.lifetime.signal, AbortSignal.timeout(this.config.countryTimeoutMs)]) + let country: string | null + try { + country = await lookupIpCountry({ endpoint, signal, maxResponseBytes: this.config.countryMaxResponseBytes }) + } catch (error) { + if (!this.lifetime.signal.aborted) this.ctx.logger.debug('IP country lookup unavailable: %s', String(error)) + country = null + } + if (!this.lifetime.signal.aborted) this.cached = { country, expiresAt: Date.now() + this.config.countryCacheTtlMs } + return country + } +} diff --git a/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx b/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx index bb226c106d..c67b13b49f 100644 --- a/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx +++ b/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx @@ -11,7 +11,6 @@ import { apply, inject, NS, PANEL_ID } from '../src/client/index.ts' import { PluginManagerPage } from '../src/client/PluginManagerPage.tsx' import { PluginsPanelIcon } from '../src/client/PluginsPanelIcon.tsx' import type { PluginManagerFace } from '../src/client/manager-store.ts' -import { apply as hostApply } from '../src/index.ts' usePinnedBrowserLanguages('zh-CN') afterEach(cleanup) @@ -32,6 +31,7 @@ async function bench() { const remote = new TestRemote(ctx, { settings: { describe: vi.fn(async () => ({ ok: true as const, value: { writable: true, hasDocument: true, namespaces: [] } })) }, pluginInventory: { list }, + pluginInstallLocation: { country: vi.fn(async () => ({ ok: true as const, value: null })) }, pluginManager: { listBundles: vi.fn(() => Promise.resolve({ ok: true as const, value: [] })), listPlugins: vi.fn(() => Promise.resolve({ ok: true as const, value: [] })), @@ -53,12 +53,8 @@ function declare(slots: SlotRegistry): () => void { } describe('ui-plugin-manager browser plugin', () => { - it('keeps the host Loader entry inert', () => { - expect(hostApply).not.toThrow() - }) - it('declares only the services the page and its Remote methods use', () => { - expect(inject).toEqual(['slots', 'locale', 'remote', 'remote.pluginManager', 'remote.pluginInventory', 'configForms']) + expect(inject).toEqual(['slots', 'locale', 'remote', 'remote.pluginManager', 'remote.pluginInventory', 'remote.pluginInstallLocation', 'configForms']) }) it('registers the sidebar entry and its page, which reads the Host only once rendered and follows Host changes', async () => { diff --git a/packages/client/ui-plugin-manager/tests/location.host.spec.ts b/packages/client/ui-plugin-manager/tests/location.host.spec.ts new file mode 100644 index 0000000000..d29e4dab22 --- /dev/null +++ b/packages/client/ui-plugin-manager/tests/location.host.spec.ts @@ -0,0 +1,71 @@ +import { Context } from '@deepseek-ai/cordis' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' +import PluginInstallLocation, { type Config } from '../src/index.ts' + +afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers() }) + +async function mount(config: Partial = {}) { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await ctx.plugin(PluginInstallLocation, PluginInstallLocation.Config(config)) + return { ctx, location: ctx.pluginInstallLocation } +} + +it('shares concurrent reads, caches the answer, and refreshes an expired answer', async () => { + vi.useFakeTimers() + const first = Promise.withResolvers() + const fetch = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValueOnce(Response.json({ country: 'US' })) + vi.stubGlobal('fetch', fetch) + const { location } = await mount({ countryCacheTtlMs: 50 }) + const a = location.country() + const b = location.country() + first.resolve(Response.json({ country: 'CN' })) + expect(await a).toBe('CN') + expect(await b).toBe('CN') + expect(await location.country()).toBe('CN') + expect(fetch).toHaveBeenCalledOnce() + await vi.advanceTimersByTimeAsync(50) + expect(await location.country()).toBe('US') + expect(fetch).toHaveBeenCalledTimes(2) +}) + +it('performs no request when disabled', async () => { + const fetch = vi.fn() + vi.stubGlobal('fetch', fetch) + const { location } = await mount({ countryLookupEnabled: false }) + expect(await location.country()).toBeNull() + expect(fetch).not.toHaveBeenCalled() +}) + +it('caches failures as unknown', async () => { + const fetch = vi.fn().mockRejectedValue(new Error('offline')) + vi.stubGlobal('fetch', fetch) + const { location } = await mount() + expect(await location.country()).toBeNull() + expect(await location.country()).toBeNull() + expect(fetch).toHaveBeenCalledOnce() +}) + +it.each(['timeout', 'dispose'] as const)('settles a pending request on %s', async (cause) => { + vi.useFakeTimers() + vi.stubGlobal('fetch', vi.fn((_url: string, init: RequestInit) => new Promise((_resolve, reject) => { + init.signal?.addEventListener('abort', () => { reject(new DOMException('Aborted', 'AbortError')) }, { once: true }) + }))) + const { ctx, location } = await mount({ countryTimeoutMs: 50 }) + const result = location.country() + if (cause === 'timeout') await vi.advanceTimersByTimeAsync(50) + else await ctx.fiber.dispose() + expect(await result).toBeNull() + if (cause === 'dispose') expect(() => location.country()).toThrow() +}) + +it.each(['file:///tmp/country', 'https://user:secret@country.example/', 'invalid'])('rejects endpoint %s at load', async (countryEndpoint) => { + await expect(mount({ countryEndpoint })).rejects.toThrow() +}) + +it.each([ + { countryTimeoutMs: 0 }, { countryTimeoutMs: 2_147_483_648 }, + { countryMaxResponseBytes: 0 }, { countryCacheTtlMs: -1 }, +])('rejects invalid lookup limits %j', (config) => { + expect(() => PluginInstallLocation.Config(config)).toThrow() +}) diff --git a/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts b/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts index d7960eeb54..6acdb81a27 100644 --- a/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts +++ b/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts @@ -85,9 +85,10 @@ function bench(overrides: Partial>> = {} setPluginEnabled: vi.fn(() => Promise.resolve(ok(APPLIED))), ...overrides, } + const location = { country: overrides.country ?? vi.fn(() => Promise.resolve(ok(null))) } const ctx = { configForms: { describe: () => ({ getSnapshot: () => ({ view: { namespaces: [] } }), subscribe: () => () => {} }), get: vi.fn((id: string) => `form:${id}`) }, - remote: { pluginManager: plugins, pluginInventory: inventory }, + remote: { pluginManager: plugins, pluginInventory: inventory, pluginInstallLocation: location }, } as never const controller = new PluginManagerController(ctx) onTestFinished(() => { controller.dispose() }) @@ -98,7 +99,7 @@ function bench(overrides: Partial>> = {} await vi.waitFor(() => { expect(state().install.phase).toBe('starting') }) return state().install.requestId as PluginInstallRequestId } - return { plugins, inventory, controller, face, state, started } + return { plugins, inventory, location, controller, face, state, started } } it('hands a custom page the shared configuration form of its entry', () => { @@ -353,7 +354,7 @@ describe('PluginManagerController', () => { // Neither typing nor a second run reaches the Host while it checks. face.editInstallSpec('other') expect(state().install.spec).toBe(' dsh-new ') - expect(plugins.inspect).toHaveBeenCalledTimes(1) + await vi.waitFor(() => { expect(plugins.inspect).toHaveBeenCalledTimes(1) }) expect(plugins.inspect).toHaveBeenCalledWith('dsh-new', { registry: null }, expect.any(AbortSignal)) const requestId = await started() expect(state().install.subject).toEqual({ spec: 'dsh-new', ...INSPECTED }) @@ -436,6 +437,7 @@ describe('PluginManagerController', () => { face.openInstall() face.editInstallSpec('dsh-x') face.runInstall() + await vi.waitFor(() => { expect(plugins.inspect).toHaveBeenCalledOnce() }) const checkSignal = (plugins.inspect.mock.calls[0] as unknown[])[2] as AbortSignal face.cancelInstall() expect(checkSignal.aborted).toBe(true) @@ -1154,3 +1156,97 @@ describe('PluginManagerController', () => { expect(state().install).toMatchObject({ phase: 'idle', spec: 'dsh-new', registryOpen: true, runs: [], failure: null }) }) }) + +describe('Host country recommendation', () => { + it('selects the mainland mirror before the first inspection, even when install was clicked during lookup', async () => { + const country = deferred>>() + const { face, state, plugins, location } = bench({ country: vi.fn(() => country.promise) }) + face.openInstall() + face.editInstallSpec('dsh-new') + face.runInstall() + await vi.waitFor(() => { expect(location.country).toHaveBeenCalledOnce() }) + expect(plugins.inspect).not.toHaveBeenCalled() + country.resolve(ok('CN')) + await vi.waitFor(() => { expect(plugins.inspect).toHaveBeenCalled() }) + expect(plugins.inspect).toHaveBeenCalledWith('dsh-new', { registry: MIRROR }, expect.any(AbortSignal)) + expect(state().install.registry).toEqual({ kind: 'offered', registry: MIRROR }) + }) + + it.each(['US', 'HK', 'MO', 'TW', null])('keeps the default for country %s', async (country) => { + const { face, state, location } = bench({ country: vi.fn(() => Promise.resolve(ok(country))) }) + face.openInstall() + await vi.waitFor(() => { expect(location.country).toHaveBeenCalledOnce() }) + expect(state().install.registry).toEqual({ kind: 'offered', registry: null }) + }) + + it('keeps the default when the Host lookup is unavailable', async () => { + const { face, state, location } = bench({ country: vi.fn(() => Promise.resolve(refused('gateway/internal', 'offline'))) }) + face.openInstall() + await vi.waitFor(() => { expect(location.country).toHaveBeenCalledOnce() }) + expect(state().install.registry).toEqual({ kind: 'offered', registry: null }) + }) + + it.each([ + { registry: MIRROR, resolved: OFFICIAL, fallbackRegistries: [MIRROR] }, + { registry: null, resolved: CORP, fallbackRegistries: [MIRROR] }, + { registry: null, resolved: null, fallbackRegistries: [MIRROR] }, + { registry: null, resolved: 'invalid', fallbackRegistries: [MIRROR] }, + { registry: null, resolved: OFFICIAL, fallbackRegistries: [] }, + ])('does not query a country for an ineligible registry configuration %j', async (registries) => { + const { face, state, location } = bench({ registries: vi.fn(() => Promise.resolve(ok(registries))) }) + face.openInstall() + await vi.waitFor(() => { expect(state().install.registries).toEqual(registries) }) + expect(state().install.registry).toEqual({ kind: 'offered', registry: registries.registry }) + expect(location.country).not.toHaveBeenCalled() + }) + + it('preserves a manual choice made before the registry list arrives', async () => { + const registries = deferred>>() + const { face, state, location } = bench({ registries: vi.fn(() => registries.promise) }) + face.openInstall() + face.chooseRegistry({ kind: 'custom', url: CORP }) + registries.resolve(ok(REGISTRIES)) + await vi.waitFor(() => { expect(state().install.registries).toEqual(REGISTRIES) }) + expect(state().install.registry).toEqual({ kind: 'custom', url: CORP }) + expect(location.country).not.toHaveBeenCalled() + }) + + it('does not overwrite a manual choice or wait for country detection after that choice', async () => { + const country = deferred>>() + const { face, state, plugins, location } = bench({ country: vi.fn(() => country.promise) }) + face.openInstall() + await vi.waitFor(() => { expect(location.country).toHaveBeenCalledOnce() }) + face.chooseRegistry({ kind: 'custom', url: CORP }) + face.editInstallSpec('dsh-new') + face.runInstall() + await vi.waitFor(() => { expect(plugins.inspect).toHaveBeenCalled() }) + country.resolve(ok('CN')) + await country.promise + expect(state().install.registry).toEqual({ kind: 'custom', url: CORP }) + expect(plugins.inspect).toHaveBeenCalledWith('dsh-new', { registry: CORP }, expect.any(AbortSignal)) + }) + + it.each(['close', 'dispose'] as const)('discards a waiting install after %s', async (action) => { + const country = deferred>>() + const { face, controller, plugins, location } = bench({ country: vi.fn(() => country.promise) }) + face.openInstall() + face.editInstallSpec('dsh-new') + face.runInstall() + await vi.waitFor(() => { expect(location.country).toHaveBeenCalledOnce() }) + if (action === 'close') face.closeInstall() + else controller.dispose() + country.resolve(ok('CN')) + await country.promise + await Promise.resolve() + expect(plugins.inspect).not.toHaveBeenCalled() + }) +}) + +it('recognizes the official registry without a trailing slash and with uppercase host letters', async () => { + const { face, state } = bench({ + registries: vi.fn(async () => ok({ ...REGISTRIES, resolved: 'https://REGISTRY.NPMJS.ORG' })), + country: vi.fn(async () => ok('CN')), + }) + face.openInstall() + await vi.waitFor(() => { expect(state().install.registry).toEqual({ kind: 'offered', registry: MIRROR }) }) +}) diff --git a/packages/client/ui-plugin-manager/tsconfig.client.json b/packages/client/ui-plugin-manager/tsconfig.client.json new file mode 100644 index 0000000000..4d56e3dee7 --- /dev/null +++ b/packages/client/ui-plugin-manager/tsconfig.client.json @@ -0,0 +1,56 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo" + }, + "references": [ + { + "path": "../../util/package-manifest" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../../boot/plugin-manager" + }, + { + "path": "../../test-support/client-runtime" + }, + { + "path": "../locale/tsconfig.client.json" + }, + { + "path": "../store" + }, + { + "path": "../ui-layout" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-renderer" + }, + { + "path": "../ui-sidebar" + }, + { + "path": "../ui-slots" + }, + { + "path": "../../util/crypto" + }, + { + "path": "../ui-settings/tsconfig.client.json" + } + ], + "include": [ + "src/client", + "src/css-modules.d.ts" + ] +} diff --git a/packages/client/ui-plugin-manager/tsconfig.host.json b/packages/client/ui-plugin-manager/tsconfig.host.json new file mode 100644 index 0000000000..9ff7998305 --- /dev/null +++ b/packages/client/ui-plugin-manager/tsconfig.host.json @@ -0,0 +1,28 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo" + }, + "files": [ + "src/index.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../util/ip-geolocation" + }, + { + "path": "../../util/timeout" + }, + { + "path": "../../typert/protocol" + } + ] +} diff --git a/packages/client/ui-plugin-manager/tsconfig.json b/packages/client/ui-plugin-manager/tsconfig.json index cf549bf543..2eca820546 100644 --- a/packages/client/ui-plugin-manager/tsconfig.json +++ b/packages/client/ui-plugin-manager/tsconfig.json @@ -1,54 +1,11 @@ { - "extends": "../../../tsconfig.base.client.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "lib/types" - }, - "include": [ - "src" - ], + "files": [], "references": [ { - "path": "../../util/package-manifest" + "path": "./tsconfig.host.json" }, { - "path": "../../../vendor/cordis" - }, - { - "path": "../../api/remotes/tsconfig.client.json" - }, - { - "path": "../../boot/plugin-manager" - }, - { - "path": "../../test-support/client-runtime" - }, - { - "path": "../locale/tsconfig.client.json" - }, - { - "path": "../store" - }, - { - "path": "../ui-layout" - }, - { - "path": "../ui-primitives" - }, - { - "path": "../ui-renderer" - }, - { - "path": "../ui-sidebar" - }, - { - "path": "../ui-slots" - }, - { - "path": "../../util/crypto" - }, - { - "path": "../ui-settings/tsconfig.client.json" + "path": "./tsconfig.client.json" } ] } diff --git a/packages/client/ui-plugin-manager/tsdown.config.ts b/packages/client/ui-plugin-manager/tsdown.config.ts index ffe90a5b59..1169a7be7c 100644 --- a/packages/client/ui-plugin-manager/tsdown.config.ts +++ b/packages/client/ui-plugin-manager/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-plugin-manager', ['lib/types/index.js']) +export default clientBundle('@deepseek-ai/dsh-client-ui-plugin-manager', ['lib/types/index.js'], { hostPhase: true }) diff --git a/packages/client/ui-settings-agent-loop/tsconfig.json b/packages/client/ui-settings-agent-loop/tsconfig.json index 480c277bdf..fc1dab7fb9 100644 --- a/packages/client/ui-settings-agent-loop/tsconfig.json +++ b/packages/client/ui-settings-agent-loop/tsconfig.json @@ -27,7 +27,7 @@ "path": "../ui-renderer" }, { - "path": "../ui-plugin-manager" + "path": "../ui-plugin-manager/tsconfig.client.json" }, { "path": "../ui-settings/tsconfig.client.json" diff --git a/packages/client/ui-settings-shell/tsconfig.json b/packages/client/ui-settings-shell/tsconfig.json index 480c277bdf..fc1dab7fb9 100644 --- a/packages/client/ui-settings-shell/tsconfig.json +++ b/packages/client/ui-settings-shell/tsconfig.json @@ -27,7 +27,7 @@ "path": "../ui-renderer" }, { - "path": "../ui-plugin-manager" + "path": "../ui-plugin-manager/tsconfig.client.json" }, { "path": "../ui-settings/tsconfig.client.json" diff --git a/packages/client/ui-settings-subagent/tsconfig.json b/packages/client/ui-settings-subagent/tsconfig.json index 480c277bdf..fc1dab7fb9 100644 --- a/packages/client/ui-settings-subagent/tsconfig.json +++ b/packages/client/ui-settings-subagent/tsconfig.json @@ -27,7 +27,7 @@ "path": "../ui-renderer" }, { - "path": "../ui-plugin-manager" + "path": "../ui-plugin-manager/tsconfig.client.json" }, { "path": "../ui-settings/tsconfig.client.json" diff --git a/packages/client/ui-settings-web-search/tsconfig.json b/packages/client/ui-settings-web-search/tsconfig.json index 480c277bdf..fc1dab7fb9 100644 --- a/packages/client/ui-settings-web-search/tsconfig.json +++ b/packages/client/ui-settings-web-search/tsconfig.json @@ -27,7 +27,7 @@ "path": "../ui-renderer" }, { - "path": "../ui-plugin-manager" + "path": "../ui-plugin-manager/tsconfig.client.json" }, { "path": "../ui-settings/tsconfig.client.json" diff --git a/packages/experimental/client-ui-voice-input/tsconfig.json b/packages/experimental/client-ui-voice-input/tsconfig.json index 5278c5d429..eab610db2d 100644 --- a/packages/experimental/client-ui-voice-input/tsconfig.json +++ b/packages/experimental/client-ui-voice-input/tsconfig.json @@ -54,7 +54,7 @@ "path": "../../client/store" }, { - "path": "../../client/ui-plugin-manager" + "path": "../../client/ui-plugin-manager/tsconfig.client.json" } ] } diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 5560861b6c..4fb8ab0fb2 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1586,6 +1586,19 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, + { + key: 'pluginInstallLocation', + summary: 'Shares a bounded Host lookup across installation dialogs; source-selection policy belongs to the Client.', + description: 'Shares a bounded Host lookup across installation dialogs; source-selection policy belongs to the Client.', + methods: [ + { + signature: '@Remote country(): Promise', + description: 'Read the Host\'s exit country through its configured outbound fetch transport. Concurrent callers share one lookup; caller disconnects do not cancel other readers.', + parameters: [], + returns: 'country code, or null when disabled, unavailable, or the lookup fails; both outcomes are cached.', + }, + ], + }, { key: 'pluginManager', summary: 'Manage profile files and apply their declared reload lifecycle.', diff --git a/packages/preset/agent-preset/skills/cordis-composition-reference/references/packages.md b/packages/preset/agent-preset/skills/cordis-composition-reference/references/packages.md index 018e5ce938..b0b8a9ff41 100644 --- a/packages/preset/agent-preset/skills/cordis-composition-reference/references/packages.md +++ b/packages/preset/agent-preset/skills/cordis-composition-reference/references/packages.md @@ -82,7 +82,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo | `@deepseek-ai/dsh-client-ui-open-in-app` | no | Web "Open In..." controls: the Session-header split button opening the workspace directory in an installed application, and the document preview's default-application controls for one file | | `@deepseek-ai/dsh-client-ui-permission-presets` | no | Permission surfaces: a new-session default in General settings and a current-session /permission popup over the permissions projection | | `@deepseek-ai/dsh-client-ui-plan` | no | Plan mode controls, persistent transcript plan cards, and sidebar Markdown previews | -| `@deepseek-ai/dsh-client-ui-plugin-manager` | no | Plugin management for the dsh web client: the sidebar Plugins panel installs, enables, disables, retries, and composes installed plugin packages | +| `@deepseek-ai/dsh-client-ui-plugin-manager` | yes | Plugin management for the dsh web client: the sidebar Plugins panel installs, enables, disables, retries, and composes installed plugin packages | | `@deepseek-ai/dsh-client-ui-reference` | no | Unified Web @file and @session reference source | | `@deepseek-ai/dsh-client-ui-renderer` | no | Browser UI renderer: React slot bindings, ctx.uiRenderer, and the assembled application root | | `@deepseek-ai/dsh-client-ui-schedule` | no | Read-only active Schedule catalog in the Web Session header | diff --git a/packages/util/README.i18n.yaml b/packages/util/README.i18n.yaml index 2499f0a247..3f1f685971 100644 --- a/packages/util/README.i18n.yaml +++ b/packages/util/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/util/README.md -README.md: a51f8304e621e1c4fba79e5492c8eddc4d786a8e -README.zh.md: d2b8734543a7332b8a18fd9202c6fcf3b9736af9 +README.md: 8d4afd796abbbaf9a76e324d4dc7988e161f29d9 +README.zh.md: ba5e243da5dffbc9324a4ab0a6b3555534dfc6c2 diff --git a/packages/util/README.md b/packages/util/README.md index a51f8304e6..8d4afd796a 100644 --- a/packages/util/README.md +++ b/packages/util/README.md @@ -34,6 +34,7 @@ Each package provides one primitive; open a package page for how to use it. | [`values/`](values/README.md) | Validates, snapshots, compares, and freezes lossless JSON-compatible values | | [`home-paths/`](home-paths/README.md) | Resolves the single Harness home and joins shared user-data paths | | [`http-proxy/`](http-proxy/README.md) | Resolves one outbound proxy policy and installs it for `fetch`, SDK agents, and spawned children | +| [`ip-geolocation/`](ip-geolocation/README.md) | Queries the calling process network exit country with bounded responses | | [`launch-environment/`](launch-environment/README.md) | Frozen launch environment that remembers which layer supplied each value | | [`atomic-write/`](atomic-write/README.md) | Atomic file replacement and cross-process writer locking | | [`lazy-require/`](lazy-require/README.md) | Loads CommonJS-compatible Host dependencies on first use with caller-relative resolution | diff --git a/packages/util/README.zh.md b/packages/util/README.zh.md index d2b8734543..ba5e243da5 100644 --- a/packages/util/README.zh.md +++ b/packages/util/README.zh.md @@ -34,6 +34,7 @@ kind: "package-group" | [`values/`](values/README.zh.md) | 校验、创建快照、比较和冻结无损 JSON 兼容值 | | [`home-paths/`](home-paths/README.zh.md) | 解析统一的 Harness 主目录并拼接共享的用户数据路径 | | [`http-proxy/`](http-proxy/README.zh.md) | 解析出唯一的出站代理策略,并为 `fetch`、SDK agent(智能体)与 spawn 的子进程安装它 | +| [`ip-geolocation/`](ip-geolocation/README.zh.md) | 限制响应大小,查询调用进程网络出口对应的国家 | | [`launch-environment/`](launch-environment/README.zh.md) | 冻结的启动环境,记住每个值来自哪一层 | | [`atomic-write/`](atomic-write/README.zh.md) | 原子文件替换与跨进程写锁 | | [`lazy-require/`](lazy-require/README.zh.md) | 在首次使用时按调用方位置加载兼容 CommonJS 的 Host 依赖 | diff --git a/packages/util/ip-geolocation/README.i18n.yaml b/packages/util/ip-geolocation/README.i18n.yaml new file mode 100644 index 0000000000..f525e2f8b5 --- /dev/null +++ b/packages/util/ip-geolocation/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/util/ip-geolocation/README.md +README.md: 4413c74695c523aaf545d89a0406db6a218dafc6 +README.zh.md: 4f7cc0aa8e246c7ef0fb87e3999093de0143008c diff --git a/packages/util/ip-geolocation/README.md b/packages/util/ip-geolocation/README.md new file mode 100644 index 0000000000..4413c74695 --- /dev/null +++ b/packages/util/ip-geolocation/README.md @@ -0,0 +1,80 @@ +--- +description: "Query the calling process's network exit country with bounded HTTP responses and caller-owned cancellation." +kind: "package-library" +--- + +# @deepseek-ai/dsh-ip-geolocation + +English | [中文](README.zh.md) + +## Summary + +Query the country associated with the calling process's public network exit. `lookupIpCountry` accepts a JSON country endpoint, an abort signal, and a response-byte limit. Consumers choose their own endpoint, deadline, caching, and business rules; the library retains no IP address or lookup result. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Call `lookupIpCountry` from the process whose exit matters. The [plugin installation dialog](../../client/ui-plugin-manager/README.md) calls it on the Host, where pnpm downloads packages. This library registers no Cordis service or event. + +Supply an HTTP(S) endpoint implementing the [GeoJS country response](https://www.geojs.io/docs/v1/endpoints/country/) or compatible caller-IP lookup, a cancellation signal covering the full operation, and a positive response-byte limit. An uppercase two-letter `country` field returns that code; JSON null or HTTP 404 returns null. Other HTTP errors, malformed data, cancellation, and oversized responses reject. Additional fields, including the returned IP, are discarded. + +The request uses ordinary `fetch`, including the Host's configured [outbound proxy](../http-proxy/README.md). Redirects are rejected. Consumers own timeout and failure policy; no country is inferred from language or time zone. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +[`src/index.ts`](src/index.ts) bounds the complete streamed body before parsing JSON. It validates the country field and releases the reader after completion or failure. No runtime invariant companion is published because the library retains no independent state; transport and parser tests observe each call directly. + +
+ +----- + + +## Further Exploration + +- [Shared utilities](../README.md) — neighboring libraries. +- [Plugin installation](../../client/ui-plugin-manager/README.md) — the consuming dialog's selection policy. + +----- + + +## Model Experience + +None, as the library registers no tools, prompt sections, or Session events. + +#### KV Cache effect + +None. Country lookup results do not enter model requests. + +## Known Limitations and Deferred Work + + + +- IP geolocation estimates the network exit, which can differ from a person's location when using a proxy or VPN. +- The endpoint must return a two-letter `country` field. The library queries neither arbitrary supplied IPs nor city-level data. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/util/ip-geolocation/README.zh.md b/packages/util/ip-geolocation/README.zh.md new file mode 100644 index 0000000000..4f7cc0aa8e --- /dev/null +++ b/packages/util/ip-geolocation/README.zh.md @@ -0,0 +1,80 @@ +--- +description: "查询调用进程网络出口对应的国家,限制 HTTP 响应大小,并由调用方控制取消。" +kind: "package-library" +--- + +# @deepseek-ai/dsh-ip-geolocation + +[English](README.md) | 中文 + +## 概述 + +查询调用进程公网出口对应的国家。`lookupIpCountry` 接受返回 JSON 国家字段的接口地址、中止信号和响应字节上限。消费方自行决定接口、超时、缓存和业务规则;库不保留 IP 地址或查询结果。 + +## 目录 + +- [使用此包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步阅读](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与暂缓工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用此包 + +在需要判断网络出口的进程中调用 `lookupIpCountry`。[插件安装对话框](../../client/ui-plugin-manager/README.zh.md) 在下载插件的 pnpm 所在 Host(宿主)进程中调用它。本库不注册 Cordis 服务或事件。 + +提供实现 [GeoJS 国家响应](https://www.geojs.io/docs/v1/endpoints/country/) 或兼容调用方 IP 查询协议的 HTTP(S) 接口、覆盖完整操作的取消信号,以及正数响应字节上限。`country` 字段为大写双字母代码时返回该代码;JSON null 或 HTTP 404 返回 null。其他 HTTP 错误、无效数据、取消和超限响应均拒绝。其余字段(包括返回的 IP)被丢弃。 + +请求使用普通 `fetch`,遵循 Host 配置的[出站代理](../http-proxy/README.zh.md)。重定向被拒绝。超时和失败策略由消费方负责;库不会根据语言或时区推断国家。 + +----- + + +## 理解实现 + +
+实现细节 — 点击展开 + +[`src/index.ts`](src/index.ts) 在解析 JSON 前限制完整流式响应体的大小,校验国家字段,并在完成或失败后释放读取器。本库不保留可独立偏离的状态,因此不发布运行时不变量伴随模块;传输和解析测试直接观察每次调用。 + +
+ +----- + + +## 进一步阅读 + +- [共享工具库](../README.zh.md) — 相邻的库。 +- [插件安装](../../client/ui-plugin-manager/README.zh.md) — 消费方对话框的安装源选择策略。 + +----- + + +## 模型体验 + +无。本库不注册工具、提示词段落或 Session(会话)事件。 + +#### KV Cache 影响 + +无。国家查询结果不进入模型请求。 + +## 已知限制与暂缓工作 + + + +- IP 地理定位估计的是网络出口,使用代理或 VPN 时可能与用户所在地不同。 +- 接口必须返回双字母 `country` 字段。本库不查询任意指定 IP,也不查询城市级信息。 + + +### 开发备注 + +
+维护者工作上下文 — 点击展开 + +无。 + +
diff --git a/packages/util/ip-geolocation/package.json b/packages/util/ip-geolocation/package.json new file mode 100644 index 0000000000..665eccd746 --- /dev/null +++ b/packages/util/ip-geolocation/package.json @@ -0,0 +1,36 @@ +{ + "name": "@deepseek-ai/dsh-ip-geolocation", + "description": "Bounded lookup of the calling process network exit country through a JSON country endpoint", + "version": "0.1.6-alpha.2", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/util/ip-geolocation" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-http-proxy": "workspace:^" + } +} diff --git a/packages/util/ip-geolocation/src/index.ts b/packages/util/ip-geolocation/src/index.ts new file mode 100644 index 0000000000..27c7063fb7 --- /dev/null +++ b/packages/util/ip-geolocation/src/index.ts @@ -0,0 +1,55 @@ +/** Country lookup for the calling process's public network exit, using a JSON country field. */ + +/** Explicit transport limits and endpoint for one country lookup. */ +export interface IpGeolocationRequest { + /** HTTP(S) endpoint returning a `country` field; omitting an IP queries the caller's exit. */ + readonly endpoint: string + /** Cancels both the request and response-body reading. */ + readonly signal: AbortSignal + /** Maximum response-body bytes, including fields the caller does not consume. */ + readonly maxResponseBytes: number +} + +/** + * Query the network exit country through the process's ordinary fetch transport. + * No address, country, or result is retained by this library. + * @param request - endpoint, cancellation, and response limit supplied by the consumer. + * @returns uppercase two-letter country code, or null for an unknown country (HTTP 404 or JSON null). + * @throws on cancellation, HTTP failure, oversized body, or invalid JSON/country data. + */ +export async function lookupIpCountry(request: IpGeolocationRequest): Promise { + const response = await fetch(request.endpoint, { signal: request.signal, redirect: 'error', headers: { accept: 'application/json' } }) + if (!response.ok) { + await response.body?.cancel() + if (response.status === 404) return null + throw new Error(`IP geolocation returned HTTP ${response.status}`) + } + if (response.body === null) throw new TypeError('IP geolocation returned no JSON body') + const reader = response.body.getReader() + const chunks: Uint8Array[] = [] + let size = 0 + try { + while (true) { + const { done, value } = await reader.read() + if (done) break + size += value.byteLength + if (size > request.maxResponseBytes) throw new RangeError('IP geolocation response exceeds maxResponseBytes') + chunks.push(value) + } + } finally { + try { await reader.cancel() } + finally { reader.releaseLock() } + } + const bytes = new Uint8Array(size) + let offset = 0 + for (const chunk of chunks) { + bytes.set(chunk, offset) + offset += chunk.byteLength + } + const value: unknown = JSON.parse(new TextDecoder().decode(bytes)) + if (typeof value !== 'object' || value === null || !('country' in value) + || (value.country !== null && (typeof value.country !== 'string' || !/^[A-Z]{2}$/.test(value.country)))) { + throw new TypeError('IP geolocation must return a country code or null') + } + return value.country +} diff --git a/packages/util/ip-geolocation/tests/country.spec.ts b/packages/util/ip-geolocation/tests/country.spec.ts new file mode 100644 index 0000000000..5e6e95f9fb --- /dev/null +++ b/packages/util/ip-geolocation/tests/country.spec.ts @@ -0,0 +1,68 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { lookupIpCountry } from '../src/index.ts' + +afterEach(() => { vi.unstubAllGlobals() }) + +function lookup(maxResponseBytes = 4096, signal = new AbortController().signal) { + return lookupIpCountry({ endpoint: 'https://country.example/', signal, maxResponseBytes }) +} + +it.each(['CN', 'US', 'HK', 'MO', 'TW', null])('reads %s without returning the IP address', async (country) => { + const fetch = vi.fn().mockResolvedValue(Response.json({ country, ip: '203.0.113.1' })) + vi.stubGlobal('fetch', fetch) + expect(await lookup()).toBe(country) + expect(fetch).toHaveBeenCalledWith('https://country.example/', expect.objectContaining({ redirect: 'error' })) +}) + +it.each([{}, [], null, { country: 1 }, { country: 'China' }, { country: 'cn' }])('rejects invalid country data %j', async (body) => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(Response.json(body))) + await expect(lookup()).rejects.toThrow('country code or null') +}) + +it('rejects invalid JSON and a response without a body', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce(new Response('{')).mockResolvedValueOnce(new Response(null))) + await expect(lookup()).rejects.toThrow(SyntaxError) + await expect(lookup()).rejects.toThrow('no JSON body') +}) + +it('returns unknown for HTTP 404 and rejects other HTTP failures', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce(new Response('missing', { status: 404 })) + .mockResolvedValueOnce(new Response(null, { status: 429 }))) + expect(await lookup()).toBeNull() + await expect(lookup()).rejects.toThrow('HTTP 429') +}) + +it('bounds the complete streamed body and cancels oversized responses', async () => { + const cancel = vi.fn() + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('{"country":"CN",')) + controller.enqueue(new TextEncoder().encode('"unused":"large"}')) + }, + cancel, + })))) + await expect(lookup(20)).rejects.toThrow('maxResponseBytes') + expect(cancel).toHaveBeenCalledOnce() +}) + +it('accepts a body exactly at the byte limit, across multiple chunks', async () => { + const body = '{"country":"CN"}' + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode(body.slice(0, 8))) + controller.enqueue(new TextEncoder().encode(body.slice(8))) + controller.close() + }, + })))) + expect(await lookup(body.length)).toBe('CN') +}) + +it('passes cancellation to the transport', async () => { + const control = new AbortController() + const failure = new Error('cancelled') + control.abort(failure) + const fetch = vi.fn(() => Promise.reject(failure)) + vi.stubGlobal('fetch', fetch) + await expect(lookup(4096, control.signal)).rejects.toBe(failure) + expect(fetch).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ signal: control.signal })) +}) diff --git a/packages/util/ip-geolocation/tests/egress.spec.ts b/packages/util/ip-geolocation/tests/egress.spec.ts new file mode 100644 index 0000000000..45ca9fc012 --- /dev/null +++ b/packages/util/ip-geolocation/tests/egress.spec.ts @@ -0,0 +1,34 @@ +import { createServer } from 'node:http' +import { expect, it } from 'vitest' +import { installProxyFromEnvironment } from '@deepseek-ai/dsh-http-proxy' +import { lookupIpCountry } from '../src/index.ts' + +it('uses the configured Host proxy for the country request', async () => { + const seen: string[] = [] + const proxy = createServer((request, response) => { + seen.push(request.url ?? '') + response.writeHead(200, { 'content-type': 'application/json' }) + response.end('{"country":"CN","ip":"203.0.113.1"}') + }) + await new Promise((resolve) => { proxy.listen(0, '127.0.0.1', resolve) }) + try { + const address = proxy.address() + if (address === null || typeof address === 'string') throw new Error('Expected a TCP listener') + const dispose = await installProxyFromEnvironment({ + get: name => name === 'HTTP_PROXY' ? { value: `http://127.0.0.1:${address.port}` } : undefined, + }, () => undefined) + try { + expect(await lookupIpCountry({ + endpoint: 'http://country.invalid/', maxResponseBytes: 4096, signal: AbortSignal.timeout(10000), + })).toBe('CN') + expect(seen).toEqual(['http://country.invalid/']) + } finally { + await dispose() + } + } finally { + await new Promise((resolve, reject) => { + proxy.close((error) => { if (error === undefined) resolve(); else reject(error) }) + proxy.closeAllConnections() + }) + } +}) diff --git a/packages/util/ip-geolocation/tsconfig.json b/packages/util/ip-geolocation/tsconfig.json new file mode 100644 index 0000000000..749cb0208e --- /dev/null +++ b/packages/util/ip-geolocation/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5a01769828..ba1baff851 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1137,6 +1137,9 @@ importers: '@deepseek-ai/dsh-client-file-upload': specifier: workspace:^ version: link:../../client/file-upload + '@deepseek-ai/dsh-client-ui-plugin-manager': + specifier: workspace:^ + version: link:../../client/ui-plugin-manager '@deepseek-ai/dsh-command-feedback': specifier: workspace:^ version: link:../../feedback/command-feedback @@ -4090,6 +4093,22 @@ importers: version: 18.3.1 packages/client/ui-plugin-manager: + dependencies: + '@deepseek-ai/dsh-ip-geolocation': + specifier: workspace:^ + version: link:../../util/ip-geolocation + '@deepseek-ai/dsh-timeout': + specifier: workspace:^ + version: link:../../util/timeout + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:^ + version: link:../../typert/protocol + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery + zod: + specifier: ^4.4.3 + version: 4.4.3 devDependencies: '@deepseek-ai/cordis': specifier: workspace:^ @@ -12840,6 +12859,15 @@ importers: specifier: workspace:^ version: link:../../runtime-diagnostics/invariants + packages/util/ip-geolocation: + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:^ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-http-proxy': + specifier: workspace:^ + version: link:../http-proxy + packages/util/launch-environment: devDependencies: '@deepseek-ai/cordis': diff --git a/scripts/doc-standard.spec.ts b/scripts/doc-standard.spec.ts index 6c6663f286..f22294a3a3 100644 --- a/scripts/doc-standard.spec.ts +++ b/scripts/doc-standard.spec.ts @@ -97,6 +97,7 @@ const PACKAGE_LIBRARIES: Readonly> = { 'packages/util/native-command': 'Host-side subprocess runner utility.', 'packages/util/output-retention': 'Zero-dependency retention utility.', 'packages/util/package-manifest': 'Shared package manifest declarations with type-only exports.', + 'packages/util/ip-geolocation': 'Country lookup library with caller-owned endpoint, cancellation, and result policy.', 'packages/util/time': 'Zero-dependency time-zone canonicalization utility.', 'packages/util/timeout': 'Zero-dependency timeout utility.', 'packages/util/values': 'Stateless lossless-JSON and immutable-value helpers.', diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 2a7914015c..463a179c54 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -59,6 +59,7 @@ export const SERVICE_PAGE: Record = { productTelemetry: 'product-telemetry.md', connection: 'web-server.md', pluginManager: 'boot.md', + pluginInstallLocation: 'boot.md', configEditor: 'boot.md', profileContext: 'boot.md', hmr: 'boot.md', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index ebc7dcd277..a9dafbd2e5 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -107,6 +107,14 @@ const SERVICE_ROLES: ServiceRole[] = [ consumers: ['app-boot'], note: 'Owns module and exact configuration watchers; application mutations share its queue and automatic reloads await the application file lock.', }, + { + key: 'pluginInstallLocation', + pkg: 'client-ui-plugin-manager', + title: 'Host exit country for plugin installation', + mode: 'core', + consumers: ['client-ui-plugin-manager'], + note: 'Shares a bounded country lookup across dialogs; the Client owns the initial registry recommendation.', + }, { key: 'pluginManager', pkg: 'plugin-manager', diff --git a/scripts/package-dependency-policy.ts b/scripts/package-dependency-policy.ts index 57903b0e03..ef05bd5c40 100644 --- a/scripts/package-dependency-policy.ts +++ b/scripts/package-dependency-policy.ts @@ -32,6 +32,7 @@ const CONFIGURATION_ONLY_DEV_DEPENDENCIES = { /** Workspace packages whose complete runtime surface is safe across duplicate installations. */ const DUPLICATE_SAFE_PACKAGES: readonly string[] = [ '@deepseek-ai/dsh-brand', + '@deepseek-ai/dsh-ip-geolocation', '@deepseek-ai/dsh-lazy-require', '@deepseek-ai/dsh-typert-protocol', '@deepseek-ai/dsh-util-crypto', diff --git a/scripts/verify-package-dependencies.spec.ts b/scripts/verify-package-dependencies.spec.ts index 2c4c147dd7..b9b0274711 100644 --- a/scripts/verify-package-dependencies.spec.ts +++ b/scripts/verify-package-dependencies.spec.ts @@ -204,6 +204,7 @@ describe('package dependency scope', () => { }) expect(PACKAGE_DEPENDENCY_POLICY.duplicateSafePackages).toEqual([ '@deepseek-ai/dsh-brand', + '@deepseek-ai/dsh-ip-geolocation', '@deepseek-ai/dsh-lazy-require', '@deepseek-ai/dsh-typert-protocol', '@deepseek-ai/dsh-util-crypto', diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index d29c12317c..1315a83e98 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -145,6 +145,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/client/ui-settings': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' }, 'packages/client/ui-settings-general': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' }, 'packages/client/ui-settings-models': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' }, + 'packages/util/ip-geolocation': { kind: 'none', reason: 'Country lookup library; consumers own product behavior and no result enters model context.' }, 'packages/client/ui-plugin-manager': { kind: 'none', reason: 'Browser-side management surface; registers nothing model-facing.' }, 'packages/client/ui-settings-plugin-inventory': { kind: 'none', reason: 'Browser-side inventory projection; registers nothing model-facing.' }, 'packages/client/locale': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index f06c555ebf..175283c636 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -384,6 +384,7 @@ "@deepseek-ai/dsh-hooks-claude-code": ["./packages/hooks/hooks-claude-code/src"], "@deepseek-ai/dsh-hooks-codex": ["./packages/hooks/hooks-codex/src"], "@deepseek-ai/dsh-http-proxy": ["./packages/util/http-proxy/src"], + "@deepseek-ai/dsh-ip-geolocation": ["./packages/util/ip-geolocation/src"], "@deepseek-ai/dsh-jobs": ["./packages/jobs/jobs/src"], "@deepseek-ai/dsh-jobs/invariant": ["./packages/jobs/jobs/src/invariant.ts"], "@deepseek-ai/dsh-jobs-local": ["./packages/jobs/jobs-local/src"], diff --git a/tsconfig.client.json b/tsconfig.client.json index 61da8ad729..a5a8570a51 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -121,7 +121,7 @@ { "path": "./packages/client/ui-settings/tsconfig.client.json" }, { "path": "./packages/client/ui-settings-general/tsconfig.client.json" }, { "path": "./packages/client/ui-settings-models" }, - { "path": "./packages/client/ui-plugin-manager" }, + { "path": "./packages/client/ui-plugin-manager/tsconfig.client.json" }, { "path": "./packages/client/ui-settings-plugin-inventory" }, { "path": "./packages/client/locale/tsconfig.client.json" }, { "path": "./packages/client/ui-renderer" }, diff --git a/tsconfig.host.json b/tsconfig.host.json index a176af9937..6a6f5353a0 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -231,6 +231,8 @@ { "path": "./packages/util/lazy-require" }, { "path": "./packages/util/native-command" }, { "path": "./packages/util/home-paths" }, + { "path": "./packages/util/ip-geolocation" }, + { "path": "./packages/client/ui-plugin-manager/tsconfig.host.json" }, { "path": "./packages/util/time" }, { "path": "./packages/util/timeout" }, { "path": "./packages/util/crypto" }, From cfa84ed4e373a2cd8f0068c5169cffeb24e17789 Mon Sep 17 00:00:00 2001 From: winewill Date: Tue, 22 Sep 2026 12:40:07 +0800 Subject: [PATCH 02/19] fix(subprocess-local): contain spill file failures instead of killing the host OutputCollector.spillAll ran openSync/writeSync inside the stream 'data' listener with no containment. When the private per-process spill directory had been removed by a temporary-file cleaner, the first overflowing chunk threw ENOENT from Pipe.onStreamRead, became an uncaught exception in the Desktop Host, and the Electron shell reported it as a fatal failure. Spilling is best-effort by contract (spillPath is optional; a failed final close already withholds it). Every filesystem failure while opening or appending the spill file now discards the spill, reports once through the owner's logger, and leaves in-memory collection untouched. Spill inputs move into one SpillOptions object with the reporter, so tail-only collectors no longer pass an empty directory; prepareManagedProcessBinding is the explicit resolve step for the directory and reporter defaults, and the runtime and SSH helper supply their plugin loggers. Tests cover ENOENT on open (removed directory), ENOTDIR on open, and ENOSPC on append after the file exists, asserting the tail stays byte-exact, the spill file is withdrawn, and the reporter fires once. --- packages/ssh/ssh/src/helper-processes.ts | 13 +- packages/ssh/subprocess-ssh/src/index.ts | 4 +- .../subprocess-local/README.i18n.yaml | 4 +- .../subprocess/subprocess-local/README.md | 5 +- .../subprocess/subprocess-local/README.zh.md | 5 +- .../subprocess/subprocess-local/src/index.ts | 18 ++- .../subprocess/subprocess-local/src/output.ts | 126 ++++++++++++++---- .../subprocess/subprocess-local/src/spawn.ts | 16 ++- .../subprocess-local/tests/spawn.spec.ts | 86 ++++++++++-- 9 files changed, 223 insertions(+), 54 deletions(-) diff --git a/packages/ssh/ssh/src/helper-processes.ts b/packages/ssh/ssh/src/helper-processes.ts index 3b33e14c75..bdf864f2f7 100644 --- a/packages/ssh/ssh/src/helper-processes.ts +++ b/packages/ssh/ssh/src/helper-processes.ts @@ -99,6 +99,14 @@ export class RemoteProcesses { private readonly limit: number, private readonly preparationMs: number, ) {} + /** Log one spill failure; the remote caller then receives the tail without a spill path. */ + private readonly reportSpillFailure = (error: unknown, label: string): void => { + this.ctx.logger.error( + `ssh helper could not write the complete ${label} stream to its spill file; the remote result keeps only the in-memory tail and reports no full-output path.`, + error, + ) + } + /** * Allocate private stream listeners; no target executes until start(). * @param raw - untrusted process request received over SSH. @@ -217,7 +225,10 @@ export class RemoteProcesses { const mode = stdio[name] const socket = await (record.endpoints[name] as Endpoint).connected if (typeof mode === 'object') { - const collector = new OutputCollector(mode.maxBytes, mode.spill?.maxBytes, name, prepareManagedProcessBinding().spillDir) + const binding = prepareManagedProcessBinding({ onSpillFailure: this.reportSpillFailure }) + const collector = new OutputCollector(mode.maxBytes, name, mode.spill === undefined ? undefined : { + maxBytes: mode.spill.maxBytes, dir: binding.spillDir, onFailure: binding.onSpillFailure, + }) collectors[name] = collector const forwarder = new CollectedOutputForwarder(socket, collector, mode.maxBytes) forwarders.push(forwarder) diff --git a/packages/ssh/subprocess-ssh/src/index.ts b/packages/ssh/subprocess-ssh/src/index.ts index b95908c8cd..9e8476594b 100644 --- a/packages/ssh/subprocess-ssh/src/index.ts +++ b/packages/ssh/subprocess-ssh/src/index.ts @@ -52,7 +52,7 @@ class RemoteProcess implements SubprocessHandle { const collect = (name: 'stdout' | 'stderr', stream: PassThrough, mode: SubprocessOutputMode) => { if (mode === 'pipe') return undefined if (mode === 'inherit') { stream.pipe(name === 'stdout' ? process.stdout : process.stderr, { end: false }); return undefined } - let collector = new OutputCollector(mode.maxBytes, undefined, name, '') + let collector = new OutputCollector(mode.maxBytes, name, undefined) let base = 0 let total = 0 let finalized = false @@ -62,7 +62,7 @@ class RemoteProcess implements SubprocessHandle { if (finalized) return if (snapshot.totalBytes < total) throw new Error('SSH helper rewound collected output') finalized = final - collector = new OutputCollector(mode.maxBytes, undefined, name, '') + collector = new OutputCollector(mode.maxBytes, name, undefined) collector.push(bytes) base = snapshot.totalBytes - bytes.length total = snapshot.totalBytes diff --git a/packages/subprocess/subprocess-local/README.i18n.yaml b/packages/subprocess/subprocess-local/README.i18n.yaml index d4858f0dad..52a8c84a8e 100644 --- a/packages/subprocess/subprocess-local/README.i18n.yaml +++ b/packages/subprocess/subprocess-local/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subprocess/subprocess-local/README.md -README.md: 24480565de2f324a451dfdb40101eb50703b30b6 -README.zh.md: c86a7eb930834d960fa25dd7b5d175af63d0b31a +README.md: 0e5423aecd46a18cde79437ca5707be5ee58d59b +README.zh.md: 32a1b937e5768ad87d72914fb6c8a90a33c5899f diff --git a/packages/subprocess/subprocess-local/README.md b/packages/subprocess/subprocess-local/README.md index 24480565de..0e5423aecd 100644 --- a/packages/subprocess/subprocess-local/README.md +++ b/packages/subprocess/subprocess-local/README.md @@ -44,7 +44,7 @@ Windows ordinary subprocesses start the private Job runner with `windowsHide` an ### Collecting output -Collect mode keeps the last `maxBytes` of a stream in memory — errors and final results cluster at the end — and, when a `spill` cap is configured, appends the complete stream to a private file under a per-process directory in the OS temp dir (a `0700` directory, `0600` random-named files). A stream larger than the spill cap discards its incomplete spill and returns only the marked truncated tail. Reads are offset-based and non-consuming, so background and batch readers coexist before and after exit. +Collect mode keeps the last `maxBytes` of a stream in memory — errors and final results cluster at the end — and, when a `spill` cap is configured, appends the complete stream to a private file under a per-process directory in the OS temp dir (a `0700` directory, `0600` random-named files). A stream larger than the spill cap discards its incomplete spill and returns only the marked truncated tail. Spilling is best-effort: when the spill file cannot be opened or appended (the per-process directory removed by a temporary-file cleaner, `EACCES`, `EMFILE`, `ENOSPC`), the collector discards the spill, logs one `error` through the plugin logger, and keeps collecting the in-memory tail, so the result is truncated with no spill path. Reads are offset-based and non-consuming, so background and batch readers coexist before and after exit. The `./output` export shares this collector and retained-spill storage with process adapters. `snapshot()` returns the retained raw bytes and total byte count, allowing remote adapters to preserve offsets without forwarding the complete stream. @@ -109,7 +109,7 @@ A spawn synchronously validates the final argv, cwd, and environment, selects co ### Safety invariants -Spill files are opened `0600` with `O_EXCL` and random names under a `0700` per-process directory, defeating symlink planting in shared temp dirs; a failed final close withholds the spill path. Fallback process identities carry start times, so cleanup never follows PID reuse. A selected native failure is reported instead of replaying argv through fallback, and a range is removed from the live set only after cleanup completes or the failure remains observable. Host-exit finalization creates no promises or timers, preserves the host exit code and diagnostic, contains each target's failure, and does not claim quiescence. +Spill files are opened `0600` with `O_EXCL` and random names under a `0700` per-process directory, defeating symlink planting in shared temp dirs; a failed open, append, or final close withholds the spill path and never interrupts collection, because collection runs inside the stream's `'data'` listener where a thrown error would kill the host process. Fallback process identities carry start times, so cleanup never follows PID reuse. A selected native failure is reported instead of replaying argv through fallback, and a range is removed from the live set only after cleanup completes or the failure remains observable. Host-exit finalization creates no promises or timers, preserves the host exit code and diagnostic, contains each target's failure, and does not claim quiescence. @@ -155,6 +155,7 @@ These limits define when the provider is a poor fit or needs special operational - **In-process cleanup requires a JavaScript-observable exit** — direct `process.exit()`, default uncaught exceptions, and default unhandled rejections emit Node's synchronous `exit` event. The default OS disposition for an unhandled `SIGTERM`, `SIGINT`, or `SIGHUP` bypasses that event; an application covers those signals only by installing a handler that performs normal disposal or calls `process.exit()`. `SIGKILL`, fatal OOM, `process.abort()`, native crashes, power loss, and any failure that cannot run JavaScript require an external supervisor, container init, or equivalent OS owner. - **The credential scrub is a name heuristic** — `*KEY*`/`*PASSWORD*`/`*SECRET*`/`*TOKEN*` only; differently named secrets (for example `*PASSPHRASE*`) pass through, and a whitelist for over-scrubbed variables is noted future work. - **Completed spill files are not deleted** — bounded full-output recovery files accumulate under the OS tmpdir until something external cleans them; the private per-process spill directory is removed at a JavaScript-observable exit only when it holds no completed spill file. +- **A removed spill directory is not recreated** — the private per-process directory is created once; after an external cleaner removes it, every later spill in that process degrades to the in-memory tail with an `error` log until the host restarts. Recreating a fresh random directory on `ENOENT` is deferred work. ### Dev Note diff --git a/packages/subprocess/subprocess-local/README.zh.md b/packages/subprocess/subprocess-local/README.zh.md index c86a7eb930..32a1b937e5 100644 --- a/packages/subprocess/subprocess-local/README.zh.md +++ b/packages/subprocess/subprocess-local/README.zh.md @@ -44,7 +44,7 @@ Windows 普通子进程通过 `windowsHide` 启动私有 Job runner,并为原 ### 收集输出 -收集模式在内存中保留一条流的最后 `maxBytes`——错误与最终结果通常聚集在末尾——并在配置了 `spill` 上限时把完整流追加到 OS 临时目录下每进程目录中的私有文件(`0700` 目录、`0600` 随机命名文件)。某条流大于 spill 上限时,会丢弃不完整的 spill,只返回带截断标记的尾部。读取基于偏移量且从不消费,因此后台读取与批量读取在退出前后都可以共存。 +收集模式在内存中保留一条流的最后 `maxBytes`——错误与最终结果通常聚集在末尾——并在配置了 `spill` 上限时把完整流追加到 OS 临时目录下每进程目录中的私有文件(`0700` 目录、`0600` 随机命名文件)。某条流大于 spill 上限时,会丢弃不完整的 spill,只返回带截断标记的尾部。spill 是尽力而为:当 spill 文件无法打开或追加(每进程目录被临时文件清理工具删除、`EACCES`、`EMFILE`、`ENOSPC`)时,收集器丢弃该 spill,通过插件 logger 记录一条 `error`,并继续收集内存尾部,因此结果带截断标记且没有 spill 路径。读取基于偏移量且从不消费,因此后台读取与批量读取在退出前后都可以共存。 `./output` 导出向进程适配器共享该收集器与保留 spill 的存储。`snapshot()` 返回保留的原始字节及总字节数,使远程适配器能够保留偏移量,而无需转发完整的流。 @@ -109,7 +109,7 @@ Linux 普通进程和终端进程即使在 bootstrap 消费启动请求前被取 ### 安全不变式 -spill 文件以 `0600` 权限、`O_EXCL` 与随机名称在 `0700` 每进程目录下创建,可抵御共享临时目录中的符号链接植入;最终关闭失败时不公布 spill 路径。fallback 进程身份携带启动时间,因此清理绝不会跟随 PID 复用。选定的 native 路径失败时会报告错误,而不会通过 fallback 重放 argv;受管范围只有在清理完成后才从存活集合移除,否则失败仍保持可观察。宿主退出最终清理不创建 Promise 或定时器,保留宿主退出码与诊断,分别包含每个目标的失败,也不会声称已经完全停稳。 +spill 文件以 `0600` 权限、`O_EXCL` 与随机名称在 `0700` 每进程目录下创建,可抵御共享临时目录中的符号链接植入;打开、追加或最终关闭失败时不公布 spill 路径,且绝不中断收集,因为收集运行在流的 `'data'` 监听器内,抛出的错误会杀死宿主进程。fallback 进程身份携带启动时间,因此清理绝不会跟随 PID 复用。选定的 native 路径失败时会报告错误,而不会通过 fallback 重放 argv;受管范围只有在清理完成后才从存活集合移除,否则失败仍保持可观察。宿主退出最终清理不创建 Promise 或定时器,保留宿主退出码与诊断,分别包含每个目标的失败,也不会声称已经完全停稳。 @@ -155,6 +155,7 @@ spill 文件以 `0600` 权限、`O_EXCL` 与随机名称在 `0700` 每进程目 - **进程内清理要求退出阶段仍能执行 JavaScript**——直接 `process.exit()`、默认未捕获异常和默认未处理 rejection 会发出 Node 同步 `exit` 事件。未安装 handler 时,`SIGTERM`、`SIGINT` 或 `SIGHUP` 的默认 OS 处置不会发出该事件;应用只有安装执行正常 dispose 或调用 `process.exit()` 的 handler 才能覆盖这些信号。`SIGKILL`、fatal OOM、`process.abort()`、native crash、断电,以及任何无法运行 JavaScript 的故障,都需要外部 supervisor、容器 init 或等价的 OS owner 负责。 - **凭据清除依赖名称启发式规则**——只匹配 `*KEY*`/`*PASSWORD*`/`*SECRET*`/`*TOKEN*`;名称不同的 secret(例如 `*PASSPHRASE*`)会继续传递,对误删变量引入白名单属于已记录的后续工作。 - **不会删除已完成的 spill 文件**——有界的完整输出恢复文件会在 OS tmpdir 下累积,直到外部机制进行清理;每进程私有 spill 目录仅在未持有任何已完成 spill 文件时于 JavaScript 可观察的退出阶段删除。 +- **被删除的 spill 目录不会重建**——每进程私有目录只创建一次;被外部清理工具删除后,该进程内之后的每次 spill 都降级为内存尾部并记录一条 `error`,直到宿主重启。在 `ENOENT` 时重新创建一个新的随机目录是待办工作。 ### 开发备注 diff --git a/packages/subprocess/subprocess-local/src/index.ts b/packages/subprocess/subprocess-local/src/index.ts index ff03daebdf..c106b071b8 100644 --- a/packages/subprocess/subprocess-local/src/index.ts +++ b/packages/subprocess/subprocess-local/src/index.ts @@ -84,6 +84,19 @@ export class LocalSubprocessRuntime extends SubprocessRuntime { }, 'local subprocess teardown') } + /** + * Log one spill failure through the plugin logger. The collector keeps only + * its in-memory tail afterwards, so the model sees a truncated result with + * no spill path; the log line is the only trace of why. + */ + private readonly reportSpillFailure = (error: unknown, label: string): void => { + this.ctx.logger.error( + `subprocess-local could not write the complete ${label} stream to its spill file; the tool result keeps only the in-memory tail and reports no full-output path. ` + + 'A removed private spill directory under the OS temp dir (ENOENT) points at a temporary-file cleaner.', + error, + ) + } + private terminateForHostExit(): void { for (const handle of this.live) { try { @@ -181,10 +194,11 @@ export class LocalSubprocessRuntime extends SubprocessRuntime { const env = targetEnvironment(spec) const containmentMode = this.selectContainmentMode('ordinary') let handle: LocalSubprocessHandle + const internals: SpawnInternals = { ...this.internals, onSpillFailure: this.reportSpillFailure } if (containmentMode === 'fallback') { - handle = spawnSubprocess(spec, this.internals) + handle = spawnSubprocess(spec, internals) } else { - const binding = prepareManagedProcessBinding(this.internals) + const binding = prepareManagedProcessBinding(internals) const launch = containmentMode === 'linux-scope' ? launchLinuxScope(spec, env) : launchWindowsJob(spec, env) diff --git a/packages/subprocess/subprocess-local/src/output.ts b/packages/subprocess/subprocess-local/src/output.ts index 2cd3a1d082..f94c11480e 100644 --- a/packages/subprocess/subprocess-local/src/output.ts +++ b/packages/subprocess/subprocess-local/src/output.ts @@ -5,16 +5,38 @@ import { join } from 'node:path' import { tmpdir } from 'node:os' import type { CollectedOutput } from '@deepseek-ai/dsh-subprocess' +/** + * Receives one spill failure so the owner can log it through its own logger. + * Called at most once per collector, after the spill has been discarded and + * the in-memory tail has kept collecting. + * @param error - the `node:fs` failure from opening or appending the spill file. + * @param label - the stream label of the collector that failed. + */ +export type SpillFailureReporter = (error: unknown, label: string) => void + +/** Spill storage for one collected stream; `undefined` means tail-only collection. */ +export interface SpillOptions { + /** Whole-stream byte cap beyond which an incomplete spill is discarded. */ + maxBytes: number + /** Private directory receiving the spill file. */ + dir: string + /** Owner-side report of a spill open or write failure. */ + onFailure: SpillFailureReporter +} + let spillCounter = 0 let defaultSpillDir: string | undefined /** * The default spill location: a private (0700) per-process directory under * the OS tmpdir, created lazily. Predictable world-readable paths would let - * other local users read command output or pre-create symlinks. At a - * JavaScript-observable process exit the directory is removed only when it - * holds no completed spill file (spill files are retained as full-output - * recovery artifacts until an external cleanup). + * other local users read command output or pre-create symlinks. The directory + * is created once per process and never recreated: when an external + * temporary-file cleaner removes it while empty, the next spill open fails and + * the collector degrades to its in-memory tail. At a JavaScript-observable + * process exit the directory is removed only when it holds no completed spill + * file (spill files are retained as full-output recovery artifacts until an + * external cleanup). */ function privateSpillDir(): string { defaultSpillDir ??= mkdtempSync(join(tmpdir(), 'dsh-subprocess-')) @@ -32,25 +54,55 @@ process.once('exit', () => { try { rmdirSync(defaultSpillDir) } catch { /* best-effort: ENOENT/ENOTEMPTY/EBUSY/EPERM must not change the exit code. */ } }) +/** + * The stderr reporter used when no owner supplies one: a bare + * {@link prepareManagedProcessBinding} caller has no plugin logger, and the + * failure must still reach the process diagnostics. + * @param error - the spill failure. + * @param label - the failed stream label. + */ +function reportSpillFailureToStderr(error: unknown, label: string): void { + process.stderr.write(`dsh-subprocess-local: ${label} spill failed; only the in-memory tail is retained: ${String(error)}\n`) +} + +/** Inputs a managed native process needs before its output streams are bound. */ +export interface ManagedProcessBinding { + /** Directory receiving spill files. */ + spillDir: string + /** Receives a spill open or write failure. */ + onSpillFailure: SpillFailureReporter +} + /** * Prepare fallible output storage before starting a managed native process. - * @param internals - optional caller-owned spill directory. + * This is the explicit resolve step for spill inputs: the spill directory + * defaults to the private per-process directory, and the failure reporter + * defaults to a stderr line when the caller has no logger. + * @param internals - optional caller-owned spill directory and failure reporter. * @returns binding inputs whose spill directory is ready for use. */ export function prepareManagedProcessBinding( - internals: { spillDir?: string } = {}, -): { spillDir: string } { - return { spillDir: internals.spillDir ?? privateSpillDir() } + internals: { spillDir?: string; onSpillFailure?: SpillFailureReporter } = {}, +): ManagedProcessBinding { + return { + spillDir: internals.spillDir ?? privateSpillDir(), + onSpillFailure: internals.onSpillFailure ?? reportSpillFailureToStderr, + } } /** - * Collects one stream with a bounded in-memory tail. With a spill cap, on + * Collects one stream with a bounded in-memory tail. With spill options, on * first overflow a spill file is created and every chunk (including those * already collected) is appended there while the full stream remains within - * the cap; without one, only the in-memory tail is ever retained (the + * the cap; without them, only the in-memory tail is ever retained (the * diagnostic-tail shape — a language server's stderr). * + * Spilling is best-effort: a spill open or write failure discards the spill, + * reports once through {@link SpillOptions.onFailure}, and never interrupts + * in-memory collection, because `push()` runs inside the stream's `'data'` + * listener where a thrown error would become an uncaught exception. + * * Tail-keep rationale (pi/OpenCode): errors and final results cluster at the * end of command output; the spill file covers the head. */ @@ -64,13 +116,17 @@ export class OutputCollector { /** Total bytes ever pushed (not just retained). */ private total = 0 + /** + * @param maxBytes - in-memory tail cap in bytes. + * @param label - stream label used in spill file names and failure reports. + * @param spill - spill storage; omit for tail-only collection. + */ constructor( private readonly maxBytes: number, - private readonly maxSpillBytes: number | undefined, private readonly label: string, - private readonly spillDir: string, + private readonly spill: SpillOptions | undefined, ) { - this.spillDisabled = maxSpillBytes === undefined + this.spillDisabled = spill === undefined } /** @@ -84,7 +140,8 @@ export class OutputCollector { push(chunk: Buffer): void { this.total += chunk.length const overflows = this.bytes + chunk.length > this.maxBytes - if (!this.spillDisabled && (overflows || this.spillFd !== undefined)) this.spillAll(chunk) + const spill = this.spill + if (spill !== undefined && !this.spillDisabled && (overflows || this.spillFd !== undefined)) this.spillAll(spill, chunk) this.chunks.push(chunk) this.bytes += chunk.length while (this.bytes > this.maxBytes) { @@ -105,24 +162,37 @@ export class OutputCollector { } } - /** Open the spill file lazily and append `chunk` (and any prior chunks once). */ - private spillAll(chunk: Buffer): void { - if (this.maxSpillBytes !== undefined && this.total > this.maxSpillBytes) { + /** + * Open the spill file lazily and append `chunk` (and any prior chunks once). + * Runs inside the stream's `'data'` listener, so every filesystem failure is + * contained here: the spill is discarded, reported once, and collection + * continues with the in-memory tail alone. + */ + private spillAll(spill: SpillOptions, chunk: Buffer): void { + if (this.total > spill.maxBytes) { this.discardSpill() return } - if (this.spillFd === undefined) { - // Random suffix + O_EXCL + no-follow-equivalent ('wx' fails on any - // existing path, symlink or not) + owner-only mode: defeats spill-path - // prediction and symlink planting in shared tmp dirs. - this.spillFile = join( - this.spillDir, - `dsh-subprocess-${process.pid}-${++spillCounter}-${randomBytes(6).toString('hex')}-${this.label}.log`, - ) - this.spillFd = openSync(this.spillFile, 'wx', 0o600) - for (const prior of this.chunks) writeSync(this.spillFd, prior) + try { + if (this.spillFd === undefined) { + // Random suffix + O_EXCL + no-follow-equivalent ('wx' fails on any + // existing path, symlink or not) + owner-only mode: defeats spill-path + // prediction and symlink planting in shared tmp dirs. + this.spillFile = join( + spill.dir, + `dsh-subprocess-${process.pid}-${++spillCounter}-${randomBytes(6).toString('hex')}-${this.label}.log`, + ) + this.spillFd = openSync(this.spillFile, 'wx', 0o600) + for (const prior of this.chunks) writeSync(this.spillFd, prior) + } + writeSync(this.spillFd, chunk) + } catch (error) { + // ENOENT (spill directory removed by a temp cleaner), EACCES/EPERM, + // EMFILE, or ENOSPC: the spill file is a recovery aid, not a + // precondition of collection. + this.discardSpill() + spill.onFailure(error, this.label) } - writeSync(this.spillFd, chunk) } /** Stop spilling and remove the file once it can no longer hold the complete stream. */ diff --git a/packages/subprocess/subprocess-local/src/spawn.ts b/packages/subprocess/subprocess-local/src/spawn.ts index 9862a0d0dd..ed9baa2020 100644 --- a/packages/subprocess/subprocess-local/src/spawn.ts +++ b/packages/subprocess/subprocess-local/src/spawn.ts @@ -25,7 +25,7 @@ import { waitWithAbort } from './managed-owner.ts' import { controlEnvironment, controlPipe } from './control-spawn.ts' import { SUBPROCESS_CONTROL_FD } from '@deepseek-ai/dsh-subprocess/control' import { linuxProcessGroupHasLiveMembers } from './process-inspector.ts' -import { OutputCollector, prepareManagedProcessBinding } from './output.ts' +import { OutputCollector, prepareManagedProcessBinding, type SpillFailureReporter } from './output.ts' type SpawnProcess = ( program: string, @@ -59,6 +59,8 @@ export interface SpawnInternals { spawn?: SpawnProcess /** Directory for spill files (defaults to the OS temp dir). */ spillDir?: string + /** Receives spill open/write failures; the runtime supplies its plugin logger, bare callers get a stderr line. */ + onSpillFailure?: SpillFailureReporter /** Windows tree-termination runner (defaults to `taskkill /PID /T /F`). */ taskkill?: (pid: number) => void /** Host platform override for signalling decisions. */ @@ -259,15 +261,15 @@ function fallbackOwner( * Bind platform launch facts to the existing stdio, outcome, abort, and termination lifecycle. * @param spec - fully resolved argv, cwd, stdio, grace, cancellation, environment. * @param launch - platform streams, direct outcome, and managed-range owner. - * @param internals - test-only spill-directory override. + * @param internals - spill-directory override and spill failure reporter. * @returns live subprocess handle. */ export function bindManagedProcess( spec: SubprocessSpawnSpec, launch: ManagedProcessLaunch, - internals: Pick = {}, + internals: Pick = {}, ): LocalSubprocessHandle { - const { spillDir } = prepareManagedProcessBinding(internals) + const { spillDir, onSpillFailure } = prepareManagedProcessBinding(internals) const { stdin, stdout, stderr } = launch const isCollect = (mode: SubprocessOutputMode): mode is SubprocessCollect => @@ -278,7 +280,11 @@ export function bindManagedProcess( const collectStream = (mode: SubprocessOutputMode, stream: Readable | null, label: string): OutputCollector | undefined => { if (!isCollect(mode) || stream === null) return undefined - const collector = new OutputCollector(mode.maxBytes, mode.spill?.maxBytes, label, spillDir) + const collector = new OutputCollector( + mode.maxBytes, + label, + mode.spill === undefined ? undefined : { maxBytes: mode.spill.maxBytes, dir: spillDir, onFailure: onSpillFailure }, + ) stream.on('data', (chunk: Buffer) => { collector.push(chunk) }) return collector } diff --git a/packages/subprocess/subprocess-local/tests/spawn.spec.ts b/packages/subprocess/subprocess-local/tests/spawn.spec.ts index d57e66a6cd..22c77f5d52 100644 --- a/packages/subprocess/subprocess-local/tests/spawn.spec.ts +++ b/packages/subprocess/subprocess-local/tests/spawn.spec.ts @@ -1,6 +1,6 @@ -import { OutputCollector } from '../src/output.ts' +import { OutputCollector, type SpillOptions } from '../src/output.ts' import { spawn as nodeSpawn, spawnSync as nodeSpawnSync } from 'node:child_process' -import { mkdtempSync, readFileSync, rmSync, statSync, unlinkSync } from 'node:fs' +import { mkdtempSync, readFileSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { afterAll, describe, expect, it, vi } from 'vitest' @@ -64,9 +64,10 @@ function shellArgv(command: string): string[] { } } -const { failNextClose, failNextUnlink } = vi.hoisted(() => ({ +const { failNextClose, failNextUnlink, failNextWrite } = vi.hoisted(() => ({ failNextClose: { value: false }, failNextUnlink: { value: false }, + failNextWrite: { value: false }, })) vi.mock('node:fs', async (importOriginal) => { const actual = await importOriginal() @@ -86,11 +87,24 @@ vi.mock('node:fs', async (importOriginal) => { } actual.unlinkSync(path) }, + writeSync(...args: Parameters): number { + if (failNextWrite.value) { + failNextWrite.value = false + throw Object.assign(new Error('simulated ENOSPC on write'), { code: 'ENOSPC' }) + } + return actual.writeSync(...args) + }, } }) const spillDir = mkdtempSync(join(tmpdir(), 'dsh-subprocess-spec-')) +/** Spill options for one collector test; failures are collected for assertions. */ +function spillOptions(maxBytes: number, dir = spillDir): { options: SpillOptions; failures: { error: unknown; label: string }[] } { + const failures: { error: unknown; label: string }[] = [] + return { options: { maxBytes, dir, onFailure: (error, label) => { failures.push({ error, label }) } }, failures } +} + /** The per-process default spill dir captured by the default-spill test. */ let defaultSpillDir: string | undefined @@ -516,7 +530,7 @@ describe('output truncation and spill', () => { describe('OutputCollector', () => { it('keeps the tail of a single oversized chunk', () => { - const collector = new OutputCollector(10, 100, 'test', spillDir) + const collector = new OutputCollector(10, 'test', spillOptions(100).options) collector.push(Buffer.from('0123456789abcdef')) const out = collector.finalize() expect(out.text).toBe('6789abcdef') @@ -527,7 +541,7 @@ describe('OutputCollector', () => { it('retains a byte-exact tail across uneven chunk boundaries', () => { // A diagnostic tail must be exactly the LAST maxBytes regardless of // chunking; dropping only whole chunks would under-retain. - const collector = new OutputCollector(10, undefined, 'exact-tail', spillDir) + const collector = new OutputCollector(10, 'exact-tail', undefined) collector.push(Buffer.from('aaaa')) collector.push(Buffer.from('bbbbbb')) collector.push(Buffer.from('cc')) @@ -538,7 +552,7 @@ describe('OutputCollector', () => { }) it('readFrom returns increments and flags lossy reads', () => { - const collector = new OutputCollector(10, 100, 'test', spillDir) + const collector = new OutputCollector(10, 'test', spillOptions(100).options) collector.push(Buffer.from('aaaaa')) const first = collector.readFrom(0) expect(first.text).toBe('aaaaa') @@ -559,7 +573,7 @@ describe('OutputCollector', () => { }) it('contains close failures and drops the spill path', () => { - const collector = new OutputCollector(4, 100, 'closefail', spillDir) + const collector = new OutputCollector(4, 'closefail', spillOptions(100).options) collector.push(Buffer.from('aaaa')) collector.push(Buffer.from('bbbb')) expect(collector.readFrom(0).spillPath).toBeDefined() @@ -575,7 +589,7 @@ describe('OutputCollector', () => { }) it('discards a spill that exceeds its configured cap', () => { - const collector = new OutputCollector(4, 8, 'bounded', spillDir) + const collector = new OutputCollector(4, 'bounded', spillOptions(8).options) collector.push(Buffer.from('aaaa')) collector.push(Buffer.from('bbbb')) const spillPath = collector.readFrom(0).spillPath! @@ -591,7 +605,7 @@ describe('OutputCollector', () => { }) it('does not create a spill when the first overflowing chunk exceeds the cap', () => { - const collector = new OutputCollector(4, 4, 'no-spill', spillDir) + const collector = new OutputCollector(4, 'no-spill', spillOptions(4).options) collector.push(Buffer.from('abcdefgh')) const out = collector.finalize() expect(out.text).toBe('efgh') @@ -600,7 +614,7 @@ describe('OutputCollector', () => { }) it('contains cleanup failures while disabling an oversize spill', () => { - const collector = new OutputCollector(4, 8, 'cleanup-fail', spillDir) + const collector = new OutputCollector(4, 'cleanup-fail', spillOptions(8).options) collector.push(Buffer.from('aaaa')) collector.push(Buffer.from('bbbb')) const spillPath = collector.readFrom(0).spillPath! @@ -613,6 +627,58 @@ describe('OutputCollector', () => { expect(collector.finalize().spillPath).toBeUndefined() unlinkSync(spillPath) }) + + it('keeps collecting when the spill directory has been removed (ENOENT on open)', () => { + const removedDir = mkdtempSync(join(tmpdir(), 'dsh-subprocess-removed-')) + rmSync(removedDir, { recursive: true, force: true }) + const { options, failures } = spillOptions(100, removedDir) + const collector = new OutputCollector(4, 'enoent', options) + collector.push(Buffer.from('aaaa')) + expect(() => { collector.push(Buffer.from('bbbb')) }).not.toThrow() + collector.push(Buffer.from('cc')) + expect(failures).toHaveLength(1) + expect((failures[0]!.error as NodeJS.ErrnoException).code).toBe('ENOENT') + expect(failures[0]!.label).toBe('enoent') + const out = collector.finalize() + expect(out.text).toBe('bbcc') + expect(out.truncated).toBe(true) + expect(out.spillPath).toBeUndefined() + }) + + it('keeps collecting when the spill directory is a file (ENOTDIR on open)', () => { + const fileAsDir = join(spillDir, `not-a-dir-${Date.now()}`) + writeFileSync(fileAsDir, '') + const { options, failures } = spillOptions(100, fileAsDir) + const collector = new OutputCollector(4, 'enotdir', options) + collector.push(Buffer.from('aaaa')) + expect(() => { collector.push(Buffer.from('bbbb')) }).not.toThrow() + expect(failures).toHaveLength(1) + expect(['ENOTDIR', 'ENOENT']).toContain((failures[0]!.error as NodeJS.ErrnoException).code) + expect(collector.finalize()).toEqual({ text: 'bbbb', truncated: true }) + }) + + it('withdraws a spill whose append fails after the file exists (ENOSPC on write)', () => { + const { options, failures } = spillOptions(100) + const collector = new OutputCollector(4, 'enospc', options) + collector.push(Buffer.from('aaaa')) + collector.push(Buffer.from('bbbb')) + const spillPath = collector.readFrom(0).spillPath! + expect(readFileSync(spillPath, 'utf8')).toBe('aaaabbbb') + + failNextWrite.value = true + expect(() => { collector.push(Buffer.from('cccc')) }).not.toThrow() + expect(failNextWrite.value).toBe(false) + expect(failures).toHaveLength(1) + expect((failures[0]!.error as NodeJS.ErrnoException).code).toBe('ENOSPC') + expect(() => readFileSync(spillPath)).toThrow() + + collector.push(Buffer.from('dd')) + expect(failures).toHaveLength(1) + const out = collector.finalize() + expect(out.text).toBe('ccdd') + expect(out.truncated).toBe(true) + expect(out.spillPath).toBeUndefined() + }) }) describe('killGroup', () => { From 9f9a50e5536fc5aff8f82414c5a8faa66ad8fcc0 Mon Sep 17 00:00:00 2001 From: winewill Date: Tue, 22 Sep 2026 12:46:37 +0800 Subject: [PATCH 03/19] feat(app-boot): treat uncaught exceptions as fatal through installFailLoud The Desktop Host and every other profile launcher installed a fail-loud handler for unhandled rejections only. A synchronous throw from a stream 'data' listener fell through to Node's default uncaught-exception path: it printed and exited without the surface's release hook, and the label and format differed from every other fatal diagnostic. installFailLoud now registers the same report for 'uncaughtException' with the label `fatal uncaught exception`, shares the exit latch and release timeout with rejections, and never resumes the process. The diagnostic is util.inspect(err, { depth: 4 }) instead of err.stack so enumerable properties (a node:fs error's code, syscall, and path) and the cause chain reach stderr; the `fatal load failure` label for rejections is unchanged because the Web profile expected-output e2e tests match it. --- packages/boot/app-boot/README.i18n.yaml | 4 +- packages/boot/app-boot/README.md | 3 +- packages/boot/app-boot/README.zh.md | 3 +- packages/boot/app-boot/src/index.ts | 52 +++++++---- packages/boot/app-boot/tests/app-boot.spec.ts | 90 ++++++++++++++----- 5 files changed, 113 insertions(+), 39 deletions(-) diff --git a/packages/boot/app-boot/README.i18n.yaml b/packages/boot/app-boot/README.i18n.yaml index f4eaa088e5..919238a1d4 100644 --- a/packages/boot/app-boot/README.i18n.yaml +++ b/packages/boot/app-boot/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/boot/app-boot/README.md -README.md: 5bbe75d641eeeaf3b87c31221b3491ad1408934e -README.zh.md: b3ac89c1cb082880622175b494d540888b19e804 +README.md: 1409ade8f6e29a629d540915212a08cf8dd47a09 +README.zh.md: 0d98af8133771d634bbd004ed1acdd6f2cf897cc diff --git a/packages/boot/app-boot/README.md b/packages/boot/app-boot/README.md index 5bbe75d641..1409ade8f6 100644 --- a/packages/boot/app-boot/README.md +++ b/packages/boot/app-boot/README.md @@ -40,7 +40,7 @@ installFailLoud('dsh') const ctx = await boot('dsh', resolveConfigPath(argv[2], process.env.DSH_SNAPSHOT)) ``` -With that entry point, startup keeps every plugin that can activate. An enabled failed plugin produces a labelled warning. A failed required entry makes startup dispose the whole app and exit nonzero; required ids absent from a profile and disabled required entries do not affect startup. The global required list covers shared Agent execution, application endpoints, and Web bootstrap/transport: `agent-loop`, `webserver`, `modules`, `connection`, `headless-runner`, `acp`, and `sdk-jsonrpc-server`. +`installFailLoud` writes one labelled `util.inspect` diagnostic to stderr for an unhandled rejection or an uncaught exception, awaits the surface's release hook under a fixed timeout, and exits 1; it never resumes execution after either, because only the throw site knows which state is intact. With that entry point, startup keeps every plugin that can activate. An enabled failed plugin produces a labelled warning. A failed required entry makes startup dispose the whole app and exit nonzero; required ids absent from a profile and disabled required entries do not affect startup. The global required list covers shared Agent execution, application endpoints, and Web bootstrap/transport: `agent-loop`, `webserver`, `modules`, `connection`, `headless-runner`, `acp`, and `sdk-jsonrpc-server`. ### Profiles @@ -97,6 +97,7 @@ After the Loader settles, app-boot warns when only optional entries are inactive | An injected service is unavailable | Warn; continue while the entry waits for its dependencies | Stop startup | Keep the entry waiting; adding the missing provider can activate it | | HTTP port binding fails | Warn; continue without that endpoint | Stop startup | Keep the process running without the failed endpoint; corrected config can restore it | | Detached asynchronous work outside the `apply()` return Promise produces an unhandled rejection | Fatal: dispose the app and exit nonzero | Fatal: dispose the app and exit nonzero | Fatal: dispose the app and exit nonzero, regardless of entry id | +| A synchronous callback (a stream `'data'` listener, a timer) throws an uncaught exception at any point in the process lifetime | Fatal: dispose the app and exit nonzero; the process never resumes | Fatal: dispose the app and exit nonzero; the process never resumes | Fatal: dispose the app and exit nonzero, regardless of entry id | | Entry is absent or explicitly disabled | Ignore it | Ignore it | Do not activate it; no required-startup audit | The required list above includes `modules` and `connection`; Web startup cannot succeed when either enabled entry fails. Failure of an optional provider can also prevent a required consumer from activating. Schema rejection before an existing entry updates is not a transactional rollback of sibling changes. diff --git a/packages/boot/app-boot/README.zh.md b/packages/boot/app-boot/README.zh.md index b3ac89c1cb..0d98af8133 100644 --- a/packages/boot/app-boot/README.zh.md +++ b/packages/boot/app-boot/README.zh.md @@ -40,7 +40,7 @@ installFailLoud('dsh') const ctx = await boot('dsh', resolveConfigPath(argv[2], process.env.DSH_SNAPSHOT)) ``` -有了这个入口,启动会保留所有能够激活的插件。启用但失败的插件会产生带标签的警告。required entry 失败时,启动会拆卸整个应用并以非零码退出;profile 中不存在的 required id 和已禁用的 required entry 不影响启动。全局 required list 覆盖共享 Agent 执行、应用 endpoint,以及 Web 启动与传输:`agent-loop`、`webserver`、`modules`、`connection`、`headless-runner`、`acp` 和 `sdk-jsonrpc-server`。 +`installFailLoud` 会为未处理 rejection 或未捕获异常向 stderr 写一条带标签的 `util.inspect` 诊断,在固定超时内等待界面的 release 钩子,然后以 1 退出;两种情况下都不会恢复执行,因为只有抛出点知道哪些状态仍然完整。有了这个入口,启动会保留所有能够激活的插件。启用但失败的插件会产生带标签的警告。required entry 失败时,启动会拆卸整个应用并以非零码退出;profile 中不存在的 required id 和已禁用的 required entry 不影响启动。全局 required list 覆盖共享 Agent 执行、应用 endpoint,以及 Web 启动与传输:`agent-loop`、`webserver`、`modules`、`connection`、`headless-runner`、`acp` 和 `sdk-jsonrpc-server`。 ### Profile @@ -97,6 +97,7 @@ Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如 | 注入的服务不可用 | 警告;继续,条目等待依赖 | 终止启动 | 条目继续等待;补上缺失的提供方后可以激活 | | HTTP 端口绑定失败 | 警告;继续,但该端点不可用 | 终止启动 | 进程继续运行,但失败的端点不可用;修正配置后可以恢复 | | 脱离 `apply()` 返回 Promise 的异步任务产生未处理 rejection | 致命错误:释放应用并以非零码退出 | 致命错误:释放应用并以非零码退出 | 致命错误:释放应用并以非零码退出,与条目 id 无关 | +| 同步回调(流的 `'data'` 监听器、定时器)在进程生命周期任一时刻抛出未捕获异常 | 致命错误:释放应用并以非零码退出;进程不会恢复运行 | 致命错误:释放应用并以非零码退出;进程不会恢复运行 | 致命错误:释放应用并以非零码退出,与条目 id 无关 | | 条目缺失或被显式禁用 | 忽略 | 忽略 | 不激活该条目;不执行 required 启动审计 | 上面的 required 列表包含 `modules` 与 `connection`;只要其中一个已启用条目失败,Web 就无法成功启动。Optional 提供方失败也可能使 required 消费方无法激活。现有条目的新配置在更新前被 schema 校验拒绝,并不等于对兄弟插件的变更做事务回滚。 diff --git a/packages/boot/app-boot/src/index.ts b/packages/boot/app-boot/src/index.ts index 39dd644846..3ca1a881c0 100644 --- a/packages/boot/app-boot/src/index.ts +++ b/packages/boot/app-boot/src/index.ts @@ -8,7 +8,7 @@ import { pathToFileURL } from 'node:url' import { readFileSync } from 'node:fs' -import { parseEnv } from 'node:util' +import { inspect, parseEnv } from 'node:util' import { basename, dirname, isAbsolute, resolve } from 'node:path' import * as yaml from 'js-yaml' import { Context, type FiberState } from '@deepseek-ai/cordis' @@ -566,13 +566,16 @@ export async function mountRootInclude( return entry } +/** The two process events {@link installFailLoud} turns into a fatal exit. */ +export type FailLoudEvent = 'unhandledRejection' | 'uncaughtException' + /** * The slice of `process` {@link installFailLoud} needs — injectable so tests * exercise the handler without registering on (or exiting) the real process. */ export interface FailLoudProcess { - on(event: 'unhandledRejection', handler: (err: unknown) => void): unknown - off(event: 'unhandledRejection', handler: (err: unknown) => void): unknown + on(event: FailLoudEvent, handler: (err: unknown) => void): unknown + off(event: FailLoudEvent, handler: (err: unknown) => void): unknown stderr: { write(chunk: string): unknown } /** * Terminate the process. Callers treat this as the end of the run, as @@ -616,11 +619,21 @@ async function observeLoaderRejectionCheckpoint(reasons: readonly unknown[]): Pr export const FAIL_LOUD_RELEASE_TIMEOUT_MS = 2_000 /** - * Install before boot to turn a late unhandled plugin-init rejection into one - * labelled stderr diagnostic and `exit(1)`. A rejection already included by - * {@link auditStartupEntries} is ignored during its process checkpoint; - * every other rejection remains fatal. Stdout remains untouched for ACP; the - * returned function removes the handler. + * Install before boot to turn an unhandled rejection or an uncaught exception, + * at any point in the process lifetime, into one labelled stderr diagnostic and + * `exit(1)`. A rejection already included by {@link auditStartupEntries} is + * ignored during its process checkpoint; every other rejection and every + * uncaught exception remains fatal. The process never resumes after either: + * only the throw site knows which state is intact, and a listener that threw + * mid-update (a stream `'data'` handler, a half-applied registry write) leaves + * silently wrong results behind if execution continues. Stdout remains + * untouched for ACP; the returned function removes both handlers. + * + * The diagnostic is `util.inspect(err)`, not `err.stack`: a `node:fs` error's + * `code`, `syscall`, and `path` and any `cause` chain are enumerable properties + * that the stack line omits, and they are what a crash report needs. Once a + * handler is installed Node prints nothing of its own, so this line is the + * only record of the failure. * * The Loader mounts entries concurrently, so a surface that owns the terminal * can already hold it when a sibling entry rejects. Exiting straight from the @@ -642,7 +655,7 @@ export const FAIL_LOUD_RELEASE_TIMEOUT_MS = 2_000 * @param release - optional teardown awaited before exit, used by a * terminal-owning surface to restore the terminal. Its own failure is * swallowed because the pending fatal exit already owns the outcome. - * @returns the uninstaller that removes the rejection handler. + * @returns the uninstaller that removes both handlers. */ export function installFailLoud( binName: string, @@ -650,14 +663,13 @@ export function installFailLoud( release?: () => Promise | void, ): () => void { let exiting = false - const handler = (err: unknown): void => { - if (assembledActivationRejections.has(err)) return - // A release in flight already owns the exit. Swallow later rejections + const report = (err: unknown, label: string): void => { + // A release in flight already owns the exit. Swallow later failures // (teardown's own included) rather than reporting a second failure over the // real one or letting Node kill the process before the terminal is back. if (exiting) return exiting = true - proc.stderr.write(`${binName}: fatal load failure: ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`) + proc.stderr.write(`${binName}: ${label}: ${inspect(err, { depth: 4 })}\n`) if (release === undefined) { proc.exit(1) return @@ -681,8 +693,18 @@ export function installFailLoud( proc.exit(1) })() } - const uninstall = (): void => void proc.off('unhandledRejection', handler) - proc.on('unhandledRejection', handler) + const onRejection = (err: unknown): void => { + if (assembledActivationRejections.has(err)) return + // Label kept stable: the Web profile expected-output e2e tests match it. + report(err, 'fatal load failure') + } + const onException = (err: unknown): void => { report(err, 'fatal uncaught exception') } + const uninstall = (): void => { + proc.off('unhandledRejection', onRejection) + proc.off('uncaughtException', onException) + } + proc.on('unhandledRejection', onRejection) + proc.on('uncaughtException', onException) return uninstall } diff --git a/packages/boot/app-boot/tests/app-boot.spec.ts b/packages/boot/app-boot/tests/app-boot.spec.ts index ba841a95f1..f291e45cc6 100644 --- a/packages/boot/app-boot/tests/app-boot.spec.ts +++ b/packages/boot/app-boot/tests/app-boot.spec.ts @@ -9,7 +9,7 @@ import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt' import { addHarnessSourceSection, auditStartupEntries, boot, StartupError, FAIL_LOUD_RELEASE_TIMEOUT_MS, HARNESS_SOURCE_SECTION, - installFailLoud, loadEnv, loadLayeredEnv, loadOverlayPatches, resolveConfigPath, type FailLoudProcess, + installFailLoud, loadEnv, loadLayeredEnv, loadOverlayPatches, resolveConfigPath, type FailLoudEvent, type FailLoudProcess, } from '../src/index.ts' const NAME = 'dsh-test-bin' @@ -360,14 +360,24 @@ describe('loadLayeredEnv', () => { }) describe('installFailLoud', () => { - function fakeProc(): FailLoudProcess & { handlers: Array<(err: unknown) => void>; written: string[]; exits: number[] } { - const handlers: Array<(err: unknown) => void> = [] + type Handler = (err: unknown) => void + function fakeProc(): FailLoudProcess & { + handlers: Handler[] + rejection: Handler + exception: Handler + written: string[] + exits: number[] + } { + const handlers: Handler[] = [] + const registered = new Map() const written: string[] = [] const exits: number[] = [] return { handlers, written, exits, - on: (_event, handler) => { handlers.push(handler) }, - off: (_event, handler) => { handlers.splice(handlers.indexOf(handler), 1) }, + get rejection() { return registered.get('unhandledRejection')! }, + get exception() { return registered.get('uncaughtException')! }, + on: (event, handler) => { handlers.push(handler); registered.set(event, handler) }, + off: (event, handler) => { handlers.splice(handlers.indexOf(handler), 1); registered.delete(event) }, stderr: { write: (chunk: string) => { written.push(chunk) } }, exit: (code: number) => { exits.push(code) }, } @@ -377,7 +387,7 @@ describe('installFailLoud', () => { const proc = fakeProc() installFailLoud(NAME, proc) const error = new Error('boom') - proc.handlers[0]!(error) + proc.rejection(error) expect(proc.written[0]).toContain(`${NAME}: fatal load failure: `) expect(proc.written[0]).toContain(error.stack) expect(proc.exits).toEqual([1]) @@ -388,7 +398,7 @@ describe('installFailLoud', () => { it('stringifies a non-Error rejection and an Error without a stack falls back to its message', () => { const plain = fakeProc() installFailLoud(NAME, plain) - plain.handlers[0]!('plain failure') + plain.rejection('plain failure') expect(plain.written[0]).toContain('plain failure') expect(plain.exits).toEqual([1]) @@ -396,7 +406,7 @@ describe('installFailLoud', () => { delete (stackless as { stack?: string }).stack const bare = fakeProc() installFailLoud(NAME, bare) - bare.handlers[0]!(stackless) + bare.rejection(stackless) expect(bare.written[0]).toContain('no stack') expect(bare.exits).toEqual([1]) }) @@ -404,16 +414,18 @@ describe('installFailLoud', () => { it('returns an uninstaller that removes the handler (and defaults to the real process)', () => { const proc = fakeProc() const uninstall = installFailLoud(NAME, proc) - expect(proc.handlers).toHaveLength(1) + expect(proc.handlers).toHaveLength(2) uninstall() expect(proc.handlers).toHaveLength(0) // Default-proc arm: install on the real process, then immediately uninstall // so the suite leaks no handler and can never exit the runner. - const before = process.listenerCount('unhandledRejection') + const before = [process.listenerCount('unhandledRejection'), process.listenerCount('uncaughtException')] const uninstallReal = installFailLoud(NAME) - expect(process.listenerCount('unhandledRejection')).toBe(before + 1) + expect(process.listenerCount('unhandledRejection')).toBe(before[0]! + 1) + expect(process.listenerCount('uncaughtException')).toBe(before[1]! + 1) uninstallReal() - expect(process.listenerCount('unhandledRejection')).toBe(before) + expect(process.listenerCount('unhandledRejection')).toBe(before[0]) + expect(process.listenerCount('uncaughtException')).toBe(before[1]) }) it('does not report an activation rejection shared by entries in the boot audit', async () => { @@ -436,12 +448,12 @@ describe('installFailLoud', () => { } as unknown as Context, NAME, warn) await Promise.resolve() await Promise.resolve() - proc.handlers[0]!(error) + proc.rejection(error) expect(proc.written).toEqual([]) expect(proc.exits).toEqual([]) await audit expect(warn).toHaveBeenCalledWith(expect.stringContaining('assembled activation failure')) - proc.handlers[0]!(error) + proc.rejection(error) expect(proc.exits).toEqual([1]) }) @@ -455,7 +467,7 @@ describe('installFailLoud', () => { await Promise.resolve() order.push('released') }) - proc.handlers[0]!(new Error('sibling entry rejected')) + proc.rejection(new Error('sibling entry rejected')) expect(proc.written[0]).toContain(`${NAME}: fatal load failure: `) // The release is in flight, so the exit has not committed yet. expect(proc.exits).toEqual([]) @@ -466,7 +478,7 @@ describe('installFailLoud', () => { it('still exits when the release hook rejects', async () => { const proc = fakeProc() installFailLoud(NAME, proc, () => Promise.reject(new Error('terminal stop failed'))) - proc.handlers[0]!(new Error('boom')) + proc.rejection(new Error('boom')) await vi.waitFor(() => { expect(proc.exits).toEqual([1]) }) }) @@ -475,7 +487,7 @@ describe('installFailLoud', () => { try { const proc = fakeProc() installFailLoud(NAME, proc, () => new Promise(() => {})) - proc.handlers[0]!(new Error('boom')) + proc.rejection(new Error('boom')) expect(proc.exits).toEqual([]) await vi.advanceTimersByTimeAsync(FAIL_LOUD_RELEASE_TIMEOUT_MS) expect(proc.exits).toEqual([1]) @@ -494,14 +506,52 @@ describe('installFailLoud', () => { await Promise.resolve() released = true }) - proc.handlers[0]!(new Error('first rejection')) - proc.handlers[0]!(new Error('second rejection')) - expect(proc.handlers).toHaveLength(1) + proc.rejection(new Error('first rejection')) + proc.rejection(new Error('second rejection')) + proc.exception(new Error('exception during teardown')) + expect(proc.handlers).toHaveLength(2) expect(proc.written).toHaveLength(1) expect(proc.written[0]).toContain('first rejection') await vi.waitFor(() => { expect(proc.exits).toEqual([1]) }) expect(released).toBe(true) }) + + it('turns an uncaught exception into a labelled diagnostic with its enumerable properties and exits 1', () => { + const proc = fakeProc() + installFailLoud(NAME, proc) + const error = Object.assign(new Error("ENOENT: no such file or directory, open '/tmp/dsh-subprocess-x/out.log'"), { + errno: -2, code: 'ENOENT', syscall: 'open', path: '/tmp/dsh-subprocess-x/out.log', + }) + proc.exception(error) + expect(proc.written).toHaveLength(1) + expect(proc.written[0]).toContain(`${NAME}: fatal uncaught exception: `) + expect(proc.written[0]).toContain(error.stack) + expect(proc.written[0]).toContain("syscall: 'open'") + expect(proc.written[0]).toContain("path: '/tmp/dsh-subprocess-x/out.log'") + expect(proc.exits).toEqual([1]) + }) + + it('includes the cause chain in the diagnostic', () => { + const proc = fakeProc() + installFailLoud(NAME, proc) + proc.exception(new Error('wrapper', { cause: new Error('root cause') })) + expect(proc.written[0]).toContain('[cause]: Error: root cause') + expect(proc.exits).toEqual([1]) + }) + + it('awaits the release hook for an uncaught exception as it does for a rejection', async () => { + const proc = fakeProc() + let released = false + installFailLoud(NAME, proc, async () => { + await Promise.resolve() + released = true + }) + proc.exception(new Error('listener threw')) + expect(proc.written[0]).toContain('fatal uncaught exception') + expect(proc.exits).toEqual([]) + await vi.waitFor(() => { expect(proc.exits).toEqual([1]) }) + expect(released).toBe(true) + }) }) describe('auditStartupEntries', () => { From 22be805026696a9c6ca95780a2611ddff7a10a40 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 22 Sep 2026 12:50:28 +0800 Subject: [PATCH 04/19] fix(ip-geolocation): align the package with the current release --- packages/util/ip-geolocation/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/util/ip-geolocation/package.json b/packages/util/ip-geolocation/package.json index 665eccd746..ff0a09283d 100644 --- a/packages/util/ip-geolocation/package.json +++ b/packages/util/ip-geolocation/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-ip-geolocation", "description": "Bounded lookup of the calling process network exit country through a JSON country endpoint", - "version": "0.1.6-alpha.2", + "version": "0.1.7-alpha.1", "publishConfig": { "access": "public" }, From 9f52c6401e3f6d6a737a25c0a36bcd9fb32faf16 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 22 Sep 2026 12:57:05 +0800 Subject: [PATCH 05/19] docs(ip-geolocation): refresh the module dependency graph --- docs/module-graph.i18n.yaml | 4 ++-- docs/module-graph.md | 2 ++ docs/module-graph.zh.md | 2 ++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/module-graph.i18n.yaml b/docs/module-graph.i18n.yaml index 8f2887a8d4..f35f369767 100644 --- a/docs/module-graph.i18n.yaml +++ b/docs/module-graph.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/module-graph.md -module-graph.md: fc5c06727e58705ac6d9b44470b1b37010dc3223 -module-graph.zh.md: 6911d9820932569c7a666b47a8bd53696fdb6393 +module-graph.md: add966eac9408b2d5ed6ebf802f078cea0848e75 +module-graph.zh.md: 2cc10e421e2a9a99082b8bcac169752ab4d986e3 diff --git a/docs/module-graph.md b/docs/module-graph.md index fc5c06727e..add966eac9 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -14,6 +14,7 @@ flowchart TD pkg_deque["deque"] pkg_home_paths["home-paths"] pkg_http_proxy["http-proxy"] + pkg_ip_geolocation["ip-geolocation"] pkg_launch_environment["launch-environment"] pkg_lazy_require["lazy-require"] pkg_native_command["native-command"] @@ -1349,6 +1350,7 @@ flowchart TD | [`deque`](../packages/util/deque) | `util` | — | | [`home-paths`](../packages/util/home-paths) | `util` | — | | [`http-proxy`](../packages/util/http-proxy) | `util` | — | +| [`ip-geolocation`](../packages/util/ip-geolocation) | `util` | — | | [`launch-environment`](../packages/util/launch-environment) | `util` | — | | [`lazy-require`](../packages/util/lazy-require) | `util` | — | | [`native-command`](../packages/util/native-command) | `util` | — | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 6911d98209..2cc10e421e 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -16,6 +16,7 @@ flowchart TD pkg_deque["deque"] pkg_home_paths["home-paths"] pkg_http_proxy["http-proxy"] + pkg_ip_geolocation["ip-geolocation"] pkg_launch_environment["launch-environment"] pkg_lazy_require["lazy-require"] pkg_native_command["native-command"] @@ -1351,6 +1352,7 @@ flowchart TD | [`deque`](../packages/util/deque) | `util` | — | | [`home-paths`](../packages/util/home-paths) | `util` | — | | [`http-proxy`](../packages/util/http-proxy) | `util` | — | +| [`ip-geolocation`](../packages/util/ip-geolocation) | `util` | — | | [`launch-environment`](../packages/util/launch-environment) | `util` | — | | [`lazy-require`](../packages/util/lazy-require) | `util` | — | | [`native-command`](../packages/util/native-command) | `util` | — | From afde35880f5368f697858688dc64b633cfec3b77 Mon Sep 17 00:00:00 2001 From: winewill Date: Tue, 22 Sep 2026 13:00:13 +0800 Subject: [PATCH 06/19] feat(client-modules): recover from a failed batch script and record import errors One application batch is a single classic script that registers every package in sequence, requested exactly once during boot. A transient failure of that one