From 27a32189d3c70c21274dd21c39e7e592c9b70876 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Tue, 10 Nov 2026 16:02:57 +0800 Subject: [PATCH 01/48] fix(checks): preserve cordis preset identifiers --- scripts/rescope-vendor.spec.ts | 14 ++++++++++++++ scripts/rescope-vendor.ts | 3 +++ 2 files changed, 17 insertions(+) diff --git a/scripts/rescope-vendor.spec.ts b/scripts/rescope-vendor.spec.ts index 4f43ef08fe..0eb3b530f8 100644 --- a/scripts/rescope-vendor.spec.ts +++ b/scripts/rescope-vendor.spec.ts @@ -87,6 +87,7 @@ describe('product identifiers', () => { it.each([ 'apps/cli/tests/optional-bundle-transitions.e2e.ts', 'apps/web/tests/agent-preset-selection.e2e.ts', + 'apps/web/tests/creator-persona.e2e.ts', 'apps/web/tests/developer-tools-settings.e2e.ts', 'docs/subsystems/extensions.md', 'docs/subsystems/extensions.zh.md', @@ -98,6 +99,8 @@ describe('product identifiers', () => { 'docs/upgrade-guide/v0.2.1-alpha.1/subagent-preset-composition/guide.zh.md', 'docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.md', 'docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.zh.md', + 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md', + 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md', 'docs/user/guide/schedule.md', 'docs/user/guide/schedule.zh.md', 'packages/bundle/web-app/cordis.patch.yml', @@ -132,6 +135,17 @@ describe('product identifiers', () => { expect(rescopeText(scoped, file, true)).toEqual({ text, lines: 2 }) }) + it.each([ + 'apps/web/tests/creator-persona.e2e.ts', + 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md', + 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md', + ])('still rewrites package imports in %s', (file) => { + const source = "const preset = 'cordis'\nimport { Context } from 'cordis'\n" + const text = file.endsWith('.md') ? `The \`cordis\` preset.\n\`\`\`ts\n${source}\`\`\`\n` : source + const scoped = text.replace("from 'cordis'", "from '@deepseek-ai/cordis'") + expectRoundTrip(file, text, scoped, 1) + }) + it('keeps unlisted package references subject to residue detection', () => { const file = 'packages/example/src/index.ts' const text = "import { Context } from 'cordis'\nimport type Schema from 'schemastery'\n" diff --git a/scripts/rescope-vendor.ts b/scripts/rescope-vendor.ts index 7a5dc46818..62259636b2 100644 --- a/scripts/rescope-vendor.ts +++ b/scripts/rescope-vendor.ts @@ -101,6 +101,7 @@ const GENERIC_SKIPS: readonly GenericSkip[] = [ { file: 'apps/cli/tests/web-agent-presets.e2e.ts', upstream: ['cordis'] }, { file: 'apps/cli/tests/profiles/web/tests/fixtures/creator-plugin-manager.mjs', upstream: ['cordis'] }, { file: 'apps/web/tests/agent-preset-authoring.e2e.ts', upstream: ['cordis'] }, + { file: 'apps/web/tests/creator-persona.e2e.ts', upstream: ['cordis'] }, { file: 'packages/preset/agent-preset-registry/tests/session.spec.ts', upstream: ['cordis'] }, { file: 'packages/experimental/creation-recommendations/src/index.ts', upstream: ['cordis'] }, { file: 'packages/experimental/creation-recommendations/tests/creation.spec.ts', upstream: ['cordis'] }, @@ -113,6 +114,8 @@ const GENERIC_SKIPS: readonly GenericSkip[] = [ { file: 'docs/tool-catalog.zh.md', upstream: ['cordis'] }, { file: 'docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.md', upstream: ['cordis'] }, { file: 'docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.zh.md', upstream: ['cordis'] }, + { file: 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md', upstream: ['cordis'] }, + { file: 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md', upstream: ['cordis'] }, { file: 'scripts/gen-tool-catalog.ts', upstream: ['cordis'] }, { file: 'docs/upgrade-guide/v0.2.0-rc.2/schedule-bundle-retired/guide.md', upstream: ['cordis'] }, { file: 'docs/upgrade-guide/v0.2.0-rc.2/schedule-bundle-retired/guide.zh.md', upstream: ['cordis'] }, From c41f0d1d1086f8b067b34f84e4820ae177e58ee4 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Tue, 10 Nov 2026 16:03:51 +0800 Subject: [PATCH 02/48] feat(session): add read-only workspace and session list tools --- docs/config-catalog.md | 17 + docs/config-catalog.zh.md | 17 + docs/event-producer-consumer.md | 10 +- docs/event-producer-consumer.zh.md | 10 +- docs/persistence-catalog.i18n.yaml | 12 +- docs/persistence-catalog.md | 6 +- docs/persistence-catalog.zh.md | 6 +- docs/persistence-schema.json | 6 +- docs/tool-catalog.i18n.yaml | 17 +- docs/tool-catalog.md | 63 ++ docs/tool-catalog.zh.md | 63 ++ package.json | 3 +- .../api/session-controller/README.i18n.yaml | 4 +- packages/api/session-controller/README.md | 2 +- packages/api/session-controller/README.zh.md | 2 +- packages/api/session-controller/src/list.ts | 47 +- packages/api/session-controller/src/types.ts | 12 +- .../session-controller/tsconfig.client.json | 1 + .../skills/dsh-doc/references/packages.md | 1 + packages/session-query/README.i18n.yaml | 4 +- packages/session-query/README.md | 1 + packages/session-query/README.zh.md | 1 + .../session-query/README.i18n.yaml | 15 +- .../session-query/session-query/README.md | 8 +- .../session-query/session-query/README.zh.md | 8 +- .../session-query/session-query/package.json | 8 +- .../session-query/session-query/src/index.ts | 1 + .../session-query/src/list-metadata.ts | 48 ++ .../session-query/session-query/src/types.ts | 19 +- .../session-query/tests/list-metadata.spec.ts | 84 +++ .../tool-session-list/README.i18n.yaml | 55 ++ .../session-query/tool-session-list/README.md | 128 ++++ .../tool-session-list/README.zh.md | 128 ++++ .../tool-session-list/locale/de.json | 6 + .../tool-session-list/locale/en.json | 6 + .../tool-session-list/locale/es.json | 6 + .../tool-session-list/locale/fr.json | 6 + .../tool-session-list/locale/ja.json | 6 + .../tool-session-list/locale/pt.json | 6 + .../tool-session-list/locale/ru.json | 6 + .../tool-session-list/locale/zh.json | 6 + .../tool-session-list/package.json | 74 ++ .../tool-session-list/src/index.ts | 99 +++ .../tool-session-list/src/list.ts | 182 +++++ .../tests/fixtures/session-list-seed.ts | 65 ++ .../tests/tool-session-list.spec.ts | 437 +++++++++++ .../tool-session-list/tsconfig.json | 39 + pnpm-lock.yaml | 64 ++ scripts/gen-tool-catalog.ts | 25 +- scripts/product-package-policy.ts | 1 + .../session-list-tools/cordis.snapshot.yml | 52 ++ .../session/session-list-tools/cordis.yml | 6 + .../session-list-tools/session.v4.jsonl | 57 ++ .../session/session-list-tools/snapshot.yml | 9 + .../tool-schemas.expected.json | 689 ++++++++++++++++++ tsconfig.base.json | 2 + tsconfig.host.json | 1 + 57 files changed, 2560 insertions(+), 97 deletions(-) create mode 100644 packages/session-query/session-query/src/list-metadata.ts create mode 100644 packages/session-query/session-query/tests/list-metadata.spec.ts create mode 100644 packages/session-query/tool-session-list/README.i18n.yaml create mode 100644 packages/session-query/tool-session-list/README.md create mode 100644 packages/session-query/tool-session-list/README.zh.md create mode 100644 packages/session-query/tool-session-list/locale/de.json create mode 100644 packages/session-query/tool-session-list/locale/en.json create mode 100644 packages/session-query/tool-session-list/locale/es.json create mode 100644 packages/session-query/tool-session-list/locale/fr.json create mode 100644 packages/session-query/tool-session-list/locale/ja.json create mode 100644 packages/session-query/tool-session-list/locale/pt.json create mode 100644 packages/session-query/tool-session-list/locale/ru.json create mode 100644 packages/session-query/tool-session-list/locale/zh.json create mode 100644 packages/session-query/tool-session-list/package.json create mode 100644 packages/session-query/tool-session-list/src/index.ts create mode 100644 packages/session-query/tool-session-list/src/list.ts create mode 100644 packages/session-query/tool-session-list/tests/fixtures/session-list-seed.ts create mode 100644 packages/session-query/tool-session-list/tests/tool-session-list.spec.ts create mode 100644 packages/session-query/tool-session-list/tsconfig.json create mode 100644 snapshots/session/session-list-tools/cordis.snapshot.yml create mode 100644 snapshots/session/session-list-tools/cordis.yml create mode 100644 snapshots/session/session-list-tools/session.v4.jsonl create mode 100644 snapshots/session/session-list-tools/snapshot.yml create mode 100644 snapshots/session/session-list-tools/tool-schemas.expected.json diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 41bd0207f3..48be42f926 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -4482,6 +4482,23 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-tool-session-list` + +- `inject`: `tools` · `sessions` · `sessionQuery` · `workspaceRegistry` · `sessionProjections` +- `source`: [`packages/session-query/tool-session-list/src/index.ts:18`](../packages/session-query/tool-session-list/src/index.ts) + +```ts config-catalog +/** Deployment-owned responsiveness for large Session lists. */ +export interface Config { + /** Positive integral work slice in milliseconds; defaults to 16. Checked between complete rows. */ + readonly listWorkSliceMs?: number +} +``` + + diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index a3bb192363..77d249aa80 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -4484,6 +4484,23 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-tool-session-list` + +- `inject`: `tools` · `sessions` · `sessionQuery` · `workspaceRegistry` · `sessionProjections` +- `source`: [`packages/session-query/tool-session-list/src/index.ts:18`](../packages/session-query/tool-session-list/src/index.ts) + +```ts config-catalog +/** Deployment-owned responsiveness for large Session lists. */ +export interface Config { + /** Positive integral work slice in milliseconds; defaults to 16. Checked between complete rows. */ + readonly listWorkSliceMs?: number +} +``` + + diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 1d80e1cfe7..fb5332b037 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -23,11 +23,11 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:691`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:698`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:697`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:677`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:704`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:683`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:690`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:55`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 9245fa8fab..18e0bd8f9b 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -25,11 +25,11 @@ | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:691`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:698`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:697`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:677`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:704`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:683`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:690`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:55`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index f2294edff6..731cdbf207 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -1368,8 +1368,8 @@ en: 4147b170f52814af zh: e78991ac1c41ebec /session-persistence-event-catalog/resolved-persistence-types/string: - en: ef89e74973f4a575 - zh: 0bb1564a0418501c + en: 3123f20799b77064 + zh: 34234db45f2769a1 /session-persistence-event-catalog/resolved-persistence-types/string~2: en: 0089620bf4638263 zh: 1922bef1713094bb @@ -1761,8 +1761,8 @@ en: f58bccca3df9c2ad zh: 5c92b6edeb7ce020 /session-persistence-event-catalog/resolved-persistence-types/kind-retry: - en: c628d0575f81407a - zh: d9a70ce1e05dcce8 + en: 898f27c058097895 + zh: bbbcf08ad8ba3a32 /session-persistence-event-catalog/resolved-persistence-types/kind-runtime-context: en: 68b5598e21cf8ba2 zh: 95ef1685af64a5f4 @@ -1899,8 +1899,8 @@ en: 4e102391d685eff5 zh: 9762243a13014f3d /session-persistence-event-catalog/resolved-persistence-types/kind-user: - en: 808d28208287e843 - zh: 18a8d63978c984a7 + en: 156e57c019aa1b28 + zh: a1629b267f7cc713 /session-persistence-event-catalog/resolved-persistence-types/kind-user-approval: en: a52d2dfbaf844127 zh: 4c5306ca40f20873 diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 33d9aa4395..0789ca87af 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -5659,7 +5659,7 @@ Array of `number`. SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -Sources: [`packages/api/session-controller/src/types.ts:391`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:383`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` @@ -7305,7 +7305,7 @@ SHA-256: `db06ef35b27a38425046b2228fa6bce9582abe140d781d363137eb2f4d233a1c` SHA-256: `8f1062573ea9184129dfdec43df1e8136eb5808746fd809bf6b539f3fd11362e` -Sources: [`packages/api/session-controller/src/types.ts:402`](../packages/api/session-controller/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:394`](../packages/api/session-controller/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7824,7 +7824,7 @@ Sources: [`packages/core/tools/src/index.ts:28`](../packages/core/tools/src/inde SHA-256: `a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302` -Sources: [`packages/api/session-controller/src/types.ts:400`](../packages/api/session-controller/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:392`](../packages/api/session-controller/src/types.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 5047ebc659..24e2e28177 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -5661,7 +5661,7 @@ SHA-256: `5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78` SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -来源:[`packages/api/session-controller/src/types.ts:391`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:383`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` @@ -7307,7 +7307,7 @@ SHA-256: `db06ef35b27a38425046b2228fa6bce9582abe140d781d363137eb2f4d233a1c` SHA-256: `8f1062573ea9184129dfdec43df1e8136eb5808746fd809bf6b539f3fd11362e` -来源:[`packages/api/session-controller/src/types.ts:402`](../packages/api/session-controller/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:394`](../packages/api/session-controller/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7826,7 +7826,7 @@ SHA-256: `8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543` SHA-256: `a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302` -来源:[`packages/api/session-controller/src/types.ts:400`](../packages/api/session-controller/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:392`](../packages/api/session-controller/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index a2832eb98c..c8effc7e32 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -259,7 +259,7 @@ {"digest":"4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731","names":["packages/llm/llm/src/message.ts#ToolResultMessage"],"sources":["packages/llm/llm/src/message.ts:173"]}, {"digest":"4b7ddaf3710b88ff9b8df66304f5f97bf03688fd19730eedc2e9535203c820ea","names":[],"sources":[]}, {"digest":"4bb451330ff699f36b45539ceb0eb2606ead72084e2c5bb637c36cc80e2252db","names":[],"sources":["packages/core/session/src/types.ts:198"]}, - {"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/index.ts#SessionTitleProviderId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/team/agent-team/src/types.ts#TeamId","packages/team/agent-team/src/types.ts#TeamMessageId","packages/team/agent-team/src/types.ts#TeamTaskId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:391","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:31","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:19","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/index.ts:42","packages/session/session-title/src/types.ts:17","packages/team/agent-team/src/types.ts:20","packages/team/agent-team/src/types.ts:32","packages/team/agent-team/src/types.ts:8","packages/workflow/workflow/src/types.ts:13"]}, + {"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/index.ts#SessionTitleProviderId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/team/agent-team/src/types.ts#TeamId","packages/team/agent-team/src/types.ts#TeamMessageId","packages/team/agent-team/src/types.ts#TeamTaskId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:383","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:31","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:19","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/index.ts:42","packages/session/session-title/src/types.ts:17","packages/team/agent-team/src/types.ts:20","packages/team/agent-team/src/types.ts:32","packages/team/agent-team/src/types.ts:8","packages/workflow/workflow/src/types.ts:13"]}, {"digest":"4d60dddaa65d3da8d4cd014d85ce3d2c2875664dd0433e331d8e9d395289686b","names":["packages/experimental/liveshare/src/host/viewer-principal.ts#ShareViewerPrincipal"],"sources":["packages/experimental/liveshare/src/host/viewer-principal.ts:24"]}, {"digest":"4e011753f8263f436efaabfbb3b4db53a98fc55342c5ded2daf7208b217be159","names":[],"sources":[]}, {"digest":"4e44c9118152f6829634bfd508e47669ab0497caffa380c94b4be91f9390d35d","names":[],"sources":[]}, @@ -426,7 +426,7 @@ {"digest":"8e611bf46821e5003a1605a73560a6f56388295149d449dfe2142d5ec335f29c","names":["packages/llm/llm/src/types.ts#ToolAdditionBlock"],"sources":["packages/llm/llm/src/types.ts:122"]}, {"digest":"8e8155594e07812356b67d732196dda894b0f9c91a5969d51612cf490b0a016d","names":[],"sources":[]}, {"digest":"8e8e91646a5cae3fc78f7532a0013ff2088ae47077642c2edd507a508209b8af","names":["packages/schedule/schedule/src/types.ts#OneShotScheduleDispatchChange"],"sources":["packages/schedule/schedule/src/types.ts:213"]}, - {"digest":"8f1062573ea9184129dfdec43df1e8136eb5808746fd809bf6b539f3fd11362e","names":[],"sources":["packages/api/session-controller/src/types.ts:402"]}, + {"digest":"8f1062573ea9184129dfdec43df1e8136eb5808746fd809bf6b539f3fd11362e","names":[],"sources":["packages/api/session-controller/src/types.ts:394"]}, {"digest":"8f324cea3916c0517261e88167def8efb3a9994c1135e23d40ed9fd48f8c7bd4","names":[],"sources":[]}, {"digest":"8f6d609794bf5afc01d7ccf3e03811d32f4b8047f58a2c9a98db0154c2ad7cb9","names":[],"sources":[]}, {"digest":"8faed5b52ab2d2df40b94a926d0f0faa75280bddcc4b17b6bdd9c8bfed7c34b5","names":[],"sources":[]}, @@ -480,7 +480,7 @@ {"digest":"a3c6f1ea38e9a61d7a9706057ba65aabe02dfe6d9dd90d4736aa62325d874531","names":[],"sources":[]}, {"digest":"a3edd1efd1fef21b72c55e213c8a8b24196b091abde2b89db52be0b2aaae3cfa","names":[],"sources":[]}, {"digest":"a43327a1739c3fa477f32981071fef7d8ba6ae5f32a84fd70f547b2eee59e93e","names":[],"sources":[]}, - {"digest":"a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302","names":[],"sources":["packages/api/session-controller/src/types.ts:400"]}, + {"digest":"a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302","names":[],"sources":["packages/api/session-controller/src/types.ts:392"]}, {"digest":"a6567ccb2e530606b775371eb4fa31468d72084339968e8b0440a516a23b39dc","names":[],"sources":[]}, {"digest":"a6b41f5bede8094d7bf635be5d69b1bd7a25e006ca9cf9415bceb9322f1a7feb","names":["packages/experimental/hook-protocol/src/types.ts#HookDialect"],"sources":["packages/experimental/hook-protocol/src/types.ts:48"]}, {"digest":"a6da9ad5d42ae83a6833a8288b076688e8e0801633ea36cbdd8a30a6d9f3160c","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowRunStartData"],"sources":["packages/workflow/tool-workflow/src/types.ts:14"]}, diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index 54f6107f2b..a8129d0f23 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -9,8 +9,8 @@ en: 6cc2cd9ced70bb09 zh: 1c0e6cb4ba2ed637 /tool-schema-catalog/tool-package-map: - en: 1bec3e5c70eae394 - zh: 922d507fa65ae319 + en: f96964e4cb922482 + zh: e3fcc1daf935ca29 /tool-schema-catalog/deepseek-ai-dsh-plugin-manager: en: e0143916bb634762 zh: e0143916bb634762 @@ -237,8 +237,17 @@ en: 927a5ac0974b7642 zh: 927a5ac0974b7642 /tool-schema-catalog/deepseek-ai-dsh-tool-skill/skill: - en: 9b159d5831855afb - zh: 275ee82af0e0f59a + en: c1124b6642c57712 + zh: ede0a9f1479b4ecd +/tool-schema-catalog/deepseek-ai-dsh-tool-session-list: + en: 6d68942100dd76e7 + zh: 6d68942100dd76e7 +/tool-schema-catalog/deepseek-ai-dsh-tool-session-list/list-session: + en: fa3ac1878f21c149 + zh: dfd5759772f99d13 +/tool-schema-catalog/deepseek-ai-dsh-tool-session-list/list-workspace: + en: 7b1f0bed364dfcd2 + zh: c907d8ff78f54268 /tool-schema-catalog/deepseek-ai-dsh-tool-session-query: en: eac1dff4b6d9e195 zh: eac1dff4b6d9e195 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index 16c42b6393..3d4070cdaf 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -40,6 +40,7 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tool-lsp` | `lsp` | `ctx.workingDirectory`, `ctx.tools`, `ctx.lsp`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | The lsp tool keeps provider selection and language-server subprocesses behind ctx.lsp, so its model-visible schema stays stable across providers. Requires a registered provider (e.g. `@deepseek-ai/dsh-lsp-stdio`) at runtime; without one, a query returns the structured `LSP_UNAVAILABLE` error rather than changing the schema. | | `@deepseek-ai/dsh-tool-ralph` | `ralph` | `ctx.tools`, `ctx.workflowEngine`, `ctx.subagents`, `ctx.systemPrompt`, `a calling Agent (exec.agent parents every fresh round)` | `tool/call`, `tool/result`, `workflow and child session events during execution` | - | A fixed foreground workflow starts one fresh structured child per round; the model selects only the immutable objective and an optional round cap. | | `@deepseek-ai/dsh-tool-skill` | `skill` | `ctx.workingDirectory`, `ctx.tools`, `ctx.agents`, `ctx.skills` | `tool/call`, `tool/result`, `user/message replacement catalogs via agent.inject()` | - | - | +| `@deepseek-ai/dsh-tool-session-list` | `list_session`, `list_workspace` | `ctx.tools`, `ctx.sessions`, `ctx.sessionQuery`, `ctx.workspaceRegistry`, `ctx.sessionProjections` | `tool/call`, `tool/result` | - | Opt-in access to all Workspace and Session list metadata in the mounted runtime. Cold titles and activity use the optional projection cache; absent values become null titles and creation-time recency. No Agent is activated. | | `@deepseek-ai/dsh-tool-session-query` | `session_event_read`, `session_event_search`, `session_event_trace`, `session_search`, `session_trace` | `ctx.tools`, `ctx.systemPrompt`, `ctx.sessionQuery`, `ctx.agents`, `a calling Agent for workspace authority` | `tool/call`, `tool/result` | - | The five read-only tools hide provider cursors and authorize every result from the immutable calling agent session. The package is opt-in; compositions that need enforced deadlines or bounded inline output also mount the generic timeout or spill policies. | | `@deepseek-ai/dsh-experimental-tool-subagent-oar` | `subagent_oar` | `ctx.tools`, `ctx.subagents` | `tool/call`, `tool/result`, `parent subagent catalog and completion notices` | - | The subagent_oar tool selects among configured aliases for external providers. This catalog shows Codex and Claude Code aliases; each deployment chooses its providers. Native model and permission settings belong to the selected provider configuration. | | `@deepseek-ai/dsh-tool-subagent` | `list_subagent_models`, `subagent` | `ctx.tools`, `ctx.subagents`, `ctx.systemPrompt`, `ctx.sessionProjections`, `ctx.llm for model discovery and selected-route validation` | `tool/call`, `tool/result`, `child session events through the chosen provider` | `subagent`, `subagent_fork` | The load-time `toolName` selects the delegation name (default `subagent`); `modelSelection` adds optional route fields. `modelDiscovery` defaults off and registers shared discovery on one instance per scope. Web and Desktop presets enable spawn discovery and route fields and leave `subagent_fork` route fields disabled. The Host settings service records authorization for each new top-level Session; child Sessions inherit it. Without a recorded policy, discovery and explicit selection permit only the current parent route. Every delegation returns the child's name promptly; local children accept follow-ups, while external backends report their single execution automatically. | @@ -1916,6 +1917,68 @@ Load the full instructions for a skill. Call it before acting on a task that nam Source: [`packages/skill/tool-skill/src/index.ts`](../packages/skill/tool-skill/src/index.ts) + + +## `@deepseek-ai/dsh-tool-session-list` + +### `list_session` + +List sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null. + +```json +{ + "type": "object", + "properties": { + "workspace_id": { + "type": "string", + "description": "Workspace ID from list_workspace. Includes its members and, when requested, subagents belonging through their nearest member ancestor. Omit to list all accessible sessions." + }, + "contain_subagent": { + "type": "boolean", + "description": "Include subagent sessions. Defaults to false." + }, + "archived": { + "type": "boolean", + "description": "Return only archived sessions when true, otherwise only unarchived sessions. Defaults to false." + }, + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } +} +``` + +Source: [`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) + +### `list_workspace` + +List workspaces in registry order, including empty workspaces. Returns IDs, titles, paths, and creation and update times. + +```json +{ + "type": "object", + "properties": { + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } +} +``` + +Source: [`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) + +Opt-in access to all Workspace and Session list metadata in the mounted runtime. Cold titles and activity use the optional projection cache; absent values become null titles and creation-time recency. No Agent is activated. + ## `@deepseek-ai/dsh-tool-session-query` diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index bf9a8255bb..4847ac26c1 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -44,6 +44,7 @@ | `@deepseek-ai/dsh-tool-lsp` | `lsp` | `ctx.workingDirectory`、`ctx.tools`、`ctx.lsp`、`ctx.systemPrompt` | `tool/call`、`tool/result` | - | lsp 工具将提供方选择和语言服务器子进程置于 ctx.lsp 之后,因此其模型可见 schema 在更换提供方时保持稳定。运行时要求已注册提供方,例如 `@deepseek-ai/dsh-lsp-stdio`;如果没有提供方,查询会返回结构化 `LSP_UNAVAILABLE` 错误,而不会改变 schema。 | | `@deepseek-ai/dsh-tool-ralph` | `ralph` | `ctx.tools`、`ctx.workflowEngine`、`ctx.subagents`、`ctx.systemPrompt`、`a calling Agent (exec.agent parents every fresh round)` | `tool/call`、`tool/result`、`workflow and child session events during execution` | - | 固定的前台工作流会在每个 Round 启动一个全新的结构化子级;模型只能选择不可变目标和可选的 Round 上限。 | | `@deepseek-ai/dsh-tool-skill` | `skill` | `ctx.workingDirectory`、`ctx.tools`、`ctx.agents`、`ctx.skills` | `tool/call`、`tool/result`、`user/message replacement catalogs via agent.inject()` | - | - | +| `@deepseek-ai/dsh-tool-session-list` | `list_session`、`list_workspace` | `ctx.tools`、`ctx.sessions`、`ctx.sessionQuery`、`ctx.workspaceRegistry`、`ctx.sessionProjections` | `tool/call`、`tool/result` | - | 选择启用后,可读取已挂载运行时中全部 Workspace 和 Session 的列表元数据。冷会话的标题和活动时间使用可选的投影缓存;值缺失时,标题为 null,最近活动时间取创建时间。不会激活 Agent。 | | `@deepseek-ai/dsh-tool-session-query` | `session_event_read`、`session_event_search`、`session_event_trace`、`session_search`、`session_trace` | `ctx.tools`、`ctx.systemPrompt`、`ctx.sessionQuery`、`a calling Agent for workspace authority` | `tool/call`、`tool/result` | - | 这 5 个只读工具会隐藏提供方游标,并根据不可变的调用 agent 会话为每个结果授权。该包需要选择启用;需要强制截止时间或限制行内输出的组合还会挂载通用超时或 spill 策略。 | | `@deepseek-ai/dsh-experimental-tool-subagent-oar` | `subagent_oar` | `ctx.tools`, `ctx.subagents` | `tool/call`, `tool/result`, `parent subagent catalog and completion notices` | - | subagent_oar 工具在为外部提供方配置的别名之间选择。本目录展示 Codex 和 Claude Code 别名;每个部署自行选择提供方。原生模型和权限设置由所选提供方的配置决定。 | | `@deepseek-ai/dsh-tool-subagent` | `list_subagent_models`、`subagent` | `ctx.tools`、`ctx.subagents`、`ctx.systemPrompt`、`ctx.sessionProjections`、`用于模型发现和所选路由校验的 ctx.llm` | `tool/call`、`tool/result`、`child session events through the chosen provider` | `subagent`、`subagent_fork` | 加载时的 `toolName` 选择委派名称(默认为 `subagent`);`modelSelection` 增加可选路由字段。`modelDiscovery` 默认关闭,每个作用域由一个实例注册共享发现工具。Web 与 Desktop preset 启用 spawn 发现和路由字段,并为 `subagent_fork` 保持路由字段关闭。Host 设置服务为每个新顶层 Session 记录授权;子 Session 继承该授权。没有已记录策略时,发现和显式选择只允许当前父级路由。每次委派都会立即返回子代理的名称;本地子代理接受后续消息,外部后端自动汇报单次执行结果。 | @@ -1922,6 +1923,68 @@ lsp 工具将提供方选择和语言服务器子进程置于 ctx.lsp 之后, 来源:[`packages/skill/tool-skill/src/index.ts`](../packages/skill/tool-skill/src/index.ts) + + +## `@deepseek-ai/dsh-tool-session-list` + +### `list_session` + +按最近人工提示词时间从新到旧列出会话,时间相同时按 ID 排列。返回 ID、可用标题以及 ISO 创建时间和更新时间。缺少活动元数据时使用创建时间;标题不可用时为 null。 + +```json +{ + "type": "object", + "properties": { + "workspace_id": { + "type": "string", + "description": "Workspace ID from list_workspace. Includes its members and, when requested, subagents belonging through their nearest member ancestor. Omit to list all accessible sessions." + }, + "contain_subagent": { + "type": "boolean", + "description": "Include subagent sessions. Defaults to false." + }, + "archived": { + "type": "boolean", + "description": "Return only archived sessions when true, otherwise only unarchived sessions. Defaults to false." + }, + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } +} +``` + +来源:[`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) + +### `list_workspace` + +按注册表顺序列出工作区,包括空工作区。返回 ID、标题、路径以及创建时间和更新时间。 + +```json +{ + "type": "object", + "properties": { + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } +} +``` + +来源:[`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) + +选择启用后,可读取已挂载运行时中全部 Workspace 和 Session 的列表元数据。冷会话的标题和活动时间使用可选的投影缓存;值缺失时,标题为 null,最近活动时间取创建时间。不会激活 Agent。 + ## `@deepseek-ai/dsh-tool-session-query` diff --git a/package.json b/package.json index 37b86b60d5..8a83bf1feb 100644 --- a/package.json +++ b/package.json @@ -307,6 +307,7 @@ "@deepseek-ai/dsh-experimental-forge": "workspace:*", "@deepseek-ai/dsh-experimental-forge-github": "workspace:*", "@deepseek-ai/dsh-experimental-forge-session": "workspace:*", - "@deepseek-ai/dsh-action-cards": "workspace:*" + "@deepseek-ai/dsh-action-cards": "workspace:*", + "@deepseek-ai/dsh-tool-session-list": "workspace:*" } } diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index 94482498be..d309647399 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1fdf707322fb6996 zh: 0204f7e9d4aa3cce /session-controller/use-this-package: - en: 50fa3dd0a2ce79c8 - zh: 88bd7ea6058d2122 + en: 179c281216ad0660 + zh: 81dbc1d8985ab21b /session-controller/client-references: en: e8979a803ec3e194 zh: c567efcd971728ba diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index f414ce78ef..12e9c840a0 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -43,7 +43,7 @@ Every Remote endpoint is access-controlled: a Peer whose principal is not the ow List rows carry `formatStatus` when available, so Clients can identify migration-required Sessions without requesting their projections. -Host list generation yields between complete rows only when its configured work slice is exhausted; cheap remaining work returns without a forced yield. Request cancellation is checked per row and after each yield and rejects without partial results. Each row is synchronous; the list does not promise one cross-Session snapshot. A Session already queued as cold remains a cached row if it attaches during a yield: Client in-flight mutation replay corrects its availability, and sequenced projections supersede cached hints. An attached Session's summary reads its blankness and last-prompt recency through the `sessionListMetadata` projection handle, and its projection hints carry every summary key computed through `snapshot`. The first summary of an attached Session computes these projections over its whole in-memory log, and later summaries advance them incrementally; this computation runs inside one synchronous row, so `listWorkSliceMs` cannot split it. +Host list generation yields between complete rows only when its configured work slice is exhausted; cheap remaining work returns without a forced yield. Request cancellation is checked per row and after each yield and rejects without partial results. Each row is synchronous; the list does not promise one cross-Session snapshot. A Session already queued as cold remains a cached row if it attaches during a yield: Client in-flight mutation replay corrects its availability, and sequenced projections supersede cached hints. An attached Session's summary reads its blankness and last-prompt recency through the [shared Session-list reader](../../session-query/session-query/README.md#shared-list-metadata), and its projection hints carry every summary key computed through `snapshot`. The first summary of an attached Session computes these projections over its whole in-memory log, and later summaries advance them incrementally; this computation runs inside one synchronous row, so `listWorkSliceMs` cannot split it. Client list rows and resident Sessions use the current `sessionListMetadata` projection to reject stale blank-session hints; recency is the later of the summary timestamp and the projected last user prompt. When SessionManager creates an instance before its list row arrives, it reconciles blankness with metadata already retained for that Session. An opened conversation is therefore not reused by New Session even when an older list response still marks it blank. diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index 2a83f4504d..1287e60744 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -43,7 +43,7 @@ Client journal 在发布 follow 快照、live entry 或历史页之前验证当 列表行在状态可用时携带 `formatStatus`,Client 无需请求其投影即可识别需要迁移的 Session。 -Host 仅在配置的工作时间片耗尽时,于完整条目之间让出事件循环;剩余工作较少时直接返回,不强制让出。每行及每次让出之后检查请求取消,取消时拒绝返回部分结果。每行同步计算;列表不承诺跨 Session 的统一快照。已经进入冷态队列的 Session 若在让出期间接入,仍返回缓存行:Client 对进行中请求的变更重放会纠正其可用性,带序号的投影会覆盖缓存提示。已接入 Session 的摘要通过 `sessionListMetadata` 投影句柄读取是否为空和最后一次提示词的最近活动时间,其投影提示携带通过 `snapshot` 计算的每个摘要 key。已接入 Session 的首次摘要在其完整内存日志上计算这些投影,之后的摘要增量推进;这次计算在单行的同步工作内进行,`listWorkSliceMs` 无法切分它。 +Host 仅在配置的工作时间片耗尽时,于完整条目之间让出事件循环;剩余工作较少时直接返回,不强制让出。每行及每次让出之后检查请求取消,取消时拒绝返回部分结果。每行同步计算;列表不承诺跨 Session 的统一快照。已经进入冷态队列的 Session 若在让出期间接入,仍返回缓存行:Client 对进行中请求的变更重放会纠正其可用性,带序号的投影会覆盖缓存提示。已接入 Session 的摘要通过[共享 Session 列表读取函数](../../session-query/session-query/README.zh.md#shared-list-metadata)读取是否为空和最后一次提示词的最近活动时间,其投影提示携带通过 `snapshot` 计算的每个摘要 key。已接入 Session 的首次摘要在其完整内存日志上计算这些投影,之后的摘要增量推进;这次计算在单行的同步工作内进行,`listWorkSliceMs` 无法切分它。 Client 列表行和驻留 Session 使用当前 `sessionListMetadata` 投影纠正过期的空白会话提示;最近活动时间取摘要时间戳与投影中最后一次用户提示词时间的较晚值。当 SessionManager 在列表行到达前创建实例时,会使用已保留的该 Session 元数据对账空白状态。因此,即使旧列表响应仍将已有对话标为空白,新会话操作也不会复用已经打开过的对话。 diff --git a/packages/api/session-controller/src/list.ts b/packages/api/session-controller/src/list.ts index 830ebe21a9..d2ff0d2a67 100644 --- a/packages/api/session-controller/src/list.ts +++ b/packages/api/session-controller/src/list.ts @@ -5,10 +5,10 @@ import { scheduler } from 'node:timers/promises' import type { Context } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-agent-preset-registry' import type { ImageAttachmentLimits } from '@deepseek-ai/dsh-attachment' -import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' -import type { ProjectionHandle, ProjectionSnapshot } from '@deepseek-ai/dsh-session-projection' +import type { Session, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' +import type { ProjectionSnapshot } from '@deepseek-ai/dsh-session-projection' import type {} from '@deepseek-ai/dsh-session-projection-cache' -import { SessionQueryError, type SessionRecord, type SessionSearchCursor } from '@deepseek-ai/dsh-session-query' +import { registerSessionListMetadata, SessionQueryError, type SessionRecord, type SessionSearchCursor } from '@deepseek-ai/dsh-session-query' import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' import { z } from 'zod' import { @@ -24,11 +24,6 @@ const SEARCH_PROVIDER_CALL_LIMIT = 100 const SESSION_SEARCH_QUERY_MAX_CHARS = 500 const MESSAGE_TYPES = new Set(['user/message', 'assistant/message']) -const sessionListMetadataSchema: z.ZodType = z.object({ - blank: z.boolean(), - lastPromptAt: z.number().nullable(), -}) - const imageLimitsSchema = z.object({ maxImageBytes: z.number().int().positive(), maxImagesPerMessage: z.number().int().positive(), @@ -38,25 +33,6 @@ const imageLimitsSchema = z.object({ mediaTypes: z.array(z.string()), }) as unknown as z.ZodType -/** - * Advance the Session-list metadata projection by one committed event. - * @param state - metadata before the event. - * @param event - next committed Session event. - * @returns the original or advanced metadata value. - */ -export function applySessionListMetadata( - state: SessionListMetadata, - event: SessionEvent, -): SessionListMetadata { - const blank = state.blank && event.type !== 'turn/start' - const lastPromptAt = event.type === 'user/message' && event.data.source.kind === 'user' - ? event.time - : state.lastPromptAt - return blank === state.blank && lastPromptAt === state.lastPromptAt - ? state - : { blank, lastPromptAt } -} - /** * Return the longest prefix containing at most `maximum` Unicode code points. * @param value - source text. @@ -76,7 +52,7 @@ export function truncateUnicodeCodePoints(value: string, maximum: number): strin /** Owns list projection registration, bounded cold summaries, and authorized search. */ export class ApiSessionList { - private listMetadata!: ProjectionHandle + private listMetadata!: (session: Session) => SessionListMetadata /** * @param ctx - Host context carrying Session, query, persistence, and projection services. @@ -89,14 +65,7 @@ export class ApiSessionList { * @returns when all required registrations are ready. */ async initialize(): Promise { - this.listMetadata = await this.ctx.sessionProjections.register<'sessionListMetadata', SessionListMetadata>({ - key: 'sessionListMetadata', - stateSchema: sessionListMetadataSchema, - init: () => ({ blank: true, lastPromptAt: null }), - apply: applySessionListMetadata, - wire: { viewSchema: sessionListMetadataSchema, view: state => state }, - stateVersion: 1, - }) + this.listMetadata = await registerSessionListMetadata(this.ctx) await this.ctx.sessionProjections.register<'imageLimits', null>({ key: 'imageLimits', stateSchema: z.null(), @@ -113,17 +82,17 @@ export class ApiSessionList { /** * Build one current attached-Session summary. - * Blankness and recency come from the `sessionListMetadata` handle; projection + * Blankness and recency come from the shared `sessionListMetadata` reader; projection * hints carry every summary key computed through `snapshot`. The first call * for a Session computes these projections over its whole in-memory log, and * later calls advance them incrementally. The handle read and the hint with - * the same key come from one cell; the handle read does not depend on any + * the same key come from one cell; the metadata read does not depend on any * other unit's view. * @param session - attached Session to summarize. * @returns current list metadata and available projections. */ summaryFor(session: Session): SessionSummary { - const metadata = this.listMetadata.stateOf(session) + const metadata = this.listMetadata(session) const projections = this.projectionsFor(session.header, session) return { sessionId: session.id, diff --git a/packages/api/session-controller/src/types.ts b/packages/api/session-controller/src/types.ts index 49cd7c0f9d..d0bea27576 100644 --- a/packages/api/session-controller/src/types.ts +++ b/packages/api/session-controller/src/types.ts @@ -14,12 +14,12 @@ import type { Principal } from '@deepseek-ai/dsh-typert-protocol' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' +export type { SessionListMetadata } from '@deepseek-ai/dsh-session-query/types' + declare module '@deepseek-ai/dsh-session-projection/types' { interface SessionProjectionMap { /** Eligible latest failed turn/end for an empty prompt, or null. */ conversationContinuation: SessionSeq | null - /** Persisted facts used to summarize a Session without activating it. */ - sessionListMetadata: SessionListMetadata /** * Image-intake limits enforced by the Session prompt endpoint. Boot * constant, excluded from Session summary payloads: every Session shares @@ -29,14 +29,6 @@ declare module '@deepseek-ai/dsh-session-projection/types' { } } -/** Persisted hints used to summarize a cold Session. */ -export interface SessionListMetadata { - /** Whether the folded prefix contains no turn. */ - readonly blank: boolean - /** Latest human-authored prompt time in the folded prefix. */ - readonly lastPromptAt: number | null -} - /** * Summary wire values a Session-list row carries. A `sequenced` block carries * every summary key computed at its `asOfSeq`; a `cached` block carries the diff --git a/packages/api/session-controller/tsconfig.client.json b/packages/api/session-controller/tsconfig.client.json index a1375420ca..6b64356246 100644 --- a/packages/api/session-controller/tsconfig.client.json +++ b/packages/api/session-controller/tsconfig.client.json @@ -23,6 +23,7 @@ { "path": "../../llm/llm" }, { "path": "../../session/session-projection" }, { "path": "../../session/session-title" }, + { "path": "../../session-query/session-query" }, { "path": "../../subagent/subagent" }, { "path": "../../util/brand" }, { "path": "../../util/crypto" }, diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md index 489d3c98ce..9651f13643 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -403,6 +403,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo |---|---|---| | `@deepseek-ai/dsh-session-log-export` | yes | Web Session-log ZIP export and Session Markdown copy | | `@deepseek-ai/dsh-session-query-sqlite` | yes | Concrete ctx.sessionQuery backend with SQLite FTS5 search | +| `@deepseek-ai/dsh-tool-session-list` | yes | Read-only paginated Workspace and Session metadata tools | ## settings diff --git a/packages/session-query/README.i18n.yaml b/packages/session-query/README.i18n.yaml index e391a1291c..6113794d2b 100644 --- a/packages/session-query/README.i18n.yaml +++ b/packages/session-query/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 /session-query-session-retrieval-capability-family/packages: - en: 03f48fd85e12934a - zh: 4fb3f345f5d91572 + en: 474c97ed08ca68c8 + zh: af8114e7219d8938 /session-query-session-retrieval-capability-family/related-documentation: en: aa03439fc68a285d zh: eb074a3318b92024 diff --git a/packages/session-query/README.md b/packages/session-query/README.md index 240076d95b..4e0b88decc 100644 --- a/packages/session-query/README.md +++ b/packages/session-query/README.md @@ -28,6 +28,7 @@ Each package README describes what you can do with its part of the family. |---|---|---| | [`session-query/`](session-query/README.md) | Unified session-history query service: exact reads, relationship traces, and filters | `ctx.sessionQuery` | | [`session-query-sqlite/`](session-query-sqlite/README.md) | Full-text search across session history backed by a SQLite FTS5 index | registers on `ctx.sessionQuery` | +| [`tool-session-list/`](tool-session-list/README.md) | Optional read-only Workspace and Session metadata tools | — | | [`session-log-export/`](session-log-export/README.md) | Web `/export` command and browser download of a session ZIP | `ctx.sessionLogDownload` (browser) | ----- diff --git a/packages/session-query/README.zh.md b/packages/session-query/README.zh.md index f443ff7ee4..3367b6271a 100644 --- a/packages/session-query/README.zh.md +++ b/packages/session-query/README.zh.md @@ -28,6 +28,7 @@ kind: "package-group" |---|---|---| | [`session-query/`](session-query/README.zh.md) | 统一的会话历史查询服务:精确读取、关系追踪与过滤 | `ctx.sessionQuery` | | [`session-query-sqlite/`](session-query-sqlite/README.zh.md) | 基于 SQLite FTS5 索引的会话历史全文搜索 | 注册到 `ctx.sessionQuery` | +| [`tool-session-list/`](tool-session-list/README.zh.md) | 可选的只读 Workspace 和 Session 元数据工具 | — | | [`session-log-export/`](session-log-export/README.zh.md) | Web `/export` 命令与浏览器下载会话 ZIP | `ctx.sessionLogDownload`(浏览器) | ----- diff --git a/packages/session-query/session-query/README.i18n.yaml b/packages/session-query/session-query/README.i18n.yaml index 9928994e13..8e8ae5bcfd 100644 --- a/packages/session-query/session-query/README.i18n.yaml +++ b/packages/session-query/session-query/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-session-query/use-this-package: - en: cc9eb8f214c57137 - zh: 76723633d0faee5d + en: dfc90afac9ef47be + zh: 0a5aa60a34f24e61 /deepseek-ai-dsh-session-query/use-this-package/what-you-can-do: en: 608cd6d4c5cf2c35 zh: 23d3c5a7374b5283 @@ -36,11 +36,14 @@ en: b34fb0d209192ff4 zh: 455bdb024d04f16a /deepseek-ai-dsh-session-query/understand-the-implementation/source-map: - en: c58f4f086e3d0728 - zh: 7d66b688c7f54c87 + en: 58964ca2cde96c32 + zh: 9699c328cefc9f09 /deepseek-ai-dsh-session-query/understand-the-implementation/corpus-resolution: - en: efa560c55a869c71 - zh: 451eb107825856ac + en: 4dde9107d05de6ee + zh: 8c775eb7630e659a +/deepseek-ai-dsh-session-query/understand-the-implementation/shared-list-metadata: + en: 30d9af561283c382 + zh: bc8ceabe718239bf /deepseek-ai-dsh-session-query/understand-the-implementation/observation-cache: en: 16d4a29af5b2ac07 zh: 7ec4a91f97697d2e diff --git a/packages/session-query/session-query/README.md b/packages/session-query/session-query/README.md index 6110432284..af901c891d 100644 --- a/packages/session-query/session-query/README.md +++ b/packages/session-query/session-query/README.md @@ -25,7 +25,7 @@ English | [中文](README.zh.md) ## Use this package -Use `ctx.sessionQuery` from application code when you need to read or search session history without touching the session service or a storage backend directly. The service is provided by a concrete backend plugin — the shipped composition mounts `@deepseek-ai/dsh-session-query-sqlite` ([README](../session-query-sqlite/README.md)) — so this package is never mounted alone. Everything below is available on `ctx.sessionQuery` once a backend is composed. +Use `ctx.sessionQuery` from application code when you need to read or search session history without touching the session service or a storage backend directly. The service is provided by a concrete backend plugin — the shipped composition mounts `@deepseek-ai/dsh-session-query-sqlite` ([README](../session-query-sqlite/README.md)) — so this package is never mounted alone. The query operations below are available on `ctx.sessionQuery` once a backend is composed. ### What you can do @@ -92,6 +92,7 @@ The decision history lives in the [unified service decision](../../../.agents/no | [`src/index.ts`](src/index.ts) | Service definition: the abstract `SessionQueryEngine`, concrete reads, config validation | | [`src/corpus.ts`](src/corpus.ts) | Live-preferred corpus resolution, optional persistence binding, batch projections | | [`src/observation.ts`](src/observation.ts) | Live-preferred point observations with a bounded revision-keyed prepared-Session cache | +| [`src/list-metadata.ts`](src/list-metadata.ts) | Shared blankness and human-prompt recency projection registration | | [`src/cold-read.ts`](src/cold-read.ts) | Handle-based cold log read with in-memory interrupted-turn closers | | [`src/types.ts`](src/types.ts) | Public records, filters, requests, and page types | | [`src/config.ts`](src/config.ts) | Inherited config and the closed `SessionQueryError` taxonomy | @@ -105,6 +106,11 @@ The decision history lives in the [unified service decision](../../../.agents/no `SessionCorpus` binds optional `ctx.sessionPersistence` through a fiber and resolves each read live-first: a known live target is snapshotted without consulting persistence; otherwise the session is listed, read completely through a short-lived read handle, and re-checked for a live attachment before cloning. A cold log whose writer crashed mid-turn is balanced in memory with `interruptedTurnClosers` — persistence is never mutated by a read. Header compatibility is asserted between listed and loaded observations. Batch title reads run one metadata listing and bounded-concurrency reads, isolating per-session failures while cancellation rejects the whole batch. + +### Shared list metadata + +`registerSessionListMetadata(ctx)` acquires the shared projection for Session blankness and the latest human-authored prompt time, and returns a synchronous reader for prepared live Sessions. The Session API and optional [listing tools](../tool-session-list/README.md) share one projection unit; disposing a consumer releases only its own reference. Registration requires `sessionProjections`, independently of the query service's header-only `listSessions()` operation. + ### Observation cache `observeSession` builds point observations without a listing preflight. A live observation fixes its cut as the current log length and materializes `events` on first read, so header-, cursor-, or projection-only consumers never copy the log; the log only appends, so a late first read still yields exactly that prefix. The cold path stats the stored session first and consults its own bounded cache keyed by the persistence instance and the `stat` revision: an unchanged revision reuses the restored unpublished Session without re-reading the log; a changed revision, or a replaced persistence instance, reloads through the handle seam and replaces the entry. The cache holds `preparedSessionCacheSize` entries with least-recently-used eviction, entries pinned by active observation leases are never evicted, and a session that goes live mid-read retries the live path. diff --git a/packages/session-query/session-query/README.zh.md b/packages/session-query/session-query/README.zh.md index 3c9bfb329a..c65fc09154 100644 --- a/packages/session-query/session-query/README.zh.md +++ b/packages/session-query/session-query/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -当你需要读取或搜索会话历史、而不直接触碰会话服务或存储后端时,从应用代码使用 `ctx.sessionQuery`。该服务由具体后端插件提供——已发布组合挂载 `@deepseek-ai/dsh-session-query-sqlite`([README](../session-query-sqlite/README.zh.md))——因此本包从不单独挂载。一旦组合了后端,以下全部能力都可在 `ctx.sessionQuery` 上使用。 +当你需要读取或搜索会话历史、而不直接触碰会话服务或存储后端时,从应用代码使用 `ctx.sessionQuery`。该服务由具体后端插件提供——已发布组合挂载 `@deepseek-ai/dsh-session-query-sqlite`([README](../session-query-sqlite/README.zh.md))——因此本包从不单独挂载。一旦组合了后端,以下查询操作都可在 `ctx.sessionQuery` 上使用。 ### 你可以做什么 @@ -92,6 +92,7 @@ kind: "package-reference" | [`src/index.ts`](src/index.ts) | 服务定义:抽象 `SessionQueryEngine`、具体读取、配置校验 | | [`src/corpus.ts`](src/corpus.ts) | 实时优先的语料库解析、可选持久化绑定、批量投影 | | [`src/observation.ts`](src/observation.ts) | 实时优先的定点观察,带按修订键控的有界 prepared-Session 缓存 | +| [`src/list-metadata.ts`](src/list-metadata.ts) | 共享的空白状态与人工提示词活动时间投影注册 | | [`src/cold-read.ts`](src/cold-read.ts) | 基于句柄的冷日志读取,附内存中的中断轮次闭合事件 | | [`src/types.ts`](src/types.ts) | 公共记录、过滤器、请求与分页类型 | | [`src/config.ts`](src/config.ts) | 继承配置与封闭的 `SessionQueryError` 分类体系 | @@ -105,6 +106,11 @@ kind: "package-reference" `SessionCorpus` 通过 fiber 绑定可选的 `ctx.sessionPersistence`,并实时优先解析每次读取:已知实时目标直接快照,不查询持久化;否则先列出会话,再通过短生命周期的读取句柄完整读出日志,并在克隆前重新检查是否出现实时挂载。写入者在轮次中途崩溃的冷日志用 `interruptedTurnClosers` 在内存中补齐——读取从不修改持久化。列表与加载观察之间会断言 header 兼容性。批量标题读取执行一次元数据列表与有界并发读取,把逐会话失败隔离,而取消会拒绝整个批次。 + +### 共享列表元数据 + +`registerSessionListMetadata(ctx)` 获取 Session 空白状态与最近人工提示词时间的共享投影,并返回准备就绪的实时 Session 的同步读取函数。Session API 与可选的[列表工具](../tool-session-list/README.zh.md)共享同一个投影单元;释放消费方时只移除它自己的引用。注册需要 `sessionProjections`,独立于查询服务仅读取 header 的 `listSessions()` 操作。 + ### 观察缓存 `observeSession` 不经过列表预检直接构建定点观察。实时观察以当前日志长度固定 cut,并在首次读取时才物化 `events`,因此只需要 header、cursor 或 projection 的消费者永远不会复制日志;日志只会追加,所以延后的首次读取得到的仍然正好是该前缀。冷路径先对存储会话执行 `stat`,再查询自有的有界缓存,缓存键为持久化实例加 `stat` 修订:修订未变则复用已恢复的未发布 Session,不再重读日志;修订变化或持久化实例被替换则经句柄 seam 重新加载并替换条目。缓存保留 `preparedSessionCacheSize` 个条目并按最久未用淘汰,被活跃观察租约钉住的条目从不被淘汰;读取中途转为实时的会话会重试实时路径。 diff --git a/packages/session-query/session-query/package.json b/packages/session-query/session-query/package.json index 62e97be451..7ab415b45b 100644 --- a/packages/session-query/session-query/package.json +++ b/packages/session-query/session-query/package.json @@ -18,11 +18,16 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./types": { + "types": "./lib/types/types.d.ts", + "default": "./lib/types/types.js" + }, "./src/*": "./src/*", "./package.json": "./package.json" }, "files": [ "lib/index.js", + "lib/types/**/*.js", "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "lib/**/*.js.map", @@ -63,6 +68,7 @@ "@deepseek-ai/cordis": "workspace:~" }, "dependencies": { - "@deepseek-ai/dsh-session-format-catalog": "workspace:*" + "@deepseek-ai/dsh-session-format-catalog": "workspace:*", + "zod": "4.6.6" } } diff --git a/packages/session-query/session-query/src/index.ts b/packages/session-query/session-query/src/index.ts index dfb11fec65..62dcbcc337 100644 --- a/packages/session-query/session-query/src/index.ts +++ b/packages/session-query/session-query/src/index.ts @@ -60,6 +60,7 @@ import { import * as tracing from './tracing.ts' export type * from './types.ts' +export { registerSessionListMetadata } from './list-metadata.ts' export { SessionSearchCursor } from './cursor.ts' export type { Config, SessionQueryErrorCode } from './config.ts' export { diff --git a/packages/session-query/session-query/src/list-metadata.ts b/packages/session-query/session-query/src/list-metadata.ts new file mode 100644 index 0000000000..46d77244fe --- /dev/null +++ b/packages/session-query/session-query/src/list-metadata.ts @@ -0,0 +1,48 @@ +/** Shared Session-list projection ownership for API and model-tool readers. */ + +import type { Context } from '@deepseek-ai/cordis' +import type { Session, SessionEvent } from '@deepseek-ai/dsh-session' +import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' +import { z } from 'zod' +import type { SessionListMetadata } from './types.ts' + +const sessionListMetadataSchema: z.ZodType = z.object({ + blank: z.boolean(), + lastPromptAt: z.number().nullable(), +}) + +/** Advance blankness and human-prompt recency without retaining history. */ +function applySessionListMetadata( + state: SessionListMetadata, + event: SessionEvent, +): SessionListMetadata { + const blank = state.blank && event.type !== 'turn/start' + const lastPromptAt = event.type === 'user/message' && event.data.source.kind === 'user' + ? event.time + : state.lastPromptAt + return blank === state.blank && lastPromptAt === state.lastPromptAt + ? state + : { blank, lastPromptAt } +} + +const sessionListMetadataDefinition = { + key: 'sessionListMetadata', + stateSchema: sessionListMetadataSchema, + init: () => ({ blank: true, lastPromptAt: null }), + apply: applySessionListMetadata, + wire: { viewSchema: sessionListMetadataSchema, view: state => state }, + stateVersion: 1, +} satisfies ProjectionDefinition<'sessionListMetadata', SessionListMetadata> + +/** + * Acquire the shared Session-list unit on the caller's fiber. + * Concurrent callers share one projection; disposal releases only the caller's reference. + * @param ctx - owner context with the required projection registry. + * @returns a synchronous domain reader ready for prepared live Sessions. + */ +export async function registerSessionListMetadata( + ctx: Context, +): Promise<(session: Session) => SessionListMetadata> { + const handle = await ctx.sessionProjections.register(sessionListMetadataDefinition) + return session => handle.stateOf(session) +} diff --git a/packages/session-query/session-query/src/types.ts b/packages/session-query/session-query/src/types.ts index cca5b2283e..8be1b4bfc6 100644 --- a/packages/session-query/session-query/src/types.ts +++ b/packages/session-query/session-query/src/types.ts @@ -14,12 +14,27 @@ import type { SessionSeq, OptionalSessionSeq, SurfaceEvent, -} from '@deepseek-ai/dsh-session' -import type { SessionTitleSnapshot } from '@deepseek-ai/dsh-session-title' +} from '@deepseek-ai/dsh-session/types' +import type { SessionTitleSnapshot } from '@deepseek-ai/dsh-session-title/types' import type { SessionSearchCursor } from './cursor.ts' export type { SessionSearchCursor } from './cursor.ts' +declare module '@deepseek-ai/dsh-session-projection/types' { + interface SessionProjectionMap { + /** Persisted facts used to summarize a Session without activating it. */ + sessionListMetadata: SessionListMetadata + } +} + +/** Persisted hints used to summarize a cold Session. */ +export interface SessionListMetadata { + /** Whether the folded prefix contains no turn. */ + readonly blank: boolean + /** Latest human-authored prompt time in the folded prefix. */ + readonly lastPromptAt: number | null +} + /** Whether an event is current model context, replaced context, or raw-log-only. */ export type SessionEventSurface = 'current' | 'shadowed' | 'log-only' diff --git a/packages/session-query/session-query/tests/list-metadata.spec.ts b/packages/session-query/session-query/tests/list-metadata.spec.ts new file mode 100644 index 0000000000..96fd8bf536 --- /dev/null +++ b/packages/session-query/session-query/tests/list-metadata.spec.ts @@ -0,0 +1,84 @@ +/** Shared list metadata keeps its values and lifetime across independent consumers. */ + +import { Context } from '@deepseek-ai/cordis' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import SessionStore from '@deepseek-ai/dsh-session' +import type { Session } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import { registerSessionListMetadata } from '../src/list-metadata.ts' + +async function setup() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + return ctx +} + +function prompt(session: Session) { + return session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Continue the task.' }], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }) +} + +describe('shared Session-list metadata', () => { + it('tracks human prompts and turns while preserving unchanged state references', async () => { + const ctx = await setup() + const read = await registerSessionListMetadata(ctx) + const session = ctx.sessions.create() + const initial = read(session) + expect(initial).toEqual({ blank: true, lastPromptAt: null }) + + session.append('session/title', { title: 'Task', messageSeqs: [], source: { kind: 'user' } }) + expect(read(session)).toBe(initial) + const first = prompt(session) + expect(read(session)).toEqual({ blank: true, lastPromptAt: first.time }) + session.append('turn/start', { turn: 1 }) + const active = read(session) + expect(active).toEqual({ blank: false, lastPromptAt: first.time }) + session.append('turn/start', { turn: 2 }) + expect(read(session)).toBe(active) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Context refresh.' }], + source: { kind: 'system-prompt' }, + }), { surfaceOp: 'append' }) + expect(read(session)).toBe(active) + const latest = prompt(session) + expect(read(session)).toEqual({ blank: false, lastPromptAt: latest.time }) + expect(ctx.sessionProjections.snapshot(session).values.sessionListMetadata).toEqual(read(session)) + expect(ctx.sessionProjections.checkpoint(session).sessionListMetadata?.ver).toBe(1) + }) + + it('shares one cell and notification across owners until the last owner unloads', async () => { + const ctx = await setup() + const first = await ctx.plugin(Object.assign(function firstOwner() {}, { inject: ['sessionProjections'] })) + const second = await ctx.plugin(Object.assign(function secondOwner() {}, { inject: ['sessionProjections'] })) + const firstRead = await registerSessionListMetadata(first.ctx) + const secondRead = await registerSessionListMetadata(second.ctx) + const session = ctx.sessions.create() + expect(firstRead(session)).toBe(secondRead(session)) + const changed = vi.fn() + ctx.sessionProjections.onChanged(changed) + session.append('turn/start', { turn: 1 }) + expect(changed).toHaveBeenCalledOnce() + expect(firstRead(session)).toBe(secondRead(session)) + + await first.dispose() + const event = prompt(session) + expect(secondRead(session)).toEqual({ blank: false, lastPromptAt: event.time }) + expect(ctx.sessionProjections.snapshot(session).values.sessionListMetadata).toEqual(secondRead(session)) + await second.dispose() + expect(ctx.sessionProjections.snapshot(session).values).not.toHaveProperty('sessionListMetadata') + }) + + it('folds existing live history when the first consumer registers', async () => { + const ctx = await setup() + const session = ctx.sessions.create() + session.append('turn/start', { turn: 1 }) + const event = prompt(session) + const read = await registerSessionListMetadata(ctx) + expect(read(session)).toEqual({ blank: false, lastPromptAt: event.time }) + }) +}) diff --git a/packages/session-query/tool-session-list/README.i18n.yaml b/packages/session-query/tool-session-list/README.i18n.yaml new file mode 100644 index 0000000000..a44227e3d0 --- /dev/null +++ b/packages/session-query/tool-session-list/README.i18n.yaml @@ -0,0 +1,55 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session-query/tool-session-list/README.md +/: + en: 3475319e48226347 + zh: 68361c3ff00d966f +/deepseek-ai-dsh-tool-session-list: + en: 963f03d1ba483ea9 + zh: 4809b66477752fe9 +/deepseek-ai-dsh-tool-session-list/summary: + en: c643c299cff0602e + zh: a4e0d8d3cb039859 +/deepseek-ai-dsh-tool-session-list/table-of-contents: + en: d152484eb41ac6b4 + zh: 5acc0d3807846b6e +/deepseek-ai-dsh-tool-session-list/use-this-package: + en: 653ca12bb7c76f9d + zh: 4dc851c44aa30eb1 +/deepseek-ai-dsh-tool-session-list/use-this-package/access-and-composition: + en: efa812b2b38914ae + zh: 4d44617966d00378 +/deepseek-ai-dsh-tool-session-list/use-this-package/listing-behavior: + en: 9170312b97f617fb + zh: 0e7a397ea03d6695 +/deepseek-ai-dsh-tool-session-list/use-this-package/failures: + en: be4dd03d3877e2ed + zh: 27c38df3c449dde9 +/deepseek-ai-dsh-tool-session-list/understand-the-implementation: + en: a9a0e5d116579be4 + zh: 1b78e7f73b639f85 +/deepseek-ai-dsh-tool-session-list/further-exploration: + en: 2a147ada18753beb + zh: d9aa75491c8fc0b7 +/deepseek-ai-dsh-tool-session-list/model-experience: + en: 215e7ba838619b7b + zh: a311da3843709f90 +/deepseek-ai-dsh-tool-session-list/model-experience/tool-schemas-and-results: + en: cadc497841430a21 + zh: af4cc374d7d16917 +/deepseek-ai-dsh-tool-session-list/model-experience/tool-schemas-and-results/what-the-model-sees: + en: 6ffb21f59acadc4e + zh: 258cded3677be923 +/deepseek-ai-dsh-tool-session-list/model-experience/tool-schemas-and-results/token-effect: + en: e699317cafee83d9 + zh: 912c0ce1a9f3957f +/deepseek-ai-dsh-tool-session-list/model-experience/tool-schemas-and-results/kv-cache-effect: + en: 0e201fbbe37798d8 + zh: fd4bd41e7393c234 +/deepseek-ai-dsh-tool-session-list/known-limitations-and-deferred-work: + en: 103c746911f87efd + zh: 58f101c6b129c9e8 +/deepseek-ai-dsh-tool-session-list/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: e88aeb617ffb74ea diff --git a/packages/session-query/tool-session-list/README.md b/packages/session-query/tool-session-list/README.md new file mode 100644 index 0000000000..c45163b510 --- /dev/null +++ b/packages/session-query/tool-session-list/README.md @@ -0,0 +1,128 @@ +--- +description: "List Workspace and Session metadata through optional read-only tools, with pagination and cached titles and activity times." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-tool-session-list + +English | [中文](README.zh.md) + +## Summary + +Discover workspaces and sessions without resuming an agent or reading cold conversation logs. List empty workspaces, find sessions in a workspace, or include subagents and archived sessions. Results contain identifiers and lightweight metadata, with bounded page sizes. Enable these tools when callers may inspect the metadata of the whole mounted runtime. + +## 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 + +Mount this optional plugin where the intended callers receive tools. It is absent from the default profiles. + +### Access and composition + +Granting these tools grants read access to every Workspace and Session in the mounted runtime. Tool availability is the access control; there is no per-agent Workspace ACL or implicit restriction to the caller's working directory. LiveShare's tool allowlist does not include these tools. + +The plugin requires `tools`, `sessions`, `sessionQuery`, `workspaceRegistry`, and `sessionProjections`. A projection cache supplies metadata for cold sessions; without it, cold rows use the documented missing-metadata values. In a headless profile, the base bundle supplies the other dependencies; add the Workspace registry and this plugin in a profile patch: + +```yaml +- insert: + - id: workspace-registry + name: '@deepseek-ai/dsh-workspace' + - id: tool-session-list + name: '@deepseek-ai/dsh-tool-session-list' +``` + +| Field | Default | Meaning | +|---|---|---| +| `listWorkSliceMs` | `16` | Positive safe integer work slice in milliseconds for Session metadata reads; checked between complete rows | + +When the composition already mounts `workspaceRegistry`, add only the tool row. Workspace initialization follows the [registry's existing history bootstrap](../../workspace/workspace/README.md); listing calls do not create or attach sessions or change registry records. + +### Listing behavior + +Both tools return an array directly. The [tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-tool-session-list) defines arguments. Pagination follows filtering and ordering; each call defaults to 20 entries, accepts at most 100, and starts at offset zero. Increase the offset by the number of returned entries to continue; an empty array ends the traversal. + +`list_workspace` preserves registry order and includes workspaces with no sessions. `list_session` includes unarchived ordinary sessions by default, including sessions outside every Workspace when no `workspace_id` is supplied. Explicit Workspace selection uses recorded membership, not a matching working directory. With subagents included, a directly assigned Workspace wins; otherwise the nearest recorded member ancestor determines membership. Ordinary forked sessions do not inherit membership through their parents. Archival matches each Session's own ID, independently of its ancestors. + +Session order is descending `updated_at`, then ascending Session ID for ties. Activity time is the later of creation and the latest human-authored prompt; assistant activity and title changes do not advance it. Titles come from live projections or persisted projection metadata. Unavailable titles are `null`, and unavailable activity metadata falls back to creation time. Timestamps are ISO 8601 strings. Pin order and manual sidebar order do not affect the results. + +Session metadata reads yield between complete rows when the configured work slice expires and check cancellation before continuing. The slice is not a hard latency bound: it cannot split one synchronous row, query enumeration, or final sorting. The list does not promise one snapshot across all Sessions. + +### Failures + +Invalid pagination and an unknown `workspace_id` fail with `ToolArgsError` (`INVALID_ARGS`); use `list_workspace` to find a registered ID. Query and storage failures fail the call, and cyclic subagent ancestry encountered during Workspace selection fails with `SESSION_QUERY_INVALID_LINEAGE`. Cancellation returns no partial result. These failures leave sessions and Workspace records untouched. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +The tools combine the existing header-only query listing with Workspace membership and projected metadata. The shared `registerSessionListMetadata` helper acquires the same projection unit used by the Session API; each consumer releases its own registration when disposed. The title projection remains owned by `dsh-session-title`. Cold rows read the projection cache without opening the underlying log, including on a cache miss. No Session Controller or Agent activation is required. + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | Tool schemas, registration, JSON result rendering, and generic tool cards | +| [`src/list.ts`](src/list.ts) | Pagination, membership selection, and live or cached metadata reads | + +
+ +----- + + +## Further Exploration + +- [Workspace registry](../../workspace/workspace/README.md) — recorded membership, registry order, and archival. +- [Session query](../session-query/README.md) — header enumeration and the shared list metadata reader. +- [Session projection cache](../../session/session-projection-cache/README.md) — persisted metadata and cache availability. +- [Session query package map](../README.md) — adjacent retrieval capabilities. + +----- + + +## Model Experience + +### Tool schemas and results + +#### What the model sees + +The [tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-tool-session-list) owns the `list_workspace` and `list_session` schemas. Each result renders as a JSON array. The plugin adds no separate system-prompt section. + +#### Token effect + +Available tool schemas contribute request tokens; each invocation adds its arguments and returned metadata. The page limit bounds the number of returned entries, while title and path lengths still affect result size. + +#### KV Cache effect + +The schemas remain stable while tool availability is unchanged. Calls append ordinary tool call and result history without replacing prior messages; enabling or disabling the tools changes the schema prefix. + +## Known Limitations and Deferred Work + + + +These constraints affect consumers of the lists. + +- **Cold metadata can be missing or stale** — listing never rebuilds it by reading the full log. A `null` title can mean either no title or unavailable title metadata. +- **Pagination is not a stable snapshot** — concurrent registry or Session changes can move entries between calls. Session listing enumerates candidates before selecting a page, so the page size does not bound total scan work. +- **Metadata access is runtime-wide** — callers needing per-agent Workspace authorization require a separately defined access policy before these tools are enabled for them. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/session-query/tool-session-list/README.zh.md b/packages/session-query/tool-session-list/README.zh.md new file mode 100644 index 0000000000..54049b9d57 --- /dev/null +++ b/packages/session-query/tool-session-list/README.zh.md @@ -0,0 +1,128 @@ +--- +description: "通过可选的只读工具列出 Workspace 和 Session 元数据,支持分页以及缓存中的标题和活动时间。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-tool-session-list + +[English](README.md) | 中文 + +## 概述 + +无需恢复 agent(智能体)运行或读取冷会话的日志,即可发现工作区和会话。可以列出空工作区、查找某工作区中的会话,或包含 subagent 和已归档会话。结果包含标识符及轻量元数据,并限制每页条目数。当调用者可以查看整个已挂载运行时的元数据时,启用这些工具。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与待办工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +在预期调用者获取工具的作用域中挂载此可选插件。默认配置方案不包含它。 + +### 访问范围与组合 + +授予这些工具即授予读取已挂载运行时中全部 Workspace 和 Session 的权限。工具可用性就是访问控制;没有逐 agent 的 Workspace ACL,也不会隐式限制到调用者的工作目录。LiveShare 的工具允许列表不包含这些工具。 + +插件需要 `tools`、`sessions`、`sessionQuery`、`workspaceRegistry` 和 `sessionProjections`。投影缓存为冷会话提供元数据;没有缓存时,冷条目使用下文规定的元数据缺失值。在 headless 配置方案中,基础 bundle 已提供其他依赖;在配置方案补丁中添加 Workspace 注册表和此插件: + +```yaml +- insert: + - id: workspace-registry + name: '@deepseek-ai/dsh-workspace' + - id: tool-session-list + name: '@deepseek-ai/dsh-tool-session-list' +``` + +| 字段 | 默认值 | 含义 | +|---|---|---| +| `listWorkSliceMs` | `16` | Session 元数据读取的工作时间片,单位为毫秒,必须是正安全整数;在完整条目之间检查 | + +如果组合已经挂载 `workspaceRegistry`,只添加工具条目。Workspace 初始化遵循[注册表现有的历史引导行为](../../workspace/workspace/README.zh.md);列表调用不会创建或接入会话,也不会修改注册表记录。 + +### 列表行为 + +两个工具都直接返回数组。[工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-session-list)定义参数。先过滤和排序,再分页;每次调用默认返回 20 条,最多接受 100 条,起始偏移为零。继续遍历时,将偏移增加已返回的条目数;空数组表示遍历结束。 + +`list_workspace` 保留注册表顺序,并包含没有会话的工作区。`list_session` 默认包含未归档的普通会话;没有指定 `workspace_id` 时,也包含不属于任何 Workspace 的会话。显式选择 Workspace 时使用已记录的成员关系,而非相同的工作目录。包含 subagent 时,直接分配的 Workspace 优先;否则由最近的已记录成员祖先确定归属。普通 fork 会话不会通过父级继承成员关系。归档筛选匹配每个 Session 自身的 ID,与祖先无关。 + +会话按 `updated_at` 降序排列,时间相同则按 Session ID 升序排列。活动时间取创建时间与最近人工提示词时间的较晚值;助手活动和标题变化不会推进它。标题来自实时投影或持久化投影元数据。标题不可用时为 `null`,活动元数据不可用时回退到创建时间。时间戳使用 ISO 8601 字符串。置顶顺序和侧边栏手动顺序不影响结果。 + +Session 元数据读取在配置的工作时间片耗尽时,于完整条目之间让出执行,并在继续前检查取消。时间片不是严格的延迟上限:它无法切分单条同步读取、查询枚举或最终排序。列表不承诺所有 Session 共享同一个快照。 + +### 失败 + +无效分页参数或未知的 `workspace_id` 以 `ToolArgsError`(`INVALID_ARGS`)失败;使用 `list_workspace` 查找已注册的 ID。查询和存储故障使调用失败,按 Workspace 筛选时遇到循环的 subagent 祖先关系则以 `SESSION_QUERY_INVALID_LINEAGE` 失败。取消不返回部分结果。这些失败不会修改会话或 Workspace 记录。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +工具将现有的仅 header 查询列表与 Workspace 成员关系及投影元数据结合。共享的 `registerSessionListMetadata` 辅助函数获取 Session API 使用的同一个投影单元;每个消费方在释放时只移除自己的注册。标题投影仍由 `dsh-session-title` 拥有。冷条目读取投影缓存,不打开底层日志,缓存未命中时也一样。不需要 Session 控制器,也不会激活 agent。 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | 工具 schema、注册、JSON 结果渲染与通用工具卡片 | +| [`src/list.ts`](src/list.ts) | 分页、成员筛选以及实时或缓存元数据读取 | + +
+ +----- + + +## 进一步探索 + +- [Workspace 注册表](../../workspace/workspace/README.zh.md)——已记录的成员关系、注册表顺序与归档。 +- [Session 查询](../session-query/README.zh.md)——header 枚举与共享列表元数据读取函数。 +- [Session 投影缓存](../../session/session-projection-cache/README.zh.md)——持久化元数据与缓存可用性。 +- [Session 查询包映射](../README.zh.md)——相邻的检索能力。 + +----- + + +## 模型体验 + +### 工具 schema 与结果 + +#### 模型可见内容 + +[工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-session-list)拥有 `list_workspace` 和 `list_session` 的 schema。每个结果渲染为 JSON 数组。插件不增加独立的系统提示词段落。 + +#### Token 影响 + +可用工具的 schema 占用请求 token;每次调用增加其参数和返回的元数据。每页上限限制返回的条目数,标题和路径长度仍会影响结果大小。 + +#### KV Cache 影响 + +工具可用性不变时,schema 保持稳定。调用追加普通工具调用与结果历史,不替换之前的消息;启用或禁用工具会改变 schema 前缀。 + +## 已知限制与待办工作 + + + +以下约束影响列表消费方。 + +- **冷元数据可能缺失或过期**——列表不会通过读取完整日志重建它。标题为 `null` 可能表示没有标题,也可能表示标题元数据不可用。 +- **分页不是稳定快照**——并发的注册表或 Session 变化可能让条目在多次调用间移动。会话列表先枚举候选项,再选取一页,因此每页大小不限制总扫描工作量。 +- **元数据访问覆盖整个运行时**——需要逐 agent Workspace 授权的调用者,必须先定义独立的访问策略,再为其启用这些工具。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +无。 + +
diff --git a/packages/session-query/tool-session-list/locale/de.json b/packages/session-query/tool-session-list/locale/de.json new file mode 100644 index 0000000000..ef94863e4f --- /dev/null +++ b/packages/session-query/tool-session-list/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Werkzeuge zur Sitzungsauflistung", + "description": "Listet Arbeitsbereiche und Sitzungen auf, ohne Agenten fortzusetzen." + } +} diff --git a/packages/session-query/tool-session-list/locale/en.json b/packages/session-query/tool-session-list/locale/en.json new file mode 100644 index 0000000000..8b3e1ef64a --- /dev/null +++ b/packages/session-query/tool-session-list/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Session listing tools", + "description": "List workspaces and sessions without resuming agents." + } +} diff --git a/packages/session-query/tool-session-list/locale/es.json b/packages/session-query/tool-session-list/locale/es.json new file mode 100644 index 0000000000..985fd3aff1 --- /dev/null +++ b/packages/session-query/tool-session-list/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Herramientas de listado de sesiones", + "description": "Lista espacios de trabajo y sesiones sin reanudar los agentes." + } +} diff --git a/packages/session-query/tool-session-list/locale/fr.json b/packages/session-query/tool-session-list/locale/fr.json new file mode 100644 index 0000000000..7e6ec40d8d --- /dev/null +++ b/packages/session-query/tool-session-list/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Outils de liste des sessions", + "description": "Liste les espaces de travail et les sessions sans relancer les agents." + } +} diff --git a/packages/session-query/tool-session-list/locale/ja.json b/packages/session-query/tool-session-list/locale/ja.json new file mode 100644 index 0000000000..43bcd18644 --- /dev/null +++ b/packages/session-query/tool-session-list/locale/ja.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "セッション一覧ツール", + "description": "エージェントを再開せずにワークスペースとセッションを一覧表示します。" + } +} diff --git a/packages/session-query/tool-session-list/locale/pt.json b/packages/session-query/tool-session-list/locale/pt.json new file mode 100644 index 0000000000..43bdfa3130 --- /dev/null +++ b/packages/session-query/tool-session-list/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Ferramentas de listagem de sessões", + "description": "Lista espaços de trabalho e sessões sem retomar os agentes." + } +} diff --git a/packages/session-query/tool-session-list/locale/ru.json b/packages/session-query/tool-session-list/locale/ru.json new file mode 100644 index 0000000000..7cbeb022f3 --- /dev/null +++ b/packages/session-query/tool-session-list/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Инструменты списка сеансов", + "description": "Показывает рабочие пространства и сеансы без возобновления работы агентов." + } +} diff --git a/packages/session-query/tool-session-list/locale/zh.json b/packages/session-query/tool-session-list/locale/zh.json new file mode 100644 index 0000000000..3588c3e15a --- /dev/null +++ b/packages/session-query/tool-session-list/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "会话列表工具", + "description": "列出工作区和会话,无需恢复智能体运行。" + } +} diff --git a/packages/session-query/tool-session-list/package.json b/packages/session-query/tool-session-list/package.json new file mode 100644 index 0000000000..897629f33e --- /dev/null +++ b/packages/session-query/tool-session-list/package.json @@ -0,0 +1,74 @@ +{ + "name": "@deepseek-ai/dsh-tool-session-list", + "description": "Read-only paginated Workspace and Session metadata tools", + "version": "0.2.2-rc.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session-query/tool-session-list" + }, + "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/*", + "./locale/*.json": "./locale/*.json", + "./package.json": "./package.json" + }, + "files": [ + "locale/*.json", + "lib/index.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-query": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-session-projection-cache": "workspace:*", + "@deepseek-ai/dsh-workspace": "workspace:*", + "@deepseek-ai/dsh-session-title": "workspace:*" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-query": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-session-projection-cache": "workspace:*", + "@deepseek-ai/dsh-workspace": "workspace:*", + "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-session-title": "workspace:*", + "@deepseek-ai/dsh-session-persistence": "workspace:*", + "@deepseek-ai/dsh-storage": "workspace:*", + "@deepseek-ai/dsh-storage-domain": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-tool-executor-native": "workspace:*", + "@deepseek-ai/dsh-tool-testkit": "workspace:*", + "@deepseek-ai/dsh-storage-json": "workspace:*" + }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-session-projection-cache": { + "optional": true + }, + "@deepseek-ai/dsh-session-title": { + "optional": true + } + }, + "dependencies": { + "@deepseek-ai/schemastery": "workspace:~" + } +} diff --git a/packages/session-query/tool-session-list/src/index.ts b/packages/session-query/tool-session-list/src/index.ts new file mode 100644 index 0000000000..24fb9b3825 --- /dev/null +++ b/packages/session-query/tool-session-list/src/index.ts @@ -0,0 +1,99 @@ +/** + * Opt-in read-only Workspace and Session metadata tools for the mounted runtime. + * @module @deepseek-ai/dsh-tool-session-list + */ + +import type { Context } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' +import { registerSessionListMetadata } from '@deepseek-ai/dsh-session-query' +import { defineTool } from '@deepseek-ai/dsh-tools' +import { listSessions, listWorkspaces } from './list.ts' + +/** Cordis plugin identity. */ +export const name = 'tool-session-list' +/** Services needed for header-only listing and live metadata. */ +export const inject = ['tools', 'sessions', 'sessionQuery', 'workspaceRegistry', 'sessionProjections'] + +/** Deployment-owned responsiveness for large Session lists. */ +export interface Config { + /** Positive integral work slice in milliseconds; defaults to 16. Checked between complete rows. */ + readonly listWorkSliceMs?: number +} + +/** Loader configuration for cooperative list scheduling. */ +export const Config: z = z.object({ + listWorkSliceMs: z.number().step(1).min(1).default(16), +}) + +const pagination = { + limit: { type: 'integer', description: 'Maximum entries to return, from 1 to 100. Defaults to 20.' }, + offset: { type: 'integer', description: 'Number of matching entries to skip. Defaults to 0.' }, +} as const + +/** + * Grant tools access to all Workspace and Session metadata in this runtime. + * @param ctx - scoped context granting these tools to its callers. + * @param config - deployment work-slice choice; omitted uses 16 milliseconds. + * @returns when the shared list metadata projection and tools are registered. + */ +export async function apply(ctx: Context, config: Config = {}): Promise { + const workSliceMs = config.listWorkSliceMs ?? 16 + if (!Number.isSafeInteger(workSliceMs) || workSliceMs < 1) { + throw new TypeError('tool-session-list: listWorkSliceMs must be a positive safe integer') + } + const readMetadata = await registerSessionListMetadata(ctx) + ctx.tools.register(defineTool({ + name: 'list_workspace', + description: 'List workspaces in registry order, including empty workspaces. Returns IDs, titles, paths, and creation and update times.', + parameters: pagination, + output: { + schema: { + type: 'array', + items: { + type: 'object', + additionalProperties: false, + properties: { + workspace_id: { type: 'string', required: true }, + title: { type: 'string', required: true }, + path: { type: 'string', required: true }, + created_at: { type: 'string', required: true, description: 'ISO 8601 creation time.' }, + updated_at: { type: 'string', required: true, description: 'ISO 8601 update time.' }, + }, + }, + }, + render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], + }, + isConcurrencySafe: () => true, + execute: (args, exec) => Promise.resolve(listWorkspaces(ctx, args, exec.signal)), + presentCall: () => ({ card: 'generic', title: 'List workspaces', kind: 'read' }), + })) + ctx.tools.register(defineTool({ + name: 'list_session', + description: 'List sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null.', + parameters: { + workspace_id: { type: 'string', description: 'Workspace ID from list_workspace. Includes its members and, when requested, subagents belonging through their nearest member ancestor. Omit to list all accessible sessions.' }, + contain_subagent: { type: 'boolean', description: 'Include subagent sessions. Defaults to false.' }, + archived: { type: 'boolean', description: 'Return only archived sessions when true, otherwise only unarchived sessions. Defaults to false.' }, + ...pagination, + }, + output: { + schema: { + type: 'array', + items: { + type: 'object', + additionalProperties: false, + properties: { + session_id: { type: 'string', required: true }, + title: { oneOf: [{ type: 'string' }, { type: 'null' }], required: true }, + created_at: { type: 'string', required: true, description: 'ISO 8601 creation time.' }, + updated_at: { type: 'string', required: true, description: 'ISO 8601 latest human prompt time, or creation time when unavailable.' }, + }, + }, + }, + render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], + }, + isConcurrencySafe: () => true, + execute: (args, exec) => listSessions(ctx, readMetadata, args, exec.signal, workSliceMs), + presentCall: args => ({ card: 'generic', title: 'List sessions', kind: 'read', rawInput: args.workspace_id }), + })) +} diff --git a/packages/session-query/tool-session-list/src/list.ts b/packages/session-query/tool-session-list/src/list.ts new file mode 100644 index 0000000000..1176e3db48 --- /dev/null +++ b/packages/session-query/tool-session-list/src/list.ts @@ -0,0 +1,182 @@ +/** Header-only selection and cached metadata for the read-only listing tools. */ + +import { performance } from 'node:perf_hooks' +import { scheduler } from 'node:timers/promises' +import type { Context } from '@deepseek-ai/cordis' +import type { Session, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' +import { SessionQueryError, type SessionListMetadata } from '@deepseek-ai/dsh-session-query' +import type {} from '@deepseek-ai/dsh-session-projection-cache' +import type {} from '@deepseek-ai/dsh-session-title' +import { ToolArgsError } from '@deepseek-ai/dsh-tools' +import { WorkspaceId } from '@deepseek-ai/dsh-workspace' + +/** Optional model pagination arguments. */ +export interface PageInput { + readonly limit?: number + readonly offset?: number +} + +/** Optional Session selection arguments. */ +export interface SessionListInput extends PageInput { + readonly workspace_id?: string + readonly contain_subagent?: boolean + readonly archived?: boolean +} + +interface WorkspaceListItem { + workspace_id: WorkspaceId + title: string + path: string + created_at: string + updated_at: string +} + +interface SessionListItem { + session_id: SessionId + title: string | null + created_at: string + updated_at: string +} + +/** + * Resolve pagination before reading any registry or persistence data. + * @param input - model pagination arguments. + * @returns the validated count and starting index. + */ +export function resolvePage(input: PageInput): { limit: number; offset: number } { + const limit = input.limit ?? 20 + const offset = input.offset ?? 0 + if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) { + throw new ToolArgsError(['limit must be an integer from 1 to 100']) + } + if (!Number.isSafeInteger(offset) || offset < 0) { + throw new ToolArgsError(['offset must be a non-negative safe integer']) + } + return { limit, offset } +} + +/** + * Read one page of the authoritative Workspace order, including empty records. + * @param ctx - context providing the Workspace registry. + * @param input - pagination arguments. + * @param signal - caller cancellation. + * @returns Workspace metadata with ISO timestamps. + */ +export function listWorkspaces(ctx: Context, input: PageInput, signal: AbortSignal): WorkspaceListItem[] { + const { limit, offset } = resolvePage(input) + signal.throwIfAborted() + return ctx.workspaceRegistry.list().slice(offset, offset + limit).map(workspace => ({ + workspace_id: workspace.id, + title: workspace.title, + path: workspace.path, + created_at: workspace.createdAt, + updated_at: workspace.updatedAt, + })) +} + +/** + * List live and persisted Session metadata without opening cold logs or activating Agents. + * @param ctx - context providing query, Workspace, and projection services. + * @param readLiveMetadata - ready reader owned by this plugin's registration. + * @param input - filters and pagination arguments. + * @param signal - caller cancellation, forwarded to the corpus listing. + * @param workSliceMs - resolved positive integral work slice between complete rows. + * @returns filtered Session metadata ordered by activity, then identity. + */ +export async function listSessions( + ctx: Context, + readLiveMetadata: (session: Session) => SessionListMetadata, + input: SessionListInput, + signal: AbortSignal, + workSliceMs: number, +): Promise { + const { limit, offset } = resolvePage(input) + signal.throwIfAborted() + const workspaceId = input.workspace_id === undefined ? undefined : WorkspaceId(input.workspace_id) + if (workspaceId !== undefined && ctx.workspaceRegistry.get(workspaceId) === undefined) { + throw new ToolArgsError([`workspace_id ${JSON.stringify(workspaceId)} is not registered; use list_workspace to find a workspace`]) + } + const records = await ctx.sessionQuery.listSessions(signal) + signal.throwIfAborted() + const archived = new Set(ctx.workspaceRegistry.archivedSessionIds) + const ownership = new Map() + if (workspaceId !== undefined) { + for (const workspace of ctx.workspaceRegistry.list()) { + for (const id of workspace.sessionIds) ownership.set(id, workspace.id) + } + } + const headers = new Map(records.map(record => [record.header.id, record.header])) + const nearestWorkspace = ancestorWorkspaceReader(headers, ownership) + const items = [] + let yieldDeadline = performance.now() + workSliceMs + for (const { header } of records) { + signal.throwIfAborted() + if (performance.now() >= yieldDeadline) { + await scheduler.yield() + signal.throwIfAborted() + yieldDeadline = performance.now() + workSliceMs + } + if (!input.contain_subagent && header.origin === 'subagent') continue + if (archived.has(header.id) !== (input.archived ?? false)) continue + if (workspaceId !== undefined) { + const owner = header.origin === 'subagent' ? nearestWorkspace(header) : ownership.get(header.id) + if (owner !== workspaceId) continue + } + const metadata = readListMetadata(ctx, header, readLiveMetadata) + items.push({ + session_id: header.id, + title: metadata.title, + created_at: new Date(header.createdAt).toISOString(), + updatedAt: Math.max(header.createdAt, metadata.lastPromptAt ?? 0), + }) + } + items.sort((left, right) => right.updatedAt - left.updatedAt + || (left.session_id < right.session_id ? -1 : 1)) + signal.throwIfAborted() + return items.slice(offset, offset + limit).map(({ updatedAt, ...item }) => ({ + ...item, + updated_at: new Date(updatedAt).toISOString(), + })) +} + +function readListMetadata( + ctx: Context, + header: SessionHeader, + readLiveMetadata: (session: Session) => SessionListMetadata, +): { title: string | null; lastPromptAt: number | null } { + const live = ctx.sessions.get(header.id) + if (live !== undefined) { + return { + title: ctx.sessionProjections.snapshot(live, ['title']).values.title ?? null, + lastPromptAt: readLiveMetadata(live).lastPromptAt, + } + } + const cache = ctx.get('sessionProjectionCache') + const snapshot = cache?.cachedSnapshot(header, ['title', 'sessionListMetadata']) + ?? cache?.cachedPredecessorTitle(header) + return { + title: snapshot?.values.title ?? null, + lastPromptAt: snapshot?.values.sessionListMetadata?.lastPromptAt ?? null, + } +} + +function ancestorWorkspaceReader( + headers: ReadonlyMap, + ownership: ReadonlyMap, +): (header: SessionHeader) => WorkspaceId | undefined { + const resolved = new Map(ownership) + return (header) => { + const visited = new Set() + let current: SessionHeader | undefined = header + while (current !== undefined && !resolved.has(current.id)) { + if (visited.has(current.id)) { + throw new SessionQueryError(`Session ${header.id} has cyclic parent ancestry`, 'SESSION_QUERY_INVALID_LINEAGE') + } + visited.add(current.id) + current = current.parentSession === undefined ? undefined : headers.get(current.parentSession) + } + const workspace = current === undefined ? undefined : resolved.get(current.id) + for (const id of visited) resolved.set(id, workspace) + return workspace + } +} diff --git a/packages/session-query/tool-session-list/tests/fixtures/session-list-seed.ts b/packages/session-query/tool-session-list/tests/fixtures/session-list-seed.ts new file mode 100644 index 0000000000..77e9986ed6 --- /dev/null +++ b/packages/session-query/tool-session-list/tests/fixtures/session-list-seed.ts @@ -0,0 +1,65 @@ +/** Deterministic Session and Workspace inputs for the shipped headless list tools. */ + +import { mkdir } from 'node:fs/promises' +import { join } from 'node:path' +import type { Context } from '@deepseek-ai/cordis' +import { SessionId } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-session-title' +import type {} from '@deepseek-ai/dsh-storage-domain' +import WorkspaceRegistry, { WorkspaceId, workspaceDomainSpec } from '@deepseek-ai/dsh-workspace' + +/** Loader fixture identity. */ +export const name = 'session-list-seed' +/** Real services used to prepare the scenario's durable registry and attached Sessions. */ +export const inject = ['sessions', 'sessionPersistence', 'storageDomain'] + +/** + * Seed stable list inputs before the Workspace registry becomes available. + * These attached Sessions have no Agent, so the agent-loop persistence owner never publishes them. + * @param ctx - fixture lifetime and the shipped storage and Session services. + * @returns when the actual Workspace registry has opened the seeded domain. + */ +export async function apply(ctx: Context): Promise { + const cwd = process.cwd() + const emptyPath = join(cwd, '.dsh', 'empty-workspace') + await mkdir(emptyPath, { recursive: true }) + const alpha = ctx.sessions.create(SessionId('list-alpha'), { meta: { cwd, createdAt: 1_000 } }) + alpha.append('session/title', { title: 'Alpha', messageSeqs: [], source: { kind: 'user' } }) + ctx.sessions.create(SessionId('list-beta'), { meta: { cwd, createdAt: 2_000 } }) + ctx.sessions.create(SessionId('list-archived'), { meta: { cwd, createdAt: 3_000 } }) + ctx.sessions.create(SessionId('list-child'), { + meta: { cwd, createdAt: 4_000, parentSession: alpha.id, origin: 'subagent', delegationDepth: 1 }, + }) + // Matching cwd alone does not make this Session a member of the stored Workspace. + ctx.sessions.create(SessionId('list-unaffiliated'), { meta: { cwd, createdAt: 5_000 } }) + + const workspaceId = WorkspaceId('list-workspace') + const emptyId = WorkspaceId('list-empty') + const domain = await ctx.storageDomain.open(workspaceDomainSpec) + try { + const table = domain.table('workspaces') + await table.put(workspaceId, { + path: cwd, + title: 'List fixture', + sessionIds: [alpha.id, SessionId('list-beta'), SessionId('list-archived')], + createdAt: '2000-01-01T00:00:00.000Z', + updatedAt: '2000-01-02T00:00:00.000Z', + }) + await table.put(emptyId, { + path: emptyPath, + title: 'Empty workspace', + sessionIds: [], + createdAt: '2000-01-03T00:00:00.000Z', + updatedAt: '2000-01-04T00:00:00.000Z', + }) + await domain.global.set({ + initialized: true, + workspaceIds: [workspaceId, emptyId], + archivedSessionIds: [SessionId('list-archived')], + pinnedSessionIds: [], + }) + } finally { + await domain.close() + } + await ctx.plugin(WorkspaceRegistry) +} diff --git a/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts new file mode 100644 index 0000000000..a39534a926 --- /dev/null +++ b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts @@ -0,0 +1,437 @@ +import { mkdir, mkdtemp, realpath, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { performance } from 'node:perf_hooks' +import { scheduler } from 'node:timers/promises' +import { Context } from '@deepseek-ai/cordis' +import AgentRegistry from '@deepseek-ai/dsh-agent' +import { createUserMessage, ToolCallId } from '@deepseek-ai/dsh-llm' +import SessionStore, { SESSION_FORMAT_VERSION, SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session' +import type { Session, SessionHeader } from '@deepseek-ai/dsh-session' +import SessionPersistence, { SessionPersistenceRevision } from '@deepseek-ai/dsh-session-persistence' +import type { SessionHandle, SessionPersistenceListOptions, SessionPersistenceSnapshot } from '@deepseek-ai/dsh-session-persistence' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import SessionProjectionCache, { projectionCacheDomainSpec } from '@deepseek-ai/dsh-session-projection-cache' +import type { CheckpointRecord } from '@deepseek-ai/dsh-session-projection-cache' +import SessionQueryEngine from '@deepseek-ai/dsh-session-query' +import type { SessionEventSearchPage, SessionSearchHit, SessionSearchPage } from '@deepseek-ai/dsh-session-query' +import { titleProjectionDefinition } from '@deepseek-ai/dsh-session-title' +import Storage from '@deepseek-ai/dsh-storage' +import * as StorageDomain from '@deepseek-ai/dsh-storage-domain' +import * as StorageJson from '@deepseek-ai/dsh-storage-json' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit' +import ToolRuntime from '@deepseek-ai/dsh-tools' +import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools' +import WorkspaceRegistry, { WorkspaceId, workspaceDomainSpec } from '@deepseek-ai/dsh-workspace' +import type { WorkspaceRecord } from '@deepseek-ai/dsh-workspace' +import { afterEach, describe, expect, it, vi } from 'vitest' +import * as ToolSessionList from '../src/index.ts' + +const contexts: Context[] = [] +const roots: string[] = [] + +afterEach(async () => { + vi.restoreAllMocks() + for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() + for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true }) +}) + +class HeaderPersistence extends SessionPersistence { + readonly headers: SessionHeader[] + + constructor(ctx: Context, config: { headers: SessionHeader[] }) { + super(ctx) + this.headers = config.headers + } + + override create = vi.fn((): Promise => Promise.reject(new Error('listing must not create a stored Session'))) + override open = vi.fn((): Promise => Promise.reject(new Error('listing must not open an event log'))) + override flush = vi.fn((): Promise => Promise.resolve()) + override stat = vi.fn((): Promise => Promise.reject(new Error('listing must not stat each Session'))) + override list = vi.fn((options?: SessionPersistenceListOptions): Promise => { + options?.signal?.throwIfAborted() + return Promise.resolve(this.headers.map(header => ({ header, revision: SessionPersistenceRevision(`rev-${header.id}`) }))) + }) +} + +class ListingQuery extends SessionQueryEngine { + override searchSessions(): Promise> { + return Promise.reject(new Error('listing must not search Session contents')) + } + + override searchEvents(): Promise { + return Promise.reject(new Error('listing must not search event contents')) + } +} + +function header(id: string, createdAt: number, options: Partial> = {}): SessionHeader { + return { id: SessionId(id), version: SESSION_FORMAT_VERSION, createdAt, isSeeded: false, ...options } +} + +function workspace(path: string, sessionIds: string[] = [], title = 'Workspace'): WorkspaceRecord { + return { + path, + title, + sessionIds: sessionIds.map(SessionId), + createdAt: '2026-01-01T00:00:00.000Z', + updatedAt: '2026-01-02T00:00:00.000Z', + } +} + +function checkpoint(meta: SessionHeader, title: string | null, lastPromptAt: number | null): CheckpointRecord { + return { + identity: { + formatVersion: meta.version, + createdAt: meta.createdAt, + isSeeded: false, + inheritedEventCount: SessionLogOffset(0), + ...meta.cwd === undefined ? {} : { cwd: meta.cwd }, + }, + rows: { + title: { ver: 1, seq: -1, val: title }, + sessionListMetadata: { ver: 1, seq: -1, val: { blank: false, lastPromptAt } }, + }, + } +} + +async function directory(): Promise { + const root = await realpath(await mkdtemp(join(tmpdir(), 'dsh-session-list-'))) + roots.push(root) + return root +} + +async function mount(options: { + headers?: SessionHeader[] + workspaces?: Array<[string, WorkspaceRecord]> + archived?: string[] + cached?: Array<[string, CheckpointRecord]> + cache?: boolean + config?: ToolSessionList.Config +} = {}) { + const workspaces = options.workspaces ?? [] + const ctx = new Context() + contexts.push(ctx) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(AgentRegistry) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRuntime) + await ctx.plugin(Storage) + await ctx.plugin(StorageJson, { root: await directory() }) + await ctx.plugin(StorageDomain, { backend: 'json' }) + const workspaceDomain = await ctx.storageDomain.open(workspaceDomainSpec) + for (const [id, record] of workspaces) await workspaceDomain.table('workspaces').put(WorkspaceId(id), record) + await workspaceDomain.global.set({ + initialized: true, + workspaceIds: workspaces.map(([id]) => WorkspaceId(id)), + archivedSessionIds: (options.archived ?? []).map(SessionId), + pinnedSessionIds: [], + }) + await workspaceDomain.close() + const cacheDomain = await ctx.storageDomain.open(projectionCacheDomainSpec) + for (const [id, record] of options.cached ?? []) await cacheDomain.table('sessions').put(SessionId(id), record) + await cacheDomain.close() + await ctx.plugin(HeaderPersistence, { headers: options.headers ?? [] }) + await ctx.plugin(WorkspaceRegistry) + if (options.cache !== false) { + await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 1000, writeIntervalMs: 60_000 }) + } + await ctx.sessionProjections.register(titleProjectionDefinition) + await ctx.plugin(ListingQuery) + const fiber = await ctx.plugin(ToolSessionList, options.config) + const read = vi.spyOn(ctx.sessionQuery, 'readSession') + const titles = vi.spyOn(ctx.sessionQuery, 'readTitleSnapshots') + const open = vi.spyOn(ctx.sessionPersistence, 'open') + let callId = 0 + return { + ctx, + fiber, + read, + titles, + open, + call: (name: string, args: unknown = {}, signal = new AbortController().signal) => executeToolFixture(ctx, { + name, arguments: args, callId: ToolCallId(`list-${++callId}`), signal, + }), + } +} + +function value(result: ToolExecutionResult) { + if (result.isError) throw new Error(result.error.message) + return result.value +} + +function item(id: string, createdAt: number, updatedAt = createdAt, title: string | null = null) { + return { session_id: id, title, created_at: new Date(createdAt).toISOString(), updated_at: new Date(updatedAt).toISOString() } +} + +function prompt(session: Session) { + session.append('turn/start', { turn: 1 }) + return session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Human prompt' }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) +} + +function measureRows(ctx: Context, summaryMs: number) { + const clock = { now: 0 } + const trace: string[] = [] + const cachedSnapshot = ctx.sessionProjectionCache.cachedSnapshot.bind(ctx.sessionProjectionCache) + vi.spyOn(ctx.sessionProjectionCache, 'cachedSnapshot').mockImplementation((meta, keys) => { + clock.now += summaryMs + trace.push(meta.id) + return cachedSnapshot(meta, keys) + }) + vi.spyOn(performance, 'now').mockImplementation(() => clock.now) + return { clock, trace } +} + +describe('read-only Session list tools', () => { + it('lists empty Workspaces in registry order and applies offset after that order', async () => { + const path = await directory() + const secondPath = join(path, 'second') + await mkdir(secondPath) + const first = workspace(path, [], 'First') + const second = workspace(secondPath, [], 'Second') + const mounted = await mount({ workspaces: [['z-workspace', first], ['a-workspace', second]] }) + const rows = [first, second].map((record, index) => ({ + workspace_id: index === 0 ? 'z-workspace' : 'a-workspace', + title: record.title, path: record.path, created_at: record.createdAt, updated_at: record.updatedAt, + })) + expect(value(await mounted.call('list_workspace'))).toEqual(rows) + expect(value(await mounted.call('list_workspace', { limit: 1, offset: 1 }))).toEqual([rows[1]]) + expect(value(await mounted.call('list_workspace', { offset: 2 }))).toEqual([]) + expect(value(await mounted.call('list_session'))).toEqual([]) + }) + + it('uses current live metadata, cached cold metadata, and creation time for cache misses without opening logs', async () => { + const cold = header('cold', 10) + const live = header('live', 20) + const missing = header('missing', 30) + const mounted = await mount({ + headers: [cold, live, missing], + cached: [['cold', checkpoint(cold, 'Cold title', 100)], ['live', checkpoint(live, 'Old title', 90)]], + }) + const session = mounted.ctx.sessions.create(live.id, { meta: { createdAt: live.createdAt } }) + expect(value(await mounted.call('list_session'))).toEqual([ + item('cold', 10, 100, 'Cold title'), item('missing', 30), item('live', 20), + ]) + const human = prompt(session) + session.append('session/title', { title: 'Live title', messageSeqs: [], source: { kind: 'user' } }) + expect(value(await mounted.call('list_session'))).toEqual([ + item('live', 20, human.time, 'Live title'), item('cold', 10, 100, 'Cold title'), item('missing', 30), + ]) + expect(mounted.ctx.agents.list()).toEqual([]) + expect(mounted.ctx.sessions.list()).toEqual([session]) + expect(mounted.read).not.toHaveBeenCalled() + expect(mounted.titles).not.toHaveBeenCalled() + expect(mounted.open).not.toHaveBeenCalled() + }) + + it('uses creation time and null titles when the optional projection cache is not mounted', async () => { + const mounted = await mount({ headers: [header('cold', 10)], cache: false }) + expect(value(await mounted.call('list_session'))).toEqual([item('cold', 10)]) + expect(mounted.open).not.toHaveBeenCalled() + }) + + it('keeps the title hint of a predecessor cache without using its activity metadata', async () => { + const cold = header('predecessor', 10) + const old = checkpoint(cold, 'Prior title', 100) + old.identity.formatVersion = SESSION_FORMAT_VERSION - 1 + const mounted = await mount({ headers: [cold], cached: [[cold.id, old]] }) + expect(value(await mounted.call('list_session'))).toEqual([item('predecessor', 10, 10, 'Prior title')]) + expect(mounted.open).not.toHaveBeenCalled() + }) + + it('filters archive status and subagents before sorting and pagination; pins do not reorder results', async () => { + const mounted = await mount({ + headers: [header('z', 100), header('b', 100), header('a', 100), header('archived', 500), header('child', 200, { origin: 'subagent', parentSession: SessionId('z') })], + archived: ['archived'], + }) + await mounted.ctx.workspaceRegistry.pinSession(SessionId('z')) + expect(value(await mounted.call('list_session', { limit: 1, offset: 1 }))).toEqual([item('b', 100)]) + expect(value(await mounted.call('list_session', { contain_subagent: true }))).toEqual([ + item('child', 200), item('a', 100), item('b', 100), item('z', 100), + ]) + expect(value(await mounted.call('list_session', { archived: true }))).toEqual([item('archived', 500)]) + expect(value(await mounted.call('list_session', { archived: true, offset: 1 }))).toEqual([]) + }) + + it('breaks cached-activity ties by ID even when creation order differs', async () => { + const headers = [header('a', 10), header('b', 20), header('z', 30)] + const mounted = await mount({ headers, cached: headers.map(meta => [meta.id, checkpoint(meta, null, 100)]) }) + expect(value(await mounted.call('list_session'))).toEqual([ + item('a', 10, 100), item('b', 20, 100), item('z', 30, 100), + ]) + }) + + it('inherits explicit Workspace membership only for subagents and stops at the nearest assigned ancestor', async () => { + const path = await directory() + const otherPath = join(path, 'other') + await mkdir(otherPath) + const mounted = await mount({ + headers: [ + header('parent', 10, { cwd: path }), + header('same-cwd', 20, { cwd: path }), + header('child', 30, { cwd: path, origin: 'subagent', parentSession: SessionId('parent') }), + header('grandchild', 40, { origin: 'subagent', parentSession: SessionId('child') }), + header('fork', 50, { cwd: path, parentSession: SessionId('parent') }), + header('assigned-child', 60, { cwd: otherPath, origin: 'subagent', parentSession: SessionId('parent') }), + header('assigned-grandchild', 70, { origin: 'subagent', parentSession: SessionId('assigned-child') }), + header('orphan', 80, { origin: 'subagent', parentSession: SessionId('absent') }), + header('unassigned-child', 90, { origin: 'subagent', parentSession: SessionId('same-cwd') }), + ], + workspaces: [['primary', workspace(path, ['parent'])], ['other', workspace(otherPath, ['assigned-child'])]], + archived: ['parent'], + }) + expect(value(await mounted.call('list_session', { workspace_id: 'primary', contain_subagent: true }))).toEqual([ + item('grandchild', 40), item('child', 30), + ]) + expect(value(await mounted.call('list_session', { workspace_id: 'primary', archived: true }))).toEqual([item('parent', 10)]) + expect(value(await mounted.call('list_session', { workspace_id: 'other', contain_subagent: true }))).toEqual([ + item('assigned-grandchild', 70), item('assigned-child', 60), + ]) + expect(value(await mounted.call('list_session', { workspace_id: 'primary' }))).toEqual([]) + }) + + it('defaults to twenty rows and accepts the upper page limit', async () => { + const headers = Array.from({ length: 101 }, (_, index) => header(`session-${String(index).padStart(3, '0')}`, index)) + const mounted = await mount({ headers }) + expect(value(await mounted.call('list_session'))).toHaveLength(20) + expect(value(await mounted.call('list_session', { limit: 100 }))).toHaveLength(100) + expect(value(await mounted.call('list_session', { limit: 100, offset: 100 }))).toEqual([item('session-000', 0)]) + }) + + it.each(['list_workspace', 'list_session'])('rejects invalid pagination for %s with INVALID_ARGS', async (name) => { + const mounted = await mount() + const invalid = [{ limit: 0 }, { limit: 101 }, { limit: 1.5 }, { offset: -1 }, { offset: 1.5 }, { offset: Number.MAX_SAFE_INTEGER + 1 }] + for (const args of invalid) { + const result = await mounted.call(name, args) + expect(result.isError).toBe(true) + expect(result.error?.info).toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) + } + }) + + it('rejects an unknown Workspace and corrupt subagent ancestry with typed failures', async () => { + const path = await directory() + const mounted = await mount({ + headers: [header('cycle-a', 10, { origin: 'subagent', parentSession: SessionId('cycle-b') }), header('cycle-b', 20, { origin: 'subagent', parentSession: SessionId('cycle-a') })], + workspaces: [['known', workspace(path)]], + }) + expect((await mounted.call('list_session', { workspace_id: 'absent' })).error?.info) + .toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) + expect((await mounted.call('list_session', { workspace_id: 'known', contain_subagent: true })).error?.info) + .toMatchObject({ name: 'SessionQueryError', code: 'SESSION_QUERY_INVALID_LINEAGE' }) + expect(mounted.open).not.toHaveBeenCalled() + }) + + it('propagates cancellation during corpus discovery without reading metadata or activating Agents', async () => { + const mounted = await mount({ headers: [header('cold', 10)] }) + const controller = new AbortController() + const list = vi.spyOn(mounted.ctx.sessionQuery, 'listSessions').mockImplementation(async (signal) => { + expect(signal).toBe(controller.signal) + controller.abort(new Error('list cancelled')) + return [] + }) + const result = await mounted.call('list_session', {}, controller.signal) + expect(result.error?.info).toMatchObject({ name: 'AbortError', code: 'ABORTED' }) + expect(list).toHaveBeenCalledOnce() + expect(mounted.open).not.toHaveBeenCalled() + expect(mounted.ctx.agents.list()).toEqual([]) + }) + + it('registers concurrency-safe generic presentation and releases both tools on disposal', async () => { + const mounted = await mount() + for (const name of ['list_workspace', 'list_session']) { + const tool = mounted.ctx.tools.get(name) + expect(tool?.isConcurrencySafe?.({})).toBe(true) + expect(tool?.presentCall?.({})).toMatchObject({ card: 'generic', kind: 'read' }) + } + await mounted.fiber.dispose() + expect(mounted.ctx.tools.get('list_workspace')).toBeUndefined() + expect(mounted.ctx.tools.get('list_session')).toBeUndefined() + }) +}) + +describe('Session list work slices', () => { + const headers = [header('first', 30), header('middle', 20), header('last', 10)] + + it('resolves the default and explicit work slice through Loader configuration', () => { + expect(ToolSessionList.Config({})).toEqual({ listWorkSliceMs: 16 }) + expect(ToolSessionList.Config({ listWorkSliceMs: 8 })).toEqual({ listWorkSliceMs: 8 }) + }) + + it.each([0, -1, 0.5, Number.NaN, Number.POSITIVE_INFINITY, Number.MAX_SAFE_INTEGER + 1])( + 'rejects invalid work slice %s before registering a projection or tool', async (listWorkSliceMs) => { + const ctx = new Context() + contexts.push(ctx) + await expect(ToolSessionList.apply(ctx, { listWorkSliceMs })).rejects.toThrow( + 'tool-session-list: listWorkSliceMs must be a positive safe integer', + ) + }, + ) + + it('keeps cheap metadata reads in one synchronous slice', async () => { + const mounted = await mount({ headers }) + const { trace } = measureRows(mounted.ctx, 2) + const yieldWork = vi.spyOn(scheduler, 'yield') + expect(value(await mounted.call('list_session'))).toEqual([item('first', 30), item('middle', 20), item('last', 10)]) + expect(trace).toEqual(['first', 'middle', 'last']) + expect(yieldWork).not.toHaveBeenCalled() + }) + + it.each([ + { listWorkSliceMs: undefined, summaryMs: 8 }, + { listWorkSliceMs: 8, summaryMs: 4 }, + ])('resumes after an exhausted $listWorkSliceMs slice and resets the deadline after waiting', async ({ listWorkSliceMs, summaryMs }) => { + const mounted = await mount({ headers, config: listWorkSliceMs === undefined ? {} : { listWorkSliceMs } }) + if (listWorkSliceMs === undefined) { + await mounted.fiber.dispose() + await mounted.ctx.plugin({ inject: ToolSessionList.inject, apply: (ctx: Context) => ToolSessionList.apply(ctx) }) + } + const { clock, trace } = measureRows(mounted.ctx, summaryMs) + const yieldWork = vi.spyOn(scheduler, 'yield').mockImplementation(async () => { + trace.push('yield') + clock.now += 1_000 + }) + expect(value(await mounted.call('list_session'))).toEqual([item('first', 30), item('middle', 20), item('last', 10)]) + expect(trace).toEqual(['first', 'middle', 'yield', 'last']) + expect(yieldWork).toHaveBeenCalledOnce() + }) + + it('returns the final completed row without a trailing yield', async () => { + const mounted = await mount({ headers: [header('last', 10)] }) + measureRows(mounted.ctx, 16) + const yieldWork = vi.spyOn(scheduler, 'yield') + expect(value(await mounted.call('list_session'))).toEqual([item('last', 10)]) + expect(yieldWork).not.toHaveBeenCalled() + }) + + it('checks the work slice while classifying rows that the filters exclude', async () => { + const mounted = await mount({ + headers: headers.map(meta => ({ ...meta, origin: 'subagent', parentSession: SessionId('outside') })), + }) + const cached = vi.spyOn(mounted.ctx.sessionProjectionCache, 'cachedSnapshot') + // Classification consumes the first slice even though no metadata row is read. + vi.spyOn(performance, 'now').mockReturnValueOnce(0).mockReturnValueOnce(0).mockReturnValue(16) + const yieldWork = vi.spyOn(scheduler, 'yield').mockResolvedValue() + expect(value(await mounted.call('list_session'))).toEqual([]) + expect(yieldWork).toHaveBeenCalledOnce() + expect(cached).not.toHaveBeenCalled() + expect(mounted.open).not.toHaveBeenCalled() + }) + + it('cancels at a yielded row without reading later metadata or returning a partial list', async () => { + const mounted = await mount({ headers, config: { listWorkSliceMs: 4 } }) + const { trace } = measureRows(mounted.ctx, 4) + const controller = new AbortController() + const yieldWork = vi.spyOn(scheduler, 'yield').mockImplementation(async () => { + controller.abort(new Error('stop between rows')) + }) + const result = await mounted.call('list_session', {}, controller.signal) + expect(result.error?.info).toMatchObject({ name: 'AbortError', code: 'ABORTED' }) + expect(result.value).toBeUndefined() + expect(trace).toEqual(['first']) + expect(yieldWork).toHaveBeenCalledOnce() + expect(mounted.open).not.toHaveBeenCalled() + }) +}) diff --git a/packages/session-query/tool-session-list/tsconfig.json b/packages/session-query/tool-session-list/tsconfig.json new file mode 100644 index 0000000000..d2eabc4754 --- /dev/null +++ b/packages/session-query/tool-session-list/tsconfig.json @@ -0,0 +1,39 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../core/tools" + }, + { + "path": "../../core/session" + }, + { + "path": "../session-query" + }, + { + "path": "../../session/session-projection" + }, + { + "path": "../../session/session-projection-cache" + }, + { + "path": "../../session/session-title" + }, + { + "path": "../../workspace/workspace" + } + ] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 65f0388b77..f27d93d4c7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -123,6 +123,9 @@ importers: '@deepseek-ai/dsh-tool-ralph': specifier: workspace:* version: link:packages/experimental/tool-ralph + '@deepseek-ai/dsh-tool-session-list': + specifier: workspace:* + version: link:packages/session-query/tool-session-list '@deepseek-ai/dsh-tool-session-query': specifier: workspace:* version: link:packages/experimental/tool-session-query @@ -14673,6 +14676,9 @@ importers: '@deepseek-ai/dsh-session-format-catalog': specifier: workspace:* version: link:../../session/session-format-catalog + zod: + specifier: 4.6.6 + version: 4.6.6 devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ @@ -14730,6 +14736,64 @@ importers: specifier: workspace:* version: link:../session-query + packages/session-query/tool-session-list: + dependencies: + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-agent': + specifier: workspace:* + version: link:../../core/agent + '@deepseek-ai/dsh-llm': + specifier: workspace:* + version: link:../../llm/llm + '@deepseek-ai/dsh-session': + specifier: workspace:* + version: link:../../core/session + '@deepseek-ai/dsh-session-persistence': + specifier: workspace:* + version: link:../../session/session-persistence + '@deepseek-ai/dsh-session-projection': + specifier: workspace:* + version: link:../../session/session-projection + '@deepseek-ai/dsh-session-projection-cache': + specifier: workspace:* + version: link:../../session/session-projection-cache + '@deepseek-ai/dsh-session-query': + specifier: workspace:* + version: link:../session-query + '@deepseek-ai/dsh-session-title': + specifier: workspace:* + version: link:../../session/session-title + '@deepseek-ai/dsh-storage': + specifier: workspace:* + version: link:../../storage/storage + '@deepseek-ai/dsh-storage-domain': + specifier: workspace:* + version: link:../../storage/storage-domain + '@deepseek-ai/dsh-storage-json': + specifier: workspace:* + version: link:../../storage/storage-json + '@deepseek-ai/dsh-system-prompt': + specifier: workspace:* + version: link:../../core/system-prompt + '@deepseek-ai/dsh-tool-executor-native': + specifier: workspace:* + version: link:../../core/tool-executor-native + '@deepseek-ai/dsh-tool-testkit': + specifier: workspace:* + version: link:../../test-support/tool-testkit + '@deepseek-ai/dsh-tools': + specifier: workspace:* + version: link:../../core/tools + '@deepseek-ai/dsh-workspace': + specifier: workspace:* + version: link:../../workspace/workspace + packages/session/message-quotes: devDependencies: '@deepseek-ai/cordis': diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index 7ca0a5d54f..871aa081e4 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -8,7 +8,7 @@ import { globSync, readFileSync, writeFileSync } from 'node:fs' import { basename, dirname, resolve } from 'node:path' -import { Context } from '@deepseek-ai/cordis' +import { Context, Service } from '@deepseek-ai/cordis' import LlmRuntime from '@deepseek-ai/dsh-llm' import type { ToolSchema } from '@deepseek-ai/dsh-llm' import AgentRegistry from '@deepseek-ai/dsh-agent' @@ -71,6 +71,8 @@ import Lsp from '@deepseek-ai/dsh-lsp' import * as ToolLsp from '@deepseek-ai/dsh-tool-lsp' import * as ToolSkill from '@deepseek-ai/dsh-tool-skill' import * as ToolSessionQuery from '@deepseek-ai/dsh-tool-session-query' +import * as ToolSessionList from '@deepseek-ai/dsh-tool-session-list' +import WorkspaceRegistry from '@deepseek-ai/dsh-workspace' import * as ToolJobs from '@deepseek-ai/dsh-tool-jobs' import BrowserUseRegistry from '@deepseek-ai/dsh-browser-use' import * as StagehandBrowserTools from '@deepseek-ai/dsh-experimental-browser-use-stagehand-native' @@ -136,6 +138,13 @@ class CatalogSessionPersistence extends SessionPersistence { list = unavailableCatalogPersistence } +/** Schema collection does not read Workspace records or open their durable domain. */ +class CatalogWorkspaceRegistry extends WorkspaceRegistry { + static override inject = [] + + protected override async [Service.init](): Promise {} +} + /** Storage operations are unreachable during schema collection. */ function unavailableCatalogPersistence(): never { throw new Error('gen-tool-catalog: persistence access is unavailable during schema harvest') @@ -570,6 +579,20 @@ const TOOL_PACKAGES: ToolPackage[] = [ await ctx.plugin(ToolSkill) }, }, + { + pkg: '@deepseek-ai/dsh-tool-session-list', + dir: 'tool-session-list', + source: 'packages/session-query/tool-session-list/src/index.ts', + requires: ['ctx.tools', 'ctx.sessions', 'ctx.sessionQuery', 'ctx.workspaceRegistry', 'ctx.sessionProjections'], + writes: ['tool/call', 'tool/result'], + async mount(ctx) { + await ctx.plugin(SessionStore) + await ctx.plugin(SqliteSessionQueryEngine, { path: ':memory:' }) + await ctx.plugin(CatalogWorkspaceRegistry) + await ctx.plugin(ToolSessionList) + }, + note: 'Opt-in access to all Workspace and Session list metadata in the mounted runtime. Cold titles and activity use the optional projection cache; absent values become null titles and creation-time recency. No Agent is activated.', + }, { pkg: '@deepseek-ai/dsh-tool-session-query', dir: 'tool-session-query', diff --git a/scripts/product-package-policy.ts b/scripts/product-package-policy.ts index d7ee247c03..0066304a50 100644 --- a/scripts/product-package-policy.ts +++ b/scripts/product-package-policy.ts @@ -16,6 +16,7 @@ export interface ProductPackagePolicy { * Optional integrations may be reached by an optional bundle without becoming default capabilities. */ export const PRODUCT_PACKAGE_POLICY: Readonly> = { + 'packages/session-query/tool-session-list': { category: 'optional', reason: 'Explicitly grants model callers read access to runtime Workspace and Session metadata.' }, 'packages/core/agent-tool-presentation': { category: 'optional', reason: 'Deprecated selector retained for existing executor configurations.' }, 'packages/browser-use/browser-use': { category: 'optional', reason: 'Service definition used by explicitly selected browser providers.' }, 'packages/computer-use/computer-use': { category: 'optional', reason: 'Service definition used by explicitly selected computer providers.' }, diff --git a/snapshots/session/session-list-tools/cordis.snapshot.yml b/snapshots/session/session-list-tools/cordis.snapshot.yml new file mode 100644 index 0000000000..d7b301ee86 --- /dev/null +++ b/snapshots/session/session-list-tools/cordis.snapshot.yml @@ -0,0 +1,52 @@ +# Replay patch shared by the ordinary headless snapshot composition. The model +# script comes from the scenario's committed session JSONL. + +- id: llm-deepseek + name: '@deepseek-ai/dsh-llm-deepseek-api-key' + disabled: true + +- id: plugin-package-inventory-deepseek + disabled: true + +- id: session-title-llm + disabled: true + +- id: session-persistence-jsonl + name: '@deepseek-ai/dsh-session-persistence-jsonl' + config: + root: !!js dshHomePath('sessions') + compression: none + +- id: sandbox + name: '@deepseek-ai/dsh-sandbox-local' + config: + runnerCommand: + - bash + - -c + - while [ "$1" != "--" ]; do shift; done; shift; exec "$@" + - passthrough-runner + runnerFailureSignatures: + - 'passthrough-runner: profile rejected' + +- insert: + - id: llm-replay + name: '@deepseek-ai/dsh-llm-replay' + config: + providers: + - id: deepseek-official + name: DeepSeek + models: + - id: deepseek-v4-flash + - id: deepseek-v4-pro + - id: deepseek-messages + name: DeepSeek Messages + models: + - id: deepseek-v4-flash + - id: deepseek-v4-pro + +- insert: + - id: session-list-seed + name: ../../../packages/session-query/tool-session-list/tests/fixtures/session-list-seed.ts + + - id: tool-session-list + name: '@deepseek-ai/dsh-tool-session-list' diff --git a/snapshots/session/session-list-tools/cordis.yml b/snapshots/session/session-list-tools/cordis.yml new file mode 100644 index 0000000000..35f941fe6d --- /dev/null +++ b/snapshots/session/session-list-tools/cordis.yml @@ -0,0 +1,6 @@ +- insert: + - id: session-list-seed + name: ../../../packages/session-query/tool-session-list/tests/fixtures/session-list-seed.ts + + - id: tool-session-list + name: '@deepseek-ai/dsh-tool-session-list' diff --git a/snapshots/session/session-list-tools/session.v4.jsonl b/snapshots/session/session-list-tools/session.v4.jsonl new file mode 100644 index 0000000000..18b6788ea5 --- /dev/null +++ b/snapshots/session/session-list-tools/session.v4.jsonl @@ -0,0 +1,57 @@ +{"type":"session","version":4,"id":"{{session:1}}","createdAt":0,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0} +{"type":"permission/preset","data":{"preset":"danger-full-access"}} +{"type":"sandbox/mode","data":{"mode":"danger-full-access"}} +{"type":"approval/policy","data":{"policy":"never"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"List the fixture workspaces and sessions."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} +{"type":"turn/start","data":{"turn":1}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":1,"step":1}} +{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"List the fixture workspaces and sessions."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} +{"type":"session/title","data":{"title":"List the fixture workspaces and","messageSeqs":[8],"source":{"kind":"fallback"}}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-1","name":"list_workspace","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-1","name":"list_workspace","arguments":"{}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"list-1","name":"list_workspace","arguments":"{}"}} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"list-1"},"toolCallId":"list-1","content":[{"type":"text","text":"[{\"workspace_id\":\"list-workspace\",\"title\":\"List fixture\",\"path\":\"{{cwd}}\",\"created_at\":\"2000-01-01T00:00:00.000Z\",\"updated_at\":\"2000-01-02T00:00:00.000Z\"},{\"workspace_id\":\"list-empty\",\"title\":\"Empty workspace\",\"path\":\"{{cwd}}/.dsh/empty-workspace\",\"created_at\":\"2000-01-03T00:00:00.000Z\",\"updated_at\":\"2000-01-04T00:00:00.000Z\"}]"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":1}} +{"type":"step/start","data":{"turn":1,"step":2}} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-2","name":"list_workspace","arguments":"{\"limit\":1,\"offset\":1}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-2","name":"list_workspace","arguments":"{\"limit\":1,\"offset\":1}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":2,"callId":"list-2","name":"list_workspace","arguments":"{\"limit\":1,\"offset\":1}"}} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"list-2"},"toolCallId":"list-2","content":[{"type":"text","text":"[{\"workspace_id\":\"list-empty\",\"title\":\"Empty workspace\",\"path\":\"{{cwd}}/.dsh/empty-workspace\",\"created_at\":\"2000-01-03T00:00:00.000Z\",\"updated_at\":\"2000-01-04T00:00:00.000Z\"}]"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[19],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":2}} +{"type":"step/start","data":{"turn":1,"step":3}} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-3","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-3","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":3,"callId":"list-3","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\"}"}} +{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"list-3"},"toolCallId":"list-3","content":[{"type":"text","text":"[{\"session_id\":\"list-beta\",\"title\":null,\"created_at\":\"1970-01-01T00:00:02.000Z\",\"updated_at\":\"1970-01-01T00:00:02.000Z\"},{\"session_id\":\"list-alpha\",\"title\":\"Alpha\",\"created_at\":\"1970-01-01T00:00:01.000Z\",\"updated_at\":\"1970-01-01T00:00:01.000Z\"}]"}],"isError":false,"id":"{{message:9}}"}},"sourceEventSeqs":[24],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":3}} +{"type":"step/start","data":{"turn":1,"step":4}} +{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"contain_subagent\":true,\"limit\":2}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"contain_subagent\":true,\"limit\":2}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":4,"callId":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"contain_subagent\":true,\"limit\":2}"}} +{"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"list-4"},"toolCallId":"list-4","content":[{"type":"text","text":"[{\"session_id\":\"list-child\",\"title\":null,\"created_at\":\"1970-01-01T00:00:04.000Z\",\"updated_at\":\"1970-01-01T00:00:04.000Z\"},{\"session_id\":\"list-beta\",\"title\":null,\"created_at\":\"1970-01-01T00:00:02.000Z\",\"updated_at\":\"1970-01-01T00:00:02.000Z\"}]"}],"isError":false,"id":"{{message:11}}"}},"sourceEventSeqs":[29],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":4}} +{"type":"step/start","data":{"turn":1,"step":5}} +{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-5","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"archived\":true}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-5","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"archived\":true}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":5,"callId":"list-5","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"archived\":true}"}} +{"type":"tool/result","data":{"turn":1,"step":5,"message":{"role":"tool","source":{"kind":"tool","callId":"list-5"},"toolCallId":"list-5","content":[{"type":"text","text":"[{\"session_id\":\"list-archived\",\"title\":null,\"created_at\":\"1970-01-01T00:00:03.000Z\",\"updated_at\":\"1970-01-01T00:00:03.000Z\"}]"}],"isError":false,"id":"{{message:13}}"}},"sourceEventSeqs":[34],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":5}} +{"type":"step/start","data":{"turn":1,"step":6}} +{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-6","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1,\"offset\":1}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:14}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-6","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1,\"offset\":1}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":6,"callId":"list-6","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1,\"offset\":1}"}} +{"type":"tool/result","data":{"turn":1,"step":6,"message":{"role":"tool","source":{"kind":"tool","callId":"list-6"},"toolCallId":"list-6","content":[{"type":"text","text":"[{\"session_id\":\"list-alpha\",\"title\":\"Alpha\",\"created_at\":\"1970-01-01T00:00:01.000Z\",\"updated_at\":\"1970-01-01T00:00:01.000Z\"}]"}],"isError":false,"id":"{{message:15}}"}},"sourceEventSeqs":[39],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":6}} +{"type":"step/start","data":{"turn":1,"step":7}} +{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-7","name":"list_session","arguments":"{\"workspace_id\":\"list-empty\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:16}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-7","name":"list_session","arguments":"{\"workspace_id\":\"list-empty\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":7,"callId":"list-7","name":"list_session","arguments":"{\"workspace_id\":\"list-empty\"}"}} +{"type":"tool/result","data":{"turn":1,"step":7,"message":{"role":"tool","source":{"kind":"tool","callId":"list-7"},"toolCallId":"list-7","content":[{"type":"text","text":"[]"}],"isError":false,"id":"{{message:17}}"}},"sourceEventSeqs":[44],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":7}} +{"type":"step/start","data":{"turn":1,"step":8}} +{"type":"assistant/message","data":{"turn":1,"step":8,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-8","name":"list_workspace","arguments":"{\"offset\":10}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:18}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-8","name":"list_workspace","arguments":"{\"offset\":10}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":8,"callId":"list-8","name":"list_workspace","arguments":"{\"offset\":10}"}} +{"type":"tool/result","data":{"turn":1,"step":8,"message":{"role":"tool","source":{"kind":"tool","callId":"list-8"},"toolCallId":"list-8","content":[{"type":"text","text":"[]"}],"isError":false,"id":"{{message:19}}"}},"sourceEventSeqs":[49],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":8}} +{"type":"step/start","data":{"turn":1,"step":9}} +{"type":"assistant/message","data":{"turn":1,"step":9,"message":{"role":"assistant","content":[{"type":"text","text":"SESSION_LIST_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:20}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"SESSION_LIST_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":9}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/session-list-tools/snapshot.yml b/snapshots/session/session-list-tools/snapshot.yml new file mode 100644 index 0000000000..a1d5d12a41 --- /dev/null +++ b/snapshots/session/session-list-tools/snapshot.yml @@ -0,0 +1,9 @@ +version: 1 +scenario: session-list-tools +profile: headless +composition: session-list-tools +recording: authored +header: + class: session-list-tools + pin: true + systemPromptSource: text-turn diff --git a/snapshots/session/session-list-tools/tool-schemas.expected.json b/snapshots/session/session-list-tools/tool-schemas.expected.json new file mode 100644 index 0000000000..0cc0d307b3 --- /dev/null +++ b/snapshots/session/session-list-tools/tool-schemas.expected.json @@ -0,0 +1,689 @@ +{ + "initial": [ + { + "name": "apply_patch", + "description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.", + "parameters": { + "type": "object", + "properties": { + "input": { + "type": "string", + "description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "input" + ] + } + }, + { + "name": "bash", + "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell; pass `workdir` instead of using `cd`. Managed `$DSH_*` variables expose current harness environment facts. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Provide `description` before `command` in the arguments. Before any delete or move, verify that the resolved absolute target path is the intended one; never run it against a computed path you have not checked. An unset variable expands to an empty string, so guard variables in such paths with `${VAR:?}`. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under mode]`, a policy denial: do not retry another way.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." + }, + "command": { + "type": "string", + "description": "The bash command to execute." + }, + "timeoutMs": { + "type": "number", + "description": "Timeout in milliseconds. The executor applies its configured default and cap; on expiry the command moves to the background as a job instead of being killed." + }, + "workdir": { + "type": "string", + "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." + }, + "run_in_background": { + "type": "boolean", + "description": "Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact command the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "description", + "command" + ] + } + }, + { + "name": "create_goal", + "description": "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The concrete completion objective inferred from the direct human request." + }, + "max_goal_rounds": { + "type": "number", + "description": "Optional positive safe-integer limit on automatic continuation rounds." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "edit", + "description": "Edit an existing UTF-8 text file by replacing literal text.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to edit, resolved by the filesystem backend. Provide `file_path` before `old_string` and `new_string` in the arguments." + }, + "old_string": { + "type": "string", + "description": "Literal text to replace." + }, + "new_string": { + "type": "string", + "description": "Literal replacement text. Use an empty string to delete the match." + }, + "replace_all": { + "type": "boolean", + "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "file_path", + "old_string", + "new_string" + ] + } + }, + { + "name": "get_goal", + "description": "Read the current session goal, including the id and revision that update_goal requires.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "glob", + "description": "Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Glob pattern to match file paths against (e.g. \"**/*.ts\", \"src/**/*.test.js\"). A pattern with no \"/\" matches the basename at any depth, so \"*\" and \"*.ts\" both search the whole tree; include a separator to anchor the depth." + }, + "path": { + "type": "string", + "description": "Directory to search in. Defaults to the session workspace; a relative path resolves against it." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "grep", + "description": "Search file contents with a ripgrep regular expression. Returns matching lines with line numbers, grouped by file. Returns up to 250 matches; a larger result reports where the complete match list was saved.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Regular expression to search for (ripgrep syntax)." + }, + "path": { + "type": "string", + "description": "File or directory to search. Defaults to the session workspace; a relative path resolves against it." + }, + "include": { + "type": "string", + "description": "One glob filter for which files to search (e.g. \"*.ts\", \"*.{js,jsx}\"). Not a list; negation is not supported." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "job_kill", + "description": "Request cancellation of a running background job.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "reason": { + "type": "string", + "description": "Optional short reason, recorded in the log and forwarded to the job." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "job_list", + "description": "List your background jobs (running and finished) with their ids, kinds, and statuses.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "job_output", + "description": "Read a background job: output since the previous read for stream jobs, or the result of a finished final-output job.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "wait": { + "type": "boolean", + "description": "Block until the job finishes or the timeout expires; a timed-out wait leaves the job running. Defaults to false." + }, + "timeout_ms": { + "type": "number", + "description": "Max wait in milliseconds with wait: true. Defaults to and is capped by configuration." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "list_agents", + "description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry names, descriptions, and status. A descendant's name is its path from the root, such as reviewer/checker. You can message any other agent in the subagent tree. running means it is working; inactive means no turn is executing; it does not indicate task completion, success, or failure. corrupt, unsupported, or unavailable means this row's own descendants could not be read; the row itself is still a member you can message. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "list_session", + "description": "List sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null.", + "parameters": { + "type": "object", + "properties": { + "workspace_id": { + "type": "string", + "description": "Workspace ID from list_workspace. Includes its members and, when requested, subagents belonging through their nearest member ancestor. Omit to list all accessible sessions." + }, + "contain_subagent": { + "type": "boolean", + "description": "Include subagent sessions. Defaults to false." + }, + "archived": { + "type": "boolean", + "description": "Return only archived sessions when true, otherwise only unarchived sessions. Defaults to false." + }, + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } + } + }, + { + "name": "list_workspace", + "description": "List workspaces in registry order, including empty workspaces. Returns IDs, titles, paths, and creation and update times.", + "parameters": { + "type": "object", + "properties": { + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } + } + }, + { + "name": "read", + "description": "Read a UTF-8 text file and return line-numbered content.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to read, resolved by the filesystem backend." + }, + "offset": { + "type": "number", + "description": "1-based first line to return. Defaults to 1." + }, + "limit": { + "type": "number", + "description": "Maximum number of lines to return. Defaults to 2000." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "read_image", + "description": "Read a PNG/JPEG/WebP/GIF file and return the image itself. Large images are downscaled automatically; do not install image libraries or create thumbnails to inspect an image.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to the image file, resolved by the filesystem backend." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "send_message", + "description": "Send a message to an agent. A working agent receives it at its next step; an idle agent starts a new turn with it. Returns delivery confirmation.", + "parameters": { + "type": "object", + "properties": { + "agent": { + "type": "string", + "description": "The name of another agent in your subagent tree, as shown by list_agents." + }, + "message": { + "type": "string", + "description": "The message to deliver to the agent." + } + }, + "required": [ + "agent", + "message" + ] + } + }, + { + "name": "skill", + "description": "Load the full instructions for a skill. Call it before acting on a task that names or clearly matches a skill in the session skill catalog.", + "parameters": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The exact skill name from the available skills list." + } + }, + "required": [ + "name" + ] + } + }, + { + "name": "subagent", + "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent returns its result, not its intermediate steps. This tool starts an independently managed subagent and immediately returns its name. If you are still online when it finishes, the runtime automatically delivers its completion notice. The notice includes the final answer unless the child sent you a message just before finishing. Use `send_message` to steer it while running or continue its conversation after it finishes.", + "parameters": { + "type": "object", + "properties": { + "cwd": { + "type": "string", + "description": "Initial child working directory. Relative paths use your current directory; omitted inherits it. Later directory changes in either agent are independent." + }, + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display. Use the language of the user's current request." + }, + "name": { + "type": "string", + "description": "Optional short name for the subagent, unique among the subagents you create: lower-case letters, digits, and hyphens, starting with a letter, at most 32 characters; lead is reserved for the root agent. Omitted names default to agent-1, agent-2, and so on." + }, + "prompt": { + "type": "string", + "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "subagent_fork", + "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn). Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive its result, not its intermediate steps. This tool starts an independently managed subagent and immediately returns its name. If you are still online when it finishes, the runtime automatically delivers its completion notice. The notice includes the final answer unless the child sent you a message just before finishing. Use `send_message` to steer it while running or continue its conversation after it finishes.", + "parameters": { + "type": "object", + "properties": { + "cwd": { + "type": "string", + "description": "Initial child working directory. Relative paths use your current directory; omitted inherits it. Later directory changes in either agent are independent." + }, + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display. Use the language of the user's current request." + }, + "name": { + "type": "string", + "description": "Optional short name for the subagent, unique among the subagents you create: lower-case letters, digits, and hyphens, starting with a letter, at most 32 characters; lead is reserved for the root agent. Omitted names default to agent-1, agent-2, and so on." + }, + "prompt": { + "type": "string", + "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "todo_write", + "description": "Record and update a task list to plan multi-step work and show progress; skip it for trivial single-step tasks. Add one todo per concrete step before you start. While work remains, keep the todos being worked on `in_progress`, several only when work runs in parallel. Mark each todo `completed` as soon as it is done.", + "parameters": { + "type": "object", + "properties": { + "todos": { + "type": "array", + "description": "The COMPLETE task list, replacing any previous list.", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "content": { + "type": "string", + "description": "What the task is — a short imperative line." + }, + "status": { + "type": "string", + "description": "pending (not started) | in_progress (now) | completed (done).", + "enum": [ + "pending", + "in_progress", + "completed" + ] + } + }, + "required": [ + "content", + "status" + ] + } + } + }, + "required": [ + "todos" + ] + } + }, + { + "name": "update_goal", + "description": "Update the current goal.", + "parameters": { + "type": "object", + "properties": { + "goal_id": { + "type": "string", + "description": "Exact id returned by get_goal." + }, + "revision": { + "type": "number", + "description": "Exact positive revision returned by get_goal." + }, + "action": { + "type": "string", + "description": "edit, pause, and resume require a direct top-level human request. complete and blocked are also allowed during an automatic continuation of this goal; blocked is rejected before the configured minimum round count.", + "enum": [ + "edit", + "pause", + "resume", + "complete", + "blocked" + ] + }, + "objective": { + "type": "string", + "description": "Replacement objective; valid only with action edit." + }, + "max_goal_rounds": { + "type": "number", + "description": "Replacement cap; valid only with action edit." + }, + "blocked_reason": { + "type": "string", + "description": "Required only with action blocked: the concrete condition that persisted across rounds and blocks progress." + } + }, + "required": [ + "goal_id", + "revision", + "action" + ] + } + }, + { + "name": "wait_agent", + "description": "Wait for input at your next step, including agent messages, completion notifications, and user steering. Returns immediately if new input is pending. `timedOut: false` means new input is pending. Pending input is delivered to the model after code execution finishes.", + "parameters": { + "type": "object", + "properties": { + "timeout_ms": { + "type": "integer", + "description": "Wait duration in milliseconds, from 10000 through 3600000. Defaults to 30000." + } + } + } + }, + { + "name": "web_fetch", + "description": "Fetch the content of a specific HTTP(S) URL and return it decoded to text.", + "parameters": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The HTTP(S) URL to fetch." + } + }, + "required": [ + "url" + ] + } + }, + { + "name": "web_search", + "description": "Search the web for current information. Returns an optional summary answer and a list of source URLs.", + "parameters": { + "type": "object", + "properties": { + "queries": { + "type": "array", + "description": "1–10 search queries; their results are merged.", + "items": { + "type": "string" + } + } + }, + "required": [ + "queries" + ] + } + }, + { + "name": "workflow", + "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides.\n- `pipeline(items, ...stages): Promise` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. A stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) end the whole script instead of producing `null`. The script has no filesystem, network, timer, or Node.js APIs; the agents do the work.", + "parameters": { + "type": "object", + "properties": { + "script": { + "type": "string", + "description": "The plain JavaScript body, not TypeScript and without an `export const meta` statement; top-level await is allowed. End with `return `; the JSON-serializable value is this tool's result." + }, + "meta": { + "type": "object", + "description": "The workflow identity as plain JSON, not code.", + "additionalProperties": true, + "properties": { + "name": { + "type": "string", + "description": "Short kebab-case workflow name." + }, + "description": { + "type": "string", + "description": "One-line description of what the workflow does." + }, + "whenToUse": { + "type": "string", + "description": "Optional guidance on when this workflow applies." + }, + "phases": { + "type": "array", + "description": "Optional phase declarations matched by phase() calls.", + "items": { + "type": "object", + "additionalProperties": true, + "properties": { + "title": { + "type": "string", + "description": "The phase title phase() calls match by exact string." + }, + "detail": { + "type": "string", + "description": "Optional one-line description of the phase." + }, + "provider": { + "type": "string", + "description": "Optional provider override this phase is expected to use." + }, + "model": { + "type": "string", + "description": "Optional model override this phase is expected to use." + } + }, + "required": [ + "title" + ] + } + } + }, + "required": [ + "name", + "description" + ] + }, + "args": { + "type": "object", + "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", + "additionalProperties": true + }, + "run_in_background": { + "type": "boolean", + "description": "Run as a background job: return a job id immediately instead of waiting; the return value arrives with the completion notice." + } + }, + "required": [ + "script", + "meta" + ] + } + }, + { + "name": "working_directory", + "description": "Read the current working directory, or change it with cd. Relative paths use the current directory. Existing shells and running processes keep their own directories.", + "parameters": { + "type": "object", + "properties": { + "cd": { + "type": "string", + "description": "Existing directory to enter. Omit to read the current directory." + } + } + } + }, + { + "name": "write", + "description": "Create or fully replace a UTF-8 text file.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to write, resolved by the filesystem backend. Provide `file_path` before `content` in the arguments." + }, + "content": { + "type": "string", + "description": "Full UTF-8 text content to write." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "file_path", + "content" + ] + } + } + ], + "changes": [] +} diff --git a/tsconfig.base.json b/tsconfig.base.json index e8ca4f8e44..946b230483 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -169,6 +169,7 @@ "@deepseek-ai/dsh-session/chunk-rows": ["./packages/core/session/src/chunk-rows.ts"], "@deepseek-ai/dsh-session/surface": ["./packages/core/session/src/surface.ts"], "@deepseek-ai/dsh-session/fork": ["./packages/core/session/src/fork.ts"], + "@deepseek-ai/dsh-session-query/types": ["./packages/session-query/session-query/src/types.ts"], "@deepseek-ai/dsh-session-projection/types": ["./packages/session/session-projection/src/types.ts"], "@deepseek-ai/dsh-tool-todo/types": ["./packages/todo/tool-todo/src/types.ts"], "@deepseek-ai/dsh-tool-todo/client": ["./packages/todo/tool-todo/src/client.ts"], @@ -597,6 +598,7 @@ "@deepseek-ai/dsh-tool-pwsh-persistent": ["./packages/shell/tool-pwsh-persistent/src"], "@deepseek-ai/dsh-tool-ralph": ["./packages/experimental/tool-ralph/src"], "@deepseek-ai/dsh-tool-schedule": ["./packages/schedule/tool-schedule/src"], + "@deepseek-ai/dsh-tool-session-list": ["./packages/session-query/tool-session-list/src"], "@deepseek-ai/dsh-tool-session-query": ["./packages/experimental/tool-session-query/src"], "@deepseek-ai/dsh-tool-skill": ["./packages/skill/tool-skill/src"], "@deepseek-ai/dsh-tool-str-replace-editor": ["./packages/fs/tool-str-replace-editor/src"], diff --git a/tsconfig.host.json b/tsconfig.host.json index 21ad8213c5..b8fa7559c2 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -424,6 +424,7 @@ { "path": "./packages/experimental/forge-bundle" }, { "path": "./packages/experimental/client-ui-forge/tsconfig.host.json" }, { "path": "./packages/session/tool-working-directory" }, + { "path": "./packages/session-query/tool-session-list" }, { "path": "./packages/session/session-title-llm" }, { "path": "./packages/session/session-title-first-prompt-llm" }, { "path": "./packages/experimental/session-title-all-prompts-llm" }, From 140547ca1f712a49d1dfd951c283891fbd37a0c7 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Tue, 10 Nov 2026 16:15:56 +0800 Subject: [PATCH 03/48] docs: regenerate module graph for session list tools --- docs/module-graph.md | 9 +++++++++ docs/module-graph.zh.md | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/docs/module-graph.md b/docs/module-graph.md index 7b28621265..fa4bd77035 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -111,6 +111,7 @@ flowchart TD pkg_session_log_export["session-log-export"] pkg_session_query["session-query"] pkg_session_query_sqlite["session-query-sqlite"] + pkg_tool_session_list["tool-session-list"] end subgraph group_acp["packages/acp"] pkg_acp["acp"] @@ -1247,6 +1248,13 @@ flowchart TD pkg_session_query_sqlite --> pkg_session pkg_session_query_sqlite --> pkg_session_persistence pkg_session_query_sqlite --> pkg_session_query + pkg_tool_session_list --> pkg_session + pkg_tool_session_list --> pkg_session_projection + pkg_tool_session_list --> pkg_session_projection_cache + pkg_tool_session_list --> pkg_session_query + pkg_tool_session_list --> pkg_session_title + pkg_tool_session_list --> pkg_tools + pkg_tool_session_list --> pkg_workspace pkg_acp --> pkg_agent pkg_acp --> pkg_attachment pkg_acp --> pkg_llm @@ -1882,6 +1890,7 @@ flowchart TD | [`subagent`](../packages/subagent/subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval), [`util-time`](../packages/util/time), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`spill-policy`](../packages/spill/spill-policy) | `spill` | [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools) | | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | +| [`tool-session-list`](../packages/session-query/tool-session-list) | `session-query` | [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`tools`](../packages/core/tools), [`workspace`](../packages/workspace/workspace) | | [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`mcp-client`](../packages/mcp/mcp-client), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`token-meter`](../packages/llm/token-meter), [`user-approval`](../packages/interaction/user-approval) | | [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`brand`](../packages/util/brand), [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 4ddd93c256..99329ee2ab 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -113,6 +113,7 @@ flowchart TD pkg_session_log_export["session-log-export"] pkg_session_query["session-query"] pkg_session_query_sqlite["session-query-sqlite"] + pkg_tool_session_list["tool-session-list"] end subgraph group_acp["packages/acp"] pkg_acp["acp"] @@ -1249,6 +1250,13 @@ flowchart TD pkg_session_query_sqlite --> pkg_session pkg_session_query_sqlite --> pkg_session_persistence pkg_session_query_sqlite --> pkg_session_query + pkg_tool_session_list --> pkg_session + pkg_tool_session_list --> pkg_session_projection + pkg_tool_session_list --> pkg_session_projection_cache + pkg_tool_session_list --> pkg_session_query + pkg_tool_session_list --> pkg_session_title + pkg_tool_session_list --> pkg_tools + pkg_tool_session_list --> pkg_workspace pkg_acp --> pkg_agent pkg_acp --> pkg_attachment pkg_acp --> pkg_llm @@ -1884,6 +1892,7 @@ flowchart TD | [`subagent`](../packages/subagent/subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval), [`util-time`](../packages/util/time), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`spill-policy`](../packages/spill/spill-policy) | `spill` | [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools) | | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | +| [`tool-session-list`](../packages/session-query/tool-session-list) | `session-query` | [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`tools`](../packages/core/tools), [`workspace`](../packages/workspace/workspace) | | [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`mcp-client`](../packages/mcp/mcp-client), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`token-meter`](../packages/llm/token-meter), [`user-approval`](../packages/interaction/user-approval) | | [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`brand`](../packages/util/brand), [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | From e8273f64667582a90fcfc5c29d4ac4e0cbcb2967 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Tue, 10 Nov 2026 16:24:56 +0800 Subject: [PATCH 04/48] test(tools): include session list tools in catalog roster --- packages/core/tools/tests/gen-tool-catalog.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/tools/tests/gen-tool-catalog.spec.ts b/packages/core/tools/tests/gen-tool-catalog.spec.ts index b9fe22584c..6df6ce6c3e 100644 --- a/packages/core/tools/tests/gen-tool-catalog.spec.ts +++ b/packages/core/tools/tests/gen-tool-catalog.spec.ts @@ -31,8 +31,8 @@ describe('gen-tool-catalog collectToolCatalog', () => { 'cordis_inspect_query', 'create_goal', 'create_worktree', 'edit', 'exit_plan_mode', 'get_goal', 'glob', 'grep', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', - 'list_agents', 'list_mcp_resource_templates', 'list_mcp_resources', - 'list_subagent_models', 'load_workspace_dependencies', 'lsp', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'plugin_market', 'present', 'propose_action', 'pwsh', 'pwsh', 'ralph', + 'list_agents', 'list_mcp_resource_templates', 'list_mcp_resources', 'list_session', + 'list_subagent_models', 'list_workspace', 'load_workspace_dependencies', 'lsp', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'plugin_market', 'present', 'propose_action', 'pwsh', 'pwsh', 'ralph', 'read', 'read_image', 'read_mcp_resource', 'run_code', 'schedule_create', 'schedule_edit', 'schedule_list', 'schedule_view', 'send_message', 'session_event_read', 'session_event_search', 'session_event_trace', 'session_search', 'session_trace', 'skill', From c0037256e01e7b6608ac16a6c528c154daa0d46f Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Tue, 10 Nov 2026 17:09:37 +0800 Subject: [PATCH 05/48] refactor(session): remove list tool work slicing --- docs/config-catalog.md | 18 +--- docs/config-catalog.zh.md | 18 +--- .../skills/dsh-doc/references/packages.md | 2 +- .../tool-session-list/README.i18n.yaml | 12 +-- .../session-query/tool-session-list/README.md | 8 +- .../tool-session-list/README.zh.md | 8 +- .../tool-session-list/package.json | 3 - .../tool-session-list/src/index.ts | 21 +--- .../tool-session-list/src/list.ts | 10 -- .../tests/tool-session-list.spec.ts | 102 +----------------- pnpm-lock.yaml | 4 - 11 files changed, 16 insertions(+), 190 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 48be42f926..13a56ed8cc 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -4482,23 +4482,6 @@ export interface Config { ``` - - - -## `@deepseek-ai/dsh-tool-session-list` - -- `inject`: `tools` · `sessions` · `sessionQuery` · `workspaceRegistry` · `sessionProjections` -- `source`: [`packages/session-query/tool-session-list/src/index.ts:18`](../packages/session-query/tool-session-list/src/index.ts) - -```ts config-catalog -/** Deployment-owned responsiveness for large Session lists. */ -export interface Config { - /** Positive integral work slice in milliseconds; defaults to 16. Checked between complete rows. */ - readonly listWorkSliceMs?: number -} -``` - - @@ -5182,6 +5165,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-tool-cordis` | `tools` · `cordisInspect` | [`packages/extensions/tool-cordis/src/index.ts`](../packages/extensions/tool-cordis/src/index.ts) | | `@deepseek-ai/dsh-tool-executor-native` | `tools` | [`packages/core/tool-executor-native/src/index.ts`](../packages/core/tool-executor-native/src/index.ts) | | `@deepseek-ai/dsh-tool-schedule` | `tools` · `systemPrompt` | [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) | +| `@deepseek-ai/dsh-tool-session-list` | `tools` · `sessions` · `sessionQuery` · `workspaceRegistry` · `sessionProjections` | [`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) | | `@deepseek-ai/dsh-tool-working-directory` | `tools` · `workingDirectory` | [`packages/session/tool-working-directory/src/index.ts`](../packages/session/tool-working-directory/src/index.ts) | | `@deepseek-ai/dsh-tools` | `systemPrompt` | [`packages/core/tools/src/index.ts`](../packages/core/tools/src/index.ts) | | `@deepseek-ai/dsh-user-questions` | — | [`packages/interaction/user-questions/src/index.ts`](../packages/interaction/user-questions/src/index.ts) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 77d249aa80..11fc3b912d 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -4484,23 +4484,6 @@ export interface Config { ``` - - - -## `@deepseek-ai/dsh-tool-session-list` - -- `inject`: `tools` · `sessions` · `sessionQuery` · `workspaceRegistry` · `sessionProjections` -- `source`: [`packages/session-query/tool-session-list/src/index.ts:18`](../packages/session-query/tool-session-list/src/index.ts) - -```ts config-catalog -/** Deployment-owned responsiveness for large Session lists. */ -export interface Config { - /** Positive integral work slice in milliseconds; defaults to 16. Checked between complete rows. */ - readonly listWorkSliceMs?: number -} -``` - - @@ -5184,6 +5167,7 @@ export interface Config { | `@deepseek-ai/dsh-tool-cordis` | `tools` · `cordisInspect` | [`packages/extensions/tool-cordis/src/index.ts`](../packages/extensions/tool-cordis/src/index.ts) | | `@deepseek-ai/dsh-tool-executor-native` | `tools` | [`packages/core/tool-executor-native/src/index.ts`](../packages/core/tool-executor-native/src/index.ts) | | `@deepseek-ai/dsh-tool-schedule` | `tools` · `systemPrompt` | [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) | +| `@deepseek-ai/dsh-tool-session-list` | `tools` · `sessions` · `sessionQuery` · `workspaceRegistry` · `sessionProjections` | [`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) | | `@deepseek-ai/dsh-tool-working-directory` | `tools` · `workingDirectory` | [`packages/session/tool-working-directory/src/index.ts`](../packages/session/tool-working-directory/src/index.ts) | | `@deepseek-ai/dsh-tools` | `systemPrompt` | [`packages/core/tools/src/index.ts`](../packages/core/tools/src/index.ts) | | `@deepseek-ai/dsh-user-questions` | — | [`packages/interaction/user-questions/src/index.ts`](../packages/interaction/user-questions/src/index.ts) | diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md index 9651f13643..54f7843405 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -403,7 +403,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo |---|---|---| | `@deepseek-ai/dsh-session-log-export` | yes | Web Session-log ZIP export and Session Markdown copy | | `@deepseek-ai/dsh-session-query-sqlite` | yes | Concrete ctx.sessionQuery backend with SQLite FTS5 search | -| `@deepseek-ai/dsh-tool-session-list` | yes | Read-only paginated Workspace and Session metadata tools | +| `@deepseek-ai/dsh-tool-session-list` | no | Read-only paginated Workspace and Session metadata tools | ## settings diff --git a/packages/session-query/tool-session-list/README.i18n.yaml b/packages/session-query/tool-session-list/README.i18n.yaml index a44227e3d0..53c6e0e891 100644 --- a/packages/session-query/tool-session-list/README.i18n.yaml +++ b/packages/session-query/tool-session-list/README.i18n.yaml @@ -15,14 +15,14 @@ en: d152484eb41ac6b4 zh: 5acc0d3807846b6e /deepseek-ai-dsh-tool-session-list/use-this-package: - en: 653ca12bb7c76f9d - zh: 4dc851c44aa30eb1 + en: 388849d88b975263 + zh: df6db1e31c9bba7c /deepseek-ai-dsh-tool-session-list/use-this-package/access-and-composition: - en: efa812b2b38914ae - zh: 4d44617966d00378 + en: 0bf65fbc8660134a + zh: f4f7b3a0049d3196 /deepseek-ai-dsh-tool-session-list/use-this-package/listing-behavior: - en: 9170312b97f617fb - zh: 0e7a397ea03d6695 + en: 77a4b342a8be5311 + zh: eb166df6d600df90 /deepseek-ai-dsh-tool-session-list/use-this-package/failures: en: be4dd03d3877e2ed zh: 27c38df3c449dde9 diff --git a/packages/session-query/tool-session-list/README.md b/packages/session-query/tool-session-list/README.md index c45163b510..a8eda14d56 100644 --- a/packages/session-query/tool-session-list/README.md +++ b/packages/session-query/tool-session-list/README.md @@ -25,7 +25,7 @@ Discover workspaces and sessions without resuming an agent or reading cold conve ## Use this package -Mount this optional plugin where the intended callers receive tools. It is absent from the default profiles. +Mount this optional plugin where the intended callers receive tools. It has no configuration fields and is absent from the default profiles. ### Access and composition @@ -41,10 +41,6 @@ The plugin requires `tools`, `sessions`, `sessionQuery`, `workspaceRegistry`, an name: '@deepseek-ai/dsh-tool-session-list' ``` -| Field | Default | Meaning | -|---|---|---| -| `listWorkSliceMs` | `16` | Positive safe integer work slice in milliseconds for Session metadata reads; checked between complete rows | - When the composition already mounts `workspaceRegistry`, add only the tool row. Workspace initialization follows the [registry's existing history bootstrap](../../workspace/workspace/README.md); listing calls do not create or attach sessions or change registry records. ### Listing behavior @@ -55,7 +51,7 @@ Both tools return an array directly. The [tool catalog](../../../docs/tool-catal Session order is descending `updated_at`, then ascending Session ID for ties. Activity time is the later of creation and the latest human-authored prompt; assistant activity and title changes do not advance it. Titles come from live projections or persisted projection metadata. Unavailable titles are `null`, and unavailable activity metadata falls back to creation time. Timestamps are ISO 8601 strings. Pin order and manual sidebar order do not affect the results. -Session metadata reads yield between complete rows when the configured work slice expires and check cancellation before continuing. The slice is not a hard latency bound: it cannot split one synchronous row, query enumeration, or final sorting. The list does not promise one snapshot across all Sessions. +After header enumeration, filtering, metadata reads, and sorting run synchronously. The call does not promise prompt handling of new cancellation requests during this work or one snapshot across all Sessions. ### Failures diff --git a/packages/session-query/tool-session-list/README.zh.md b/packages/session-query/tool-session-list/README.zh.md index 54049b9d57..65492ef42b 100644 --- a/packages/session-query/tool-session-list/README.zh.md +++ b/packages/session-query/tool-session-list/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -在预期调用者获取工具的作用域中挂载此可选插件。默认配置方案不包含它。 +在预期调用者获取工具的作用域中挂载此可选插件。它没有配置字段,默认配置方案不包含它。 ### 访问范围与组合 @@ -41,10 +41,6 @@ kind: "package-reference" name: '@deepseek-ai/dsh-tool-session-list' ``` -| 字段 | 默认值 | 含义 | -|---|---|---| -| `listWorkSliceMs` | `16` | Session 元数据读取的工作时间片,单位为毫秒,必须是正安全整数;在完整条目之间检查 | - 如果组合已经挂载 `workspaceRegistry`,只添加工具条目。Workspace 初始化遵循[注册表现有的历史引导行为](../../workspace/workspace/README.zh.md);列表调用不会创建或接入会话,也不会修改注册表记录。 ### 列表行为 @@ -55,7 +51,7 @@ kind: "package-reference" 会话按 `updated_at` 降序排列,时间相同则按 Session ID 升序排列。活动时间取创建时间与最近人工提示词时间的较晚值;助手活动和标题变化不会推进它。标题来自实时投影或持久化投影元数据。标题不可用时为 `null`,活动元数据不可用时回退到创建时间。时间戳使用 ISO 8601 字符串。置顶顺序和侧边栏手动顺序不影响结果。 -Session 元数据读取在配置的工作时间片耗尽时,于完整条目之间让出执行,并在继续前检查取消。时间片不是严格的延迟上限:它无法切分单条同步读取、查询枚举或最终排序。列表不承诺所有 Session 共享同一个快照。 +header 枚举之后,筛选、元数据读取和排序同步执行。调用不承诺在这段工作中及时处理新收到的取消请求,也不承诺所有 Session 共享同一个快照。 ### 失败 diff --git a/packages/session-query/tool-session-list/package.json b/packages/session-query/tool-session-list/package.json index 897629f33e..26ac358141 100644 --- a/packages/session-query/tool-session-list/package.json +++ b/packages/session-query/tool-session-list/package.json @@ -67,8 +67,5 @@ "@deepseek-ai/dsh-session-title": { "optional": true } - }, - "dependencies": { - "@deepseek-ai/schemastery": "workspace:~" } } diff --git a/packages/session-query/tool-session-list/src/index.ts b/packages/session-query/tool-session-list/src/index.ts index 24fb9b3825..f3e2ed47c7 100644 --- a/packages/session-query/tool-session-list/src/index.ts +++ b/packages/session-query/tool-session-list/src/index.ts @@ -4,7 +4,6 @@ */ import type { Context } from '@deepseek-ai/cordis' -import z from '@deepseek-ai/schemastery' import { registerSessionListMetadata } from '@deepseek-ai/dsh-session-query' import { defineTool } from '@deepseek-ai/dsh-tools' import { listSessions, listWorkspaces } from './list.ts' @@ -14,17 +13,6 @@ export const name = 'tool-session-list' /** Services needed for header-only listing and live metadata. */ export const inject = ['tools', 'sessions', 'sessionQuery', 'workspaceRegistry', 'sessionProjections'] -/** Deployment-owned responsiveness for large Session lists. */ -export interface Config { - /** Positive integral work slice in milliseconds; defaults to 16. Checked between complete rows. */ - readonly listWorkSliceMs?: number -} - -/** Loader configuration for cooperative list scheduling. */ -export const Config: z = z.object({ - listWorkSliceMs: z.number().step(1).min(1).default(16), -}) - const pagination = { limit: { type: 'integer', description: 'Maximum entries to return, from 1 to 100. Defaults to 20.' }, offset: { type: 'integer', description: 'Number of matching entries to skip. Defaults to 0.' }, @@ -33,14 +21,9 @@ const pagination = { /** * Grant tools access to all Workspace and Session metadata in this runtime. * @param ctx - scoped context granting these tools to its callers. - * @param config - deployment work-slice choice; omitted uses 16 milliseconds. * @returns when the shared list metadata projection and tools are registered. */ -export async function apply(ctx: Context, config: Config = {}): Promise { - const workSliceMs = config.listWorkSliceMs ?? 16 - if (!Number.isSafeInteger(workSliceMs) || workSliceMs < 1) { - throw new TypeError('tool-session-list: listWorkSliceMs must be a positive safe integer') - } +export async function apply(ctx: Context): Promise { const readMetadata = await registerSessionListMetadata(ctx) ctx.tools.register(defineTool({ name: 'list_workspace', @@ -93,7 +76,7 @@ export async function apply(ctx: Context, config: Config = {}): Promise { render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], }, isConcurrencySafe: () => true, - execute: (args, exec) => listSessions(ctx, readMetadata, args, exec.signal, workSliceMs), + execute: (args, exec) => listSessions(ctx, readMetadata, args, exec.signal), presentCall: args => ({ card: 'generic', title: 'List sessions', kind: 'read', rawInput: args.workspace_id }), })) } diff --git a/packages/session-query/tool-session-list/src/list.ts b/packages/session-query/tool-session-list/src/list.ts index 1176e3db48..68fed14528 100644 --- a/packages/session-query/tool-session-list/src/list.ts +++ b/packages/session-query/tool-session-list/src/list.ts @@ -1,7 +1,5 @@ /** Header-only selection and cached metadata for the read-only listing tools. */ -import { performance } from 'node:perf_hooks' -import { scheduler } from 'node:timers/promises' import type { Context } from '@deepseek-ai/cordis' import type { Session, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import { SessionQueryError, type SessionListMetadata } from '@deepseek-ai/dsh-session-query' @@ -80,7 +78,6 @@ export function listWorkspaces(ctx: Context, input: PageInput, signal: AbortSign * @param readLiveMetadata - ready reader owned by this plugin's registration. * @param input - filters and pagination arguments. * @param signal - caller cancellation, forwarded to the corpus listing. - * @param workSliceMs - resolved positive integral work slice between complete rows. * @returns filtered Session metadata ordered by activity, then identity. */ export async function listSessions( @@ -88,7 +85,6 @@ export async function listSessions( readLiveMetadata: (session: Session) => SessionListMetadata, input: SessionListInput, signal: AbortSignal, - workSliceMs: number, ): Promise { const { limit, offset } = resolvePage(input) signal.throwIfAborted() @@ -108,14 +104,8 @@ export async function listSessions( const headers = new Map(records.map(record => [record.header.id, record.header])) const nearestWorkspace = ancestorWorkspaceReader(headers, ownership) const items = [] - let yieldDeadline = performance.now() + workSliceMs for (const { header } of records) { signal.throwIfAborted() - if (performance.now() >= yieldDeadline) { - await scheduler.yield() - signal.throwIfAborted() - yieldDeadline = performance.now() + workSliceMs - } if (!input.contain_subagent && header.origin === 'subagent') continue if (archived.has(header.id) !== (input.archived ?? false)) continue if (workspaceId !== undefined) { diff --git a/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts index a39534a926..87dd7fcac7 100644 --- a/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts +++ b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts @@ -1,8 +1,6 @@ import { mkdir, mkdtemp, realpath, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { performance } from 'node:perf_hooks' -import { scheduler } from 'node:timers/promises' import { Context } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' import { createUserMessage, ToolCallId } from '@deepseek-ai/dsh-llm' @@ -107,7 +105,6 @@ async function mount(options: { archived?: string[] cached?: Array<[string, CheckpointRecord]> cache?: boolean - config?: ToolSessionList.Config } = {}) { const workspaces = options.workspaces ?? [] const ctx = new Context() @@ -139,7 +136,7 @@ async function mount(options: { } await ctx.sessionProjections.register(titleProjectionDefinition) await ctx.plugin(ListingQuery) - const fiber = await ctx.plugin(ToolSessionList, options.config) + const fiber = await ctx.plugin(ToolSessionList) const read = vi.spyOn(ctx.sessionQuery, 'readSession') const titles = vi.spyOn(ctx.sessionQuery, 'readTitleSnapshots') const open = vi.spyOn(ctx.sessionPersistence, 'open') @@ -172,19 +169,6 @@ function prompt(session: Session) { }), { surfaceOp: 'append' }) } -function measureRows(ctx: Context, summaryMs: number) { - const clock = { now: 0 } - const trace: string[] = [] - const cachedSnapshot = ctx.sessionProjectionCache.cachedSnapshot.bind(ctx.sessionProjectionCache) - vi.spyOn(ctx.sessionProjectionCache, 'cachedSnapshot').mockImplementation((meta, keys) => { - clock.now += summaryMs - trace.push(meta.id) - return cachedSnapshot(meta, keys) - }) - vi.spyOn(performance, 'now').mockImplementation(() => clock.now) - return { clock, trace } -} - describe('read-only Session list tools', () => { it('lists empty Workspaces in registry order and applies offset after that order', async () => { const path = await directory() @@ -351,87 +335,3 @@ describe('read-only Session list tools', () => { expect(mounted.ctx.tools.get('list_session')).toBeUndefined() }) }) - -describe('Session list work slices', () => { - const headers = [header('first', 30), header('middle', 20), header('last', 10)] - - it('resolves the default and explicit work slice through Loader configuration', () => { - expect(ToolSessionList.Config({})).toEqual({ listWorkSliceMs: 16 }) - expect(ToolSessionList.Config({ listWorkSliceMs: 8 })).toEqual({ listWorkSliceMs: 8 }) - }) - - it.each([0, -1, 0.5, Number.NaN, Number.POSITIVE_INFINITY, Number.MAX_SAFE_INTEGER + 1])( - 'rejects invalid work slice %s before registering a projection or tool', async (listWorkSliceMs) => { - const ctx = new Context() - contexts.push(ctx) - await expect(ToolSessionList.apply(ctx, { listWorkSliceMs })).rejects.toThrow( - 'tool-session-list: listWorkSliceMs must be a positive safe integer', - ) - }, - ) - - it('keeps cheap metadata reads in one synchronous slice', async () => { - const mounted = await mount({ headers }) - const { trace } = measureRows(mounted.ctx, 2) - const yieldWork = vi.spyOn(scheduler, 'yield') - expect(value(await mounted.call('list_session'))).toEqual([item('first', 30), item('middle', 20), item('last', 10)]) - expect(trace).toEqual(['first', 'middle', 'last']) - expect(yieldWork).not.toHaveBeenCalled() - }) - - it.each([ - { listWorkSliceMs: undefined, summaryMs: 8 }, - { listWorkSliceMs: 8, summaryMs: 4 }, - ])('resumes after an exhausted $listWorkSliceMs slice and resets the deadline after waiting', async ({ listWorkSliceMs, summaryMs }) => { - const mounted = await mount({ headers, config: listWorkSliceMs === undefined ? {} : { listWorkSliceMs } }) - if (listWorkSliceMs === undefined) { - await mounted.fiber.dispose() - await mounted.ctx.plugin({ inject: ToolSessionList.inject, apply: (ctx: Context) => ToolSessionList.apply(ctx) }) - } - const { clock, trace } = measureRows(mounted.ctx, summaryMs) - const yieldWork = vi.spyOn(scheduler, 'yield').mockImplementation(async () => { - trace.push('yield') - clock.now += 1_000 - }) - expect(value(await mounted.call('list_session'))).toEqual([item('first', 30), item('middle', 20), item('last', 10)]) - expect(trace).toEqual(['first', 'middle', 'yield', 'last']) - expect(yieldWork).toHaveBeenCalledOnce() - }) - - it('returns the final completed row without a trailing yield', async () => { - const mounted = await mount({ headers: [header('last', 10)] }) - measureRows(mounted.ctx, 16) - const yieldWork = vi.spyOn(scheduler, 'yield') - expect(value(await mounted.call('list_session'))).toEqual([item('last', 10)]) - expect(yieldWork).not.toHaveBeenCalled() - }) - - it('checks the work slice while classifying rows that the filters exclude', async () => { - const mounted = await mount({ - headers: headers.map(meta => ({ ...meta, origin: 'subagent', parentSession: SessionId('outside') })), - }) - const cached = vi.spyOn(mounted.ctx.sessionProjectionCache, 'cachedSnapshot') - // Classification consumes the first slice even though no metadata row is read. - vi.spyOn(performance, 'now').mockReturnValueOnce(0).mockReturnValueOnce(0).mockReturnValue(16) - const yieldWork = vi.spyOn(scheduler, 'yield').mockResolvedValue() - expect(value(await mounted.call('list_session'))).toEqual([]) - expect(yieldWork).toHaveBeenCalledOnce() - expect(cached).not.toHaveBeenCalled() - expect(mounted.open).not.toHaveBeenCalled() - }) - - it('cancels at a yielded row without reading later metadata or returning a partial list', async () => { - const mounted = await mount({ headers, config: { listWorkSliceMs: 4 } }) - const { trace } = measureRows(mounted.ctx, 4) - const controller = new AbortController() - const yieldWork = vi.spyOn(scheduler, 'yield').mockImplementation(async () => { - controller.abort(new Error('stop between rows')) - }) - const result = await mounted.call('list_session', {}, controller.signal) - expect(result.error?.info).toMatchObject({ name: 'AbortError', code: 'ABORTED' }) - expect(result.value).toBeUndefined() - expect(trace).toEqual(['first']) - expect(yieldWork).toHaveBeenCalledOnce() - expect(mounted.open).not.toHaveBeenCalled() - }) -}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f27d93d4c7..248122fec9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14737,10 +14737,6 @@ importers: version: link:../session-query packages/session-query/tool-session-list: - dependencies: - '@deepseek-ai/schemastery': - specifier: link:../../../vendor/schemastery - version: link:../../../vendor/schemastery devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ From d42563e4ba83cb1adefe5b14952434040810d0aa Mon Sep 17 00:00:00 2001 From: LegGasai Date: Tue, 10 Nov 2026 19:59:14 +0800 Subject: [PATCH 06/48] refactor(llm): publish DeepSeek route credentials through ctx.llm `LlmAdapter.routeCredential(provider)` publishes the credential a route currently sends: kind, resolved base URL, optional reference, a value-free presence check, and per-endpoint grants carrying protocol headers, the bare value, and an optional 401 invalidation. `LlmRuntime.routeCredential()` forwards to the owning adapter. `dsh-llm-deepseek` reads no credential: `resolveAuth(connection, endpoint)` returns a grant or `undefined`, `missingCredential` names the failure, and `credential` declares the publication. The route plugins own their credentials through the new `dsh-credentials` reference helpers and the account service's `resolveRequestCredential()`; the account route also owns sign-out cancellation and registers a running-task report. The account service inspects no Agents, drops its `dsh-agent` and `dsh-llm` peers, and moves to `packages/account/`. The web providers consume route publications and drop their dependencies on `dsh-llm-deepseek`, the route plugins, and the Loader. Documented in the Agent Note and the `llm-route-credential` upgrade guide. --- ...ch-offered-by-provider-readiness.i18n.yaml | 4 +- ...eb-search-offered-by-provider-readiness.md | 2 +- ...search-offered-by-provider-readiness.zh.md | 2 +- ...026-10-29-web-provider-selection.i18n.yaml | 4 +- .../2026-10-29-web-provider-selection.md | 4 +- .../2026-10-29-web-provider-selection.zh.md | 4 +- ...-11-10-llm-route-credential-seam.i18n.yaml | 19 ++ .../2026-11-10-llm-route-credential-seam.md | 37 +++ ...2026-11-10-llm-route-credential-seam.zh.md | 37 +++ ...-10-15-deepseek-search-fetch-api.i18n.yaml | 4 +- .../2026-10-15-deepseek-search-fetch-api.md | 2 +- ...2026-10-15-deepseek-search-fetch-api.zh.md | 2 +- ...dis-cleanup-dependency-lifetimes.i18n.yaml | 4 +- ...-09-cordis-cleanup-dependency-lifetimes.md | 2 +- ...-cordis-cleanup-dependency-lifetimes.zh.md | 2 +- AGENTS.md | 1 + apps/desktop-host/tsconfig.json | 2 +- apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 2 +- apps/desktop/README.zh.md | 2 +- apps/desktop/tsconfig.client.json | 2 +- apps/desktop/tsconfig.host.json | 2 +- docs/capability-seams.i18n.yaml | 4 +- docs/capability-seams.md | 21 +- docs/capability-seams.zh.md | 21 +- docs/config-catalog.md | 6 +- docs/config-catalog.zh.md | 6 +- docs/event-producer-consumer.md | 12 +- docs/event-producer-consumer.zh.md | 12 +- docs/module-graph.md | 92 ++++--- docs/module-graph.zh.md | 92 ++++--- docs/persistence-catalog.i18n.yaml | 72 +++--- docs/persistence-catalog.md | 36 +-- docs/persistence-catalog.zh.md | 36 +-- docs/persistence-schema.json | 34 +-- docs/subsystems/README.i18n.yaml | 4 +- docs/subsystems/README.md | 1 + docs/subsystems/README.zh.md | 1 + docs/subsystems/account.i18n.yaml | 16 ++ docs/subsystems/account.md | 234 ++++++++++++++++++ docs/subsystems/account.zh.md | 234 ++++++++++++++++++ docs/subsystems/credentials.i18n.yaml | 10 +- docs/subsystems/credentials.md | 197 +-------------- docs/subsystems/credentials.zh.md | 197 +-------------- docs/subsystems/llm-streaming.i18n.yaml | 8 +- docs/subsystems/llm-streaming.md | 96 +++++++ docs/subsystems/llm-streaming.zh.md | 96 +++++++ .../llm-route-credential/guide.i18n.yaml | 16 ++ .../v0.2.2-rc.1/llm-route-credential/guide.md | 29 +++ .../llm-route-credential/guide.zh.md | 29 +++ packages/README.i18n.yaml | 4 +- packages/README.md | 7 +- packages/README.zh.md | 7 +- packages/account/README.i18n.yaml | 25 ++ packages/account/README.md | 51 ++++ packages/account/README.zh.md | 51 ++++ .../deepseek-account/README.i18n.yaml | 10 +- .../deepseek-account/README.md | 6 +- .../deepseek-account/README.zh.md | 6 +- .../deepseek-account/locale/de.json | 0 .../deepseek-account/locale/en.json | 0 .../deepseek-account/locale/es.json | 0 .../deepseek-account/locale/fr.json | 0 .../deepseek-account/locale/ja.json | 0 .../deepseek-account/locale/pt.json | 0 .../deepseek-account/locale/ru.json | 0 .../deepseek-account/locale/zh.json | 0 .../deepseek-account/package.json | 11 +- .../deepseek-account/src/client-metadata.ts | 0 .../deepseek-account/src/details.ts | 0 .../deepseek-account/src/index.ts | 43 +++- .../deepseek-account/src/logout.ts | 0 .../deepseek-account/src/notifications.ts | 0 .../deepseek-account/src/protocol.ts | 13 +- .../deepseek-account/src/types.ts | 18 ++ .../deepseek-account/tests/account-stub.ts | 35 +++ .../deepseek-account/tests/account.spec.ts | 29 +++ .../tests/authorization-response.spec.ts | 0 .../tests/client-headers.spec.ts | 0 .../deepseek-account/tests/details.spec.ts | 0 .../tests/diagnostics.spec.ts | 0 .../tests/expected/web-exchange-failure.txt | 0 .../deepseek-account/tests/logout.spec.ts | 0 .../tests/notifications.spec.ts | 0 .../deepseek-account/tests/origins.spec.ts | 0 .../deepseek-account/tests/remote.spec.ts | 19 +- .../deepseek-account/tsconfig.json | 9 +- packages/api/remotes/tsconfig.client.json | 2 +- packages/api/remotes/tsconfig.host.json | 2 +- .../product-analytics/tsconfig.host.json | 2 +- .../ui-account-notifications/tsconfig.json | 2 +- .../client/ui-settings-account/tsconfig.json | 2 +- .../credentials/authorization/package.json | 8 +- .../credentials/authorization/src/index.ts | 2 +- .../credentials/authorization/tsconfig.json | 2 +- .../credentials/credentials/README.i18n.yaml | 4 +- packages/credentials/credentials/README.md | 2 + packages/credentials/credentials/README.zh.md | 2 + packages/credentials/credentials/package.json | 6 +- packages/credentials/credentials/src/index.ts | 33 +++ .../tests/reference-fallback.spec.ts | 50 ++++ .../credentials/credentials/tsconfig.json | 3 + .../deepseek-account/src/account-tasks.ts | 35 --- .../translator/tests/paid-fixture.ts | 6 +- .../extensions/tool-cordis/src/api-catalog.ts | 44 +++- .../llm/llm-deepseek-account/README.i18n.yaml | 12 +- packages/llm/llm-deepseek-account/README.md | 8 +- .../llm/llm-deepseek-account/README.zh.md | 8 +- .../llm/llm-deepseek-account/package.json | 9 +- .../llm-deepseek-account/src/account-tasks.ts | 40 +++ .../llm/llm-deepseek-account/src/index.ts | 36 ++- .../tests/account-quota.spec.ts | 12 +- .../tests/account-tasks.spec.ts | 13 +- .../tests/provider.spec.ts | 37 ++- .../llm/llm-deepseek-account/tsconfig.json | 5 +- .../llm/llm-deepseek-api-key/README.i18n.yaml | 12 +- packages/llm/llm-deepseek-api-key/README.md | 6 +- .../llm/llm-deepseek-api-key/README.zh.md | 6 +- .../llm/llm-deepseek-api-key/src/index.ts | 51 ++-- .../tests/discovery.spec.ts | 23 ++ packages/llm/llm-deepseek/README.i18n.yaml | 4 +- packages/llm/llm-deepseek/README.md | 6 +- packages/llm/llm-deepseek/README.zh.md | 6 +- packages/llm/llm-deepseek/src/adapter.ts | 27 +- packages/llm/llm-deepseek/src/auth-headers.ts | 12 + packages/llm/llm-deepseek/src/credential.ts | 58 ----- packages/llm/llm-deepseek/src/file-store.ts | 6 +- packages/llm/llm-deepseek/src/host.ts | 8 +- packages/llm/llm-deepseek/src/index.ts | 3 +- .../llm/llm-deepseek/src/listing-cache.ts | 25 +- packages/llm/llm-deepseek/src/types.ts | 45 +++- .../tests/account-routing.spec.ts | 12 +- .../llm/llm-deepseek/tests/adapter.spec.ts | 45 ++-- .../llm/llm-deepseek/tests/credential.spec.ts | 71 ------ packages/llm/llm-deepseek/tests/files.spec.ts | 2 +- packages/llm/llm-deepseek/tests/helpers.ts | 2 +- .../llm-deepseek/tests/listing-cache.spec.ts | 19 +- .../llm-deepseek/tests/prepared-call.spec.ts | 5 +- .../llm-deepseek/tests/provider-hooks.spec.ts | 4 +- .../tests/route-credential.spec.ts | 92 +++++++ .../llm/llm-deepseek/tests/runtime.spec.ts | 20 +- packages/llm/llm-deepseek/tsconfig.json | 2 +- packages/llm/llm/src/index.ts | 27 ++ packages/llm/llm/src/types.ts | 81 ++++++ packages/llm/llm/tests/topology.spec.ts | 24 +- .../skills/dsh-doc/references/packages.md | 7 +- .../continuation-messages-adapter.spec.ts | 2 +- .../web/web-deepseek-api/README.i18n.yaml | 12 +- packages/web/web-deepseek-api/README.md | 16 +- packages/web/web-deepseek-api/README.zh.md | 16 +- packages/web/web-deepseek-api/package.json | 26 +- packages/web/web-deepseek-api/src/index.ts | 210 +++++++++------- .../web/web-deepseek-api/src/transport.ts | 99 ++++---- .../tests/composition.spec.ts | 4 +- .../tests/credential-resolution.spec.ts | 95 +++---- .../web/web-deepseek-api/tests/egress.spec.ts | 3 +- .../web/web-deepseek-api/tests/fetch.spec.ts | 7 +- .../web-deepseek-api/tests/redirect.spec.ts | 6 +- packages/web/web-deepseek-api/tests/routes.ts | 73 +++--- .../web/web-deepseek-api/tests/search.spec.ts | 14 +- .../web-deepseek-api/tests/transport.spec.ts | 60 ++++- .../tests/web-deepseek-api.e2e.ts | 6 +- packages/web/web-deepseek-api/tsconfig.json | 12 +- .../web/web-search-deepseek/README.i18n.yaml | 12 +- packages/web/web-search-deepseek/README.md | 12 +- packages/web/web-search-deepseek/README.zh.md | 12 +- packages/web/web-search-deepseek/package.json | 21 +- packages/web/web-search-deepseek/src/index.ts | 74 +++--- .../web/web-search-deepseek/src/provider.ts | 42 ++-- .../tests/deepseek.spec.ts | 113 ++++++--- .../web/web-search-deepseek/tsconfig.json | 5 +- packages/web/web/package.json | 10 +- packages/web/web/src/types.ts | 2 +- packages/web/web/tsconfig.json | 2 +- pnpm-lock.yaml | 121 +++++---- scripts/gen-cordis-catalog.ts | 30 +-- scripts/gen-doc-graphs.ts | 10 +- scripts/plugin-entry-existing-exports.ts | 2 - scripts/type-equiv.manifest.json | 10 + .../verify-package-readme-model-experience.ts | 2 +- .../web-search-billing-fixture.mjs | 5 +- tsconfig.base.json | 6 +- tsconfig.host.json | 2 +- 183 files changed, 2775 insertions(+), 1577 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md create mode 100644 .agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md create mode 100644 docs/subsystems/account.i18n.yaml create mode 100644 docs/subsystems/account.md create mode 100644 docs/subsystems/account.zh.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.zh.md create mode 100644 packages/account/README.i18n.yaml create mode 100644 packages/account/README.md create mode 100644 packages/account/README.zh.md rename packages/{credentials => account}/deepseek-account/README.i18n.yaml (86%) rename packages/{credentials => account}/deepseek-account/README.md (96%) rename packages/{credentials => account}/deepseek-account/README.zh.md (96%) rename packages/{credentials => account}/deepseek-account/locale/de.json (100%) rename packages/{credentials => account}/deepseek-account/locale/en.json (100%) rename packages/{credentials => account}/deepseek-account/locale/es.json (100%) rename packages/{credentials => account}/deepseek-account/locale/fr.json (100%) rename packages/{credentials => account}/deepseek-account/locale/ja.json (100%) rename packages/{credentials => account}/deepseek-account/locale/pt.json (100%) rename packages/{credentials => account}/deepseek-account/locale/ru.json (100%) rename packages/{credentials => account}/deepseek-account/locale/zh.json (100%) rename packages/{credentials => account}/deepseek-account/package.json (87%) rename packages/{credentials => account}/deepseek-account/src/client-metadata.ts (100%) rename packages/{credentials => account}/deepseek-account/src/details.ts (100%) rename packages/{credentials => account}/deepseek-account/src/index.ts (95%) rename packages/{credentials => account}/deepseek-account/src/logout.ts (100%) rename packages/{credentials => account}/deepseek-account/src/notifications.ts (100%) rename packages/{credentials => account}/deepseek-account/src/protocol.ts (95%) rename packages/{credentials => account}/deepseek-account/src/types.ts (89%) create mode 100644 packages/account/deepseek-account/tests/account-stub.ts rename packages/{credentials => account}/deepseek-account/tests/account.spec.ts (97%) rename packages/{credentials => account}/deepseek-account/tests/authorization-response.spec.ts (100%) rename packages/{credentials => account}/deepseek-account/tests/client-headers.spec.ts (100%) rename packages/{credentials => account}/deepseek-account/tests/details.spec.ts (100%) rename packages/{credentials => account}/deepseek-account/tests/diagnostics.spec.ts (100%) rename packages/{credentials => account}/deepseek-account/tests/expected/web-exchange-failure.txt (100%) rename packages/{credentials => account}/deepseek-account/tests/logout.spec.ts (100%) rename packages/{credentials => account}/deepseek-account/tests/notifications.spec.ts (100%) rename packages/{credentials => account}/deepseek-account/tests/origins.spec.ts (100%) rename packages/{credentials => account}/deepseek-account/tests/remote.spec.ts (84%) rename packages/{credentials => account}/deepseek-account/tsconfig.json (78%) create mode 100644 packages/credentials/credentials/tests/reference-fallback.spec.ts delete mode 100644 packages/credentials/deepseek-account/src/account-tasks.ts create mode 100644 packages/llm/llm-deepseek-account/src/account-tasks.ts rename packages/{credentials/deepseek-account => llm/llm-deepseek-account}/tests/account-tasks.spec.ts (78%) create mode 100644 packages/llm/llm-deepseek/src/auth-headers.ts delete mode 100644 packages/llm/llm-deepseek/src/credential.ts delete mode 100644 packages/llm/llm-deepseek/tests/credential.spec.ts create mode 100644 packages/llm/llm-deepseek/tests/route-credential.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml index badb03541e..8344fd2eb2 100644 --- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml @@ -9,8 +9,8 @@ en: 32ba2b2b42e8deb5 zh: 6a6532561f81b8e2 /agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/decision: - en: 08a54b37e157da29 - zh: 65f633055d9df242 + en: 8513348797d8b8c3 + zh: 13d4066e07db0fb9 /agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/alternatives-considered: en: 6da221f6b821ea44 zh: b15774011abed7ed diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md index 2399e3f1fc..ed8c3c2803 100644 --- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md +++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md @@ -13,7 +13,7 @@ English | [中文](2026-09-27-web-search-offered-by-provider-readiness.zh.md) Each role of the web capability seam owns one part of a per-step check: - **Service Definition.** `WebSearchProvider` and `WebFetchProvider` have an optional `ready(llmProvider)` that answers whether an operation made for a model request on that chat route has a credential to send. It checks configuration only and makes no network calls. `ctx.web.searchReady(llmProvider?)` and `ctx.web.fetchReady(llmProvider?)` resolve the provider with the same rules as `search()` and `fetch()` and return its answer. A provider without `ready()` counts as ready, and a selection failure answers true because the operation reports that failure as a structured `WebError`. -- **Service Provider.** Each DeepSeek provider checks its credentials in the order its operation resolves them. `dsh-web-search-deepseek` checks, on the `deepseek-account` route, whether `ctx.deepseekAccount.resolveToken()` returns a token for its Messages endpoint, and then its literal `apiKey` or its `apiKeyEnv` reference. The Search and Fetch API providers of `dsh-web-deepseek-api` resolve the same plan as the operation ([credential resolution](2026-10-29-web-provider-selection.md)): a capability with its own YAML fields checks only the key under its `*ApiKeyEnv`; otherwise, on the account route with the account model route mounted, a token for that route's `/v1/tools` base counts, and then the key of the `deepseek-official` route, or `DEEPSEEK_API_KEY` without that route. A key counts when `ctx.credentials.describe()` reports its reference configured (without that service, when the launching environment carries it); the [shared credential helpers](../../../../packages/llm/llm-deepseek/src/credential.ts) perform these presence checks. A failed account-token or credential-store read answers false, because the operation fails on that read instead of trying the next credential. The providers name no tool or prompt section. +- **Service Provider.** Each DeepSeek provider checks its credentials in the order its operation resolves them. `dsh-web-search-deepseek` checks, on a route whose `ctx.llm.routeCredential()` publishes an account credential, whether that credential is configured for its Messages endpoint, and then its literal `apiKey` or its `apiKeyEnv` reference. The Search and Fetch API providers of `dsh-web-deepseek-api` resolve the same plan as the operation ([credential resolution](2026-10-29-web-provider-selection.md)): a capability with its own YAML fields checks only the key under its `*ApiKeyEnv`; otherwise, on the account route with the account model route mounted, that route's credential configured for its `/v1/tools` base counts, and then the key of the `deepseek-official` route, or `DEEPSEEK_API_KEY` without that route. A key counts when `ctx.credentials.describe()` reports its reference configured (without that service, when the launching environment carries it); the reference helpers of `dsh-credentials` and each route's own presence check perform these checks. A failed account-token or credential-store read answers false, because the operation fails on that read instead of trying the next credential. The providers name no tool or prompt section. - **Consumer.** `dsh-tool-web` registers `web_search` and `web_fetch` with [step activation conditions](../../../../packages/core/tools/README.md#conditional-tools) that ask `ctx.web.searchReady()` and `ctx.web.fetchReady()` about the route of the step's model selection. The agent loop resolves conditions before it assembles the step, so the declared tools, the `tool:web_search` and `tool:web_fetch` prompt sections, PTC program bindings, and dispatch all read the same admitted set. The route decides only whether the account token is checked before the API key, which happens on the `deepseek-account` route; an API key counts on every route, so a conversation on another provider's model is offered the DeepSeek web tools whenever a DeepSeek key is configured. A Search or Fetch API capability with its own YAML fields ignores the route and is ready exactly when its own key is configured. diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md index 61f8acb6f8..96277e8532 100644 --- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md @@ -13,7 +13,7 @@ Status: implemented web 能力 seam 的每个角色各负责逐步骤检查的一部分: - **Service Definition。** `WebSearchProvider` 与 `WebFetchProvider` 有一个可选的 `ready(llmProvider)`,回答为该对话路由上的模型请求发起的操作是否有可发送的凭据。它只检查配置,不发起网络调用。`ctx.web.searchReady(llmProvider?)` 与 `ctx.web.fetchReady(llmProvider?)` 按与 `search()`、`fetch()` 相同的规则解析提供方并返回其回答。没有 `ready()` 的提供方视为就绪;选择失败时回答 true,因为对应操作会把该失败报告为结构化 `WebError`。 -- **Service Provider。** 每个 DeepSeek 提供方都按其操作解析凭据的顺序检查凭据。`dsh-web-search-deepseek` 在 `deepseek-account` 路由上检查 `ctx.deepseekAccount.resolveToken()` 是否为其 Messages 端点返回 token,然后检查其字面 `apiKey` 或 `apiKeyEnv` 引用。`dsh-web-deepseek-api` 的 Search 与 Fetch API 提供方解析与操作相同的方案([凭据解析](2026-10-29-web-provider-selection.zh.md)):在 YAML 中设置了单独字段的能力只检查其 `*ApiKeyEnv` 下的密钥;否则,在账号路由上且账号模型路由已挂载时,该路由 `/v1/tools` 基础地址的 token 算数,然后是 `deepseek-official` 路由的密钥,没有该路由时为 `DEEPSEEK_API_KEY`。`ctx.credentials.describe()` 报告其引用已配置时(没有该服务时,启动环境中存在该变量),密钥即算存在;这些存在性检查由[共享凭据函数](../../../../packages/llm/llm-deepseek/src/credential.ts)执行。读取账号 token 或凭据存储失败时回答 false,因为操作会在该次读取上失败,而不会尝试下一种凭据。提供方不点名任何工具或提示词段落。 +- **Service Provider。** 每个 DeepSeek 提供方都按其操作解析凭据的顺序检查凭据。`dsh-web-search-deepseek` 在 `ctx.llm.routeCredential()` 发布账号凭据的路由上检查该凭据是否已为其 Messages 端点配置,然后检查其字面 `apiKey` 或 `apiKeyEnv` 引用。`dsh-web-deepseek-api` 的 Search 与 Fetch API 提供方解析与操作相同的方案([凭据解析](2026-10-29-web-provider-selection.zh.md)):在 YAML 中设置了单独字段的能力只检查其 `*ApiKeyEnv` 下的密钥;否则,在账号路由上且账号模型路由已挂载时,该路由为其 `/v1/tools` 基础地址配置的凭据算数,然后是 `deepseek-official` 路由的密钥,没有该路由时为 `DEEPSEEK_API_KEY`。`ctx.credentials.describe()` 报告其引用已配置时(没有该服务时,启动环境中存在该变量),密钥即算存在;这些存在性检查由 `dsh-credentials` 的引用函数和各路由自身的存在性检查执行。读取账号 token 或凭据存储失败时回答 false,因为操作会在该次读取上失败,而不会尝试下一种凭据。提供方不点名任何工具或提示词段落。 - **Consumer。** `dsh-tool-web` 注册 `web_search` 与 `web_fetch` 时各带一个[步骤激活条件](../../../../packages/core/tools/README.zh.md#conditional-tools),以该步骤模型选择的路由询问 `ctx.web.searchReady()` 与 `ctx.web.fetchReady()`。agent loop 在组装该步骤之前解析各条件,因此声明的工具、`tool:web_search` 与 `tool:web_fetch` 提示词段落、PTC 程序绑定与派发都读取同一个准入集合。 路由只决定是否先检查账号 token 再检查 API 密钥,这发生在 `deepseek-account` 路由上;API 密钥在每条路由上都算数,因此只要配置了 DeepSeek 密钥,使用其他提供方模型的对话也会获得 DeepSeek Web 工具。在 YAML 中设置了单独字段的 Search 或 Fetch API 能力不看路由,恰在其自身密钥已配置时就绪。 diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml index 9ad135dbed..4c0e201093 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml @@ -18,8 +18,8 @@ en: 9d68ffca5c8be681 zh: 36bb661f98de0ebb /agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/credential-resolution: - en: 15f6fb26c8605260 - zh: 93467641a8ff0aad + en: 6650000bd819e2ce + zh: 9e141db8bc3f51f8 /agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/defaults-and-stored-selections: en: 5fcd3319fbceed1d zh: 20771646b9c36fa6 diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md index 82bfa34cfb..42aca3fdbc 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md @@ -30,11 +30,11 @@ The Search and Fetch APIs read one `web-deepseek-api` namespace, and each resolv Each of Search and Fetch has a billing setting, `web-deepseek-api.searchBilling` or `fetchBilling`, which the settings page edits as a **Billing** menu under the selected API. The default, `auto`, follows the DeepSeek credential of the conversation; `account` sends only the signed-in account's token and `api-key` only the API key, without falling back to the other. The conversation's route is the `provider` of the initiating Session's latest request context, which account sign-out also reads; `ready()` uses the route of the model request being prepared, so readiness and execution resolve the same plan. -The account token is the one `ctx.deepseekAccount` releases for the dispatch endpoint under the origin of the active `@deepseek-ai/dsh-llm-deepseek-account` Loader entry at the entry root that the model provider directory lists, with `/v1/tools`; without that entry, the origin of that route's default base URL is used. An HTTP 401 invalidates that token. With `auto` billing on the `deepseek-account` route, the operation sends the account token when that entry exists and a token is released. Every other `auto` operation, including one in an account conversation without a sign-in or a token, sends the key under the `apiKeyEnv` of the active `@deepseek-ai/dsh-llm-deepseek-api-key` entry for `deepseek-official`, resolved with that package's own resolver (including `DEEPSEEK_BASE_URL`), to the origin of that route's base URL with `/v1/tools`; without that entry, `DEEPSEEK_API_KEY` goes to `https://api.deepseek.com/v1/tools`. With `auto` billing on a route other than the two DeepSeek routes, or outside a Session, an operation without a configured key sends the account token instead, so a signed-in user without a key keeps web tools in conversations on other model providers; on the `deepseek-official` route it never sends the token, because that conversation bills the API key. Sending the API key in a signed-out account conversation keeps web tools available there. A user with only `DEEPSEEK_API_KEY`, including every headless, SDK, and ACP run, therefore searches and fetches by default, and a gateway or internal deployment set through the model provider's base URL serves web access at the same origin. A missing credential makes the capability not ready, and an operation fails with `WEB_PROVIDER_CREDENTIAL_MISSING` and guidance for its billing that names the account sign-in, the Models page and the reference, and the billing field. A mounted route entry whose settings its resolver rejects is not treated as absent: an operation that needs that route is not ready and fails with `WEB_PROVIDER_MISCONFIGURED` before reading the credential that depends on that route, without trying later sources or sending the request, so a broken gateway setting never redirects requests to the official endpoint. +The account credential is the one `ctx.deepseekAccount` releases for the dispatch endpoint under the origin of the base URL the mounted `deepseek-account` route publishes through `ctx.llm.routeCredential()`, with `/v1/tools`; without that route, the origin `DEEPSEEK_BASE_URL` names is used. An HTTP 401 invalidates that credential. With `auto` billing on the `deepseek-account` route, the operation sends the account credential when that route is mounted and a credential is released. Every other `auto` operation, including one in an account conversation without a sign-in or a credential, sends the key the mounted `deepseek-official` route publishes, which the route resolves under its `apiKeyEnv` (its base URL includes `DEEPSEEK_BASE_URL`), to the origin of that route's base URL with `/v1/tools`; without that route, `DEEPSEEK_API_KEY` goes to `https://api.deepseek.com/v1/tools`. With `auto` billing on a route other than the two DeepSeek routes, or outside a Session, an operation without a configured key sends the account token instead, so a signed-in user without a key keeps web tools in conversations on other model providers; on the `deepseek-official` route it never sends the token, because that conversation bills the API key. Sending the API key in a signed-out account conversation keeps web tools available there. A user with only `DEEPSEEK_API_KEY`, including every headless, SDK, and ACP run, therefore searches and fetches by default, and a gateway or internal deployment set through the model provider's base URL serves web access at the same origin. A missing credential makes the capability not ready, and an operation fails with `WEB_PROVIDER_CREDENTIAL_MISSING` and guidance for its billing that names the account sign-in, the Models page and the reference, and the billing field. A mounted route whose configuration does not resolve is not treated as absent: an operation that needs that route is not ready and fails with `WEB_PROVIDER_MISCONFIGURED` before reading the credential that depends on that route, without trying later sources or sending the request, so a broken gateway setting never redirects requests to the official endpoint. A capability whose YAML sets a non-empty `searchBaseURL` or `searchApiKeyEnv` (`fetchBaseURL` or `fetchApiKeyEnv` for Fetch) instead, whatever its billing, always sends the key under its `*ApiKeyEnv` (`DEEPSEEK_API_KEY` when unset) to its `*BaseURL` (the official base when unset) and never the account token, so an intranet or third-party endpoint receives only the key chosen for it. Each capability has its own fields because a deployment can serve search and fetch from different gateways. These fields are YAML-only, and an empty value counts as unset. Stored values of fields outside the schema, including `baseURL`, `apiKeyEnv`, and `apiKey`, load without schema errors and have no effect. -The [credential helpers](../../../../packages/llm/llm-deepseek/src/credential.ts) of `@deepseek-ai/dsh-llm-deepseek` read and validate API keys, check key presence, and release account tokens for the DeepSeek model routes, Messages search, and the Search and Fetch APIs, so every DeepSeek request reads the credential store the same way; the account model route, Messages search, and the Search and Fetch APIs also invalidate the token that an HTTP 401 rejects. Shipped profiles need no per-profile credential override, because the API-key path works wherever `DEEPSEEK_API_KEY` or the DeepSeek API-key route has a key. +The DeepSeek model routes publish the credential they send through `ctx.llm.routeCredential()` ([route credentials](2026-11-10-llm-route-credential-seam.md)): the API-key route its key under `apiKeyEnv`, the account route the credential `ctx.deepseekAccount` releases for a destination. Messages search and the Search and Fetch APIs read those publications instead of provider configuration, and read `DEEPSEEK_API_KEY` and own keys through the reference helpers of `dsh-credentials`, so every DeepSeek request reads the credential store the same way; a credential whose grant offers invalidation is invalidated after an HTTP 401. Shipped profiles need no per-profile credential override, because the API-key path works wherever `DEEPSEEK_API_KEY` or the DeepSeek API-key route has a key. ### Defaults and stored selections diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md index f995d39d19..58bb904d33 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md @@ -30,11 +30,11 @@ Search 与 Fetch API 读取同一个 `web-deepseek-api` namespace,并各自解 Search 与 Fetch 各有一个计费方式设置 `web-deepseek-api.searchBilling` 或 `fetchBilling`,设置页在选中的 API 下方以**计费方式**下拉框编辑它。默认值 `auto` 跟随会话的 DeepSeek 凭据;`account` 只发送已登录账号的令牌,`api-key` 只发送 API 密钥,都不回退到另一种凭据。会话的路由是发起会话最近一次请求上下文的 `provider`,账号退出登录读取的也是它;`ready()` 使用正在准备的模型请求的路由,因此就绪判断与执行解析出相同的方案。 -账号令牌是 `ctx.deepseekAccount` 为模型提供方目录列出的入口根部活动 `@deepseek-ai/dsh-llm-deepseek-account` Loader 条目的 origin 加 `/v1/tools` 下的请求端点给出的令牌;没有该条目时使用该路由默认基础地址的 origin。HTTP 401 会作废该令牌。`auto` 计费在 `deepseek-account` 路由上,若存在该条目且取得令牌,操作发送账号令牌。其他所有 `auto` 操作,包括账号会话中没有登录或没有令牌的操作,都把 `deepseek-official` 的活动 `@deepseek-ai/dsh-llm-deepseek-api-key` 条目的 `apiKeyEnv` 下的密钥(用该包自己的解析函数解析,包括 `DEEPSEEK_BASE_URL`)发往该路由基础地址的 origin 加 `/v1/tools`;没有该条目时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。`auto` 计费在两个 DeepSeek 路由之外的路由上或会话之外,没有配置密钥的操作改为发送账号令牌,因此已登录但没有密钥的用户在其他模型提供方的会话中仍可使用网页工具;在 `deepseek-official` 路由上从不发送令牌,因为该会话按 API 密钥计费。未登录的账号会话发送 API 密钥,网页工具因此在其中仍然可用。因此只有 `DEEPSEEK_API_KEY` 的用户(包括所有 headless、SDK 与 ACP 运行)默认即可搜索和抓取,通过模型提供方基础地址设置的网关或内部部署也在同一 origin 上提供 Web 访问。缺少凭据时,该能力未就绪,操作以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败,指引信息按计费方式点名账号登录、模型页面与该引用,以及计费方式字段。已挂载、但其解析函数拒绝其设置的路由条目不视为不存在:需要该路由的操作未就绪,并在读取依赖该路由的凭据前以 `WEB_PROVIDER_MISCONFIGURED` 失败,不再尝试后续来源,也不发送请求,因此网关设置出错时请求不会被改发到官方端点。 +账号凭据是 `ctx.deepseekAccount` 为请求端点释放的凭据,端点位于已挂载的 `deepseek-account` 路由通过 `ctx.llm.routeCredential()` 发布的基础地址的 origin 加 `/v1/tools` 下;没有该路由时使用 `DEEPSEEK_BASE_URL` 所指的 origin。HTTP 401 会作废该凭据。`auto` 计费在 `deepseek-account` 路由上,若该路由已挂载且释放出凭据,操作发送账号凭据。其他所有 `auto` 操作,包括账号会话中没有登录或没有凭据的操作,都把已挂载的 `deepseek-official` 路由发布的密钥(由该路由按其 `apiKeyEnv` 解析,其基础地址包含 `DEEPSEEK_BASE_URL`)发往该路由基础地址的 origin 加 `/v1/tools`;没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。`auto` 计费在两个 DeepSeek 路由之外的路由上或会话之外,没有配置密钥的操作改为发送账号令牌,因此已登录但没有密钥的用户在其他模型提供方的会话中仍可使用网页工具;在 `deepseek-official` 路由上从不发送令牌,因为该会话按 API 密钥计费。未登录的账号会话发送 API 密钥,网页工具因此在其中仍然可用。因此只有 `DEEPSEEK_API_KEY` 的用户(包括所有 headless、SDK 与 ACP 运行)默认即可搜索和抓取,通过模型提供方基础地址设置的网关或内部部署也在同一 origin 上提供 Web 访问。缺少凭据时,该能力未就绪,操作以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败,指引信息按计费方式点名账号登录、模型页面与该引用,以及计费方式字段。已挂载但配置无法解析的路由不视为不存在:需要该路由的操作未就绪,并在读取依赖该路由的凭据前以 `WEB_PROVIDER_MISCONFIGURED` 失败,不再尝试后续来源,也不发送请求,因此网关设置出错时请求不会被改发到官方端点。 在 YAML 中设置了非空 `searchBaseURL` 或 `searchApiKeyEnv`(Fetch 为 `fetchBaseURL` 或 `fetchApiKeyEnv`)的能力,则无论计费方式如何,始终把其 `*ApiKeyEnv`(未设置时为 `DEEPSEEK_API_KEY`)下的密钥发往其 `*BaseURL`(未设置时为官方基础地址),从不发送账号令牌,因此内网或第三方端点只收到为它选择的密钥。每个能力有自己的字段,因为一个部署可以由不同网关提供搜索和抓取。这些字段只能在 YAML 中设置,空值视为未设置。schema 之外字段的已保存值,包括 `baseURL`、`apiKeyEnv` 和 `apiKey`,可以加载而不产生 schema 错误,且不生效。 -`@deepseek-ai/dsh-llm-deepseek` 的[凭据函数](../../../../packages/llm/llm-deepseek/src/credential.ts)为 DeepSeek 模型路由、Messages 搜索以及 Search 与 Fetch API 读取并校验 API 密钥、检查密钥是否存在、取得账号令牌,因此每个 DeepSeek 请求都以同一方式读取凭据库;账号模型路由、Messages 搜索以及 Search 与 Fetch API 还会作废被 HTTP 401 拒绝的令牌。内置配置不需要按 profile 覆盖凭据,因为只要 `DEEPSEEK_API_KEY` 或 DeepSeek API 密钥路由有密钥,API 密钥路径就能工作。 +DeepSeek 模型路由通过 `ctx.llm.routeCredential()` 发布自己发送的凭据([路由凭据](2026-11-10-llm-route-credential-seam.zh.md)):API 密钥路由发布其 `apiKeyEnv` 下的密钥,账号路由发布 `ctx.deepseekAccount` 为目标地址释放的凭据。Messages 搜索以及 Search 与 Fetch API 读取这些发布的凭据而不读取提供方配置,并通过 `dsh-credentials` 的引用函数读取 `DEEPSEEK_API_KEY` 和单独配置的密钥,因此每个 DeepSeek 请求都以同一方式读取凭据库;授权提供失效操作的凭据会在 HTTP 401 后被作废。内置配置不需要按 profile 覆盖凭据,因为只要 `DEEPSEEK_API_KEY` 或 DeepSeek API 密钥路由有密钥,API 密钥路径就能工作。 ### 默认值与已保存的选择 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml new file mode 100644 index 0000000000..2d080f2a52 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-10-llm-route-credential-seam.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse: + en: d11883f28d5cdd99 + zh: 860795ae4d93c317 +/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/problem: + en: 9665e1879893fe76 + zh: 9da30ad0be6fc38d +/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision: + en: d7f7ef9ed3038ef7 + zh: c003e6b3338d1f3e +/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered: + en: 8177946a6bfa1a6d + zh: f523f9057b4b47c5 +/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/consequences: + en: e558492c672907dc + zh: 3748557528dc3055 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md new file mode 100644 index 0000000000..9e73be3c88 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -0,0 +1,37 @@ +# Agent Note: Route credentials - DeepSeek model routes publish the credential consumers reuse + +Status: implemented + +English | [中文](2026-11-10-llm-route-credential-seam.zh.md) + +## Problem + +Several packages shared one DeepSeek credential without an owner. `@deepseek-ai/dsh-llm-deepseek`, the protocol transport, exported helpers that read `ctx.credentials`, the launch environment, and `ctx.deepseekAccount`, so the transport depended on both credential services although it only sends the headers a route gives it. The two route plugins resolved their credentials through those helpers and threw their own missing-credential failures from inside `resolveAuth`. The Search and Fetch API providers re-derived each route's base URL and key reference from the Loader entry of the route package with that package's own config resolver, and Messages search hard-coded the account route id, so both web packages depended on `llm-deepseek`, on both route plugins, and on the Loader. The account service, which sits below every consumer, owned Agent cancellation after sign-out and lived in the `credentials/` group beside the credential store it only uses. A change to how one route authenticates touched the transport, both web providers, and their tests. + +## Decision + +`@deepseek-ai/dsh-llm` owns the Service Definition. `LlmAdapter.routeCredential(provider)` publishes a `RouteCredential`: the route's `kind` (merge-extensible, with `api-key` and `account` declared), its resolved `baseURL`, an optional credential `reference` for diagnostics, `configured(endpoint)` for presence checks that read no value, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with the protocol `headers`, the bare `value` for destinations that render it differently, and an optional `reject()` for HTTP 401. `LlmRuntime.routeCredential(provider)` forwards to the owning adapter; an unregistered route answers `undefined`, and a route whose configuration does not resolve propagates the adapter's failure. The adapter reads one configuration generation per call, as it does per model request. + +`@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the grant or `undefined`; `missingCredential(connection, provider)` names the failure of a request without one, `MISSING_CREDENTIAL` by default; `credential` declares the published kind, reference, and presence check. The listing cache scopes by endpoint and a hash of the credential headers. + +The route plugins own credentials. `llm-deepseek-api-key` reads its key through `resolveCredentialRef` and `credentialRefConfigured`, new in `@deepseek-ai/dsh-credentials`, which treat a mounted credentials service as authoritative and read the launch environment only without one; it publishes kind `api-key` with the `apiKeyEnv` reference. `llm-deepseek-account` reads `ctx.deepseekAccount.resolveRequestCredential(endpoint)`, maps HTTP 401 to `ACCOUNT_TOKEN_INVALID` and quota failures to `ACCOUNT_QUOTA`, fails without a credential as `ACCOUNT_SIGN_IN_REQUIRED`, publishes kind `account`, and owns the sign-out policy: it cancels its running Agents on `deepseek-account/signed-out` and registers a running-task report with the account service. + +`@deepseek-ai/dsh-deepseek-account` releases request credentials. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, the bare token, and a `reject()` that removes the grant while it still matches and contains storage failures; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The service inspects no Agents and depends on neither `dsh-agent` nor `dsh-llm`. The package lives in the `packages/account/` group under its unchanged name. + +The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.routeCredential('deepseek-official')` and `routeCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account`, and the reference helpers otherwise. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. + +## Alternatives considered + +**A `deepseek-auth` package holding the credential seam.** The seam needs a Service Definition only, no Cordis service, and that one Definition role belongs beside `LlmAdapter`; a package for an interface adds a dependency without an owner of behavior. + +**A credential fingerprint in the published credential.** Consumers only send requests, so they need headers and a value; cache scoping by credential is the adapter's own concern, which the listing cache meets by hashing the headers it sends. + +**A `credentials-env` provider instead of reference helpers.** A provider that reads the environment would change which composition is authoritative for every consumer; the helpers keep the launch-environment fallback local to the consumers that need it, so such a provider remains an independent option. + +**The account service's inference origin for the web fallback without the account route.** Routing that fallback through `DEEPSEEK_BASE_URL` keeps the keyless billing snapshot and every documented deployment unchanged; the account service still refuses every origin but its own. + +**Moving the account package into `identity/`.** That group defines anonymous, user-independent ids; a signed-in account is the opposite, so it gets a group of its own. + +## Consequences + +Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `routeCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`. diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md new file mode 100644 index 0000000000..663d216dff --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -0,0 +1,37 @@ +# Agent Note: Route credentials - DeepSeek model routes publish the credential consumers reuse + +Status: implemented + +[English](2026-11-10-llm-route-credential-seam.md) | 中文 + +## 问题 + +多个包共用同一份 DeepSeek 凭据,却没有所有者。协议传输层 `@deepseek-ai/dsh-llm-deepseek` 导出读取 `ctx.credentials`、启动环境和 `ctx.deepseekAccount` 的辅助函数,因此尽管传输层只发送路由交给它的请求头,它仍依赖两个凭据服务。两个路由插件通过这些函数解析凭据,并在 `resolveAuth` 内部抛出各自的凭据缺失错误。Search 与 Fetch API 提供方用路由包自己的配置解析函数,从路由包的 Loader 条目重新推导每条路由的基础地址和密钥引用,Messages 搜索则硬编码账号路由 id,因此两个 Web 包都依赖 `llm-deepseek`、两个路由插件和 Loader。位于所有消费方之下的账号服务拥有退登后的 Agent 取消逻辑,并和它仅仅使用的凭据库一起放在 `credentials/` 组。改变一条路由的鉴权方式要同时触及传输层、两个 Web 提供方及其测试。 + +## 决策 + +`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.routeCredential(provider)` 发布一个 `RouteCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不读取值的存在性检查 `configured(endpoint)`,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`,以及可选的 HTTP 401 `reject()`。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 + +`@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回授权或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`;`credential` 声明发布的种类、引用和存在性检查。列表缓存以端点和凭据请求头的哈希划分作用域。 + +路由插件拥有凭据。`llm-deepseek-api-key` 通过 `@deepseek-ai/dsh-credentials` 新增的 `resolveCredentialRef` 和 `credentialRefConfigured` 读取密钥,二者把已挂载的凭据服务视为权威,仅在没有该服务时读取启动环境;它发布种类 `api-key` 并附带 `apiKeyEnv` 引用。`llm-deepseek-account` 读取 `ctx.deepseekAccount.resolveRequestCredential(endpoint)`,把 HTTP 401 映射为 `ACCOUNT_TOKEN_INVALID`、配额失败映射为 `ACCOUNT_QUOTA`,没有凭据时以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,发布种类 `account`,并拥有退登策略:在 `deepseek-account/signed-out` 时取消其运行中的 Agent,并向账号服务注册运行中任务报告。 + +`@deepseek-ai/dsh-deepseek-account` 释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、裸 token 和 `reject()`;`reject()` 仅在授权仍一致时删除它并隔离存储失败。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。该服务不检查任何 Agent,也不依赖 `dsh-agent` 或 `dsh-llm`。包以不变的名字位于 `packages/account/` 组。 + +Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.routeCredential('deepseek-official')` 和 `routeCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类时使用其账号凭据,否则使用引用函数。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 + +## 考虑过的替代方案 + +**用一个 `deepseek-auth` 包承载凭据 seam。** 该 seam 只需要 Service Definition,不需要 Cordis 服务,而这一个 Definition 角色应与 `LlmAdapter` 放在一起;为一个接口建包只会增加一个没有行为所有者的依赖。 + +**在发布的凭据中加入凭据指纹。** 消费方只负责发送请求,因此只需要请求头和值;按凭据划分缓存作用域是适配器自己的事,列表缓存通过哈希它发送的请求头即可满足。 + +**用 `credentials-env` 提供方代替引用函数。** 读取环境的提供方会改变每个消费方眼中哪个组合具有权威性;引用函数把启动环境后备保留在需要它的消费方本地,使这样的提供方仍是独立的选项。 + +**没有账号路由时的 Web 后备使用账号服务的推理 origin。** 让该后备经由 `DEEPSEEK_BASE_URL` 可保持无密钥计费快照和所有已记录部署不变;账号服务仍拒绝除自身 origin 以外的一切来源。 + +**把账号包并入 `identity/`。** 该组定义匿名、不识别用户的 id;已登录账号与之相反,因此单独成组。 + +## 后果 + +新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `routeCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml index 98c3a9541a..d683eb8924 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml @@ -27,8 +27,8 @@ en: 0dcc97d8105fab60 zh: d80d40ae3a0c601d /agent-note-direct-deepseek-search-and-fetch-apis/alternatives-considered: - en: 907e0b8424943d43 - zh: f45e583e7cb4eb63 + en: 88708dc170d3e77b + zh: e04536e494769d9c /agent-note-direct-deepseek-search-and-fetch-apis/consequences: en: 7ec21c5b1124e5f8 zh: af769dbdb4face9f diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md index ee8b912b2e..18c1946887 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md @@ -52,7 +52,7 @@ The independent `dsh-web-search-deepseek` provider sends Messages search request **Keep the APIs inside the Messages provider behind a provider-local switch.** A switch inside the Messages provider cannot change fetch routing, so `web_fetch` would stay on HTTP unless the user also edited `web.fetchProvider`; it also ties the APIs' lifecycle to Messages search. Separate registrations let the web service's existing selection choose each provider, without coupling either API to the Messages provider. -**Share one transport between Messages search and the new APIs.** A shared web transport would couple different request formats and failure mappings. Credential values instead come from the shared [`llm-deepseek` credential helpers](../../../../packages/llm/llm-deepseek/src/credential.ts); Messages search and the Search/Fetch API transports remain independent. +**Share one transport between Messages search and the new APIs.** A shared web transport would couple different request formats and failure mappings. Credential values instead come from the credentials the model routes publish through `ctx.llm.routeCredential()` and from the `dsh-credentials` reference helpers; Messages search and the Search/Fetch API transports remain independent. **Split Search and Fetch into separate packages.** The guide serves both APIs from one base with one credential; separate packages would duplicate settings that address one deployment. Independent selection does not require separate packages, because each API registers its own provider id. Each operation lives in its own module, so either API can change without the other. diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md index c7493c8e23..324fcd1d0c 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md @@ -52,7 +52,7 @@ HTTP 提供方继续负责自身的 URL 校验和资源限制。选择 DeepSeek **把两个 API 放在 Messages 提供方内部,由提供方自己的开关切换。** Messages 提供方内的开关无法改变抓取路由,因此除非用户另外修改 `web.fetchProvider`,`web_fetch` 仍会走 HTTP;它还会把两个 API 的生命周期绑在 Messages 搜索上。独立注册让 Web 服务通过现有的提供方选择机制选择各个提供方,不会把任一 API 与 Messages 提供方绑定。 -**让 Messages 搜索与新 API 共用一套传输层。** 共享 Web 传输层会耦合不同的请求格式和失败映射。凭据值改为通过共享的 [`llm-deepseek` 凭据函数](../../../../packages/llm/llm-deepseek/src/credential.ts)获取;Messages 搜索与 Search/Fetch API 传输层保持独立。 +**让 Messages 搜索与新 API 共用一套传输层。** 共享 Web 传输层会耦合不同的请求格式和失败映射。凭据值改为来自模型路由通过 `ctx.llm.routeCredential()` 发布的凭据以及 `dsh-credentials` 的引用函数;Messages 搜索与 Search/Fetch API 传输层保持独立。 **把 Search 和 Fetch 拆成两个包。** 指南从同一基础地址、以同一份凭据提供两个 API;拆成两个包会让指向同一部署的设置重复出现。分别选择不需要拆包,因为每个 API 注册自己的提供方 id。每种操作位于独立模块,任一 API 都可以单独修改。 diff --git a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml index db6139954a..9346ae7076 100644 --- a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml +++ b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml @@ -21,8 +21,8 @@ en: 8a9578bbc700c0bf zh: 8ee46e5ef1cf3972 /agent-note-keep-cleanup-dependencies-usable-until-consumers-finish/p0-findings/authorization-loses-required-observation-or-an-accepted-credential-write: - en: c6b0d746185d0d3b - zh: a228633ecdf42800 + en: 0532e871788d6ef7 + zh: 75131f43216bd05f /agent-note-keep-cleanup-dependencies-usable-until-consumers-finish/p0-findings/ssh-disables-cleanup-requests-before-dependent-process-cleanup-finishes: en: 85fb2b564bc40230 zh: 97c3e794124f8044 diff --git a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md index cb7ad564cd..86111905d8 100644 --- a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md +++ b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md @@ -36,7 +36,7 @@ A focused in-memory experiment using the actual Cordis and storage-domain implem ### Authorization loses required observation or an accepted credential write -**Owners and evidence.** Authorization's [commit observer (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) is a caller-owned `ctx.on` effect. Its [commit operation (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) awaits credential storage, while [success requires the observed update (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts). The account service [leaves committing attempts un-aborted and awaits their completion (`DeepSeekAccount`)](../../../../packages/credentials/deepseek-account/src/index.ts). +**Owners and evidence.** Authorization's [commit observer (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) is a caller-owned `ctx.on` effect. Its [commit operation (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) awaits credential storage, while [success requires the observed update (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts). The account service [leaves committing attempts un-aborted and awaits their completion (`DeepSeekAccount`)](../../../../packages/account/deepseek-account/src/index.ts). **Successful write, false failure.** Pause a credential write, dispose the account consumer, then complete the write and emit its update. The observer can auto-unsubscribe alongside the account's drain; Authorization then rejects with `NOT_COMMITTED` despite successful storage. Keep observation owned by the operation until its result settles, or acknowledge successful `session.commit` directly while giving legacy direct-write observation an explicit lifetime. A focused experiment using actual Cordis and Authorization with a deferred in-memory credential provider reproduced `NOT_COMMITTED` after the provider write succeeded; the complete browser sign-in path is source-traced. diff --git a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md index fd5a6c3f45..8b779d84cc 100644 --- a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md +++ b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md @@ -36,7 +36,7 @@ Status: proposed ### Authorization 丢失必需的提交观察或已接受的凭据写入 -**所有者与证据。** Authorization 的[提交观察器 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)是调用方拥有的 `ctx.on` effect。[提交操作 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)等待凭据存储,而[成功要求观察到更新 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)。账号服务[不会中止正在提交的尝试,并等待其完成 (`DeepSeekAccount`)](../../../../packages/credentials/deepseek-account/src/index.ts)。 +**所有者与证据。** Authorization 的[提交观察器 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)是调用方拥有的 `ctx.on` effect。[提交操作 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)等待凭据存储,而[成功要求观察到更新 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)。账号服务[不会中止正在提交的尝试,并等待其完成 (`DeepSeekAccount`)](../../../../packages/account/deepseek-account/src/index.ts)。 **写入成功,却报告失败。** 暂停凭据写入,释放账号消费者,再完成写入并发出更新。观察器可以与账号的排空并发自动退订;随后 Authorization 即使存储成功也会以 `NOT_COMMITTED` 拒绝。应让操作拥有观察器直到结果确定,或直接确认成功的 `session.commit`,同时给旧式直接写入观察明确的生命周期。使用实际 Cordis 与 Authorization、配合延迟的内存凭据 provider 的实验,复现了 provider 写入成功后返回 `NOT_COMMITTED`;完整浏览器登录路径由源码追踪确认。 diff --git a/AGENTS.md b/AGENTS.md index f189147619..6353b6a7dc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,6 +58,7 @@ packages/ @deepseek-ai/dsh- workspaces at packages/// identity/ anonymous identity settings/ user settings credentials/ credentials/authorization + account/ DeepSeek account acp/ automation-only ACP interaction/ human interaction boot/ application boot diff --git a/apps/desktop-host/tsconfig.json b/apps/desktop-host/tsconfig.json index c30951a3a4..9664d632b8 100644 --- a/apps/desktop-host/tsconfig.json +++ b/apps/desktop-host/tsconfig.json @@ -26,7 +26,7 @@ "path": "../../packages/host/webserver" }, { - "path": "../../packages/credentials/deepseek-account" + "path": "../../packages/account/deepseek-account" }, { "path": "../../packages/boot/plugin-manager" diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 7b4f37e1ad..9ef268ef5c 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -15,8 +15,8 @@ en: 127ea90553cb6af7 zh: 7b1c5aec8558c684 /deepseek-harness-desktop/application-overview: - en: 37d36f8d57214336 - zh: ceb50c0fa866eb24 + en: fba8dc2cecbe0350 + zh: 61092170a17906ad /deepseek-harness-desktop/terminal-command: en: 5f2d25a1d8472647 zh: 2acb5c5d7d1917e2 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index ffe4f5b520..0fc6a891ab 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -49,7 +49,7 @@ Desktop ships one pnpm distribution at `resources/runtime/primary-runtime/depend Embedded Platform documents use a persistent WebContentsView partition keyed by a hash of the Platform origin and stable account ID. localStorage preferences, including dismissed notices, survive view closure and application restart; different accounts and origins use separate storage. The Host supplies the account ID from its latest successful profile read; while no ID is known, the document opens in a disposable partition that keeps no preference across opens. Opening a persistent partition clears cookies, filesystem, IndexedDB, Cache Storage, the HTTP and shader caches, service workers, and HTTP authentication before the document loads; a disposable partition clears all of its storage. Closing a view destroys the document, removes its request interceptors, and schedules the same cleanup, so authentication left by an unclean exit is cleared before the next document loads. The next open and application shutdown await that cleanup, and an update install waits for it before the installer takes over the exit. A failed cleanup rejects that open and blocks the same account until a later cleanup succeeds; other accounts keep opening. Sign-out destroys the document but retains account-scoped preferences for the next sign-in. A document already open in a disposable partition stays mounted when the account ID arrives for the same credential; the next open uses the account-scoped partition. The [storage decision](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.md) describes the retention policy. Host sends account credentials through private Node IPC; account RPC and the Harness renderer receive no token. Before page scripts execute, the Platform preload performs one synchronous IPC to read the prepared main-process credential. It exposes displayMode, synchronous getAuthToken() and getLocale() getters, and onLocaleChange(listener), which returns an unsubscribe function. Both getters read preload memory without further IPC. The bootstrap includes the resolved Desktop language (`zh_CN` or `en_US`); Settings language changes update the preload cache and notify the open Platform document without reloading. Platform applies this language before its first render and does not persist it as a browser preference. The main-process handler performs only sender validation and an in-memory read; it never waits for Host, disk, or network. Trusted-page initialization failures retain embedded mode and make the getter throw, preventing browser-credential fallback. Only the owned Platform main frame on the configured issuer origin can initialize. Sign-out, credential replacement, Host shutdown, and view closure destroy the document. Cross-origin document navigation is blocked. HTTPS links requesting a new window open in the system browser without the embedded session or token; other schemes and URL credentials are rejected. Native views occupy the viewport below the Account feature’s return bar. -Desktop Host Platform API requests and update-policy requests identify the installed client with the same Platform client headers: platform, client version, locale, timezone offset in seconds, and a bundle id that is intentionally empty. Account operations take the calling UI's identity per call; the account provider owns [API-only header configuration](../../packages/credentials/deepseek-account/README.md#use-this-package). Update policy additionally reports architecture, update channel, and bundled runtime version. The native account-state decoder accepts `no-response` sign-in failures and preserves the error code in the UI-safe projection. +Desktop Host Platform API requests and update-policy requests identify the installed client with the same Platform client headers: platform, client version, locale, timezone offset in seconds, and a bundle id that is intentionally empty. Account operations take the calling UI's identity per call; the account provider owns [API-only header configuration](../../packages/account/deepseek-account/README.md#use-this-package). Update policy additionally reports architecture, update channel, and bundled runtime version. The native account-state decoder accepts `no-response` sign-in failures and preserves the error code in the UI-safe projection. A server-expired account credential returns to Welcome when no official API key is configured; an available API key keeps the workspace open. Explicit sign-out follows the same rule. Both Welcome and the workspace display the localized expiry notice. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index a6c2493fbc..e5d1a3d89c 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -49,7 +49,7 @@ Desktop 在 `resources/runtime/primary-runtime/dependencies/pnpm` 中携带一 Platform 内嵌文档使用持久化 WebContentsView 分区,分区名由 Platform 来源和稳定账号 ID 的哈希决定。localStorage 中的页面偏好(包括已关闭的通知)在关闭视图和重启应用后保留;不同账号和来源使用独立存储。账号 ID 来自 Host 最近一次成功的资料读取;尚无该 ID 时,文档在一次性分区中打开,该分区不跨次保留偏好。打开持久分区会先清理 Cookie、文件系统、IndexedDB、Cache Storage、HTTP 与着色器缓存、Service Worker 及 HTTP 认证状态;一次性分区则清理其全部存储。关闭视图会销毁文档、移除请求拦截器并安排相同的清理,因此异常退出遗留的认证会在下一个文档加载前被清除。下次打开和应用退出都会等待该清理完成,更新安装也会在安装器接管退出前等待。清理失败会使该次打开失败,并在后续清理成功前阻止同一账号打开;其他账号不受影响。退出登录会销毁文档,但保留账号偏好供下次登录使用。同一凭证下账号 ID 迟到时,已以一次性分区打开的文档保持挂载;下次打开使用账号分区。[存储决策](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.zh.md)说明保留策略。Host 通过私有 Node IPC 发送账号凭证;账号 RPC 和 Harness 渲染进程不接收 token。Platform preload 在页面脚本执行前通过一次同步 IPC 读取主进程中已准备的凭证。它暴露 displayMode、同步的 getAuthToken() 和 getLocale() getter,以及返回取消订阅函数的 onLocaleChange(listener)。两个 getter 都只读取 preload 内存,不再调用 IPC。bootstrap 包含 Desktop 已解析的语言(`zh_CN` 或 `en_US`);Settings 语言变更会更新 preload 缓存并通知已打开的 Platform 文档,无需重载。Platform 在首屏渲染前应用该语言,且不将其持久化为浏览器偏好。主进程处理器仅校验调用来源并读取内存,不等待 Host、磁盘或网络。可信页面初始化失败时保留内嵌模式,由 getter 抛错,避免回退到浏览器凭证。只有受控 Platform 页面中、位于所配置签发来源的主 frame 能完成初始化。退登、凭证替换、Host 关闭及视图关闭都会销毁文档。跨来源文档导航被阻止。请求新窗口的 HTTPS 链接在系统浏览器中打开,不携带内嵌会话或 token;其他协议及带 URL 凭证的链接被拒绝。原生视图占据 Account 功能返回栏下方的视口。 -Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform 客户端请求头标识已安装客户端:平台、客户端版本、语言、以秒为单位的时区偏移,以及有意保持为空的 bundle id。账号操作按调用逐次传入调用界面的身份;账号 provider 管理[仅 API 使用的请求头配置](../../packages/credentials/deepseek-account/README.zh.md#use-this-package)。更新策略额外上报架构、更新通道和内置运行时版本。 原生账号状态解析器接受 `no-response` 登录失败,并在供 UI 使用的安全投影中保留该错误码。 +Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform 客户端请求头标识已安装客户端:平台、客户端版本、语言、以秒为单位的时区偏移,以及有意保持为空的 bundle id。账号操作按调用逐次传入调用界面的身份;账号 provider 管理[仅 API 使用的请求头配置](../../packages/account/deepseek-account/README.zh.md#use-this-package)。更新策略额外上报架构、更新通道和内置运行时版本。 原生账号状态解析器接受 `no-response` 登录失败,并在供 UI 使用的安全投影中保留该错误码。 账号凭据被服务端判定失效后,未配置官方 API key 时返回 Welcome;有可用 API key 时保持工作区打开。主动退出登录遵循相同规则。Welcome 和工作区均显示本地化的登录失效提示。 diff --git a/apps/desktop/tsconfig.client.json b/apps/desktop/tsconfig.client.json index eb17ebe087..7e24cdcda3 100644 --- a/apps/desktop/tsconfig.client.json +++ b/apps/desktop/tsconfig.client.json @@ -14,7 +14,7 @@ "path": "../../packages/client/ui-primitives" }, { - "path": "../../packages/credentials/deepseek-account" + "path": "../../packages/account/deepseek-account" }, { "path": "../../packages/client/product-analytics/tsconfig.client.json" diff --git a/apps/desktop/tsconfig.host.json b/apps/desktop/tsconfig.host.json index 2701caf5a6..92ec693165 100644 --- a/apps/desktop/tsconfig.host.json +++ b/apps/desktop/tsconfig.host.json @@ -18,7 +18,7 @@ "path": "../../packages/util/home-paths" }, { - "path": "../../packages/credentials/deepseek-account" + "path": "../../packages/account/deepseek-account" }, { "path": "../../packages/api/gateway/tsconfig.host.json" diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index 77f025f1e9..040ac417df 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: b76743a3ff14d2f4 - zh: 82431aa3ded14a89 + en: 6fc86dc663906645 + zh: b1833a4bd578896a diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 145a4f5317..d52b5b4727 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -85,6 +85,8 @@ flowchart LR pkg_llm_replay["llm-replay"] pkg_agent_loop["agent-loop"] pkg_compaction_basic["compaction-basic"] + pkg_web_deepseek_api["web-deepseek-api"] + pkg_web_search_deepseek["web-search-deepseek"] pkg_session_log_deepseek["session-log-deepseek"] svc_sessionLogDeepSeek["ctx.sessionLogDeepSeek
Session-log upload policy"] pkg_deepseek_llm_api_extensions["deepseek-llm-api-extensions"] @@ -140,8 +142,10 @@ flowchart LR pkg_credentials["credentials"] svc_credentials["ctx.credentials
Credential seam"] pkg_credentials_local["credentials-local"] + pkg_llm_deepseek_api_key["llm-deepseek-api-key"] pkg_deepseek_account["deepseek-account"] svc_deepseekAccount["ctx.deepseekAccount
DeepSeek account"] + pkg_llm_deepseek_account["llm-deepseek-account"] pkg_authorization["authorization"] svc_authorization["ctx.authorization
Authorization flow registry"] pkg_client_product_analytics["client-product-analytics"] @@ -282,8 +286,6 @@ flowchart LR pkg_tool_jobs["tool-jobs"] pkg_web["web"] svc_web["ctx.web
Web access provider registry"] - pkg_web_search_deepseek["web-search-deepseek"] - pkg_web_deepseek_api["web-deepseek-api"] pkg_web_fetch_http["web-fetch-http"] pkg_spill["spill"] svc_spillStore["ctx.spillStore
Spill storage seam"] @@ -512,10 +514,13 @@ flowchart LR svc_connection --> pkg_host_frontend_static svc_cordisInspect --> pkg_tool_cordis svc_credentials --> pkg_api_settings_controller - svc_credentials --> pkg_llm_deepseek + svc_credentials --> pkg_llm_deepseek_api_key svc_credentials --> pkg_llm_pi_ai + svc_credentials --> pkg_web_deepseek_api + svc_credentials --> pkg_web_search_deepseek svc_cuaAccess --> pkg_cua - svc_deepseekAccount --> pkg_llm_deepseek + svc_deepseekAccount --> pkg_llm_deepseek_account + svc_deepseekAccount --> pkg_web_deepseek_api svc_deepseekLlmApiExtensions --> pkg_llm_deepseek svc_directoryPicker --> pkg_api_workspace_controller svc_dynamicCordisRunner --> pkg_tool_cordis @@ -534,6 +539,8 @@ flowchart LR svc_jobs --> pkg_tool_terminal svc_llm --> pkg_agent_loop svc_llm --> pkg_compaction_basic + svc_llm --> pkg_web_deepseek_api + svc_llm --> pkg_web_search_deepseek svc_lsp --> pkg_tool_lsp svc_mcpResources --> pkg_mcp_resources svc_officeKit --> pkg_client_ui_sidebar_documentpreview @@ -674,7 +681,7 @@ flowchart LR | `ctx.officeKit` | `core` | [`office-kit`](../packages/document/office-kit) | - | [`client-ui-sidebar-documentpreview`](../packages/client/ui-sidebar-documentpreview), [`tool-office`](../packages/document/tool-office) | - | Authorized Office bytes are rendered as PDFs or images, converted, or recalculated on the Host using the declared native target engine, or Node WASM when no native target is declared. | | `ctx.attachments` | `seam` | [`attachment`](../packages/attachment/attachment) | [`attachment-local`](../packages/attachment/attachment-local) | [`api-session-controller`](../packages/api/session-controller), [`tool-fs`](../packages/fs/tool-fs), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | The host commits accepted images before session events; provider adapters resolve authorized durable references into provider-native content. | | `ctx.fileUploads` | `core` | [`client-file-upload`](../packages/client/file-upload) | - | [`api-session-controller`](../packages/api/session-controller) | - | Owns streaming intake, durable storage, and staged receipt lifetime; the Session controller binds receipts to accepted submissions. | -| `ctx.llm` | `seam` | [`llm`](../packages/llm/llm) | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-replay`](../packages/test-support/llm-replay) | [`agent-loop`](../packages/core/agent-loop), [`compaction-basic`](../packages/compaction/compaction-basic) | - | Adapters register provider implementations; the loop and compaction call the provider-neutral stream service. | +| `ctx.llm` | `seam` | [`llm`](../packages/llm/llm) | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-replay`](../packages/test-support/llm-replay) | [`agent-loop`](../packages/core/agent-loop), [`compaction-basic`](../packages/compaction/compaction-basic), [`web-deepseek-api`](../packages/web/web-deepseek-api), [`web-search-deepseek`](../packages/web/web-search-deepseek) | - | Adapters register provider implementations; the loop and compaction call the provider-neutral stream service, and the DeepSeek web providers read the credential a route publishes. | | `ctx.sessionLogDeepSeek` | `core` | [`session-log-deepseek`](../packages/session/session-log-deepseek) | - | - | - | Plugins register caller-owned exclusions before the canonical Session-log request contribution is prepared; unmatched requests use normal upload eligibility. | | `ctx.deepseekLlmApiExtensions` | `seam` | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions) | [`session-log-deepseek`](../packages/session/session-log-deepseek), [`plugin-package-inventory-deepseek`](../packages/llm/plugin-package-inventory-deepseek) | [`llm-deepseek`](../packages/llm/llm-deepseek) | - | Plugins prepare independent top-level fields; the official adapter merges them and commits their delivery state after HTTP acceptance. | | `ctx.tokenMeter` | `core` | [`token-meter`](../packages/llm/token-meter) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | Owns isolated per-session replay folds; pressure consumers share immutable revisioned measurements. | @@ -699,8 +706,8 @@ flowchart LR | `ctx.configEditor` | `core` | [`config-editor`](../packages/boot/config-editor) | - | [`settings`](../packages/settings/settings), [`agent-default-model`](../packages/core/agent-default-model) | - | Persists profile config patches under the application file lock and HMR queue, then reconciles Loader entries. | | `ctx.settings` | `core` | [`settings`](../packages/settings/settings) | - | [`api-settings-controller`](../packages/api/settings-controller) | - | Forms project volatile Config fields from active profile entries and delegate validated edits to config-editor. Plugins consume their own Config references. | | `ctx.subagentModelSelection` | `core` | [`tool-subagent`](../packages/subagent/tool-subagent) | - | [`tool-subagent`](../packages/subagent/tool-subagent) | - | Owns the default-off settings namespace that Agent-scoped delegation tools sample when composing a new top-level Session. | -| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the settings controller exposes value-free views and write-only storage. | -| `ctx.deepseekAccount` | `service` | [`deepseek-account`](../packages/credentials/deepseek-account) | - | [`llm-deepseek`](../packages/llm/llm-deepseek) | - | The Host owns browser authorization and local credentials; UI consumers receive state without tokens. | +| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`web-deepseek-api`](../packages/web/web-deepseek-api), [`web-search-deepseek`](../packages/web/web-search-deepseek) | - | Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the settings controller exposes value-free views and write-only storage. | +| `ctx.deepseekAccount` | `service` | [`deepseek-account`](../packages/account/deepseek-account) | - | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`web-deepseek-api`](../packages/web/web-deepseek-api) | - | The Host owns browser authorization and local credentials and releases per-request credentials to the account model route and the web providers; UI consumers receive state without tokens. | | `ctx.authorization` | `seam` | [`authorization`](../packages/credentials/authorization) | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | Flows are registered by the plugin that knows how to obtain one credential and keyed by the record they write; the seam owns the conversation and the one-attempt-per-key lifecycle, never the protocol. | | `ctx.productAnalytics` | `service` | [`client-product-analytics`](../packages/client/product-analytics) | - | - | - | Accepts selected Desktop events, enriches available login identity, and observes live compaction under the live Host collection policy. | | `ctx.otel` | `service` | [`otel`](../packages/telemetry/otel) | - | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel), [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | - | Product analytics and Session feedback adapters create independent reporting channels through one injected service. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index 5effa1f8c4..bfc8a1df8c 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -87,6 +87,8 @@ flowchart LR pkg_llm_replay["llm-replay"] pkg_agent_loop["agent-loop"] pkg_compaction_basic["compaction-basic"] + pkg_web_deepseek_api["web-deepseek-api"] + pkg_web_search_deepseek["web-search-deepseek"] pkg_session_log_deepseek["session-log-deepseek"] svc_sessionLogDeepSeek["ctx.sessionLogDeepSeek
Session-log upload policy"] pkg_deepseek_llm_api_extensions["deepseek-llm-api-extensions"] @@ -142,8 +144,10 @@ flowchart LR pkg_credentials["credentials"] svc_credentials["ctx.credentials
Credential seam"] pkg_credentials_local["credentials-local"] + pkg_llm_deepseek_api_key["llm-deepseek-api-key"] pkg_deepseek_account["deepseek-account"] svc_deepseekAccount["ctx.deepseekAccount
DeepSeek account"] + pkg_llm_deepseek_account["llm-deepseek-account"] pkg_authorization["authorization"] svc_authorization["ctx.authorization
Authorization flow registry"] pkg_client_product_analytics["client-product-analytics"] @@ -284,8 +288,6 @@ flowchart LR pkg_tool_jobs["tool-jobs"] pkg_web["web"] svc_web["ctx.web
Web access provider registry"] - pkg_web_search_deepseek["web-search-deepseek"] - pkg_web_deepseek_api["web-deepseek-api"] pkg_web_fetch_http["web-fetch-http"] pkg_spill["spill"] svc_spillStore["ctx.spillStore
Spill storage seam"] @@ -514,10 +516,13 @@ flowchart LR svc_connection --> pkg_host_frontend_static svc_cordisInspect --> pkg_tool_cordis svc_credentials --> pkg_api_settings_controller - svc_credentials --> pkg_llm_deepseek + svc_credentials --> pkg_llm_deepseek_api_key svc_credentials --> pkg_llm_pi_ai + svc_credentials --> pkg_web_deepseek_api + svc_credentials --> pkg_web_search_deepseek svc_cuaAccess --> pkg_cua - svc_deepseekAccount --> pkg_llm_deepseek + svc_deepseekAccount --> pkg_llm_deepseek_account + svc_deepseekAccount --> pkg_web_deepseek_api svc_deepseekLlmApiExtensions --> pkg_llm_deepseek svc_directoryPicker --> pkg_api_workspace_controller svc_dynamicCordisRunner --> pkg_tool_cordis @@ -536,6 +541,8 @@ flowchart LR svc_jobs --> pkg_tool_terminal svc_llm --> pkg_agent_loop svc_llm --> pkg_compaction_basic + svc_llm --> pkg_web_deepseek_api + svc_llm --> pkg_web_search_deepseek svc_lsp --> pkg_tool_lsp svc_mcpResources --> pkg_mcp_resources svc_officeKit --> pkg_client_ui_sidebar_documentpreview @@ -676,7 +683,7 @@ flowchart LR | `ctx.officeKit` | `core` | [`office-kit`](../packages/document/office-kit) | - | [`client-ui-sidebar-documentpreview`](../packages/client/ui-sidebar-documentpreview), [`tool-office`](../packages/document/tool-office) | - | 已授权的 Office 字节在宿主上使用已声明的原生目标引擎渲染为 PDF 或图片、转换或重算;未声明原生目标时使用 Node WASM。 | | `ctx.attachments` | `seam` | [`attachment`](../packages/attachment/attachment) | [`attachment-local`](../packages/attachment/attachment-local) | [`api-session-controller`](../packages/api/session-controller), [`tool-fs`](../packages/fs/tool-fs), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | 宿主会在会话事件之前提交已接受的图片;提供方适配器将已授权的持久引用解析为提供方原生内容。 | | `ctx.fileUploads` | `core` | [`client-file-upload`](../packages/client/file-upload) | - | [`api-session-controller`](../packages/api/session-controller) | - | 负责流式接收、持久存储和暂存回执生命周期;Session Controller 将回执绑定到已接受的提交。 | -| `ctx.llm` | `seam` | [`llm`](../packages/llm/llm) | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-replay`](../packages/test-support/llm-replay) | [`agent-loop`](../packages/core/agent-loop), [`compaction-basic`](../packages/compaction/compaction-basic) | - | 适配器注册提供方实现;agent loop(智能体循环)与压缩功能调用提供方无关的流服务。 | +| `ctx.llm` | `seam` | [`llm`](../packages/llm/llm) | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-replay`](../packages/test-support/llm-replay) | [`agent-loop`](../packages/core/agent-loop), [`compaction-basic`](../packages/compaction/compaction-basic), [`web-deepseek-api`](../packages/web/web-deepseek-api), [`web-search-deepseek`](../packages/web/web-search-deepseek) | - | 适配器注册提供方实现;agent loop(智能体循环)与压缩功能调用与提供方无关的流式服务,DeepSeek Web 提供方读取路由发布的凭据。 | | `ctx.sessionLogDeepSeek` | `core` | [`session-log-deepseek`](../packages/session/session-log-deepseek) | - | - | - | 插件在准备权威 Session 日志请求贡献前注册归调用方所有的排除条件;没有条件匹配的请求应用普通上传资格判断。 | | `ctx.deepseekLlmApiExtensions` | `seam` | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions) | [`session-log-deepseek`](../packages/session/session-log-deepseek), [`plugin-package-inventory-deepseek`](../packages/llm/plugin-package-inventory-deepseek) | [`llm-deepseek`](../packages/llm/llm-deepseek) | - | 插件准备彼此独立的顶层字段;官方适配器会合并这些字段,并在 HTTP 接受后提交其交付状态。 | | `ctx.tokenMeter` | `core` | [`token-meter`](../packages/llm/token-meter) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | 拥有按会话隔离的回放折叠区;压力消费方共享不可变且带修订版本的测量结果。 | @@ -701,8 +708,8 @@ flowchart LR | `ctx.configEditor` | `core` | [`config-editor`](../packages/boot/config-editor) | - | [`settings`](../packages/settings/settings), [`agent-default-model`](../packages/core/agent-default-model) | - | Persists profile config patches under the application file lock and HMR queue, then reconciles Loader entries. | | `ctx.settings` | `core` | [`settings`](../packages/settings/settings) | - | [`api-settings-controller`](../packages/api/settings-controller) | - | Forms project volatile Config fields from active profile entries and delegate validated edits to config-editor. Plugins consume their own Config references. | | `ctx.subagentModelSelection` | `core` | [`tool-subagent`](../packages/subagent/tool-subagent) | - | [`tool-subagent`](../packages/subagent/tool-subagent) | - | 拥有默认关闭的设置命名空间;Agent 作用域的委派工具会在组合新顶层 Session 时读取它。 | -| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | 配置携带对机密信息的引用;提供方拥有实际值。消费方按操作解析,因此轮换后的凭据会在紧接着的下一次请求中生效;settings controller 提供不含实际值的视图和只写存储。 | -| `ctx.deepseekAccount` | `service` | [`deepseek-account`](../packages/credentials/deepseek-account) | - | [`llm-deepseek`](../packages/llm/llm-deepseek) | - | Host 负责浏览器授权和本地凭证;UI 使用方只接收不含 token 的状态。 | +| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`web-deepseek-api`](../packages/web/web-deepseek-api), [`web-search-deepseek`](../packages/web/web-search-deepseek) | - | 配置携带对机密信息的引用;提供方拥有实际值。消费方按操作解析,因此轮换后的凭据会在紧接着的下一次请求中生效;settings controller 提供不含实际值的视图和只写存储。 | +| `ctx.deepseekAccount` | `service` | [`deepseek-account`](../packages/account/deepseek-account) | - | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`web-deepseek-api`](../packages/web/web-deepseek-api) | - | Host 负责浏览器授权和本地凭证,并向账号模型路由和 Web 提供方释放按请求的凭据;UI 使用方只接收不含 token 的状态。 | | `ctx.authorization` | `seam` | [`authorization`](../packages/credentials/authorization) | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | flow 由知道如何取得某份凭据的插件注册,并以其写入的记录为键;seam 拥有这段对话与"每个键同时只跑一次尝试"的生命周期,而非协议本身。 | | `ctx.productAnalytics` | `service` | [`client-product-analytics`](../packages/client/product-analytics) | - | - | - | 根据 Host 动态采集策略接收指定桌面事件、补充可用登录身份并监听实时压缩。 | | `ctx.otel` | `service` | [`otel`](../packages/telemetry/otel) | - | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel), [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | - | 产品埋点和 Session 反馈适配器通过同一个注入服务创建独立上报通道。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 41bd0207f3..e60acb4e73 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -892,7 +892,7 @@ export interface Config { ## `@deepseek-ai/dsh-deepseek-account` - `inject`: `credentials` · `authorization` -- `source`: [`packages/credentials/deepseek-account/src/index.ts:40`](../packages/credentials/deepseek-account/src/index.ts) +- `source`: [`packages/account/deepseek-account/src/index.ts:39`](../packages/account/deepseek-account/src/index.ts) ```ts config-catalog /** Deployment-specific platform and request deadlines. */ @@ -4851,7 +4851,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-deepseek-api/src/index.ts:64`](../packages/web/web-deepseek-api/src/index.ts) +- `source`: [`packages/web/web-deepseek-api/src/index.ts:56`](../packages/web/web-deepseek-api/src/index.ts) ```ts config-catalog /** @@ -4929,7 +4929,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-search-deepseek/src/index.ts:54`](../packages/web/web-search-deepseek/src/index.ts) +- `source`: [`packages/web/web-search-deepseek/src/index.ts:53`](../packages/web/web-search-deepseek/src/index.ts) ```ts config-catalog /** Plugin config (all optional — `apply` fills env-var and constant defaults). */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index a3bb192363..5abff53155 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -894,7 +894,7 @@ export interface Config { ## `@deepseek-ai/dsh-deepseek-account` - `inject`: `credentials` · `authorization` -- `source`: [`packages/credentials/deepseek-account/src/index.ts:40`](../packages/credentials/deepseek-account/src/index.ts) +- `source`: [`packages/account/deepseek-account/src/index.ts:39`](../packages/account/deepseek-account/src/index.ts) ```ts config-catalog /** Deployment-specific platform and request deadlines. */ @@ -4853,7 +4853,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-deepseek-api/src/index.ts:64`](../packages/web/web-deepseek-api/src/index.ts) +- `source`: [`packages/web/web-deepseek-api/src/index.ts:56`](../packages/web/web-deepseek-api/src/index.ts) ```ts config-catalog /** @@ -4931,7 +4931,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-search-deepseek/src/index.ts:54`](../packages/web/web-search-deepseek/src/index.ts) +- `source`: [`packages/web/web-search-deepseek/src/index.ts:53`](../packages/web/web-search-deepseek/src/index.ts) ```ts config-catalog /** Plugin config (all optional — `apply` fills env-var and constant defaults). */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 1d80e1cfe7..c9c6deebc2 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -15,7 +15,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | | `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:291`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | @@ -40,11 +40,11 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `cordis/inspect-query-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:401`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:371`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:377`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | -| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:100`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account`](../packages/credentials/deepseek-account), `remotes` | +| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:100`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account`](../packages/account/deepseek-account), `remotes` | | `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:88`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | -| `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:110`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` | -| `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:106`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account), `remotes` | -| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | +| `deepseek-account/model-sign-in-required` | `emit` | [`packages/account/deepseek-account/src/types.ts:110`](../packages/account/deepseek-account/src/types.ts) | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) (`emit`) | `remotes` | +| `deepseek-account/session-expired` | `emit` | [`packages/account/deepseek-account/src/types.ts:106`](../packages/account/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`deepseek-account`](../packages/account/deepseek-account), `remotes` | +| `deepseek-account/signed-out` | `emit` | [`packages/account/deepseek-account/src/index.ts:28`](../packages/account/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | | `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` | | `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | | `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:29`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | @@ -59,7 +59,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:114`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:77`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 9245fa8fab..0e89f97f00 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -17,7 +17,7 @@ | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | | `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:291`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | @@ -42,11 +42,11 @@ | `cordis/inspect-query-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:401`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:371`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:377`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | -| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:100`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account`](../packages/credentials/deepseek-account), `remotes` | +| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:100`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account`](../packages/account/deepseek-account), `remotes` | | `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:88`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | -| `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:110`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` | -| `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:106`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account), `remotes` | -| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | +| `deepseek-account/model-sign-in-required` | `emit` | [`packages/account/deepseek-account/src/types.ts:110`](../packages/account/deepseek-account/src/types.ts) | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) (`emit`) | `remotes` | +| `deepseek-account/session-expired` | `emit` | [`packages/account/deepseek-account/src/types.ts:106`](../packages/account/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`deepseek-account`](../packages/account/deepseek-account), `remotes` | +| `deepseek-account/signed-out` | `emit` | [`packages/account/deepseek-account/src/index.ts:28`](../packages/account/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | | `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` | | `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | | `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:29`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | @@ -61,7 +61,7 @@ | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:114`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:77`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | diff --git a/docs/module-graph.md b/docs/module-graph.md index f7b3d5563c..bdbe8d7067 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -115,6 +115,9 @@ flowchart TD subgraph group_acp["packages/acp"] pkg_acp["acp"] end + subgraph group_account["packages/account"] + pkg_deepseek_account["deepseek-account"] + end subgraph group_api["packages/api"] pkg_api_gateway["api-gateway"] pkg_api_job_controller["api-job-controller"] @@ -245,7 +248,6 @@ flowchart TD pkg_authorization["authorization"] pkg_credentials["credentials"] pkg_credentials_local["credentials-local"] - pkg_deepseek_account["deepseek-account"] end subgraph group_deliverables["packages/deliverables"] pkg_deliverable_file_references["deliverable-file-references"] @@ -488,6 +490,7 @@ flowchart TD end pkg_llm --> pkg_error pkg_session --> pkg_scope + pkg_web --> pkg_error pkg_api_remotes --> pkg_scope pkg_attachment --> pkg_brand pkg_attachment --> pkg_error @@ -496,10 +499,7 @@ flowchart TD pkg_browser_use --> pkg_brand pkg_client_connection --> pkg_scope pkg_computer_use --> pkg_brand - pkg_credentials_local --> pkg_atomic_write - pkg_credentials_local --> pkg_credentials - pkg_credentials_local --> pkg_home_paths - pkg_credentials_local --> pkg_launch_environment + pkg_credentials --> pkg_launch_environment pkg_experimental_liveshare --> pkg_scope pkg_anonymous_user_id --> pkg_brand pkg_anonymous_user_id --> pkg_home_paths @@ -516,7 +516,8 @@ flowchart TD pkg_system_prompt --> pkg_scope pkg_skill --> pkg_llm pkg_skill --> pkg_scope - pkg_web --> pkg_llm + pkg_web_fetch_http --> pkg_timeout + pkg_web_fetch_http --> pkg_web pkg_spill --> pkg_brand pkg_spill --> pkg_llm pkg_spill --> pkg_session @@ -526,7 +527,11 @@ flowchart TD pkg_hmr --> pkg_app_boot pkg_hmr --> pkg_cmdline pkg_authorization --> pkg_credentials - pkg_authorization --> pkg_llm + pkg_authorization --> pkg_error + pkg_credentials_local --> pkg_atomic_write + pkg_credentials_local --> pkg_credentials + pkg_credentials_local --> pkg_home_paths + pkg_credentials_local --> pkg_launch_environment pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use pkg_experimental_forge_github --> pkg_experimental_forge pkg_experimental_forge_github --> pkg_subprocess @@ -564,11 +569,15 @@ flowchart TD pkg_fs --> pkg_llm pkg_fs --> pkg_sandbox pkg_skill_office --> pkg_skill - pkg_web_fetch_http --> pkg_timeout - pkg_web_fetch_http --> pkg_web pkg_spill_local --> pkg_spill pkg_session_log_export --> pkg_session pkg_session_log_export --> pkg_session_persistence + pkg_deepseek_account --> pkg_authorization + pkg_deepseek_account --> pkg_brand + pkg_deepseek_account --> pkg_credentials + pkg_deepseek_account --> pkg_host_webserver + pkg_deepseek_account --> pkg_typert_protocol + pkg_deepseek_account --> pkg_util_values pkg_config_editor --> pkg_app_boot pkg_config_editor --> pkg_hmr pkg_deliverable_file_references --> pkg_system_prompt @@ -667,6 +676,11 @@ flowchart TD pkg_pwsh_local --> pkg_shell pkg_pwsh_local --> pkg_subprocess pkg_pwsh_local --> pkg_timeout + pkg_llm_deepseek_account --> pkg_agent + pkg_llm_deepseek_account --> pkg_deepseek_account + pkg_llm_deepseek_account --> pkg_launch_environment + pkg_llm_deepseek_account --> pkg_llm + pkg_llm_deepseek_account --> pkg_llm_deepseek pkg_llm_deepseek_api_key --> pkg_credentials pkg_llm_deepseek_api_key --> pkg_launch_environment pkg_llm_deepseek_api_key --> pkg_llm @@ -686,6 +700,19 @@ flowchart TD pkg_goal --> pkg_session pkg_goal --> pkg_session_projection pkg_goal --> pkg_typert_protocol + pkg_web_deepseek_api --> pkg_agent + pkg_web_deepseek_api --> pkg_credentials + pkg_web_deepseek_api --> pkg_deepseek_account + pkg_web_deepseek_api --> pkg_launch_environment + pkg_web_deepseek_api --> pkg_llm + pkg_web_deepseek_api --> pkg_session + pkg_web_deepseek_api --> pkg_web + pkg_web_search_deepseek --> pkg_agent + pkg_web_search_deepseek --> pkg_credentials + pkg_web_search_deepseek --> pkg_launch_environment + pkg_web_search_deepseek --> pkg_llm + pkg_web_search_deepseek --> pkg_session + pkg_web_search_deepseek --> pkg_web pkg_file_reference --> pkg_agent pkg_harness_dev_context --> pkg_agent pkg_harness_dev_context --> pkg_session @@ -700,14 +727,6 @@ flowchart TD pkg_tmux_context --> pkg_session pkg_tmux_context --> pkg_session_projection pkg_tmux_context --> pkg_shell - pkg_deepseek_account --> pkg_agent - pkg_deepseek_account --> pkg_authorization - pkg_deepseek_account --> pkg_brand - pkg_deepseek_account --> pkg_credentials - pkg_deepseek_account --> pkg_host_webserver - pkg_deepseek_account --> pkg_llm - pkg_deepseek_account --> pkg_typert_protocol - pkg_deepseek_account --> pkg_util_values pkg_commands --> pkg_agent pkg_commands --> pkg_attachment pkg_commands --> pkg_brand @@ -763,10 +782,6 @@ flowchart TD pkg_workflow --> pkg_brand pkg_workflow --> pkg_llm pkg_workflow --> pkg_session - pkg_llm_deepseek_account --> pkg_deepseek_account - pkg_llm_deepseek_account --> pkg_launch_environment - pkg_llm_deepseek_account --> pkg_llm - pkg_llm_deepseek_account --> pkg_llm_deepseek pkg_tools --> pkg_agent pkg_tools --> pkg_llm pkg_tools --> pkg_scope @@ -780,13 +795,6 @@ flowchart TD pkg_fs_sandbox --> pkg_fs_local pkg_fs_sandbox --> pkg_sandbox pkg_fs_sandbox --> pkg_sandbox_policy - pkg_web_search_deepseek --> pkg_agent - pkg_web_search_deepseek --> pkg_credentials - pkg_web_search_deepseek --> pkg_deepseek_account - pkg_web_search_deepseek --> pkg_launch_environment - pkg_web_search_deepseek --> pkg_llm_deepseek - pkg_web_search_deepseek --> pkg_session - pkg_web_search_deepseek --> pkg_web pkg_compaction --> pkg_brand pkg_compaction --> pkg_commands pkg_compaction --> pkg_llm @@ -900,16 +908,6 @@ flowchart TD pkg_tool_web --> pkg_system_prompt pkg_tool_web --> pkg_tools pkg_tool_web --> pkg_web - pkg_web_deepseek_api --> pkg_agent - pkg_web_deepseek_api --> pkg_credentials - pkg_web_deepseek_api --> pkg_deepseek_account - pkg_web_deepseek_api --> pkg_launch_environment - pkg_web_deepseek_api --> pkg_llm - pkg_web_deepseek_api --> pkg_llm_deepseek - pkg_web_deepseek_api --> pkg_llm_deepseek_account - pkg_web_deepseek_api --> pkg_llm_deepseek_api_key - pkg_web_deepseek_api --> pkg_session - pkg_web_deepseek_api --> pkg_web pkg_tool_todo --> pkg_agent pkg_tool_todo --> pkg_session pkg_tool_todo --> pkg_session_projection @@ -1654,7 +1652,6 @@ flowchart TD | [`client-ui-workflow-run`](../packages/client/ui-workflow-run) | `client` | — | | [`client-ui-workspace`](../packages/client/ui-workspace) | `client` | — | | [`client-web`](../packages/client/web) | `client` | — | -| [`credentials`](../packages/credentials/credentials) | `credentials` | — | | [`office-kit`](../packages/document/office-kit) | `document` | — | | [`client-ui-action-cards`](../packages/experimental/client-ui-action-cards) | `experimental` | — | | [`client-ui-creation-recommendations`](../packages/experimental/client-ui-creation-recommendations) | `experimental` | — | @@ -1700,13 +1697,14 @@ flowchart TD | [`typert-registry`](../packages/typert/registry) | `typert` | — | | [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) | | [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) | +| [`web`](../packages/web/web) | `web` | [`error`](../packages/util/error) | | [`api-remotes`](../packages/api/remotes) | `api` | [`scope`](../packages/core/scope) | | [`attachment`](../packages/attachment/attachment) | `attachment` | [`brand`](../packages/util/brand), [`error`](../packages/util/error) | | [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`browser-use`](../packages/browser-use/browser-use) | `browser-use` | [`brand`](../packages/util/brand) | | [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) | | [`computer-use`](../packages/computer-use/computer-use) | `computer-use` | [`brand`](../packages/util/brand) | -| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | +| [`credentials`](../packages/credentials/credentials) | `credentials` | [`launch-environment`](../packages/util/launch-environment) | | [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`scope`](../packages/core/scope) | | [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) | | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`storage`](../packages/storage/storage) | @@ -1719,12 +1717,13 @@ flowchart TD | [`util-ripgrep`](../packages/util/ripgrep) | `util` | [`subprocess`](../packages/subprocess/subprocess) | | [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | | [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | -| [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) | +| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) | | [`spill`](../packages/spill/spill) | `spill` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`api-terminal-controller`](../packages/api/terminal-controller) | `api` | [`subprocess`](../packages/subprocess/subprocess) | | [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) | | [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) | -| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) | +| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`error`](../packages/util/error) | +| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) | | [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) | @@ -1742,9 +1741,9 @@ flowchart TD | [`session-snapshot`](../packages/test-support/session-snapshot) | `test-support` | [`http-proxy`](../packages/util/http-proxy), [`session`](../packages/core/session) | | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | | [`skill-office`](../packages/skill/skill-office) | `skill` | [`skill`](../packages/skill/skill) | -| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) | | [`spill-local`](../packages/spill/spill-local) | `spill` | [`spill`](../packages/spill/spill) | | [`session-log-export`](../packages/session-query/session-log-export) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | +| [`deepseek-account`](../packages/account/deepseek-account) | `account` | [`authorization`](../packages/credentials/authorization), [`brand`](../packages/util/brand), [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | | [`config-editor`](../packages/boot/config-editor) | `boot` | [`app-boot`](../packages/boot/app-boot), [`hmr`](../packages/boot/hmr) | | [`deliverable-file-references`](../packages/deliverables/deliverable-file-references) | `deliverables` | [`system-prompt`](../packages/core/system-prompt) | | [`experimental-speech-to-text`](../packages/experimental/speech-to-text) | `experimental` | [`settings`](../packages/settings/settings) | @@ -1776,15 +1775,17 @@ flowchart TD | [`lsp-stdio`](../packages/lsp/lsp-stdio) | `lsp` | [`brand`](../packages/util/brand), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`bash-local`](../packages/shell/bash-local) | `shell` | [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`pwsh-local`](../packages/shell/pwsh-local) | `shell` | [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | +| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/account/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key) | `llm` | [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`llm-retry`](../packages/llm/llm-retry) | `llm` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`timeout`](../packages/util/timeout) | | [`agent-default-model`](../packages/core/agent-default-model) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm) | | [`goal`](../packages/goal/goal) | `goal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | +| [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/account/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`web`](../packages/web/web) | +| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`file-reference`](../packages/context/file-reference) | `context` | [`agent`](../packages/core/agent) | | [`harness-dev-context`](../packages/context/harness-dev-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`util-time`](../packages/util/time) | | [`tmux-context`](../packages/context/tmux-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell) | -| [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`agent`](../packages/core/agent), [`authorization`](../packages/credentials/authorization), [`brand`](../packages/util/brand), [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`llm`](../packages/llm/llm), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | | [`commands`](../packages/interaction/commands) | `interaction` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`user-questions`](../packages/interaction/user-questions) | `interaction` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | @@ -1796,11 +1797,9 @@ flowchart TD | [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`error`](../packages/util/error) | | [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`http-proxy`](../packages/util/http-proxy), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | | [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | | [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | -| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm-deepseek`](../packages/llm/llm-deepseek), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`compaction`](../packages/compaction/compaction) | `compaction` | [`brand`](../packages/util/brand), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | @@ -1822,7 +1821,6 @@ flowchart TD | [`tool-skill`](../packages/skill/tool-skill) | `skill` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-workspace-dependencies`](../packages/skill/tool-workspace-dependencies) | `skill` | [`tools`](../packages/core/tools) | | [`tool-web`](../packages/web/tool-web) | `web` | [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`web`](../packages/web/web) | -| [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`tool-todo`](../packages/todo/tool-todo) | `todo` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`tools`](../packages/core/tools) | | [`plan-mode`](../packages/plan/plan-mode) | `plan` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`command-compact`](../packages/compaction/command-compact) | `compaction` | [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 340164d5a3..319d57e90c 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -117,6 +117,9 @@ flowchart TD subgraph group_acp["packages/acp"] pkg_acp["acp"] end + subgraph group_account["packages/account"] + pkg_deepseek_account["deepseek-account"] + end subgraph group_api["packages/api"] pkg_api_gateway["api-gateway"] pkg_api_job_controller["api-job-controller"] @@ -247,7 +250,6 @@ flowchart TD pkg_authorization["authorization"] pkg_credentials["credentials"] pkg_credentials_local["credentials-local"] - pkg_deepseek_account["deepseek-account"] end subgraph group_deliverables["packages/deliverables"] pkg_deliverable_file_references["deliverable-file-references"] @@ -490,6 +492,7 @@ flowchart TD end pkg_llm --> pkg_error pkg_session --> pkg_scope + pkg_web --> pkg_error pkg_api_remotes --> pkg_scope pkg_attachment --> pkg_brand pkg_attachment --> pkg_error @@ -498,10 +501,7 @@ flowchart TD pkg_browser_use --> pkg_brand pkg_client_connection --> pkg_scope pkg_computer_use --> pkg_brand - pkg_credentials_local --> pkg_atomic_write - pkg_credentials_local --> pkg_credentials - pkg_credentials_local --> pkg_home_paths - pkg_credentials_local --> pkg_launch_environment + pkg_credentials --> pkg_launch_environment pkg_experimental_liveshare --> pkg_scope pkg_anonymous_user_id --> pkg_brand pkg_anonymous_user_id --> pkg_home_paths @@ -518,7 +518,8 @@ flowchart TD pkg_system_prompt --> pkg_scope pkg_skill --> pkg_llm pkg_skill --> pkg_scope - pkg_web --> pkg_llm + pkg_web_fetch_http --> pkg_timeout + pkg_web_fetch_http --> pkg_web pkg_spill --> pkg_brand pkg_spill --> pkg_llm pkg_spill --> pkg_session @@ -528,7 +529,11 @@ flowchart TD pkg_hmr --> pkg_app_boot pkg_hmr --> pkg_cmdline pkg_authorization --> pkg_credentials - pkg_authorization --> pkg_llm + pkg_authorization --> pkg_error + pkg_credentials_local --> pkg_atomic_write + pkg_credentials_local --> pkg_credentials + pkg_credentials_local --> pkg_home_paths + pkg_credentials_local --> pkg_launch_environment pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use pkg_experimental_forge_github --> pkg_experimental_forge pkg_experimental_forge_github --> pkg_subprocess @@ -566,11 +571,15 @@ flowchart TD pkg_fs --> pkg_llm pkg_fs --> pkg_sandbox pkg_skill_office --> pkg_skill - pkg_web_fetch_http --> pkg_timeout - pkg_web_fetch_http --> pkg_web pkg_spill_local --> pkg_spill pkg_session_log_export --> pkg_session pkg_session_log_export --> pkg_session_persistence + pkg_deepseek_account --> pkg_authorization + pkg_deepseek_account --> pkg_brand + pkg_deepseek_account --> pkg_credentials + pkg_deepseek_account --> pkg_host_webserver + pkg_deepseek_account --> pkg_typert_protocol + pkg_deepseek_account --> pkg_util_values pkg_config_editor --> pkg_app_boot pkg_config_editor --> pkg_hmr pkg_deliverable_file_references --> pkg_system_prompt @@ -669,6 +678,11 @@ flowchart TD pkg_pwsh_local --> pkg_shell pkg_pwsh_local --> pkg_subprocess pkg_pwsh_local --> pkg_timeout + pkg_llm_deepseek_account --> pkg_agent + pkg_llm_deepseek_account --> pkg_deepseek_account + pkg_llm_deepseek_account --> pkg_launch_environment + pkg_llm_deepseek_account --> pkg_llm + pkg_llm_deepseek_account --> pkg_llm_deepseek pkg_llm_deepseek_api_key --> pkg_credentials pkg_llm_deepseek_api_key --> pkg_launch_environment pkg_llm_deepseek_api_key --> pkg_llm @@ -688,6 +702,19 @@ flowchart TD pkg_goal --> pkg_session pkg_goal --> pkg_session_projection pkg_goal --> pkg_typert_protocol + pkg_web_deepseek_api --> pkg_agent + pkg_web_deepseek_api --> pkg_credentials + pkg_web_deepseek_api --> pkg_deepseek_account + pkg_web_deepseek_api --> pkg_launch_environment + pkg_web_deepseek_api --> pkg_llm + pkg_web_deepseek_api --> pkg_session + pkg_web_deepseek_api --> pkg_web + pkg_web_search_deepseek --> pkg_agent + pkg_web_search_deepseek --> pkg_credentials + pkg_web_search_deepseek --> pkg_launch_environment + pkg_web_search_deepseek --> pkg_llm + pkg_web_search_deepseek --> pkg_session + pkg_web_search_deepseek --> pkg_web pkg_file_reference --> pkg_agent pkg_harness_dev_context --> pkg_agent pkg_harness_dev_context --> pkg_session @@ -702,14 +729,6 @@ flowchart TD pkg_tmux_context --> pkg_session pkg_tmux_context --> pkg_session_projection pkg_tmux_context --> pkg_shell - pkg_deepseek_account --> pkg_agent - pkg_deepseek_account --> pkg_authorization - pkg_deepseek_account --> pkg_brand - pkg_deepseek_account --> pkg_credentials - pkg_deepseek_account --> pkg_host_webserver - pkg_deepseek_account --> pkg_llm - pkg_deepseek_account --> pkg_typert_protocol - pkg_deepseek_account --> pkg_util_values pkg_commands --> pkg_agent pkg_commands --> pkg_attachment pkg_commands --> pkg_brand @@ -765,10 +784,6 @@ flowchart TD pkg_workflow --> pkg_brand pkg_workflow --> pkg_llm pkg_workflow --> pkg_session - pkg_llm_deepseek_account --> pkg_deepseek_account - pkg_llm_deepseek_account --> pkg_launch_environment - pkg_llm_deepseek_account --> pkg_llm - pkg_llm_deepseek_account --> pkg_llm_deepseek pkg_tools --> pkg_agent pkg_tools --> pkg_llm pkg_tools --> pkg_scope @@ -782,13 +797,6 @@ flowchart TD pkg_fs_sandbox --> pkg_fs_local pkg_fs_sandbox --> pkg_sandbox pkg_fs_sandbox --> pkg_sandbox_policy - pkg_web_search_deepseek --> pkg_agent - pkg_web_search_deepseek --> pkg_credentials - pkg_web_search_deepseek --> pkg_deepseek_account - pkg_web_search_deepseek --> pkg_launch_environment - pkg_web_search_deepseek --> pkg_llm_deepseek - pkg_web_search_deepseek --> pkg_session - pkg_web_search_deepseek --> pkg_web pkg_compaction --> pkg_brand pkg_compaction --> pkg_commands pkg_compaction --> pkg_llm @@ -902,16 +910,6 @@ flowchart TD pkg_tool_web --> pkg_system_prompt pkg_tool_web --> pkg_tools pkg_tool_web --> pkg_web - pkg_web_deepseek_api --> pkg_agent - pkg_web_deepseek_api --> pkg_credentials - pkg_web_deepseek_api --> pkg_deepseek_account - pkg_web_deepseek_api --> pkg_launch_environment - pkg_web_deepseek_api --> pkg_llm - pkg_web_deepseek_api --> pkg_llm_deepseek - pkg_web_deepseek_api --> pkg_llm_deepseek_account - pkg_web_deepseek_api --> pkg_llm_deepseek_api_key - pkg_web_deepseek_api --> pkg_session - pkg_web_deepseek_api --> pkg_web pkg_tool_todo --> pkg_agent pkg_tool_todo --> pkg_session pkg_tool_todo --> pkg_session_projection @@ -1656,7 +1654,6 @@ flowchart TD | [`client-ui-workflow-run`](../packages/client/ui-workflow-run) | `client` | — | | [`client-ui-workspace`](../packages/client/ui-workspace) | `client` | — | | [`client-web`](../packages/client/web) | `client` | — | -| [`credentials`](../packages/credentials/credentials) | `credentials` | — | | [`office-kit`](../packages/document/office-kit) | `document` | — | | [`client-ui-action-cards`](../packages/experimental/client-ui-action-cards) | `experimental` | — | | [`client-ui-creation-recommendations`](../packages/experimental/client-ui-creation-recommendations) | `experimental` | — | @@ -1702,13 +1699,14 @@ flowchart TD | [`typert-registry`](../packages/typert/registry) | `typert` | — | | [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) | | [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) | +| [`web`](../packages/web/web) | `web` | [`error`](../packages/util/error) | | [`api-remotes`](../packages/api/remotes) | `api` | [`scope`](../packages/core/scope) | | [`attachment`](../packages/attachment/attachment) | `attachment` | [`brand`](../packages/util/brand), [`error`](../packages/util/error) | | [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`browser-use`](../packages/browser-use/browser-use) | `browser-use` | [`brand`](../packages/util/brand) | | [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) | | [`computer-use`](../packages/computer-use/computer-use) | `computer-use` | [`brand`](../packages/util/brand) | -| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | +| [`credentials`](../packages/credentials/credentials) | `credentials` | [`launch-environment`](../packages/util/launch-environment) | | [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`scope`](../packages/core/scope) | | [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) | | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`storage`](../packages/storage/storage) | @@ -1721,12 +1719,13 @@ flowchart TD | [`util-ripgrep`](../packages/util/ripgrep) | `util` | [`subprocess`](../packages/subprocess/subprocess) | | [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | | [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | -| [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) | +| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) | | [`spill`](../packages/spill/spill) | `spill` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`api-terminal-controller`](../packages/api/terminal-controller) | `api` | [`subprocess`](../packages/subprocess/subprocess) | | [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) | | [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) | -| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) | +| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`error`](../packages/util/error) | +| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) | | [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) | @@ -1744,9 +1743,9 @@ flowchart TD | [`session-snapshot`](../packages/test-support/session-snapshot) | `test-support` | [`http-proxy`](../packages/util/http-proxy), [`session`](../packages/core/session) | | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | | [`skill-office`](../packages/skill/skill-office) | `skill` | [`skill`](../packages/skill/skill) | -| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) | | [`spill-local`](../packages/spill/spill-local) | `spill` | [`spill`](../packages/spill/spill) | | [`session-log-export`](../packages/session-query/session-log-export) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | +| [`deepseek-account`](../packages/account/deepseek-account) | `account` | [`authorization`](../packages/credentials/authorization), [`brand`](../packages/util/brand), [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | | [`config-editor`](../packages/boot/config-editor) | `boot` | [`app-boot`](../packages/boot/app-boot), [`hmr`](../packages/boot/hmr) | | [`deliverable-file-references`](../packages/deliverables/deliverable-file-references) | `deliverables` | [`system-prompt`](../packages/core/system-prompt) | | [`experimental-speech-to-text`](../packages/experimental/speech-to-text) | `experimental` | [`settings`](../packages/settings/settings) | @@ -1778,15 +1777,17 @@ flowchart TD | [`lsp-stdio`](../packages/lsp/lsp-stdio) | `lsp` | [`brand`](../packages/util/brand), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`bash-local`](../packages/shell/bash-local) | `shell` | [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`pwsh-local`](../packages/shell/pwsh-local) | `shell` | [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | +| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/account/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key) | `llm` | [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`llm-retry`](../packages/llm/llm-retry) | `llm` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`timeout`](../packages/util/timeout) | | [`agent-default-model`](../packages/core/agent-default-model) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm) | | [`goal`](../packages/goal/goal) | `goal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | +| [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/account/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`web`](../packages/web/web) | +| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`file-reference`](../packages/context/file-reference) | `context` | [`agent`](../packages/core/agent) | | [`harness-dev-context`](../packages/context/harness-dev-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`util-time`](../packages/util/time) | | [`tmux-context`](../packages/context/tmux-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell) | -| [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`agent`](../packages/core/agent), [`authorization`](../packages/credentials/authorization), [`brand`](../packages/util/brand), [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`llm`](../packages/llm/llm), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | | [`commands`](../packages/interaction/commands) | `interaction` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`user-questions`](../packages/interaction/user-questions) | `interaction` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | @@ -1798,11 +1799,9 @@ flowchart TD | [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`error`](../packages/util/error) | | [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`http-proxy`](../packages/util/http-proxy), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | | [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | | [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | -| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm-deepseek`](../packages/llm/llm-deepseek), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`compaction`](../packages/compaction/compaction) | `compaction` | [`brand`](../packages/util/brand), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | @@ -1824,7 +1823,6 @@ flowchart TD | [`tool-skill`](../packages/skill/tool-skill) | `skill` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-workspace-dependencies`](../packages/skill/tool-workspace-dependencies) | `skill` | [`tools`](../packages/core/tools) | | [`tool-web`](../packages/web/tool-web) | `web` | [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`web`](../packages/web/web) | -| [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`tool-todo`](../packages/todo/tool-todo) | `todo` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`tools`](../packages/core/tools) | | [`plan-mode`](../packages/plan/plan-mode) | `plan` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`command-compact`](../packages/compaction/command-compact) | `compaction` | [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index f2294edff6..e7a2915d50 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -294,8 +294,8 @@ en: d278748103cf1640 zh: d278748103cf1640 /session-persistence-event-catalog/events/web/web-deepseek-search-llm-request-log-only: - en: a3e7718f295ba130 - zh: e6435b44b42f0784 + en: 52d1a5b0a68ac0a4 + zh: 1df3a7a0da7f5fa0 /session-persistence-event-catalog/events/working-directory: en: e8dd0cebbb930eb7 zh: e8dd0cebbb930eb7 @@ -558,8 +558,8 @@ en: 028791baa24a6a0a zh: 028791baa24a6a0a /session-persistence-event-catalog/resolved-persistence-types/in-history: - en: ad2f023eedbc2a7e - zh: 2124b8dedfbf8383 + en: eef7993dfeef3c9d + zh: 36f6a03a24688113 /session-persistence-event-catalog/resolved-persistence-types/in-progress: en: 61de2b0c9de8c15b zh: 61de2b0c9de8c15b @@ -1026,8 +1026,8 @@ en: a6a2e38fdd6d127a zh: 1fe82356d89f5769 /session-persistence-event-catalog/resolved-persistence-types/deepseeksearchllmrequest: - en: 8cc704c4048167a7 - zh: d27823620065ad25 + en: ee82cea3594af41c + zh: c8e879993414b727 /session-persistence-event-catalog/resolved-persistence-types/developermessage: en: b91fd6f924b6d84e zh: c74abb179c889ed6 @@ -1194,8 +1194,8 @@ en: 8d2873c634bf6405 zh: 91e92b5730462cf0 /session-persistence-event-catalog/resolved-persistence-types/replayenvelope: - en: 34cbedee7bc95921 - zh: f7deeddb8d60152a + en: c0559f92b5275c58 + zh: 50616ae676eeee4c /session-persistence-event-catalog/resolved-persistence-types/requestcontext: en: 544039047a28b6bb zh: c691f0bb1e23db08 @@ -1245,8 +1245,8 @@ en: ecc15ebadb77afdf zh: 97ac27d6a4175f6f /session-persistence-event-catalog/resolved-persistence-types/streamchunk: - en: 747e384b3176e0cb - zh: defbff408ea7c97c + en: 1585ce86ccaaca53 + zh: b3073eb80e23a11f /session-persistence-event-catalog/resolved-persistence-types/subagentcatalogevent: en: 8a56ae8e701509b3 zh: caef4f0223f65470 @@ -1284,8 +1284,8 @@ en: b6bd8e9986773217 zh: ed177c2f090964af /session-persistence-event-catalog/resolved-persistence-types/textblock: - en: 7ad0f4915397b511 - zh: bcaa8bd449927989 + en: e820b2d216671243 + zh: a569cf66b82c57d7 /session-persistence-event-catalog/resolved-persistence-types/todoitem: en: ee24f9407df530ac zh: 310bedf3ac730d77 @@ -1314,8 +1314,8 @@ en: 2258683c3cfa4ce3 zh: 5663aa76c911761b /session-persistence-event-catalog/resolved-persistence-types/toolschema: - en: afa1e3fd9ccdd95b - zh: 7af667e3ebac25e8 + en: a1613c3dc1fd1b54 + zh: eb4590c068e2699c /session-persistence-event-catalog/resolved-persistence-types/toolschema~2: en: 12c14727bb7834e2 zh: b0f3c877873c36db @@ -1932,8 +1932,8 @@ en: b28ca6b37f5a338d zh: 4c4f2f05721b8b62 /session-persistence-event-catalog/resolved-persistence-types/max-tokens-messages-model-thinking: - en: 3216b23c131d0070 - zh: 73ca171c6014f16e + en: efe43158304eaf7b + zh: 7a4b0d7f1a9f1c65 /session-persistence-event-catalog/resolved-persistence-types/member-teamid-version: en: 33c28b8c72b73604 zh: 8b606ec7196176c8 @@ -1959,8 +1959,8 @@ en: b8d80b4b1e6441ad zh: d5c52e1bfe560297 /session-persistence-event-catalog/resolved-persistence-types/role-user: - en: 04b34b8ffe7e7764 - zh: a792d5371516fd9d + en: d05bb42138160fbd + zh: 9a17d062eefa48a3 /session-persistence-event-catalog/resolved-persistence-types/sessionformatversion-sessionid-throughseq: en: 8063597183ef767f zh: b064698c54089f07 @@ -2007,11 +2007,11 @@ en: bb507524bcc39c53 zh: 8314898562437473 /session-persistence-event-catalog/resolved-persistence-types/type-block-end: - en: 7513d6a33f4ad113 - zh: 652201059a3de858 + en: c65956b2e4936b98 + zh: 04a10188520dd9e2 /session-persistence-event-catalog/resolved-persistence-types/type-block-start: - en: 56230efa41e79869 - zh: 9ca4b8990a28d4d9 + en: 10eec3e1fa456886 + zh: a62e18e8e00a5f18 /session-persistence-event-catalog/resolved-persistence-types/type-chunk: en: 2186ede3e9917aea zh: 0cfef64045dce95b @@ -2040,8 +2040,8 @@ en: 6b632a8f70a45496 zh: ad6c793e41731fd7 /session-persistence-event-catalog/resolved-persistence-types/type-disabled: - en: 585627a50ece4e5f - zh: 157837aee3da0ac3 + en: 04db8a26a3befdd4 + zh: 8b24a37ac00bac8a /session-persistence-event-catalog/resolved-persistence-types/type-feedback-message-delete: en: 204561e2311db97e zh: 77264396bd5e25c4 @@ -2052,8 +2052,8 @@ en: 14e4b48d856bcf57 zh: 72ba176535dc7f3f /session-persistence-event-catalog/resolved-persistence-types/type-finish: - en: 30f8f49d0755dc2d - zh: d8553c9590a0e9bf + en: df64e36d97f48908 + zh: 86cf679e6b3fdb85 /session-persistence-event-catalog/resolved-persistence-types/type-goal-change: en: aad2516b62d3ee83 zh: e7204c4dc4e8e408 @@ -2091,8 +2091,8 @@ en: 34e5591d75322649 zh: a216839f305c9796 /session-persistence-event-catalog/resolved-persistence-types/type-reasoning-delta: - en: a3f08ffda3526201 - zh: e599517be130ff99 + en: bcafe0c539f6a5e2 + zh: 3be968698a8985bc /session-persistence-event-catalog/resolved-persistence-types/type-request-context: en: f8addb1a01da9ca1 zh: 4ef11ebddd302c05 @@ -2154,8 +2154,8 @@ en: 1484738718de5312 zh: 3e6fbe9c64068225 /session-persistence-event-catalog/resolved-persistence-types/type-text-delta: - en: 5f30a603fab07135 - zh: 3b7e2076351a1473 + en: 908a84e2ee82a7cc + zh: 5d8994c209e864a0 /session-persistence-event-catalog/resolved-persistence-types/type-todo-write: en: 2fa7ba77598a95b4 zh: 50972b51d77e9155 @@ -2163,8 +2163,8 @@ en: 32f732b97739e4d2 zh: f288e48e356969c0 /session-persistence-event-catalog/resolved-persistence-types/type-tool-call-delta: - en: 0e907728f330a8c7 - zh: d9d1400d4c468ab2 + en: 9663efae6bd28efb + zh: d8765a82a6b537a5 /session-persistence-event-catalog/resolved-persistence-types/type-tool-workflow-agent-end: en: 8eb5e1eb95722bc7 zh: 8dd5980029600648 @@ -2196,8 +2196,8 @@ en: 1b045de96172be4b zh: 8a15c6f35b576b37 /session-persistence-event-catalog/resolved-persistence-types/type-usage: - en: 5c4bf682faecace1 - zh: e2014c3dc10bae79 + en: 20d2e379fc64c866 + zh: b2d35dba5d3006af /session-persistence-event-catalog/resolved-persistence-types/type-user-message: en: fd9f5dacef8c0ce8 zh: 79eab747b55dfaac @@ -2205,8 +2205,8 @@ en: 99c8837344178a47 zh: bf746f5678346596 /session-persistence-event-catalog/resolved-persistence-types/type-web-search-20250305: - en: e0071555851c7cee - zh: 1f368baf78a7d689 + en: 557e9462b176c4a3 + zh: 4dddcab9de61639f /session-persistence-event-catalog/resolved-persistence-types/type-working-directory-change: en: 2fcb09b83898ee18 zh: 44c7f987f0bf3588 diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 33d9aa4395..30e9eaf416 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -1313,7 +1313,7 @@ Source: [`packages/core/session/src/types.ts:315`](../packages/core/session/src/ 'web/deepseek-search-llm-request': DeepSeekSearchLlmRequest ``` -Source: [`packages/web/web-search-deepseek/src/provider.ts:89`](../packages/web/web-search-deepseek/src/provider.ts) +Source: [`packages/web/web-search-deepseek/src/provider.ts:90`](../packages/web/web-search-deepseek/src/provider.ts) ### `working-directory/*` @@ -2018,7 +2018,7 @@ SHA-256: `ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8` SHA-256: `f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5` -Sources: [`packages/llm/llm/src/types.ts:440`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:521`](../packages/llm/llm/src/types.ts) `"in-history"` @@ -3418,7 +3418,7 @@ Sources: [`packages/subagent/subagent/src/descriptor.ts:72`](../packages/subagen SHA-256: `abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c` -Sources: [`packages/web/web-search-deepseek/src/provider.ts:55`](../packages/web/web-search-deepseek/src/provider.ts) +Sources: [`packages/web/web-search-deepseek/src/provider.ts:56`](../packages/web/web-search-deepseek/src/provider.ts) | Property | Presence | Type | |---|---|---| @@ -4564,7 +4564,7 @@ Sources: [`packages/llm/llm/src/types.ts:75`](../packages/llm/llm/src/types.ts) SHA-256: `0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555` -Sources: [`packages/llm/llm/src/types.ts:474`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:555`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4878,7 +4878,7 @@ Sources: [`packages/skill/skill/src/index.ts:146`](../packages/skill/skill/src/i SHA-256: `47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180` -Sources: [`packages/llm/llm/src/types.ts:496`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:577`](../packages/llm/llm/src/types.ts) One of: @@ -5135,7 +5135,7 @@ One of: SHA-256: `4e887768586528565381dadbddee6cef555874148089f4579e0b4b1ad096fc9c` -Sources: [`packages/llm/llm/src/types.ts:69`](../packages/llm/llm/src/types.ts) · [`packages/web/web-search-deepseek/src/provider.ts:66`](../packages/web/web-search-deepseek/src/provider.ts) +Sources: [`packages/llm/llm/src/types.ts:69`](../packages/llm/llm/src/types.ts) · [`packages/web/web-search-deepseek/src/provider.ts:67`](../packages/web/web-search-deepseek/src/provider.ts) | Property | Presence | Type | |---|---|---| @@ -5307,7 +5307,7 @@ Sources: [`packages/llm/llm/src/message.ts:173`](../packages/llm/llm/src/message SHA-256: `66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2` -Sources: [`packages/llm/llm/src/types.ts:517`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:598`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7961,7 +7961,7 @@ Sources: [`packages/session/working-directory/src/index.ts:48`](../packages/sess SHA-256: `9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee` -Sources: [`packages/web/web-search-deepseek/src/provider.ts:61`](../packages/web/web-search-deepseek/src/provider.ts) +Sources: [`packages/web/web-search-deepseek/src/provider.ts:62`](../packages/web/web-search-deepseek/src/provider.ts) | Property | Presence | Type | |---|---|---| @@ -8085,7 +8085,7 @@ Sources: [`packages/core/session/src/types.ts:303`](../packages/core/session/src SHA-256: `9a2a9029f8d7ede05336980d8342737557f487b913bfd28853d0ab5214600ab5` -Sources: [`packages/web/web-search-deepseek/src/provider.ts:64`](../packages/web/web-search-deepseek/src/provider.ts) +Sources: [`packages/web/web-search-deepseek/src/provider.ts:65`](../packages/web/web-search-deepseek/src/provider.ts) | Property | Presence | Type | |---|---|---| @@ -8316,7 +8316,7 @@ SHA-256: `1033093edd0db80ff410e00830b523405e00bb0c7684948e531ff65095799625` SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d` -Sources: [`packages/llm/llm/src/types.ts:501`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:582`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8330,7 +8330,7 @@ Sources: [`packages/llm/llm/src/types.ts:501`](../packages/llm/llm/src/types.ts) SHA-256: `3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90` -Sources: [`packages/llm/llm/src/types.ts:497`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:578`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8488,7 +8488,7 @@ SHA-256: `510826cf4e1f9220d75c1efd90b349dd9a77fc5ba15d19e16f87e85a48db5f99` SHA-256: `37ff65426bcf130f045d3a59ef2a4648eb170cd30280cbd024108a2e9b4401d1` -Sources: [`packages/web/web-search-deepseek/src/provider.ts:82`](../packages/web/web-search-deepseek/src/provider.ts) +Sources: [`packages/web/web-search-deepseek/src/provider.ts:83`](../packages/web/web-search-deepseek/src/provider.ts) | Property | Presence | Type | |---|---|---| @@ -8548,7 +8548,7 @@ SHA-256: `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` SHA-256: `a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1` -Sources: [`packages/llm/llm/src/types.ts:503`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:584`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8754,7 +8754,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:28`](../packages/llm/llm/src SHA-256: `2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095` -Sources: [`packages/llm/llm/src/types.ts:499`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:580`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -9090,7 +9090,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:21`](../packages/llm/llm/src SHA-256: `95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65` -Sources: [`packages/llm/llm/src/types.ts:498`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:579`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -9138,7 +9138,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:35`](../packages/llm/llm/src SHA-256: `88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a` -Sources: [`packages/llm/llm/src/types.ts:500`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:581`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -9316,7 +9316,7 @@ SHA-256: `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515` -Sources: [`packages/llm/llm/src/types.ts:502`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:583`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -9363,7 +9363,7 @@ SHA-256: `0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52` SHA-256: `2d11ca7b0d4493e244b74eba093227866b33249841e59a1e9bf56afed38604c3` -Sources: [`packages/web/web-search-deepseek/src/provider.ts:71`](../packages/web/web-search-deepseek/src/provider.ts) +Sources: [`packages/web/web-search-deepseek/src/provider.ts:72`](../packages/web/web-search-deepseek/src/provider.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 5047ebc659..7604079d8d 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -1315,7 +1315,7 @@ export type SessionEvent = { 'web/deepseek-search-llm-request': DeepSeekSearchLlmRequest ``` -来源:[`packages/web/web-search-deepseek/src/provider.ts:89`](../packages/web/web-search-deepseek/src/provider.ts) +来源:[`packages/web/web-search-deepseek/src/provider.ts:90`](../packages/web/web-search-deepseek/src/provider.ts) ### `working-directory/*` @@ -2020,7 +2020,7 @@ SHA-256: `ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8` SHA-256: `f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5` -来源:[`packages/llm/llm/src/types.ts:440`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:521`](../packages/llm/llm/src/types.ts) `"in-history"` @@ -3420,7 +3420,7 @@ SHA-256: `6487b10ba7542f3c447b1e41a1c6a590b7bfafe0b9b66b49f34028da85bb970f` SHA-256: `abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c` -来源:[`packages/web/web-search-deepseek/src/provider.ts:55`](../packages/web/web-search-deepseek/src/provider.ts) +来源:[`packages/web/web-search-deepseek/src/provider.ts:56`](../packages/web/web-search-deepseek/src/provider.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4566,7 +4566,7 @@ SHA-256: `814d9434e1ddf9078612b3b34322f26e9363b469213335007f7e9ba7fee9464e` SHA-256: `0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555` -来源:[`packages/llm/llm/src/types.ts:474`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:555`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4880,7 +4880,7 @@ SHA-256: `672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db` SHA-256: `47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180` -来源:[`packages/llm/llm/src/types.ts:496`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:577`](../packages/llm/llm/src/types.ts) 以下类型之一: @@ -5137,7 +5137,7 @@ SHA-256: `b2d2a01e51341a3bfec809198952c8c830a7899f4cb6ecd3c1dc0b5d9a2af943` SHA-256: `4e887768586528565381dadbddee6cef555874148089f4579e0b4b1ad096fc9c` -来源:[`packages/llm/llm/src/types.ts:69`](../packages/llm/llm/src/types.ts) · [`packages/web/web-search-deepseek/src/provider.ts:66`](../packages/web/web-search-deepseek/src/provider.ts) +来源:[`packages/llm/llm/src/types.ts:69`](../packages/llm/llm/src/types.ts) · [`packages/web/web-search-deepseek/src/provider.ts:67`](../packages/web/web-search-deepseek/src/provider.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5309,7 +5309,7 @@ SHA-256: `4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731` SHA-256: `66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2` -来源:[`packages/llm/llm/src/types.ts:517`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:598`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7963,7 +7963,7 @@ SHA-256: `2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5` SHA-256: `9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee` -来源:[`packages/web/web-search-deepseek/src/provider.ts:61`](../packages/web/web-search-deepseek/src/provider.ts) +来源:[`packages/web/web-search-deepseek/src/provider.ts:62`](../packages/web/web-search-deepseek/src/provider.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8087,7 +8087,7 @@ SHA-256: `e481c46af3813e0010558e93f578b2986acd658404cec2d1679e3ac2a6c48654` SHA-256: `9a2a9029f8d7ede05336980d8342737557f487b913bfd28853d0ab5214600ab5` -来源:[`packages/web/web-search-deepseek/src/provider.ts:64`](../packages/web/web-search-deepseek/src/provider.ts) +来源:[`packages/web/web-search-deepseek/src/provider.ts:65`](../packages/web/web-search-deepseek/src/provider.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8318,7 +8318,7 @@ SHA-256: `1033093edd0db80ff410e00830b523405e00bb0c7684948e531ff65095799625` SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d` -来源:[`packages/llm/llm/src/types.ts:501`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:582`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8332,7 +8332,7 @@ SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d` SHA-256: `3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90` -来源:[`packages/llm/llm/src/types.ts:497`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:578`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8490,7 +8490,7 @@ SHA-256: `510826cf4e1f9220d75c1efd90b349dd9a77fc5ba15d19e16f87e85a48db5f99` SHA-256: `37ff65426bcf130f045d3a59ef2a4648eb170cd30280cbd024108a2e9b4401d1` -来源:[`packages/web/web-search-deepseek/src/provider.ts:82`](../packages/web/web-search-deepseek/src/provider.ts) +来源:[`packages/web/web-search-deepseek/src/provider.ts:83`](../packages/web/web-search-deepseek/src/provider.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8550,7 +8550,7 @@ SHA-256: `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` SHA-256: `a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1` -来源:[`packages/llm/llm/src/types.ts:503`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:584`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8756,7 +8756,7 @@ SHA-256: `71bb3254ec8f1e491ce63b762a7b5f18709de23aa4e8abcc8b886f4b6ce051dd` SHA-256: `2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095` -来源:[`packages/llm/llm/src/types.ts:499`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:580`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -9092,7 +9092,7 @@ SHA-256: `e72269f931559e901e5e8fe1cfcbd0669fb795f43cc038ff39fba62f60403c33` SHA-256: `95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65` -来源:[`packages/llm/llm/src/types.ts:498`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:579`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -9140,7 +9140,7 @@ SHA-256: `3860b4757d512a2869be833acb0faf834335b1b056bf3f83df5474dce95f8fa6` SHA-256: `88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a` -来源:[`packages/llm/llm/src/types.ts:500`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:581`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -9318,7 +9318,7 @@ SHA-256: `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515` -来源:[`packages/llm/llm/src/types.ts:502`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:583`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -9365,7 +9365,7 @@ SHA-256: `0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52` SHA-256: `2d11ca7b0d4493e244b74eba093227866b33249841e59a1e9bf56afed38604c3` -来源:[`packages/web/web-search-deepseek/src/provider.ts:71`](../packages/web/web-search-deepseek/src/provider.ts) +来源:[`packages/web/web-search-deepseek/src/provider.ts:72`](../packages/web/web-search-deepseek/src/provider.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index a2832eb98c..7594740854 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -88,7 +88,7 @@ {"digest":"0a8a062bc9c3c0d97fd97742262f2ea53dd32297f834e81114870d38ac3dc6da","names":[],"sources":[]}, {"digest":"0a92c5bdfa06c2e2615b777728f3aa95f408d43b9012e7b754568311251db623","names":[],"sources":["packages/experimental/liveshare/src/host/viewer-principal.ts:29"]}, {"digest":"0aa62ab51b36c0e64b134bd03ba8725d758744180a1a447da49beaad194f219f","names":[],"sources":[]}, - {"digest":"0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555","names":["packages/llm/llm/src/types.ts#ReplayEnvelope"],"sources":["packages/llm/llm/src/types.ts:474"]}, + {"digest":"0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555","names":["packages/llm/llm/src/types.ts#ReplayEnvelope"],"sources":["packages/llm/llm/src/types.ts:555"]}, {"digest":"0af3ecfb8c60d416fc40a7cc4fb2c4851a8e46608b2b38ab9e510670c971aa1f","names":[],"sources":[]}, {"digest":"0b6d718c693fdf7f06dcccb0bcbbabe78cc63514eafc62d6b2a3899735279d6f","names":["packages/goal/goal/src/types.ts#GoalRef"],"sources":["packages/goal/goal/src/types.ts:20"]}, {"digest":"0b9b8facbe2c19773b3fb0ecc824ccbcc603d41b8f18069faa3807d449572fce","names":[],"sources":[]}, @@ -180,11 +180,11 @@ {"digest":"297fbd8067d7815adae02b89790ec6ff5fb7c2cb0d0eb026e1746c24ec857761","names":[],"sources":[]}, {"digest":"2aad1179f957631477b582e57cd8f538cb82618fc3fb816bde1171154235b065","names":[],"sources":[]}, {"digest":"2ab12a0e345658f9342816d773fe610f049982bcad82631f43b9205abe43e5ee","names":[],"sources":[]}, - {"digest":"2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095","names":[],"sources":["packages/llm/llm/src/types.ts:499"]}, + {"digest":"2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095","names":[],"sources":["packages/llm/llm/src/types.ts:580"]}, {"digest":"2aed07493b1c65b6d00de5586da1e743cf501684b9ad43a1765fb4007d4ea456","names":[],"sources":[]}, {"digest":"2c4c21f19f426a58f2dac914e34313aa43f8408972de857a486d1f086d5adb6c","names":[],"sources":[]}, {"digest":"2c64d4bc7264fd3f8bed47e96ab8a593bce05a1e4e1c436dcd244a3b7e0c2a9d","names":[],"sources":[]}, - {"digest":"2d11ca7b0d4493e244b74eba093227866b33249841e59a1e9bf56afed38604c3","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:71"]}, + {"digest":"2d11ca7b0d4493e244b74eba093227866b33249841e59a1e9bf56afed38604c3","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:72"]}, {"digest":"2da725e554cd89301d829ed9dc45a572c3cd1b93b5e91d0d71f007976d8a0863","names":[],"sources":[]}, {"digest":"2e3523541e942ef6cc9fbc5b91f242e0ca4c6ada479b79b96025b797f6e41f3f","names":["packages/schedule/schedule/src/types.ts#ScheduleChange"],"sources":["packages/schedule/schedule/src/types.ts:232"]}, {"digest":"2e4debca12f2c449f96dc6574f3fbf2fb346193443114a241d01a236362ec48c","names":[],"sources":[]}, @@ -208,7 +208,7 @@ {"digest":"374fdd68aee5ff844e378c0cbdd961d247a0f22e4ade0bb03d800cd2a46a2b8b","names":[],"sources":["packages/llm/llm-retry/src/types.ts:30"]}, {"digest":"378f90f9f6022a0991928a1eaf7991094ea1920fe89a9248358a1da106e1a970","names":[],"sources":[]}, {"digest":"37cbc9cf06d494cfe5c67f078af1605eacb8e4c2c853e9e26455b73de0ee7ccf","names":[],"sources":[]}, - {"digest":"37ff65426bcf130f045d3a59ef2a4648eb170cd30280cbd024108a2e9b4401d1","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:82"]}, + {"digest":"37ff65426bcf130f045d3a59ef2a4648eb170cd30280cbd024108a2e9b4401d1","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:83"]}, {"digest":"383cf73ae4748e5beb281ae74857ba1ffb92ae01075b9fbf51af78b666007a8f","names":[],"sources":[]}, {"digest":"3860b4757d512a2869be833acb0faf834335b1b056bf3f83df5474dce95f8fa6","names":[],"sources":["packages/llm/llm/src/assistant-stream.ts:35"]}, {"digest":"390eed1028aba02774f14408647acec10ec5516e97d4f15ecde2b9989d5a69f2","names":["packages/feedback/message-feedback/src/types.ts#MessageFeedbackRating"],"sources":["packages/feedback/message-feedback/src/types.ts:17"]}, @@ -220,7 +220,7 @@ {"digest":"3bca25b2baa6b22be9b577621a7603497f40870ed88a8dac4383d37dc2bb6e18","names":[],"sources":[]}, {"digest":"3bd652ebfa8726b3ce3937a4f1bd2759e02f86b3a08a20f9e41a8513656fbc5f","names":["packages/core/session/src/types.ts#OptionalSessionSeq"],"sources":["packages/core/session/src/types.ts:66"]}, {"digest":"3bdb8dc6989655b0d4ec361edafb8e2629bc263e1ea591819414fdafc1a413b3","names":[],"sources":[]}, - {"digest":"3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90","names":[],"sources":["packages/llm/llm/src/types.ts:497"]}, + {"digest":"3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90","names":[],"sources":["packages/llm/llm/src/types.ts:578"]}, {"digest":"3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1","names":[],"sources":[]}, {"digest":"3c2535ca0a2062f172f15344f8040755002b5ac506cf94fc4ebaa822b15feb8c","names":[],"sources":[]}, {"digest":"3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f","names":["packages/core/tools/src/contracts.ts#ToolRestriction"],"sources":["packages/core/tools/src/contracts.ts:395"]}, @@ -245,7 +245,7 @@ {"digest":"45f2a07ea94573123b6ae14db787a40062dec3834f36d8be92c523d40ba28448","names":[],"sources":["packages/interaction/user-approval/src/types.ts:44"]}, {"digest":"477614bca595a9e7adb5a1870be446b9a8684f3ba8950259d6289f2d3b74f028","names":[],"sources":["packages/compaction/compaction-image-offload/src/projection.ts:25"]}, {"digest":"47e5d84f1a93450a78c7f3954b43990d0f629af7c034a56313e5deb63e772c1b","names":[],"sources":[]}, - {"digest":"47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180","names":["packages/llm/llm/src/types.ts#StreamChunk"],"sources":["packages/llm/llm/src/types.ts:496"]}, + {"digest":"47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180","names":["packages/llm/llm/src/types.ts#StreamChunk"],"sources":["packages/llm/llm/src/types.ts:577"]}, {"digest":"487b65c37bfedb8b72088c4107a0a90a6249701f6b26745f6d98f9b8a22b07c7","names":[],"sources":["packages/llm/llm/src/assistant-stream.ts:44"]}, {"digest":"48e5c9861f16ac07e78cb7b5ae9dabdf7bb85c58baed5a51b4ad275050ea58e3","names":[],"sources":[]}, {"digest":"48f9c19417a1abbedfa59f4667bba36b93ac2db407adf5e84cb3ba0de30942cb","names":[],"sources":[]}, @@ -263,7 +263,7 @@ {"digest":"4d60dddaa65d3da8d4cd014d85ce3d2c2875664dd0433e331d8e9d395289686b","names":["packages/experimental/liveshare/src/host/viewer-principal.ts#ShareViewerPrincipal"],"sources":["packages/experimental/liveshare/src/host/viewer-principal.ts:24"]}, {"digest":"4e011753f8263f436efaabfbb3b4db53a98fc55342c5ded2daf7208b217be159","names":[],"sources":[]}, {"digest":"4e44c9118152f6829634bfd508e47669ab0497caffa380c94b4be91f9390d35d","names":[],"sources":[]}, - {"digest":"4e887768586528565381dadbddee6cef555874148089f4579e0b4b1ad096fc9c","names":["packages/llm/llm/src/types.ts#TextBlock"],"sources":["packages/llm/llm/src/types.ts:69","packages/web/web-search-deepseek/src/provider.ts:66"]}, + {"digest":"4e887768586528565381dadbddee6cef555874148089f4579e0b4b1ad096fc9c","names":["packages/llm/llm/src/types.ts#TextBlock"],"sources":["packages/llm/llm/src/types.ts:69","packages/web/web-search-deepseek/src/provider.ts:67"]}, {"digest":"4edec1b770e8ec4ce1220bf42edc5ac46713a1b48d4caa778dcfc98bad1f28a3","names":[],"sources":[]}, {"digest":"4f507598cf476214aa7646ce7841a7064a9dcb05d0a1eaaefaf79c2b738f160f","names":[],"sources":[]}, {"digest":"4f91f187baeabef5c7950c4780d31bbe39f3345dff591a6cf26ac7e135ac1cf4","names":[],"sources":["packages/context/session-reference/src/types.ts:18"]}, @@ -323,7 +323,7 @@ {"digest":"6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25","names":["packages/team/agent-team/src/types.ts#TeamMemberSnapshot"],"sources":["packages/team/agent-team/src/types.ts:50"]}, {"digest":"65a8400e451e667e5b6e34df72ceb81fca8c12330330fa72083ad40279b189ad","names":["packages/llm/llm/src/message.ts#SystemPromptMessageSource"],"sources":["packages/llm/llm/src/message.ts:35"]}, {"digest":"65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099","names":["packages/skill/tool-skill/src/index.ts#SkillCatalogSource"],"sources":["packages/skill/tool-skill/src/index.ts:35"]}, - {"digest":"66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2","names":["packages/llm/llm/src/types.ts#ToolSchema"],"sources":["packages/llm/llm/src/types.ts:517"]}, + {"digest":"66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2","names":["packages/llm/llm/src/types.ts#ToolSchema"],"sources":["packages/llm/llm/src/types.ts:598"]}, {"digest":"672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db","names":["packages/skill/skill/src/index.ts#SkillInvocationSource"],"sources":["packages/skill/skill/src/index.ts:146"]}, {"digest":"67d5f73ceae82f5265258142ad6cf172de2c1fef93ba551b7f0454e0a93bffe0","names":["packages/llm/llm/src/call-config.ts#LlmCallConfig"],"sources":["packages/llm/llm/src/call-config.ts:31"]}, {"digest":"68141cbe3994a5ffcd064c07c75996538437fd9dbf77ce8a2927e89ec577fabe","names":[],"sources":[]}, @@ -411,7 +411,7 @@ {"digest":"871bfd6f7bb91061246768d3377f3fd58d6b8ea7c31f44c714ae7ab215650d62","names":[],"sources":[]}, {"digest":"87b1a33564b9a4d63b00988a524c12259243953aebb9c9a05127d87b27464df9","names":[],"sources":[]}, {"digest":"88841202942c7683b3b7e5ea6a796047ec326b6701ac23e58cc236d85613b9fa","names":[],"sources":[]}, - {"digest":"88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a","names":[],"sources":["packages/llm/llm/src/types.ts:500"]}, + {"digest":"88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a","names":[],"sources":["packages/llm/llm/src/types.ts:581"]}, {"digest":"8a046b52331959aa3394680d6acbe09b8a5447c6b61375f263445bfcef19b7f1","names":[],"sources":[]}, {"digest":"8a54d228b1b7d8453e4304d32723d489f28b4b33b221f335342146926ad94fc6","names":[],"sources":[]}, {"digest":"8a6e1ec9e8db346b0e02f027db73c07a94f067a26d40c1aef1abd09c47ce7ba0","names":[],"sources":[]}, @@ -440,7 +440,7 @@ {"digest":"93cbbc5a7fd0b1aa1ff1b9a6bb5ec52b073f48e5a5200365c45c0cd54059e1b9","names":[],"sources":["packages/interaction/user-approval/src/types.ts:55"]}, {"digest":"93d38436347f67c9022aacbc4472e283d722bcab8eb73fc376aaf7b6a6b9fb35","names":[],"sources":[]}, {"digest":"94c56aeb1564ad735eb773d88636b40761d063efa1610f1308004d32923f5378","names":[],"sources":[]}, - {"digest":"95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65","names":[],"sources":["packages/llm/llm/src/types.ts:498"]}, + {"digest":"95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65","names":[],"sources":["packages/llm/llm/src/types.ts:579"]}, {"digest":"95a3ffccbf3c8afcf9a2f3b355f724da8e07e98dc47ee741166dde7f9ea058bd","names":[],"sources":[]}, {"digest":"95c0e88fcf0bafb2087f912ad9e2369de6ae6530cc0c4c2772c96205b57f7f60","names":[],"sources":[]}, {"digest":"9645cf93769a6dfb227bd400bd6cb9fa7bab9140f4a851e4ae92514ade6e3114","names":[],"sources":[]}, @@ -452,13 +452,13 @@ {"digest":"998f22585a5d73ec005365e203f07fc3b3a029e82323fdda3fd7f13b0a9639d0","names":[],"sources":[]}, {"digest":"99e7e7d7fed55ae6a3a648b35192f16ab1248ddcb0179a0e275128ac1487d7c7","names":[],"sources":[]}, {"digest":"99f0e98184709ad10f27bfdeaafb4457d9d2b413f402331764798cdb7d3cbe4d","names":[],"sources":[]}, - {"digest":"9a2a9029f8d7ede05336980d8342737557f487b913bfd28853d0ab5214600ab5","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:64"]}, + {"digest":"9a2a9029f8d7ede05336980d8342737557f487b913bfd28853d0ab5214600ab5","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:65"]}, {"digest":"9a410ddf56792b2b7cd4a224a2e54dc4dee30a8e8e6b1c2b9a1d19992b217adc","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowAgentStartData"],"sources":["packages/workflow/tool-workflow/src/types.ts:20"]}, {"digest":"9a930283b91d493d6347146f2475bb107294b379415ca02162354f46a64164f7","names":["packages/core/session/src/types.ts#EpochHeader"],"sources":["packages/core/session/src/types.ts:246"]}, {"digest":"9ac52f0f84fec2eb9f71c2937e497d759db5ca0da4836d93a679d113684141f2","names":[],"sources":[]}, {"digest":"9acbe713f3f641921dd3333b240aa72e176d795327c24e8d9db9b68b16771b49","names":[],"sources":[]}, {"digest":"9b4fd974c124c83743efe030ba4e1250e087505f3f74588716a521fb8d453267","names":[],"sources":[]}, - {"digest":"9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:61"]}, + {"digest":"9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:62"]}, {"digest":"9d80129e13edfb6feb03ed327e6085c6ef60b97ad074244b2f5fd4667424a6a4","names":[],"sources":[]}, {"digest":"9e07693fd7cd9babe0688c22c986e4d519ae1c0e40eeea13b2dc583bed2abc86","names":[],"sources":[]}, {"digest":"9e2c06d8653585b33d72d5c1a80da79c8a24a88c284409bca15cc0f0ead5ebfb","names":[],"sources":[]}, @@ -474,7 +474,7 @@ {"digest":"a15a19ef63cf5d1b711db1d249821dab0cedcd3a9ad09137b47352c93841fd20","names":[],"sources":[]}, {"digest":"a16e567c8cd2c55cf1e911aed3c200c4e1f6febb1459ff2a9e7adf159afb68cb","names":[],"sources":[]}, {"digest":"a2066bd52f61218ba15b758def2641cc6a8bd3d4a594a488ee4c65be356d7e39","names":[],"sources":[]}, - {"digest":"a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1","names":[],"sources":["packages/llm/llm/src/types.ts:503"]}, + {"digest":"a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1","names":[],"sources":["packages/llm/llm/src/types.ts:584"]}, {"digest":"a2be0f0cb59f0d4a06557d45847d1938aced238baa77a6da416e590b8b958553","names":[],"sources":[]}, {"digest":"a3a259a1aa5401af786ce08c4a8419681d3000d73467991b5fc563389bc4ebd2","names":[],"sources":[]}, {"digest":"a3c6f1ea38e9a61d7a9706057ba65aabe02dfe6d9dd90d4736aa62325d874531","names":[],"sources":[]}, @@ -502,7 +502,7 @@ {"digest":"aae343bc3d663c83f2e8b5e1c7eea5d509dc7a5361bc8bd8b5ac3bb8d3b1ed56","names":[],"sources":[]}, {"digest":"ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7","names":[],"sources":["packages/core/session/src/types.ts:220","packages/llm/llm/src/types.ts:166"]}, {"digest":"aba175fb20ffc71112c55efe70458ff5d7dbfb83501892b4ba8d077f0ea5d7ba","names":[],"sources":[]}, - {"digest":"abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c","names":["packages/web/web-search-deepseek/src/provider.ts#DeepSeekSearchLlmRequest"],"sources":["packages/web/web-search-deepseek/src/provider.ts:55"]}, + {"digest":"abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c","names":["packages/web/web-search-deepseek/src/provider.ts#DeepSeekSearchLlmRequest"],"sources":["packages/web/web-search-deepseek/src/provider.ts:56"]}, {"digest":"ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585","names":[],"sources":["packages/core/session/src/types.ts:398"]}, {"digest":"ad22a5ca5bbaab2e1440779cd3648e85ddfc6f73b5207394eda699555cf31430","names":[],"sources":[]}, {"digest":"ad3b56aa2fc1ad4250e7399295d34a8eae592e1907e85852e2291b2e498a30bc","names":[],"sources":[]}, @@ -596,7 +596,7 @@ {"digest":"d0fbb0ca1bbba059830826f33f801da1aced35a2504376d61e020bdfec8d50c0","names":[],"sources":[]}, {"digest":"d28765f87d6b6ab408e0b2f3e7e297791b004b806d8e302c49903ebae815feb2","names":[],"sources":[]}, {"digest":"d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41","names":[],"sources":[]}, - {"digest":"d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d","names":[],"sources":["packages/llm/llm/src/types.ts:501"]}, + {"digest":"d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d","names":[],"sources":["packages/llm/llm/src/types.ts:582"]}, {"digest":"d4c799e3d51cae1040362ba4968efc484739e14416c9c1df20c2f108b4ef2eb5","names":[],"sources":[]}, {"digest":"d4e4d575abeb4b72d616dc65c17ac0eaa943cc135609395044c38d5afcb10e31","names":[],"sources":[]}, {"digest":"d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9","names":[],"sources":[]}, @@ -670,11 +670,11 @@ {"digest":"f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402","names":["packages/core/session/src/types.ts#TurnEndReason"],"sources":["packages/core/session/src/types.ts:238"]}, {"digest":"f1996af2602e6f62b5ab179ca5c4af00d8753938b74cc6ef102de09e99e74a7e","names":[],"sources":[]}, {"digest":"f19bee84bf3d20904553cdcd57465232bc1c2a194f54c4d195292ba0487223a6","names":["packages/attachment/attachment/src/types.ts#FileAttachmentRef"],"sources":["packages/attachment/attachment/src/types.ts:39"]}, - {"digest":"f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515","names":[],"sources":["packages/llm/llm/src/types.ts:502"]}, + {"digest":"f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515","names":[],"sources":["packages/llm/llm/src/types.ts:583"]}, {"digest":"f230c0b583e23b25ee0a61dbe4c05e95c1e2ae44b27939501eb9e03696f0c278","names":[],"sources":[]}, {"digest":"f29d63336e8266d80dd7baeab219436db86341304f6be1cd0edb36f5134c4a47","names":[],"sources":[]}, {"digest":"f2da0f27c1e6add59982c37b15e4a4912c5b33466859cce3b13d503600e24aef","names":["packages/llm/llm/src/types.ts#FileBlock"],"sources":["packages/llm/llm/src/types.ts:105"]}, - {"digest":"f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5","names":["packages/llm/llm/src/types.ts#SystemPromptUpdate"],"sources":["packages/llm/llm/src/types.ts:440"]}, + {"digest":"f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5","names":["packages/llm/llm/src/types.ts#SystemPromptUpdate"],"sources":["packages/llm/llm/src/types.ts:521"]}, {"digest":"f4a66f654996c093aae700ea4c434ff2ee3569fea9c0e5813ccf6afdccabd163","names":[],"sources":[]}, {"digest":"f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1","names":[],"sources":[]}, {"digest":"f56c5b59ca0161310c338d31dd16cf14287ccd602ff4181058df178c1c286d7f","names":["packages/context/session-reference/src/types.ts#SessionReferenceSource"],"sources":["packages/context/session-reference/src/types.ts:13"]}, diff --git a/docs/subsystems/README.i18n.yaml b/docs/subsystems/README.i18n.yaml index 6501690aa5..213de39754 100644 --- a/docs/subsystems/README.i18n.yaml +++ b/docs/subsystems/README.i18n.yaml @@ -3,5 +3,5 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/README.md /subsystems: - en: 1a570deda3572868 - zh: 4d256f68b7e39701 + en: 8e833255afdc9a87 + zh: 89c2af912ed35a49 diff --git a/docs/subsystems/README.md b/docs/subsystems/README.md index bea5c3f895..77dad38082 100644 --- a/docs/subsystems/README.md +++ b/docs/subsystems/README.md @@ -24,6 +24,7 @@ One page per subsystem of the DeepSeek Harness: what it is, the data structures | [persistence.md](persistence.md) | the durability seam: `SessionPersistence`, the JSONL provider, `session/flush`, crash recovery, `SessionHeader` | | [settings.md](settings.md) | the user-settings seam: `SettingsNamespace` registration, layered resolution (defaults → composition `base` → user document), owner scopes, hot commits | | [credentials.md](credentials.md) | the credential seam: `CredentialRef` references (never values) in configuration, per-operation resolution, UI-safe `CredentialInfo`, provider source layers | +| [account.md](account.md) | the DeepSeek account: browser sign-in state, the stored grant, Host-only request credentials for the account model route and the web providers, and the Platform session projection | | [session-query.md](session-query.md) | logical records, bounded exact-event reads, relationship traces, semantic filters/documents, and full-text result pages | | [feedback.md](feedback.md) | lifecycle-bound per-message feedback records, optimistic versions, sidecar persistence, and the Host Remote contract | | [session-title.md](session-title.md) | durable title snapshots, cited source-message seqs, and the asynchronous provider contract | diff --git a/docs/subsystems/README.zh.md b/docs/subsystems/README.zh.md index 4c714de6a0..db3ba392a0 100644 --- a/docs/subsystems/README.zh.md +++ b/docs/subsystems/README.zh.md @@ -24,6 +24,7 @@ | [persistence.md](persistence.zh.md) | 持久性 seam:`SessionPersistence`、JSONL 提供方、`session/flush`、崩溃恢复、`SessionHeader` | | [settings.md](settings.zh.md) | 用户设置 seam:`SettingsNamespace` 注册、分层解析(默认值 → 组合 `base` → 用户文档)、owner scope、热提交 | | [credentials.md](credentials.zh.md) | 凭据 seam:配置中的 `CredentialRef` 引用(绝不含值)、按操作解析、对 UI 安全的 `CredentialInfo`、提供方来源层 | +| [account.md](account.zh.md) | DeepSeek 账号:浏览器登录状态、已存授权、供账号模型路由与 Web 提供方使用的仅限 Host 的请求凭据,以及 Platform 会话投影 | | [session-query.md](session-query.zh.md) | 逻辑记录、有界精确事件读取、关系追踪、语义筛选器/文档与全文检索结果页 | | [feedback.md](feedback.zh.md) | 绑定生命周期的逐消息反馈记录、乐观版本、伴随记录持久化与 Host Remote 约定 | | [session-title.md](session-title.zh.md) | 持久标题快照、被引用的来源消息 seq 与异步提供方约定 | diff --git a/docs/subsystems/account.i18n.yaml b/docs/subsystems/account.i18n.yaml new file mode 100644 index 0000000000..90e4efdb1c --- /dev/null +++ b/docs/subsystems/account.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for account.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/subsystems/account.md +/deepseek-account: + en: 2302e2999588bac3 + zh: 5e0ac058b50036dc +/deepseek-account/request-credentials: + en: 76f2eb1df1948c8a + zh: 70f698243f8e3ae8 +/deepseek-account/embedded-platform-credentials: + en: 9a651d70acbe83a6 + zh: 4624b0299f5fdd8e +/deepseek-account/cordis-api/deepseek-account-events/deepseek-account-signed-out-emit: + en: b2c8c533124a121c + zh: c2a5c227b5a01146 diff --git a/docs/subsystems/account.md b/docs/subsystems/account.md new file mode 100644 index 0000000000..0706d14f80 --- /dev/null +++ b/docs/subsystems/account.md @@ -0,0 +1,234 @@ +# DeepSeek Account + +English | [中文](account.zh.md) + +The account service of [dsh-deepseek-account](../../packages/account/deepseek-account) signs the user in through the system browser, stores the resulting grant as a credential record of the [credential seam](credentials.md), and releases per-request account credentials to Host consumers. Consumers name the destination of one request and receive the headers that request carries; they never read the stored token, choose its header, or decide which origin may receive it. Clients observe account state through the `account` Remote namespace, which carries no credential. + +Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts) + +## Request credentials + +`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. The `deepseek-account` model route publishes this credential through `ctx.llm.routeCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `resolveToken(url)` returns the bare token under the same policy for consumers that compose their own request, and `rejectToken(token)` is the invalidation `reject()` performs. + +Model routes that bill the account register a running-task report with `registerRunningTaskReport(report)` inside `ctx.effect()`; `hasRunningAccountTasks()` answers true while any report does, so the sign-out confirmation can warn about work the sign-out interrupts. The route plugin owns cancellation of that work after `deepseek-account/signed-out`. + +## Embedded Platform credentials + +PlatformSession is a Host-only snapshot from getPlatformSession: origin names the configured Platform issuer and token contains its stored account credential. userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID. The snapshot reuses that ID without issuing a profile request of its own, so an unknown ID leaves userId null instead of delaying the caller; a profile read whose stable ID first becomes available or changes notifies only Host subscribers using `watch(signal, true)`, which lets identity consumers re-read the snapshot. Consumers key persistent browser storage by origin and userId and fall back to temporary storage for null. Signed-out accounts and credentials changed during the credential read return no snapshot; a mismatched issuer fails. Native consumers own document invalidation when credentials change. This snapshot is excluded from account Remote API, AccountView, and AccountDetails. + +AccountDetails.balance projects recharge wallets in value and promotional wallets in bonusWallets, with independent currency and decimal balance strings. Failed queries contain no wallet arrays. + +Notification queries return an AccountNotificationBatch with the server's nextPollAfterSeconds and its notifications in server order. Each AccountNotification carries an opaque id, createdAt, a nullable displayUntil, localized title and body, ordered actions, and optional JSON data, never credentials. getNotificationContent reads one notification by id, including consumed ones, and reportNotificationEvent reports displayed, cta_clicked, or dismissed for it. Notification operations use the initiating UI language through x-client-locale, without a language query parameter. + + + + + +## Cordis API + +Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md). + + + +### `ctx.deepseekAccount` — `DeepSeekAccount` + +Account login, credentials, and client-safe Remote operations. + +```ts cordis-catalog +/** + * Read stored-account presence and the latest login attempt. + * @returns a snapshot without credentials or PKCE secrets. + */ +@Remote async getState(): Promise + +/** + * Query Platform profile independently of wallet balances. + * A ready result whose stable profile ID first becomes available or changes notifies identity-enabled watch + * consumers, so they re-read getPlatformSession; repeated IDs stay silent. + * @param client - identity of the requesting UI for this call. + * @returns profile outcome, or null if signed out or the grant changed during the query. + */ +@Remote async getProfile(client: AccountClientMetadata): Promise + +/** + * Query Platform recharge and bonus wallet balances independently of profile data. + * @param client - identity of the requesting UI for this call. + * @returns balance outcome, or null if signed out or the grant changed during the query. + */ +@Remote getBalance(client: AccountClientMetadata): Promise + +/** + * Query unconsumed account notifications in server order without reading profile data. + * @param client - identity of the requesting UI for this call; its language selects the server-authored message. + * @returns notifications with their next query delay, or null if signed out or the grant changed during the query. + */ +@Remote async getNotifications(client: AccountClientMetadata): Promise + +/** + * Query localized content of a notification, including one already consumed. + * @param id - notification whose content is requested. + * @param client - identity of the requesting UI; its language selects the localized content. + * @returns content without changing consumption, or null if signed out or the grant changed. + */ +@Remote async getNotificationContent(id: AccountNotificationId, client: AccountClientMetadata): Promise + +/** + * Report a notification interaction; the backend decides consumption. + * @param id - notification the user interacted with. + * @param event - displayed frame, non-dismiss action click, or explicit dismissal. + * @param client - identity of the requesting UI for this call. + * @returns true once the server accepts the event; false if signed out or credentials changed during the call. + */ +@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise + +/** + * Remove an inference-rejected token only while it still matches the stored login. + * @param token - token captured by the rejected inference request. + * @returns after matching credentials are removed and the expiry notification is emitted. + */ +async rejectToken(token: string): Promise + +/** + * Read existing login identity without creating a device or returning credentials. + * @returns optional device/account identifiers and the provider's OS version string. + */ +async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> + +/** + * Read credentials for the configured embedded-page origin, bound to their account environment, and + * pair them with the account ID from the last successful profile read; no profile request is made. + * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. + */ +async getPlatformSession(): Promise + +/** + * Resolve a credential only for the inference origin allowed by the provider. + * @param url - actual request destination or API base URL. + * @returns stored token, or undefined for other origins or a signed-out account. + */ +async resolveToken(url: string): Promise + +/** + * Release the account credential for one request to `url` as the request + * carries it, together with its invalidation. Host-only. + * @param url - actual request destination or API base URL. + * @returns the request credential, or undefined for other origins or a signed-out account. + */ +async resolveRequestCredential(url: string): Promise + +/** + * Join an active attempt or start browser authorization. + * @param client - identity of the requesting UI; a new attempt captures it, and joining retains the original attempt's identity. + * @param callbackOrigin - browser-accessible loopback HTTP origin, including any SSH local port. + * @param loginSource - initiating UI, used to return from a failed exchange. + * @returns the initial snapshot without waiting for browser approval. + */ +@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise + +/** + * Cancel only the named attempt; committing attempts settle before returning. + * @param attemptId - attempt identity from this Host. + * @returns state after cancellation or an already-started commit. + */ +@Remote async cancelSignIn(attemptId: SignInAttemptId): Promise + +/** + * Remove the local grant while retaining API keys; the provider revokes it in the background. + * @param client - identity of the requesting UI, captured for the background revocation retries. + * @returns the signed-out state after local removal; remote failures never restore the grant. + */ +@Remote signOut(client: AccountClientMetadata): Promise + +/** + * Register a report of running work that signing out would interrupt. The + * plugin billing the account to a model route registers one from within + * `ctx.effect()`; without any report nothing is known to be running. + * @param report - answers whether such work is running now. + * @returns the disposer removing the report. + */ +registerRunningTaskReport(report: () => boolean): () => void + +/** + * Inspect running work before sign-out. + * @returns whether a registered report says a running task uses the account; false without reports. + */ +@Remote hasRunningAccountTasks(): boolean + +/** + * Subscribe to live credential expiry without replay. + * @param signal - subscription lifetime; provider disposal also ends it. + * @returns expiry notifications emitted during the subscription. + */ +@Remote({ mode: 'stream' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<'session-expired'> + +/** + * Subscribe to ordered updates including a complete initial snapshot. + * @param signal - subscription lifetime; ending it never cancels login. + * @param includeIdentityChanges - also notify when cached Platform identity changes; defaults to false. + * @returns complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce. + */ +watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable + +/** + * Stream account state without the Host-only identity subscription option. + * @param signal - subscription lifetime. + * @returns initial state, login progress, and credential-change updates. + */ +@Remote({ name: 'watch', mode: 'stream' }) watchState(signal: AbortSignal): AsyncIterable +``` + +Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts) + + + +### `deepseek-account/*` events + + + +#### `deepseek-account/model-sign-in-required` — emit + +An account model request requires the user to sign in. + +```ts cordis-catalog +/** An account model request requires the user to sign in. + * @mode emit + */ +'deepseek-account/model-sign-in-required'(): void +``` + +Source: [`packages/account/deepseek-account/src/types.ts`](../../packages/account/deepseek-account/src/types.ts) + + + +#### `deepseek-account/session-expired` — emit + +Server rejection removed the current account credential; this notification is not replayed. + +```ts cordis-catalog +/** Server rejection removed the current account credential; this notification is not replayed. + * @mode emit + */ +'deepseek-account/session-expired'(): void +``` + +Source: [`packages/account/deepseek-account/src/types.ts`](../../packages/account/deepseek-account/src/types.ts) + + + +#### `deepseek-account/signed-out` — emit + +Local grant removal has completed. + +```ts cordis-catalog +/** Local grant removal has completed. + * @mode emit + */ +'deepseek-account/signed-out'(): void +``` + +Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts) + + +The account Service Definition exposes getState, getProfile, getBalance, getNotifications, getNotificationContent, reportNotificationEvent, startSignIn, cancelSignIn, signOut, watch, and Host-only resolveToken, resolveRequestCredential, registerRunningTaskReport, and getPlatformSession. The platform provider implements it with an AuthorizationFlow and a private GrantRecord. AccountView distinguishes stored presence from server validation; attempt IDs bind cancellation to one local flow. AccountUpdate carries a complete AccountView in state and a type of snapshot for initial or progress updates, or credentials-changed for credential writes and removal. Pending credential changes take priority over progress updates. See [the account package](../../packages/account/deepseek-account/README.md). + +`AccountClientMetadata` carries `version` from the caller’s `DSH_CLIENT_VERSION`, its active UI `locale`, and `timezoneOffsetSeconds` sampled when the operation begins. The offset is local time minus UTC in seconds: UTC+8 is `28800`. It contains no credentials. Login attempts retain their initiating metadata through exchange and cancellation; sign-out retains its metadata for revocation retries. diff --git a/docs/subsystems/account.zh.md b/docs/subsystems/account.zh.md new file mode 100644 index 0000000000..45d5d03973 --- /dev/null +++ b/docs/subsystems/account.zh.md @@ -0,0 +1,234 @@ +# DeepSeek 账号 + +[English](account.md) | 中文 + +[dsh-deepseek-account](../../packages/account/deepseek-account) 的账号服务通过系统浏览器完成登录,把得到的授权作为[凭据 seam](credentials.zh.md) 的一条凭据记录保存,并向 Host 消费方释放按请求的账号凭据。消费方只说明一次请求的目标地址并取得该请求所携带的请求头;它们既不读取已存 token,也不选择其请求头,也不决定哪个来源可以接收它。客户端通过不携带凭据的 `account` Remote 命名空间观察账号状态。 + +来源:[`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts) + +## 请求凭据 + +`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`resolveToken(url)` 在同一策略下为自行组装请求的消费方返回裸 token,`rejectToken(token)` 则是 `reject()` 执行的失效操作。 + +按账号计费的模型路由在 `ctx.effect()` 内用 `registerRunningTaskReport(report)` 注册运行中任务报告;只要有报告回答 true,`hasRunningAccountTasks()` 就回答 true,使退登确认能够提醒退登将打断的工作。`deepseek-account/signed-out` 之后取消这些工作由路由插件负责。 + +## 内嵌 Platform 凭证 + +PlatformSession 是 getPlatformSession 返回的仅限 Host 快照:origin 指定所配置的 Platform 签发来源,token 包含其已存账号凭证。userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照复用该 ID,不自行发起资料请求,因此 ID 未知时只会让 userId 为 null,而不会延迟调用方;资料读取首次取得稳定 ID 或该 ID 变化时仅通知使用 `watch(signal, true)` 的 Host 订阅者,供标识使用方重新读取快照。使用方以 origin 和 userId 作为持久化浏览器存储的键,为 null 时退回临时存储。账号已退登或读取凭证期间凭证变化时不返回快照;签发来源不匹配时失败。原生使用方负责在凭证变化时使文档失效。账号 Remote API、AccountView 和 AccountDetails 均不包含此快照。 + +AccountDetails.balance 将充值钱包投影为 value、赠送钱包投影为 bonusWallets,分别保留币种和十进制余额字符串。查询失败不包含钱包数组。 + +通知查询返回 AccountNotificationBatch,包含服务端的 nextPollAfterSeconds 和按服务端顺序排列的通知。每条 AccountNotification 携带不透明 id、createdAt、可为 null 的 displayUntil、本地化的 title 与 body、有序 actions 以及可选的 JSON data,绝不包含凭证。getNotificationContent 按 id 读取一条通知,包括已消费的通知;reportNotificationEvent 为其上报 displayed、cta_clicked 或 dismissed。通知操作通过 x-client-locale 传递发起界面的语言,不使用语言查询参数。 + + + + + +## Cordis API + +Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.zh.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md). + + + +### `ctx.deepseekAccount` — `DeepSeekAccount` + +Account login, credentials, and client-safe Remote operations. + +```ts cordis-catalog +/** + * Read stored-account presence and the latest login attempt. + * @returns a snapshot without credentials or PKCE secrets. + */ +@Remote async getState(): Promise + +/** + * Query Platform profile independently of wallet balances. + * A ready result whose stable profile ID first becomes available or changes notifies identity-enabled watch + * consumers, so they re-read getPlatformSession; repeated IDs stay silent. + * @param client - identity of the requesting UI for this call. + * @returns profile outcome, or null if signed out or the grant changed during the query. + */ +@Remote async getProfile(client: AccountClientMetadata): Promise + +/** + * Query Platform recharge and bonus wallet balances independently of profile data. + * @param client - identity of the requesting UI for this call. + * @returns balance outcome, or null if signed out or the grant changed during the query. + */ +@Remote getBalance(client: AccountClientMetadata): Promise + +/** + * Query unconsumed account notifications in server order without reading profile data. + * @param client - identity of the requesting UI for this call; its language selects the server-authored message. + * @returns notifications with their next query delay, or null if signed out or the grant changed during the query. + */ +@Remote async getNotifications(client: AccountClientMetadata): Promise + +/** + * Query localized content of a notification, including one already consumed. + * @param id - notification whose content is requested. + * @param client - identity of the requesting UI; its language selects the localized content. + * @returns content without changing consumption, or null if signed out or the grant changed. + */ +@Remote async getNotificationContent(id: AccountNotificationId, client: AccountClientMetadata): Promise + +/** + * Report a notification interaction; the backend decides consumption. + * @param id - notification the user interacted with. + * @param event - displayed frame, non-dismiss action click, or explicit dismissal. + * @param client - identity of the requesting UI for this call. + * @returns true once the server accepts the event; false if signed out or credentials changed during the call. + */ +@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise + +/** + * Remove an inference-rejected token only while it still matches the stored login. + * @param token - token captured by the rejected inference request. + * @returns after matching credentials are removed and the expiry notification is emitted. + */ +async rejectToken(token: string): Promise + +/** + * Read existing login identity without creating a device or returning credentials. + * @returns optional device/account identifiers and the provider's OS version string. + */ +async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> + +/** + * Read credentials for the configured embedded-page origin, bound to their account environment, and + * pair them with the account ID from the last successful profile read; no profile request is made. + * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. + */ +async getPlatformSession(): Promise + +/** + * Resolve a credential only for the inference origin allowed by the provider. + * @param url - actual request destination or API base URL. + * @returns stored token, or undefined for other origins or a signed-out account. + */ +async resolveToken(url: string): Promise + +/** + * Release the account credential for one request to `url` as the request + * carries it, together with its invalidation. Host-only. + * @param url - actual request destination or API base URL. + * @returns the request credential, or undefined for other origins or a signed-out account. + */ +async resolveRequestCredential(url: string): Promise + +/** + * Join an active attempt or start browser authorization. + * @param client - identity of the requesting UI; a new attempt captures it, and joining retains the original attempt's identity. + * @param callbackOrigin - browser-accessible loopback HTTP origin, including any SSH local port. + * @param loginSource - initiating UI, used to return from a failed exchange. + * @returns the initial snapshot without waiting for browser approval. + */ +@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise + +/** + * Cancel only the named attempt; committing attempts settle before returning. + * @param attemptId - attempt identity from this Host. + * @returns state after cancellation or an already-started commit. + */ +@Remote async cancelSignIn(attemptId: SignInAttemptId): Promise + +/** + * Remove the local grant while retaining API keys; the provider revokes it in the background. + * @param client - identity of the requesting UI, captured for the background revocation retries. + * @returns the signed-out state after local removal; remote failures never restore the grant. + */ +@Remote signOut(client: AccountClientMetadata): Promise + +/** + * Register a report of running work that signing out would interrupt. The + * plugin billing the account to a model route registers one from within + * `ctx.effect()`; without any report nothing is known to be running. + * @param report - answers whether such work is running now. + * @returns the disposer removing the report. + */ +registerRunningTaskReport(report: () => boolean): () => void + +/** + * Inspect running work before sign-out. + * @returns whether a registered report says a running task uses the account; false without reports. + */ +@Remote hasRunningAccountTasks(): boolean + +/** + * Subscribe to live credential expiry without replay. + * @param signal - subscription lifetime; provider disposal also ends it. + * @returns expiry notifications emitted during the subscription. + */ +@Remote({ mode: 'stream' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<'session-expired'> + +/** + * Subscribe to ordered updates including a complete initial snapshot. + * @param signal - subscription lifetime; ending it never cancels login. + * @param includeIdentityChanges - also notify when cached Platform identity changes; defaults to false. + * @returns complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce. + */ +watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable + +/** + * Stream account state without the Host-only identity subscription option. + * @param signal - subscription lifetime. + * @returns initial state, login progress, and credential-change updates. + */ +@Remote({ name: 'watch', mode: 'stream' }) watchState(signal: AbortSignal): AsyncIterable +``` + +Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts) + + + +### `deepseek-account/*` events + + + +#### `deepseek-account/model-sign-in-required` — emit + +An account model request requires the user to sign in. + +```ts cordis-catalog +/** An account model request requires the user to sign in. + * @mode emit + */ +'deepseek-account/model-sign-in-required'(): void +``` + +Source: [`packages/account/deepseek-account/src/types.ts`](../../packages/account/deepseek-account/src/types.ts) + + + +#### `deepseek-account/session-expired` — emit + +Server rejection removed the current account credential; this notification is not replayed. + +```ts cordis-catalog +/** Server rejection removed the current account credential; this notification is not replayed. + * @mode emit + */ +'deepseek-account/session-expired'(): void +``` + +Source: [`packages/account/deepseek-account/src/types.ts`](../../packages/account/deepseek-account/src/types.ts) + + + +#### `deepseek-account/signed-out` — emit + +Local grant removal has completed. + +```ts cordis-catalog +/** Local grant removal has completed. + * @mode emit + */ +'deepseek-account/signed-out'(): void +``` + +Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts) + + +账号服务定义提供 getState、getProfile、getBalance、getNotifications、getNotificationContent、reportNotificationEvent、startSignIn、cancelSignIn、signOut、watch 及仅限 Host 的 resolveToken、resolveRequestCredential、registerRunningTaskReport 和 getPlatformSession。平台提供者使用 AuthorizationFlow 和私有 GrantRecord 实现这些操作。AccountView 区分本地存在与服务器验证;尝试 ID 将取消绑定到单次本地流程。AccountUpdate 的 state 携带完整 AccountView,type 为 snapshot 时表示首次或进度更新,为 credentials-changed 时表示凭据写入或删除。待发送的凭据变化优先于进度更新。参见[账号包](../../packages/account/deepseek-account/README.zh.md)。 + +`AccountClientMetadata` 携带调用方 `DSH_CLIENT_VERSION` 提供的 `version`、当前界面 `locale`,以及操作发起时采样的 `timezoneOffsetSeconds`。偏移为本地时间减 UTC 的秒数:UTC+8 对应 `28800`。其中不含凭证。登录申请在兑换及取消期间保留发起时的元数据;退出操作为撤销重试保留其元数据。 diff --git a/docs/subsystems/credentials.i18n.yaml b/docs/subsystems/credentials.i18n.yaml index 174bd14fc4..a2d00f31df 100644 --- a/docs/subsystems/credentials.i18n.yaml +++ b/docs/subsystems/credentials.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/credentials.md /user-credentials: - en: 4589c745baf092c7 - zh: 3a782e6a06825201 + en: cdf4cba4b28c4d9b + zh: ca46998bc56d30e6 /user-credentials/identity: en: 0083032b9d19467d zh: 15d7a7520bac094e @@ -17,9 +17,3 @@ /user-credentials/change-commits: en: 464315a953330eb2 zh: d9815591f3abc2cb -/user-credentials/embedded-platform-credentials: - en: 6f80d44cdec8e05a - zh: 658e5e4958f9baa6 -/user-credentials/cordis-api/deepseek-account-events/deepseek-account-signed-out-emit: - en: 664f0f89d89ac686 - zh: 178263324ad76307 diff --git a/docs/subsystems/credentials.md b/docs/subsystems/credentials.md index 444b2b8a52..31d2fbccfd 100644 --- a/docs/subsystems/credentials.md +++ b/docs/subsystems/credentials.md @@ -6,6 +6,8 @@ The credential seam of [dsh-credentials](../../packages/credentials/credentials) Source: [`packages/credentials/credentials/src/index.ts`](../../packages/credentials/credentials/src/index.ts) +The DeepSeek account grant is one such record; its sign-in, request credentials, and Platform session are documented in [account.md](account.md). + ## Identity A reference names one credential as a POSIX-style environment-variable name. The brand prevents callers from mixing credential references with other strings passed between packages or processes; construction validates the shell-identifier syntax. @@ -55,14 +57,6 @@ interface CredentialInfo { `credentials/reference-updated (ref)` fires after a committed change to a provider-managed source — a `set`, an `unset`, or an external edit observed in storage. Ambient process-environment changes are not observable and never emit. Consumers do not need the event (they re-resolve per operation); it exists for configuration surfaces refreshing a "configured" badge. -## Embedded Platform credentials - -PlatformSession is a Host-only snapshot from getPlatformSession: origin names the configured Platform issuer and token contains its stored account credential. userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID. The snapshot reuses that ID without issuing a profile request of its own, so an unknown ID leaves userId null instead of delaying the caller; a profile read whose stable ID first becomes available or changes notifies only Host subscribers using `watch(signal, true)`, which lets identity consumers re-read the snapshot. Consumers key persistent browser storage by origin and userId and fall back to temporary storage for null. Signed-out accounts and credentials changed during the credential read return no snapshot; a mismatched issuer fails. Native consumers own document invalidation when credentials change. This snapshot is excluded from account Remote API, AccountView, and AccountDetails. - -AccountDetails.balance projects recharge wallets in value and promotional wallets in bonusWallets, with independent currency and decimal balance strings. Failed queries contain no wallet arrays. - -Bonus notification queries return an AccountBonusBatch with the current Platform account id and eligible orders in server order. AccountBonusNotification retains the server message and expiry without projecting credentials. Acknowledgment carries the expected account id and order id; the Host refuses it after an account change. Both notification operations use the initiating UI language through x-client-locale, without a language query parameter. - @@ -262,140 +256,6 @@ Host service backing the generated `ctx.remote.credentials` namespace. It carrie Source: [`packages/api/settings-controller/src/credentials.ts`](../../packages/api/settings-controller/src/credentials.ts) - - -### `ctx.deepseekAccount` — `DeepSeekAccount` - -Account login, credentials, and client-safe Remote operations. - -```ts cordis-catalog -/** - * Read stored-account presence and the latest login attempt. - * @returns a snapshot without credentials or PKCE secrets. - */ -@Remote async getState(): Promise - -/** - * Query Platform profile independently of wallet balances. - * A ready result whose stable profile ID first becomes available or changes notifies identity-enabled watch - * consumers, so they re-read getPlatformSession; repeated IDs stay silent. - * @param client - identity of the requesting UI for this call. - * @returns profile outcome, or null if signed out or the grant changed during the query. - */ -@Remote async getProfile(client: AccountClientMetadata): Promise - -/** - * Query Platform recharge and bonus wallet balances independently of profile data. - * @param client - identity of the requesting UI for this call. - * @returns balance outcome, or null if signed out or the grant changed during the query. - */ -@Remote getBalance(client: AccountClientMetadata): Promise - -/** - * Query unconsumed account notifications in server order without reading profile data. - * @param client - identity of the requesting UI for this call; its language selects the server-authored message. - * @returns notifications with their next query delay, or null if signed out or the grant changed during the query. - */ -@Remote async getNotifications(client: AccountClientMetadata): Promise - -/** - * Query localized content of a notification, including one already consumed. - * @param id - notification whose content is requested. - * @param client - identity of the requesting UI; its language selects the localized content. - * @returns content without changing consumption, or null if signed out or the grant changed. - */ -@Remote async getNotificationContent(id: AccountNotificationId, client: AccountClientMetadata): Promise - -/** - * Report a notification interaction; the backend decides consumption. - * @param id - notification the user interacted with. - * @param event - displayed frame, non-dismiss action click, or explicit dismissal. - * @param client - identity of the requesting UI for this call. - * @returns true once the server accepts the event; false if signed out or credentials changed during the call. - */ -@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise - -/** - * Remove an inference-rejected token only while it still matches the stored login. - * @param token - token captured by the rejected inference request. - * @returns after matching credentials are removed and the expiry notification is emitted. - */ -async rejectToken(token: string): Promise - -/** - * Read existing login identity without creating a device or returning credentials. - * @returns optional device/account identifiers and the provider's OS version string. - */ -async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> - -/** - * Read credentials for the configured embedded-page origin, bound to their account environment, and - * pair them with the account ID from the last successful profile read; no profile request is made. - * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. - */ -async getPlatformSession(): Promise - -/** - * Resolve a credential only for the inference origin allowed by the provider. - * @param url - actual request destination or API base URL. - * @returns stored token, or undefined for other origins or a signed-out account. - */ -async resolveToken(url: string): Promise - -/** - * Join an active attempt or start browser authorization. - * @param client - identity of the requesting UI; a new attempt captures it, and joining retains the original attempt's identity. - * @param callbackOrigin - browser-accessible loopback HTTP origin, including any SSH local port. - * @param loginSource - initiating UI, used to return from a failed exchange. - * @returns the initial snapshot without waiting for browser approval. - */ -@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise - -/** - * Cancel only the named attempt; committing attempts settle before returning. - * @param attemptId - attempt identity from this Host. - * @returns state after cancellation or an already-started commit. - */ -@Remote async cancelSignIn(attemptId: SignInAttemptId): Promise - -/** - * Remove the local grant while retaining API keys; the provider revokes it in the background. - * @param client - identity of the requesting UI, captured for the background revocation retries. - * @returns the signed-out state after local removal; remote failures never restore the grant. - */ -@Remote signOut(client: AccountClientMetadata): Promise - -/** - * Inspect running work before sign-out. - * @returns whether a running task's latest request uses the account route; false when the optional agents service is absent. - */ -@Remote hasRunningAccountTasks(): boolean - -/** - * Subscribe to live credential expiry without replay. - * @param signal - subscription lifetime; provider disposal also ends it. - * @returns expiry notifications emitted during the subscription. - */ -@Remote({ mode: 'stream' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<'session-expired'> - -/** - * Subscribe to ordered updates including a complete initial snapshot. - * @param signal - subscription lifetime; ending it never cancels login. - * @param includeIdentityChanges - also notify when cached Platform identity changes; defaults to false. - * @returns complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce. - */ -watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable - -/** - * Stream account state without the Host-only identity subscription option. - * @param signal - subscription lifetime. - * @returns initial state, login progress, and credential-change updates. - */ -@Remote({ name: 'watch', mode: 'stream' }) watchState(signal: AbortSignal): AsyncIterable -``` - -Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts) - ### `authorization/*` events @@ -466,57 +326,4 @@ Committed change to a provider-managed credential source: a `set`, an `unset`, o ``` Source: [`packages/credentials/credentials/src/types.ts`](../../packages/credentials/credentials/src/types.ts) - - - -### `deepseek-account/*` events - - - -#### `deepseek-account/model-sign-in-required` — emit - -An account model request requires the user to sign in. - -```ts cordis-catalog -/** An account model request requires the user to sign in. - * @mode emit - */ -'deepseek-account/model-sign-in-required'(): void -``` - -Source: [`packages/credentials/deepseek-account/src/types.ts`](../../packages/credentials/deepseek-account/src/types.ts) - - - -#### `deepseek-account/session-expired` — emit - -Server rejection removed the current account credential; this notification is not replayed. - -```ts cordis-catalog -/** Server rejection removed the current account credential; this notification is not replayed. - * @mode emit - */ -'deepseek-account/session-expired'(): void -``` - -Source: [`packages/credentials/deepseek-account/src/types.ts`](../../packages/credentials/deepseek-account/src/types.ts) - - - -#### `deepseek-account/signed-out` — emit - -Local grant removal has completed. - -```ts cordis-catalog -/** Local grant removal has completed. - * @mode emit - */ -'deepseek-account/signed-out'(): void -``` - -Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts) - -The account Service Definition exposes getState, getProfile, getBalance, getNotifications, getNotificationContent, reportNotificationEvent, startSignIn, cancelSignIn, signOut, watch, and Host-only resolveToken and getPlatformSession. The platform provider implements it with an AuthorizationFlow and a private GrantRecord. AccountView distinguishes stored presence from server validation; attempt IDs bind cancellation to one local flow. AccountUpdate carries a complete AccountView in state and a type of snapshot for initial or progress updates, or credentials-changed for credential writes and removal. Pending credential changes take priority over progress updates. See [the account package](../../packages/credentials/deepseek-account/README.md). - -`AccountClientMetadata` carries `version` from the caller’s `DSH_CLIENT_VERSION`, its active UI `locale`, and `timezoneOffsetSeconds` sampled when the operation begins. The offset is local time minus UTC in seconds: UTC+8 is `28800`. It contains no credentials. Login attempts retain their initiating metadata through exchange and cancellation; sign-out retains its metadata for revocation retries. diff --git a/docs/subsystems/credentials.zh.md b/docs/subsystems/credentials.zh.md index ce9fbdadd5..1aeb209dfb 100644 --- a/docs/subsystems/credentials.zh.md +++ b/docs/subsystems/credentials.zh.md @@ -6,6 +6,8 @@ 来源:[`packages/credentials/credentials/src/index.ts`](../../packages/credentials/credentials/src/index.ts) +DeepSeek 账号授权是其中一条记录;其登录、请求凭据和 Platform 会话见 [account.zh.md](account.zh.md)。 + ## 标识 引用以 POSIX 风格环境变量名命名一条凭据。brand 防止调用方将凭据引用与在包或进程之间传递的其他字符串混用;构造时校验 shell 标识符语法。 @@ -55,14 +57,6 @@ interface CredentialInfo { `credentials/reference-updated (ref)` 在提供方管理的来源发生已提交变更后发出——`set`、`unset` 或在存储中观察到的外部编辑。进程环境自身的变化不可观测,永不发出事件。消费方不需要该事件(它们按操作重新解析);它服务于配置界面刷新「已配置」徽标。 -## 内嵌 Platform 凭证 - -PlatformSession 是 getPlatformSession 返回的仅限 Host 快照:origin 指定所配置的 Platform 签发来源,token 包含其已存账号凭证。userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照复用该 ID,不自行发起资料请求,因此 ID 未知时只会让 userId 为 null,而不会延迟调用方;资料读取首次取得稳定 ID 或该 ID 变化时仅通知使用 `watch(signal, true)` 的 Host 订阅者,供标识使用方重新读取快照。使用方以 origin 和 userId 作为持久化浏览器存储的键,为 null 时退回临时存储。账号已退登或读取凭证期间凭证变化时不返回快照;签发来源不匹配时失败。原生使用方负责在凭证变化时使文档失效。账号 Remote API、AccountView 和 AccountDetails 均不包含此快照。 - -AccountDetails.balance 将充值钱包投影为 value、赠送钱包投影为 bonusWallets,分别保留币种和十进制余额字符串。查询失败不包含钱包数组。 - -赠金通知查询返回 AccountBonusBatch,包含当前 Platform 账号 id 和按服务端顺序排列的可通知订单。AccountBonusNotification 保留服务端消息与到期时间,不投影凭证。确认请求携带预期账号 id 和订单 id;账号变化后 Host 拒绝该请求。两项通知操作都通过 x-client-locale 传递发起界面的语言,不使用语言查询参数。 - @@ -262,140 +256,6 @@ Host service backing the generated `ctx.remote.credentials` namespace. It carrie Source: [`packages/api/settings-controller/src/credentials.ts`](../../packages/api/settings-controller/src/credentials.ts) - - -### `ctx.deepseekAccount` — `DeepSeekAccount` - -Account login, credentials, and client-safe Remote operations. - -```ts cordis-catalog -/** - * Read stored-account presence and the latest login attempt. - * @returns a snapshot without credentials or PKCE secrets. - */ -@Remote async getState(): Promise - -/** - * Query Platform profile independently of wallet balances. - * A ready result whose stable profile ID first becomes available or changes notifies identity-enabled watch - * consumers, so they re-read getPlatformSession; repeated IDs stay silent. - * @param client - identity of the requesting UI for this call. - * @returns profile outcome, or null if signed out or the grant changed during the query. - */ -@Remote async getProfile(client: AccountClientMetadata): Promise - -/** - * Query Platform recharge and bonus wallet balances independently of profile data. - * @param client - identity of the requesting UI for this call. - * @returns balance outcome, or null if signed out or the grant changed during the query. - */ -@Remote getBalance(client: AccountClientMetadata): Promise - -/** - * Query unconsumed account notifications in server order without reading profile data. - * @param client - identity of the requesting UI for this call; its language selects the server-authored message. - * @returns notifications with their next query delay, or null if signed out or the grant changed during the query. - */ -@Remote async getNotifications(client: AccountClientMetadata): Promise - -/** - * Query localized content of a notification, including one already consumed. - * @param id - notification whose content is requested. - * @param client - identity of the requesting UI; its language selects the localized content. - * @returns content without changing consumption, or null if signed out or the grant changed. - */ -@Remote async getNotificationContent(id: AccountNotificationId, client: AccountClientMetadata): Promise - -/** - * Report a notification interaction; the backend decides consumption. - * @param id - notification the user interacted with. - * @param event - displayed frame, non-dismiss action click, or explicit dismissal. - * @param client - identity of the requesting UI for this call. - * @returns true once the server accepts the event; false if signed out or credentials changed during the call. - */ -@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise - -/** - * Remove an inference-rejected token only while it still matches the stored login. - * @param token - token captured by the rejected inference request. - * @returns after matching credentials are removed and the expiry notification is emitted. - */ -async rejectToken(token: string): Promise - -/** - * Read existing login identity without creating a device or returning credentials. - * @returns optional device/account identifiers and the provider's OS version string. - */ -async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> - -/** - * Read credentials for the configured embedded-page origin, bound to their account environment, and - * pair them with the account ID from the last successful profile read; no profile request is made. - * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. - */ -async getPlatformSession(): Promise - -/** - * Resolve a credential only for the inference origin allowed by the provider. - * @param url - actual request destination or API base URL. - * @returns stored token, or undefined for other origins or a signed-out account. - */ -async resolveToken(url: string): Promise - -/** - * Join an active attempt or start browser authorization. - * @param client - identity of the requesting UI; a new attempt captures it, and joining retains the original attempt's identity. - * @param callbackOrigin - browser-accessible loopback HTTP origin, including any SSH local port. - * @param loginSource - initiating UI, used to return from a failed exchange. - * @returns the initial snapshot without waiting for browser approval. - */ -@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise - -/** - * Cancel only the named attempt; committing attempts settle before returning. - * @param attemptId - attempt identity from this Host. - * @returns state after cancellation or an already-started commit. - */ -@Remote async cancelSignIn(attemptId: SignInAttemptId): Promise - -/** - * Remove the local grant while retaining API keys; the provider revokes it in the background. - * @param client - identity of the requesting UI, captured for the background revocation retries. - * @returns the signed-out state after local removal; remote failures never restore the grant. - */ -@Remote signOut(client: AccountClientMetadata): Promise - -/** - * Inspect running work before sign-out. - * @returns whether a running task's latest request uses the account route; false when the optional agents service is absent. - */ -@Remote hasRunningAccountTasks(): boolean - -/** - * Subscribe to live credential expiry without replay. - * @param signal - subscription lifetime; provider disposal also ends it. - * @returns expiry notifications emitted during the subscription. - */ -@Remote({ mode: 'stream' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<'session-expired'> - -/** - * Subscribe to ordered updates including a complete initial snapshot. - * @param signal - subscription lifetime; ending it never cancels login. - * @param includeIdentityChanges - also notify when cached Platform identity changes; defaults to false. - * @returns complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce. - */ -watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable - -/** - * Stream account state without the Host-only identity subscription option. - * @param signal - subscription lifetime. - * @returns initial state, login progress, and credential-change updates. - */ -@Remote({ name: 'watch', mode: 'stream' }) watchState(signal: AbortSignal): AsyncIterable -``` - -Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts) - ### `authorization/*` events @@ -466,57 +326,4 @@ Committed change to a provider-managed credential source: a `set`, an `unset`, o ``` Source: [`packages/credentials/credentials/src/types.ts`](../../packages/credentials/credentials/src/types.ts) - - - -### `deepseek-account/*` events - - - -#### `deepseek-account/model-sign-in-required` — emit - -An account model request requires the user to sign in. - -```ts cordis-catalog -/** An account model request requires the user to sign in. - * @mode emit - */ -'deepseek-account/model-sign-in-required'(): void -``` - -Source: [`packages/credentials/deepseek-account/src/types.ts`](../../packages/credentials/deepseek-account/src/types.ts) - - - -#### `deepseek-account/session-expired` — emit - -Server rejection removed the current account credential; this notification is not replayed. - -```ts cordis-catalog -/** Server rejection removed the current account credential; this notification is not replayed. - * @mode emit - */ -'deepseek-account/session-expired'(): void -``` - -Source: [`packages/credentials/deepseek-account/src/types.ts`](../../packages/credentials/deepseek-account/src/types.ts) - - - -#### `deepseek-account/signed-out` — emit - -Local grant removal has completed. - -```ts cordis-catalog -/** Local grant removal has completed. - * @mode emit - */ -'deepseek-account/signed-out'(): void -``` - -Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts) - -账号服务定义提供 getState、getProfile、getBalance、getNotifications、getNotificationContent、reportNotificationEvent、startSignIn、cancelSignIn、signOut、watch 及仅限 Host 的 resolveToken 和 getPlatformSession。平台提供者使用 AuthorizationFlow 和私有 GrantRecord 实现这些操作。AccountView 区分本地存在与服务器验证;尝试 ID 将取消绑定到单次本地流程。AccountUpdate 的 state 携带完整 AccountView,type 为 snapshot 时表示首次或进度更新,为 credentials-changed 时表示凭据写入或删除。待发送的凭据变化优先于进度更新。参见[账号包](../../packages/credentials/deepseek-account/README.zh.md)。 - -`AccountClientMetadata` 携带调用方 `DSH_CLIENT_VERSION` 提供的 `version`、当前界面 `locale`,以及操作发起时采样的 `timezoneOffsetSeconds`。偏移为本地时间减 UTC 的秒数:UTC+8 对应 `28800`。其中不含凭证。登录申请在兑换及取消期间保留发起时的元数据;退出操作为撤销重试保留其元数据。 diff --git a/docs/subsystems/llm-streaming.i18n.yaml b/docs/subsystems/llm-streaming.i18n.yaml index 59d8d46494..6f5c92fbc5 100644 --- a/docs/subsystems/llm-streaming.i18n.yaml +++ b/docs/subsystems/llm-streaming.i18n.yaml @@ -36,8 +36,8 @@ en: 58dec2259b0b1c6f zh: fc99fe965acaabf3 /llm-streaming/the-model-request: - en: 834d3d8d6b5871ab - zh: 393889ec6075f622 + en: 1962ba10f5515278 + zh: 9fa56ed8f54136aa /llm-streaming/the-model-request/the-request-envelope-llmcallconfig-and-the-logged-header: en: b0eb4620c6953646 zh: fabf51c7245a4855 @@ -48,5 +48,5 @@ en: 8c140f9c5a799f01 zh: f66b895594247e92 /llm-streaming/service-and-provider-contracts: - en: 8dc79d4cc82824c2 - zh: 3ebabd3a117ad717 + en: 4d210152ca139cb0 + zh: d131e11d95666342 diff --git a/docs/subsystems/llm-streaming.md b/docs/subsystems/llm-streaming.md index 565da04ff2..e94dbef6dc 100644 --- a/docs/subsystems/llm-streaming.md +++ b/docs/subsystems/llm-streaming.md @@ -525,6 +525,79 @@ interface LlmNativeAuth { } ``` +A route's adapter can also publish the credential the route currently sends, so consumers that call the same deployment outside the model request path, such as the DeepSeek web providers, reuse it through `ctx.llm.routeCredential(provider)` instead of reading provider configuration or choosing header names. A grant is Host-only and is held for one operation; `kind` is merge-extensible through `LlmCredentialKindMap`, whose declared members are `api-key` and `account`. + +```ts type-equiv +/** + * One credential released for one destination. Host-only: it carries the + * secret, so it never crosses a Remote boundary and never enters a log. + */ +interface RouteCredentialGrant { + /** + * Request headers carrying the credential as the route's own protocol + * expects it, such as `x-api-key` for an API key. Consumers speaking that + * protocol send them unchanged. + */ + readonly headers: Readonly> + /** + * The bare credential value, for destinations whose protocol renders it + * differently from {@link headers}, such as `Authorization: Bearer`. + */ + readonly value: string + /** + * Invalidate this exact credential after the destination rejected it with + * HTTP 401 so no later request resends it. Absent for kinds without + * invalidation. The owner contains storage failures: the caller reports the + * destination's rejection, never a failure of this call. + * @returns settlement after the invalidation attempt. + */ + reject?(): Promise +} +``` + +```ts type-equiv +/** + * The credential one registered provider route currently sends, answered by + * the route's owning adapter so that consumers read no provider configuration + * and choose no header names. `ctx.llm.routeCredential()` resolves a new value + * per call from one configuration generation; a caller keeps it for one + * operation only. + */ +interface RouteCredential { + /** Kind of credential the route sends. */ + readonly kind: LlmCredentialKind + /** + * The route's current request base URL as its configuration resolves it, + * environment fallbacks included: the destination this credential is meant + * for. Consumers derive sibling endpoints of the same deployment from it. + */ + readonly baseURL: string + /** + * Credential reference the route resolves, for diagnostics that tell the user + * where to configure the credential; absent for kinds without a stored + * reference, such as sign-in grants. + */ + readonly reference?: string + /** + * Whether {@link resolve} would release a credential for `endpoint`, checked + * without reading the credential's value, validating it, or contacting the + * destination. Store failures reject. + * @param endpoint - absolute URL the credential would be sent to. + * @returns whether a credential is configured for that destination. + */ + configured(endpoint: string): Promise + /** + * Release the credential for `endpoint`, or `undefined` when none is + * configured or the destination may not receive it. The caller chooses the + * failure it reports for `undefined`. Store and format failures reject. + * @param endpoint - absolute URL the credential will be sent to. + * @param signal - cancellation for the lookup. + * @returns the released credential, or `undefined`. + */ + resolve(endpoint: string, signal?: AbortSignal): Promise +} +``` + A catalog entry may carry a provider-authored `badge` that selectors show beside the model name. It is display data: `resolveModelInfo` omits it, and no model request carries it. ```ts type-equiv @@ -868,6 +941,8 @@ The [wire reference](../deepseek-llm-api-wire-extensions.md) defines the exact r `LlmAdapter` is the provider contract: subclass, implement `stream()`, and register one adapter instance with `ctx.llm.registerAdapter(providers, adapter)`. `GenerateOptions.provider` selects the registered adapter; `GenerateOptions.model` is passed to that adapter and need not be registered at lifecycle start. Duplicate provider routes fail atomically. Optional `providerRetryPolicy()` is captured per route with normal defaults, while `providerInfo()` and asynchronous `listModels()` feed `LlmRuntime.listProviders()` / `listModels()` with detached selector metadata. That catalog is advisory rather than a request whitelist: the adapter remains authoritative and may accept unlisted model ids. One asynchronous `resolveModel()` query returns exact model identity plus optional correctness-sensitive context capacity, an adapter-configured `defaultMaxTokens`, and ordered model-owned reasoning ids with an optional deployment default; absent fields mean unavailable metadata or provider-owned behavior, not invalid catalog membership. The resolver receives optional cancellation and must settle promptly after abort. `LlmRuntime.resolveModelInfo()` validates and detaches the aggregate. At the final adapter boundary, `resolveCallConfig()` materializes the output default only when `maxTokens` is absent and validates and materializes reasoning, so direct calls cannot bypass either configured behavior; direct dispatch captures one registration before awaiting that resolution. The agent loop instead uses `prepareCall()` to keep the same registration across model resolution, durable header logging, and dispatch, retain detached context metadata from that exact lookup, and report which config fields the adapter defaulted. Adapter lookup happens at the terminal continuation of the `llm/stream` waterfall, so a listener may short-circuit the call or route a mutable one-shot request before lookup. AgentLoop observes a request attempt once the outer waterfall returns a stream handle; that limited boundary does not prove a lazy terminal adapter was constructed or began provider I/O. The `block-start` / `block-end` `index` correlation and the assembler together mean an adapter only has to emit well-formed chunks — block reassembly is not each adapter's problem. [architecture.md](../architecture.md#turn-flow) shows where `ctx.llm.stream()` and the `llm/stream` waterfall sit in one turn. +Optional `routeCredential()` publishes the credential a route currently sends, with the route's base URL, its kind, and an optional credential reference. `LlmRuntime.routeCredential(provider)` forwards to the owning adapter: an unregistered route answers `undefined`, because callers ask about routes a conversation named earlier, and a registered route whose configuration does not resolve propagates the adapter's failure. The DeepSeek web providers read it to call the deployment of the conversation's route with that route's credential, so no consumer reads another plugin's configuration or chooses its header names. + ```ts type-equiv /** One model call whose config and adapter registration were resolved together. */ interface PreparedLlmCall { @@ -935,6 +1010,16 @@ declare abstract class LlmAdapter { * @returns the same target used by request serialization, before provider-internal processing. */ imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget; + /** + * Describe the credential one owned route currently sends, for consumers that + * call the same deployment outside the model request path, such as web + * providers that share a route's credential and endpoint. The default + * publishes none. Implementations answer from one configuration generation + * per call and may throw when that configuration does not resolve. + * @param _provider - a route passed to `registerAdapter()` for this instance. + * @returns the route's current credential, or `undefined` when the route publishes none. + */ + routeCredential(_provider: string): RouteCredential | undefined; /** * List models this adapter can currently advertise for one owned provider. * Core routing accepts unlisted model ids; catalog-driven entry points such @@ -1115,6 +1200,17 @@ imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | u */ imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget +/** + * Resolve the credential one registered route currently sends, through its + * owning adapter. An unregistered route answers `undefined` rather than + * throwing because callers ask about routes a conversation named earlier, + * which may no longer be mounted; a registered route whose configuration + * does not resolve propagates the adapter's failure. + * @param provider - provider route whose credential is wanted. + * @returns the route credential, or `undefined` when the route is unregistered or publishes none. + */ +routeCredential(provider: string): RouteCredential | undefined + /** * Resolve the exact text one durable file occurrence contributes to every * provider request in the current execution environment. diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index 2f360b8f8f..36bc2aad2d 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -531,6 +531,79 @@ interface LlmNativeAuth { } ``` +路由的适配器还可以发布该路由当前发送的凭据,使在模型请求路径之外调用同一部署的消费方(如 DeepSeek Web 提供方)通过 `ctx.llm.routeCredential(provider)` 复用它,而不读取提供方配置或自行选择请求头名称。授权仅限 Host,且只在一次操作内持有;`kind` 通过 `LlmCredentialKindMap` 可合并扩展,已声明的成员为 `api-key` 和 `account`。 + +```ts type-equiv +/** + * One credential released for one destination. Host-only: it carries the + * secret, so it never crosses a Remote boundary and never enters a log. + */ +interface RouteCredentialGrant { + /** + * Request headers carrying the credential as the route's own protocol + * expects it, such as `x-api-key` for an API key. Consumers speaking that + * protocol send them unchanged. + */ + readonly headers: Readonly> + /** + * The bare credential value, for destinations whose protocol renders it + * differently from {@link headers}, such as `Authorization: Bearer`. + */ + readonly value: string + /** + * Invalidate this exact credential after the destination rejected it with + * HTTP 401 so no later request resends it. Absent for kinds without + * invalidation. The owner contains storage failures: the caller reports the + * destination's rejection, never a failure of this call. + * @returns settlement after the invalidation attempt. + */ + reject?(): Promise +} +``` + +```ts type-equiv +/** + * The credential one registered provider route currently sends, answered by + * the route's owning adapter so that consumers read no provider configuration + * and choose no header names. `ctx.llm.routeCredential()` resolves a new value + * per call from one configuration generation; a caller keeps it for one + * operation only. + */ +interface RouteCredential { + /** Kind of credential the route sends. */ + readonly kind: LlmCredentialKind + /** + * The route's current request base URL as its configuration resolves it, + * environment fallbacks included: the destination this credential is meant + * for. Consumers derive sibling endpoints of the same deployment from it. + */ + readonly baseURL: string + /** + * Credential reference the route resolves, for diagnostics that tell the user + * where to configure the credential; absent for kinds without a stored + * reference, such as sign-in grants. + */ + readonly reference?: string + /** + * Whether {@link resolve} would release a credential for `endpoint`, checked + * without reading the credential's value, validating it, or contacting the + * destination. Store failures reject. + * @param endpoint - absolute URL the credential would be sent to. + * @returns whether a credential is configured for that destination. + */ + configured(endpoint: string): Promise + /** + * Release the credential for `endpoint`, or `undefined` when none is + * configured or the destination may not receive it. The caller chooses the + * failure it reports for `undefined`. Store and format failures reject. + * @param endpoint - absolute URL the credential will be sent to. + * @param signal - cancellation for the lookup. + * @returns the released credential, or `undefined`. + */ + resolve(endpoint: string, signal?: AbortSignal): Promise +} +``` + 目录条目可以携带提供方编写的 `badge`,供选择器显示在模型名称旁。它只是展示数据:`resolveModelInfo` 不返回它,模型请求也不携带它。 ```ts type-equiv @@ -874,6 +947,8 @@ interface LlmCallConfigAdapterDefaults { `LlmAdapter` 是提供方约定:创建子类、实现 `stream()`,再用 `ctx.llm.registerAdapter(providers, adapter)` 注册一个适配器实例。`GenerateOptions.provider` 选择已注册适配器;`GenerateOptions.model` 会传给该适配器,无需在生命周期启动时注册。重复提供方路由会原子失败。可选的 `providerRetryPolicy()` 会按路由捕获并填入 normal 默认值,`providerInfo()` 与异步 `listModels()` 方法则为 `LlmRuntime.listProviders()` / `listModels()` 提供分离的 selector 元数据。该目录仅供参考,不是请求白名单:适配器仍是权威,并可接受未列出的模型 id。单次异步 `resolveModel()` 查询返回确切模型身份,以及可选的对正确性敏感的上下文容量、适配器配置的 `defaultMaxTokens`、由模型持有的有序推理强度 ID 和可选的部署默认值;字段缺失表示元数据不可用或保留提供方持有的行为,而不表示目录成员关系无效。解析器会接收可选的取消信号,并且必须在信号中止后迅速完成结算。`LlmRuntime.resolveModelInfo()` 会校验聚合结果并返回分离值。在最终适配器边界,`resolveCallConfig()` 仅在 `maxTokens` 缺失时填入输出默认值,并校验和填入推理强度,因此直接调用也无法绕过任何一项已配置行为;直接分派会在等待解析前捕获一项适配器注册。agent loop 则使用 `prepareCall()`,使模型解析、请求头持久记录和分派全程使用同一项注册,保留来自同一次查询的分离上下文元数据,并报告适配器填入的配置字段。适配器查找发生在 `llm/stream` waterfall 的终端 continuation,因此 listener 可以在查找前短路调用,或路由一个可变的一次性请求。AgentLoop 在外层 waterfall 返回流句柄时观察到一次请求尝试;这个有限边界不能证明惰性终端适配器已构造完成或开始提供方 I/O。`block-start` / `block-end` 的 `index` 关联与 assembler 共同意味着适配器只需 emit 格式正确的分片——块重组不是每个适配器各自的问题。`ctx.llm.stream()` 与 `llm/stream` waterfall 在一个轮次中的位置见 [architecture.md](../architecture.zh.md#turn-flow)。 +可选的 `routeCredential()` 发布路由当前发送的凭据,连同路由的基础地址、凭据种类和可选的凭据引用。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器:未注册的路由回答 `undefined`,因为调用方询问的是会话早先命名的路由;已注册但配置无法解析的路由则传播适配器的失败。DeepSeek Web 提供方据此用会话路由的凭据调用同一部署,因此没有消费方需要读取其他插件的配置或自行选择请求头名称。 + ```ts type-equiv /** One model call whose config and adapter registration were resolved together. */ interface PreparedLlmCall { @@ -941,6 +1016,16 @@ declare abstract class LlmAdapter { * @returns the same target used by request serialization, before provider-internal processing. */ imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget; + /** + * Describe the credential one owned route currently sends, for consumers that + * call the same deployment outside the model request path, such as web + * providers that share a route's credential and endpoint. The default + * publishes none. Implementations answer from one configuration generation + * per call and may throw when that configuration does not resolve. + * @param _provider - a route passed to `registerAdapter()` for this instance. + * @returns the route's current credential, or `undefined` when the route publishes none. + */ + routeCredential(_provider: string): RouteCredential | undefined; /** * List models this adapter can currently advertise for one owned provider. * Core routing accepts unlisted model ids; catalog-driven entry points such @@ -1121,6 +1206,17 @@ imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | u */ imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget +/** + * Resolve the credential one registered route currently sends, through its + * owning adapter. An unregistered route answers `undefined` rather than + * throwing because callers ask about routes a conversation named earlier, + * which may no longer be mounted; a registered route whose configuration + * does not resolve propagates the adapter's failure. + * @param provider - provider route whose credential is wanted. + * @returns the route credential, or `undefined` when the route is unregistered or publishes none. + */ +routeCredential(provider: string): RouteCredential | undefined + /** * Resolve the exact text one durable file occurrence contributes to every * provider request in the current execution environment. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.i18n.yaml new file mode 100644 index 0000000000..752379e39f --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md +/: + en: f0cf30e5430471e8 + zh: 2e6e871797dfdd6b +/deepseek-routes-publish-the-credential-web-consumers-reuse: + en: d7412a58aadc57a0 + zh: 82243a8cd8563083 +/deepseek-routes-publish-the-credential-web-consumers-reuse/change: + en: 7a63f24e07fb3d33 + zh: 99c64684a589088e +/deepseek-routes-publish-the-credential-web-consumers-reuse/migration: + en: 64ac045c8d9a1336 + zh: 4712f6eacd85a151 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md new file mode 100644 index 0000000000..2ec50f9a98 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md @@ -0,0 +1,29 @@ +--- +kind: upgrade-guide +description: "DeepSeek model routes publish their credential through ctx.llm.routeCredential(); the llm-deepseek credential helpers, the route plugins' config exports, and account Agent inspection are removed." +--- + +# DeepSeek routes publish the credential web consumers reuse + +English | [中文](guide.zh.md) + +## Change + +`LlmAdapter.routeCredential(provider)` and `LlmRuntime.routeCredential(provider)` publish a route's current credential as a `RouteCredential`: kind, resolved base URL, optional reference, a value-free `configured(endpoint)` check, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with protocol headers, the bare value, and an optional `reject()`. + +`@deepseek-ai/dsh-llm-deepseek` no longer exports `resolveDeepSeekApiKey`, `deepSeekApiKeyConfigured`, `resolveDeepSeekAccountToken`, or `rejectDeepSeekAccountToken`. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns `DeepSeekRequestAuth | undefined`, and `DeepSeekRequestAuth` requires `value` beside `headers`; the new `missingCredential` and `credential` options name the missing-credential failure and the published credential. `createModelListingCache` takes `credential(url)` returning request headers, and its `load` is optional. + +`@deepseek-ai/dsh-llm-deepseek-api-key` no longer exports `plainOptions` and `resolveAdapterOptions`; `@deepseek-ai/dsh-llm-deepseek-account` no longer exports `plainAccountOptions` and `resolveAccountOptions`. The account route plugin cancels its running Agents after sign-out and registers a running-task report. + +`@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)`; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name. `@deepseek-ai/dsh-credentials` adds `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`. + +`@deepseek-ai/dsh-web-deepseek-api` drops its peer dependencies on `dsh-llm-deepseek`, both route plugins, and `cordis-plugin-loader`; `@deepseek-ai/dsh-web-search-deepseek` drops `dsh-llm-deepseek` and `dsh-deepseek-account` and adds `dsh-llm`. Both read route credentials through `ctx.llm.routeCredential()`, so an adapter registered under a DeepSeek route id without a published credential counts as no route. Without the account route, the Search and Fetch APIs send the account credential to the origin `DEEPSEEK_BASE_URL` names and reject a value that is not an HTTP(S) URL without embedded credentials. `DeepSeekSearchProviderOptions` replaces `resolveAccountToken` and `rejectAccountToken` with `resolveAccountCredential(endpoint)`. + +## Migration + +1. Replace the removed `llm-deepseek` helpers: read keys with `resolveCredentialRef` and `credentialRefConfigured` from `@deepseek-ai/dsh-credentials` and validate them with `assertUsableApiKey`; read account credentials with `ctx.deepseekAccount.resolveRequestCredential(url)` and invalidate through the returned `reject()`. To reuse a mounted route's credential and endpoint, call `ctx.llm.routeCredential(provider)`. +2. In custom `DeepSeekAdapter` or `registerDeepSeekProvider` consumers, return `undefined` from `resolveAuth` when no credential exists, add `value` to every `DeepSeekRequestAuth`, supply `missingCredential` for a route-specific failure, and declare `credential` to publish the route's credential. Pass credential headers, not a token, to `createModelListingCache`. +3. Replace imports of the route plugins' config exports with the plugins' own `Config`, and read a route's endpoint from its published credential instead of its resolver. +4. Make `deepseekAccount` stand-ins used by the account route or the web providers implement `resolveRequestCredential`; stand-ins that supplied `ctx.agents` for `hasRunningAccountTasks()` register a report instead. +5. Update workspace references to `packages/account/deepseek-account`; the npm package name, Remote namespace, and configuration keys are unchanged. +6. Replace `resolveAccountToken` and `rejectAccountToken` in `DeepSeekSearchProviderOptions` with `resolveAccountCredential` returning a `RouteCredentialGrant`. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.zh.md new file mode 100644 index 0000000000..187434d603 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.zh.md @@ -0,0 +1,29 @@ +--- +kind: upgrade-guide +description: "DeepSeek 模型路由通过 ctx.llm.routeCredential() 发布自己的凭据;移除 llm-deepseek 的凭据辅助函数、路由插件的配置导出和账号服务对 Agent 的检查。" +--- + +# DeepSeek 路由发布 Web 消费方复用的凭据 + +[English](guide.md) | 中文 + +## 变更 + +`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、不读取值的 `configured(endpoint)` 检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值和可选的 `reject()`。 + +`@deepseek-ai/dsh-llm-deepseek` 不再导出 `resolveDeepSeekApiKey`、`deepSeekApiKeyConfigured`、`resolveDeepSeekAccountToken` 和 `rejectDeepSeekAccountToken`。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回 `DeepSeekRequestAuth | undefined`,且 `DeepSeekRequestAuth` 在 `headers` 之外要求 `value`;新增的 `missingCredential` 与 `credential` 选项分别命名凭据缺失的失败和发布的凭据。`createModelListingCache` 的 `credential(url)` 返回请求头,其 `load` 变为可选。 + +`@deepseek-ai/dsh-llm-deepseek-api-key` 不再导出 `plainOptions` 和 `resolveAdapterOptions`;`@deepseek-ai/dsh-llm-deepseek-account` 不再导出 `plainAccountOptions` 和 `resolveAccountOptions`。账号路由插件在退登后取消其运行中的 Agent,并注册运行中任务报告。 + +`@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。该包移除 `dsh-agent` 与 `dsh-llm` peer 依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。`@deepseek-ai/dsh-credentials` 新增 `resolveCredentialRef(ctx, ref)` 与 `credentialRefConfigured(ctx, ref)`。 + +`@deepseek-ai/dsh-web-deepseek-api` 移除对 `dsh-llm-deepseek`、两个路由插件和 `cordis-plugin-loader` 的 peer 依赖;`@deepseek-ai/dsh-web-search-deepseek` 移除 `dsh-llm-deepseek` 与 `dsh-deepseek-account`,新增 `dsh-llm`。两者都通过 `ctx.llm.routeCredential()` 读取路由凭据,因此以 DeepSeek 路由 id 注册但不发布凭据的适配器视为没有路由。没有账号路由时,Search 与 Fetch API 把账号凭据发往 `DEEPSEEK_BASE_URL` 所指的 origin,并拒绝不是不含内嵌凭据的 HTTP(S) URL 的值。`DeepSeekSearchProviderOptions` 用 `resolveAccountCredential(endpoint)` 替换 `resolveAccountToken` 与 `rejectAccountToken`。 + +## 迁移 + +1. 替换被移除的 `llm-deepseek` 辅助函数:用 `@deepseek-ai/dsh-credentials` 的 `resolveCredentialRef` 与 `credentialRefConfigured` 读取密钥并用 `assertUsableApiKey` 校验;用 `ctx.deepseekAccount.resolveRequestCredential(url)` 读取账号凭据并通过返回的 `reject()` 作废。要复用已挂载路由的凭据和端点,调用 `ctx.llm.routeCredential(provider)`。 +2. 在自定义的 `DeepSeekAdapter` 或 `registerDeepSeekProvider` 消费方中,没有凭据时让 `resolveAuth` 返回 `undefined`,为每个 `DeepSeekRequestAuth` 加上 `value`,为路由专属的失败提供 `missingCredential`,并声明 `credential` 以发布路由凭据。向 `createModelListingCache` 传递凭据请求头而不是 token。 +3. 用路由插件自身的 `Config` 替换对其配置导出的导入,并从路由发布的凭据而非其解析函数读取端点。 +4. 让账号路由或 Web 提供方使用的 `deepseekAccount` 替身实现 `resolveRequestCredential`;为 `hasRunningAccountTasks()` 提供 `ctx.agents` 的替身改为注册报告。 +5. 把工作区引用更新为 `packages/account/deepseek-account`;npm 包名、Remote 命名空间和配置键均不变。 +6. 把 `DeepSeekSearchProviderOptions` 中的 `resolveAccountToken` 与 `rejectAccountToken` 替换为返回 `RouteCredentialGrant` 的 `resolveAccountCredential`。 diff --git a/packages/README.i18n.yaml b/packages/README.i18n.yaml index 686f5672c1..81357d69c5 100644 --- a/packages/README.i18n.yaml +++ b/packages/README.i18n.yaml @@ -15,8 +15,8 @@ en: ffc55792d6e922e1 zh: 83bd759638857e2d /packages/package-groups: - en: 704e948001e25580 - zh: dcfbb1b483d2a95a + en: 2f76ab75d2b0b872 + zh: 7e6ce5f883d805c9 /packages/release-expectations: en: 236081c1659b25ab zh: 809110adf003802e diff --git a/packages/README.md b/packages/README.md index 431eadfc37..a8c0dbc993 100644 --- a/packages/README.md +++ b/packages/README.md @@ -57,7 +57,7 @@ Every package lives in exactly one group; new packages join existing groups, and | [`experimental/`](experimental/README.md) | Capabilities under evaluation; [status and support policy](experimental/README.md#status) | | [`workflow/`](workflow/README.md) | Workflow seam, PTC process engine, and the model-facing `workflow` tool | | [`web/`](web/README.md) | Web capability family: seam, search/fetch providers, model-facing web tools | -| [`document/`](document/README.md) | Shared Host Office rendering, conversion, and recalculation, the Office tools, and Kit engine resolution | +| [`document/`](document/README.md) | Host Office rendering, conversion, and recalculation, the Office tools, and Kit engine resolution | | [`attachment/`](attachment/README.md) | Durable attachment identity, validation, local content-addressed storage | | [`spill/`](spill/README.md) | Spill capability family: storage seam, local impl, tool-result spill policy | | [`todo/`](todo/README.md) | The model-facing `todo_write` tool | @@ -70,7 +70,8 @@ Every package lives in exactly one group; new packages join existing groups, and | [`session/`](session/README.md) | Durable session data plane: persistence seam + backends, projection seam, log-backed titles, session reporting | | [`session-query/`](session-query/README.md) | Session retrieval family: logical corpus, bounded reads, lineage, semantic filtering, SQLite full-text search | | [`settings/`](settings/README.md) | User-settings seam + file-backed provider | -| [`credentials/`](credentials/README.md) | Credential-reference and credential-record seam + env-over-`.env` provider + authorization flows that ask a human | +| [`credentials/`](credentials/README.md) | Credential reference and record seam, env-over-`.env` provider, and authorization flows that ask a human | +| [`account/`](account/README.md) | DeepSeek account sign-in and Host-only request credentials | | [`storage/`](storage/README.md) | Non-session storage hub + backends + domain form | | [`workspace/`](workspace/README.md) | Workspace entity | | [`sdk/`](sdk/README.md) | Out-of-process SDK: JSON-RPC protocol and TypeScript client/server | @@ -80,7 +81,7 @@ Every package lives in exactly one group; new packages join existing groups, and | [`host/`](host/README.md) | Web GUI host services, directory picking, application launch, plugin inventory, and product telemetry | | [`client/`](client/README.md) | Web-GUI browser half: shell, wire, object services, slots, `ui-*` plugins | | [`test-support/`](test-support/README.md) | Test infrastructure (testkits, replay, Loader smokes) | -| [`util/`](util/README.md) | Low-level utilities and data-only package lists shared across groups (`Branded`, home/path helpers, timeout, retention, official bundle lists) | +| [`util/`](util/README.md) | Low-level utilities and data-only package lists shared across groups | ----- diff --git a/packages/README.zh.md b/packages/README.zh.md index 5855d9c3fd..fda5527ba1 100644 --- a/packages/README.zh.md +++ b/packages/README.zh.md @@ -57,7 +57,7 @@ harness 由 `packages/` 下的 npm 包组装而成,按能力系列分组:会 | [`experimental/`](experimental/README.zh.md) | 仍在评估中的能力;[状态与支持策略](experimental/README.zh.md#status) | | [`workflow/`](workflow/README.zh.md) | 工作流 seam、PTC 进程引擎、面向模型的 `workflow` 工具 | | [`web/`](web/README.zh.md) | Web 能力系列:seam、搜索/获取提供方、面向模型的 Web 工具 | -| [`document/`](document/README.zh.md) | 共享宿主 Office 渲染、转换与重算、Office 工具与 Kit 引擎解析 | +| [`document/`](document/README.zh.md) | 宿主 Office 渲染、转换与重算、Office 工具与 Kit 引擎解析 | | [`attachment/`](attachment/README.zh.md) | 持久附件标识、校验、本地内容寻址存储 | | [`spill/`](spill/README.zh.md) | spill 能力系列:存储 seam、本地实现、工具结果 spill 策略 | | [`todo/`](todo/README.zh.md) | 面向模型的 `todo_write` 工具 | @@ -70,7 +70,8 @@ harness 由 `packages/` 下的 npm 包组装而成,按能力系列分组:会 | [`session/`](session/README.zh.md) | 持久会话数据平面:持久化 seam + 后端、投影 seam、基于日志的标题、会话上报 | | [`session-query/`](session-query/README.zh.md) | 会话检索系列:逻辑语料库、有界读取、血缘、语义过滤、SQLite 全文搜索 | | [`settings/`](settings/README.zh.md) | 用户设置 seam + 基于文件的提供方 | -| [`credentials/`](credentials/README.zh.md) | 凭据引用与凭据记录 seam + 环境变量优先于 `.env` 的提供方 + 需要向人询问的授权流程 | +| [`credentials/`](credentials/README.zh.md) | 凭据引用与记录 seam、环境变量优先于 `.env` 的提供方,以及需要向人询问的授权流程 | +| [`account/`](account/README.zh.md) | DeepSeek 账号登录与仅限 Host 的请求凭据 | | [`storage/`](storage/README.zh.md) | 非会话存储中枢 + 后端 + 领域形式 | | [`workspace/`](workspace/README.zh.md) | Workspace 实体 | | [`sdk/`](sdk/README.zh.md) | 进程外 SDK:JSON-RPC 协议与 TypeScript 客户端/服务器 | @@ -80,7 +81,7 @@ harness 由 `packages/` 下的 npm 包组装而成,按能力系列分组:会 | [`host/`](host/README.zh.md) | Web GUI 宿主服务、目录选择、应用启动、插件清单和产品遥测 | | [`client/`](client/README.zh.md) | web GUI 浏览器半侧:shell、协议层、对象服务、slot、`ui-*` 插件 | | [`test-support/`](test-support/README.zh.md) | 测试基础设施(testkit、回放、Loader 冒烟测试) | -| [`util/`](util/README.zh.md) | 组间共享的低层工具与纯数据包列表(`Branded`、home/路径辅助函数、超时、留存、官方组合包列表) | +| [`util/`](util/README.zh.md) | 组间共享的低层工具与纯数据包列表 | ----- diff --git a/packages/account/README.i18n.yaml b/packages/account/README.i18n.yaml new file mode 100644 index 0000000000..ae0a4268ed --- /dev/null +++ b/packages/account/README.i18n.yaml @@ -0,0 +1,25 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/account/README.md +/: + en: c603fc9f9990181e + zh: fc045770018269cd +/account-deepseek-account: + en: 15e52f323c5ffdba + zh: e32a4d077fd5ef98 +/account-deepseek-account/summary: + en: b75f72f3404fcd85 + zh: c24435d70528c5a4 +/account-deepseek-account/table-of-contents: + en: 1eb35b015a6c423f + zh: a8a3dceee2c9e943 +/account-deepseek-account/packages: + en: 4f342c1e06b8c9e2 + zh: f36f298ef3bd1be2 +/account-deepseek-account/related-documentation: + en: 6667d1a41ac182d1 + zh: 065a196972782a34 +/account-deepseek-account/dev-note: + en: 5de1d6304e00c58f + zh: 8d8225361cfa29e5 diff --git a/packages/account/README.md b/packages/account/README.md new file mode 100644 index 0000000000..278ac10749 --- /dev/null +++ b/packages/account/README.md @@ -0,0 +1,51 @@ +--- +description: "Package map for the DeepSeek account family: browser sign-in, the stored account grant, and the Host-only request credentials released to the account model route and the DeepSeek web providers." +kind: "package-group" +--- + +# account/ — DeepSeek account + +English | [中文](README.zh.md) + +## Summary + +The `account/` group signs the user in to DeepSeek through the system browser and keeps the account grant in the local credential store that [`credentials/`](../credentials/README.md) owns. Host consumers never read the token: the `deepseek-account` model route and the DeepSeek web providers ask `ctx.deepseekAccount` for the credential of one request destination and receive its request headers, the bare value, and an invalidation for an HTTP 401. Clients receive account state through the `account` Remote namespace without credentials. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +One package provides the account feature; its README covers day-to-day use, and the subsystem reference owns the exhaustive contracts. + +| Package | Role | ctx key | +|---|---|---| +| [`deepseek-account/`](deepseek-account/README.md) | Browser sign-in, the stored grant, Platform profile, balance, and notification reads, and Host-only request credentials for allowed destinations | `ctx.deepseekAccount` | + +----- + + +## Related documentation + +Start with the subsystem reference for the account contracts, then the credential store the grant lives in. + +- [Account subsystem reference](../../docs/subsystems/account.md) — sign-in state, request credentials, the Platform session projection, and the generated Cordis surface. +- [Credentials subsystem reference](../../docs/subsystems/credentials.md) — the credential records the grant is stored in. +- [Capability seams](../../docs/capability-seams.md) — the Service Definition / Service Provider / Consumer split this family follows. +- [Generated configuration catalog](../../docs/config-catalog.md#deepseek-aidsh-deepseek-account) — every accepted field of the account service. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/account/README.zh.md b/packages/account/README.zh.md new file mode 100644 index 0000000000..1bc1a0a936 --- /dev/null +++ b/packages/account/README.zh.md @@ -0,0 +1,51 @@ +--- +description: "DeepSeek 账号能力族的包映射:浏览器登录、已存账号授权,以及向账号模型路由和 DeepSeek Web 提供方释放的仅限 Host 的请求凭据。" +kind: "package-group" +--- + +# account/:DeepSeek 账号 + +[English](README.md) | 中文 + +## 概述 + +`account/` 组通过系统浏览器让用户登录 DeepSeek,并把账号授权保存在 [`credentials/`](../credentials/README.zh.md) 拥有的本地凭据库中。Host 消费方从不读取 token:`deepseek-account` 模型路由和 DeepSeek Web 提供方向 `ctx.deepseekAccount` 索取某个请求目标的凭据,取得其请求头、裸值以及用于 HTTP 401 的失效操作。客户端通过不携带凭据的 `account` Remote 命名空间获得账号状态。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +一个包提供账号功能;它的 README 覆盖日常使用,全部约定以子系统参考为准。 + +| 包 | 角色 | ctx 键 | +|---|---|---| +| [`deepseek-account/`](deepseek-account/README.zh.md) | 浏览器登录、已存授权、Platform 资料、余额与通知读取,以及面向允许目标的仅限 Host 的请求凭据 | `ctx.deepseekAccount` | + +----- + + +## 相关文档 + +先从子系统参考了解账号约定,再看授权所在的凭据库。 + +- [账号子系统参考](../../docs/subsystems/account.zh.md)——登录状态、请求凭据、Platform 会话投影与生成的 Cordis 接口面。 +- [凭据子系统参考](../../docs/subsystems/credentials.zh.md)——保存授权的凭据记录。 +- [能力 seam](../../docs/capability-seams.zh.md)——本家族遵循的 Service Definition / Service Provider / Consumer 拆分。 +- [生成配置目录](../../docs/config-catalog.zh.md#deepseek-aidsh-deepseek-account)——账号服务的每个受支持字段。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/credentials/deepseek-account/README.i18n.yaml b/packages/account/deepseek-account/README.i18n.yaml similarity index 86% rename from packages/credentials/deepseek-account/README.i18n.yaml rename to packages/account/deepseek-account/README.i18n.yaml index 7c8e7b9d6f..95ce3a191b 100644 --- a/packages/credentials/deepseek-account/README.i18n.yaml +++ b/packages/account/deepseek-account/README.i18n.yaml @@ -1,13 +1,13 @@ # Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading # section, a hash of its English and Chinese blocks outside code blocks and generated regions. # After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write packages/credentials/deepseek-account/README.md +# pnpm run verify-translation-pairing --write packages/account/deepseek-account/README.md /: en: 9dbb9bc3960a11fe zh: ed58987926489d3e /deepseek-ai-dsh-deepseek-account: - en: 78e86576b7f38038 - zh: 7ec9f58f21ce00bf + en: 06fe55f319bd1b2c + zh: 9559b712e50bbc73 /deepseek-ai-dsh-deepseek-account/summary: en: 28bcca957bf6abf4 zh: 4a3fc8a59f2925bc @@ -15,8 +15,8 @@ en: af856ba79fe31b8e zh: 15b7d1a5d1856de2 /deepseek-ai-dsh-deepseek-account/use-this-package: - en: a334962d65816a50 - zh: 28f66b089476123a + en: 02b899ac5ad80227 + zh: 0cb4d6984ae6ed62 /deepseek-ai-dsh-deepseek-account/understand-the-implementation: en: 76d2da2dab100ac3 zh: 2c9404f27915daab diff --git a/packages/credentials/deepseek-account/README.md b/packages/account/deepseek-account/README.md similarity index 96% rename from packages/credentials/deepseek-account/README.md rename to packages/account/deepseek-account/README.md index 28e3b20afe..34d87bf729 100644 --- a/packages/credentials/deepseek-account/README.md +++ b/packages/account/deepseek-account/README.md @@ -13,7 +13,7 @@ getPlatformSession exports the stored grant only when its issuer matches platfor `desktopPlatform` defaults to `null`, which sends `x-client-platform: web`; the Desktop profile supplies `darwin` or `win32`, becoming `desktop-mac` or `desktop-win`. The service owns all five headers, so deployment configuration cannot override them; `x-client-bundle-id` is intentionally empty, and `x-client-locale` reduces the caller's language to `zh_CN` or `en_US`. PlatformSession carries deployment headers only, and the embedding client composes the same five headers for the Platform documents and API requests it opens, only at the configured origin. -Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. Host inference consumers can report a rejected request token through `rejectToken`; removal requires that it still matches the stored login. +Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. Host inference consumers can report a rejected request token through `rejectToken`; removal requires that it still matches the stored login. `resolveRequestCredential(url)` releases the credential for one allowed destination as the request headers, the bare token, and a `reject()` that performs that removal after an HTTP 401 while containing storage failures; the account model route and the DeepSeek web providers use it instead of composing headers themselves. ## Summary @@ -36,9 +36,9 @@ The service exposes its client-safe operations through the `account` Remote name `DeepSeekAccount` is the concrete service owning login, credentials, and Remote operations. The `/types` entry exposes types without loading the service implementation. `watch` returns complete state tagged as `snapshot` or `credentials-changed`; Host-only `watch(signal, true)` also receives profile-identity changes, while Remote subscriptions omit that option. -The `/client-metadata` entry provides pure Platform header and cookie helpers for Host consumers. The configuration schema is `DeepSeekAccount.Config`; the plugin entry exports no helper functions. Mounting the service installs account-task cancellation. +The `/client-metadata` entry provides pure Platform header and cookie helpers for Host consumers. The configuration schema is `DeepSeekAccount.Config`; the plugin entry exports no helper functions. -The `agents` service is optional. `hasRunningAccountTasks()` returns false when it is absent; when present, it checks running tasks for the account provider. +`hasRunningAccountTasks()` answers through the reports model routes register with `registerRunningTaskReport()` inside `ctx.effect()`; without a report, nothing is known to be running. The `llm-deepseek-account` route registers one and owns cancelling its running Agents after sign-out. The profile projection maps `id_profile.picture` to `avatarUrl`, using null when no picture is configured. diff --git a/packages/credentials/deepseek-account/README.zh.md b/packages/account/deepseek-account/README.zh.md similarity index 96% rename from packages/credentials/deepseek-account/README.zh.md rename to packages/account/deepseek-account/README.zh.md index 628fd2ed61..88b4801909 100644 --- a/packages/credentials/deepseek-account/README.zh.md +++ b/packages/account/deepseek-account/README.zh.md @@ -13,7 +13,7 @@ getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导 `desktopPlatform` 默认为 `null`,此时携带 `x-client-platform: web`;Desktop profile 提供 `darwin` 或 `win32`,改为 `desktop-mac` 或 `desktop-win`。五个请求头均由 provider 拥有,部署配置无法覆盖;`x-client-bundle-id` 有意保持为空,`x-client-locale` 将调用方语言归约为 `zh_CN` 或 `en_US`。PlatformSession 只携带部署请求头,内嵌客户端为自行打开的 Platform 文档和 API 请求组装同样的五个请求头,且仅在配置来源发送。 -资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。Host 推理调用方可以通过 `rejectToken` 报告被拒绝的请求 token;仅当它仍匹配当前登录凭据时才执行清除。 +资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。Host 推理调用方可以通过 `rejectToken` 报告被拒绝的请求 token;仅当它仍匹配当前登录凭据时才执行清除。`resolveRequestCredential(url)` 把一个允许目标的凭据以请求头、裸 token 和 `reject()` 的形式释放;`reject()` 在 HTTP 401 后执行上述清除并隔离存储失败。账号模型路由和 DeepSeek Web 提供方使用它,而不自行组装请求头。 ## 概述 @@ -36,9 +36,9 @@ getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导 `DeepSeekAccount` 是具体服务,拥有登录、凭证和 Remote 操作。`/types` 提供不加载服务实现的类型出口。`watch` 返回完整状态与 `snapshot` 或 `credentials-changed` 类型;仅 Host 的 `watch(signal, true)` 还接收资料身份变化,Remote 订阅不启用该选项。 -`/client-metadata` 为 Host 使用方提供纯函数形式的 Platform 请求头和 Cookie 辅助函数。配置 schema 为 `DeepSeekAccount.Config`;插件入口不导出辅助函数。挂载服务时会安装账号任务取消逻辑。 +`/client-metadata` 为 Host 使用方提供纯函数形式的 Platform 请求头和 Cookie 辅助函数。配置 schema 为 `DeepSeekAccount.Config`;插件入口不导出辅助函数。 -`agents` 服务为可选依赖。未提供时,`hasRunningAccountTasks()` 返回 false;提供时,检查使用账号服务的运行中任务。 +`hasRunningAccountTasks()` 通过模型路由在 `ctx.effect()` 内用 `registerRunningTaskReport()` 注册的报告作答;没有报告时视为没有运行中的工作。`llm-deepseek-account` 路由注册一份报告,并负责在退登后取消其运行中的 Agent。 账号资料投影将 `id_profile.picture` 映射为 `avatarUrl`,没有配置头像时返回 null。 diff --git a/packages/credentials/deepseek-account/locale/de.json b/packages/account/deepseek-account/locale/de.json similarity index 100% rename from packages/credentials/deepseek-account/locale/de.json rename to packages/account/deepseek-account/locale/de.json diff --git a/packages/credentials/deepseek-account/locale/en.json b/packages/account/deepseek-account/locale/en.json similarity index 100% rename from packages/credentials/deepseek-account/locale/en.json rename to packages/account/deepseek-account/locale/en.json diff --git a/packages/credentials/deepseek-account/locale/es.json b/packages/account/deepseek-account/locale/es.json similarity index 100% rename from packages/credentials/deepseek-account/locale/es.json rename to packages/account/deepseek-account/locale/es.json diff --git a/packages/credentials/deepseek-account/locale/fr.json b/packages/account/deepseek-account/locale/fr.json similarity index 100% rename from packages/credentials/deepseek-account/locale/fr.json rename to packages/account/deepseek-account/locale/fr.json diff --git a/packages/credentials/deepseek-account/locale/ja.json b/packages/account/deepseek-account/locale/ja.json similarity index 100% rename from packages/credentials/deepseek-account/locale/ja.json rename to packages/account/deepseek-account/locale/ja.json diff --git a/packages/credentials/deepseek-account/locale/pt.json b/packages/account/deepseek-account/locale/pt.json similarity index 100% rename from packages/credentials/deepseek-account/locale/pt.json rename to packages/account/deepseek-account/locale/pt.json diff --git a/packages/credentials/deepseek-account/locale/ru.json b/packages/account/deepseek-account/locale/ru.json similarity index 100% rename from packages/credentials/deepseek-account/locale/ru.json rename to packages/account/deepseek-account/locale/ru.json diff --git a/packages/credentials/deepseek-account/locale/zh.json b/packages/account/deepseek-account/locale/zh.json similarity index 100% rename from packages/credentials/deepseek-account/locale/zh.json rename to packages/account/deepseek-account/locale/zh.json diff --git a/packages/credentials/deepseek-account/package.json b/packages/account/deepseek-account/package.json similarity index 87% rename from packages/credentials/deepseek-account/package.json rename to packages/account/deepseek-account/package.json index 088b4e8106..15cf18c2de 100644 --- a/packages/credentials/deepseek-account/package.json +++ b/packages/account/deepseek-account/package.json @@ -8,7 +8,7 @@ "repository": { "type": "git", "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", - "directory": "packages/credentials/deepseek-account" + "directory": "packages/account/deepseek-account" }, "type": "module", "main": "lib/index.js", @@ -56,8 +56,6 @@ "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-brand": "workspace:*", - "@deepseek-ai/dsh-agent": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", "@deepseek-ai/dsh-authorization": "workspace:*", "@deepseek-ai/dsh-credentials": "workspace:*", @@ -67,19 +65,12 @@ "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-brand": "workspace:*", - "@deepseek-ai/dsh-agent": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", "@deepseek-ai/dsh-authorization": "workspace:*", "@deepseek-ai/dsh-credentials": "workspace:*", "@deepseek-ai/dsh-host-webserver": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*" }, - "peerDependenciesMeta": { - "@deepseek-ai/dsh-agent": { - "optional": true - } - }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~", "zod": "4.6.6" diff --git a/packages/credentials/deepseek-account/src/client-metadata.ts b/packages/account/deepseek-account/src/client-metadata.ts similarity index 100% rename from packages/credentials/deepseek-account/src/client-metadata.ts rename to packages/account/deepseek-account/src/client-metadata.ts diff --git a/packages/credentials/deepseek-account/src/details.ts b/packages/account/deepseek-account/src/details.ts similarity index 100% rename from packages/credentials/deepseek-account/src/details.ts rename to packages/account/deepseek-account/src/details.ts diff --git a/packages/credentials/deepseek-account/src/index.ts b/packages/account/deepseek-account/src/index.ts similarity index 95% rename from packages/credentials/deepseek-account/src/index.ts rename to packages/account/deepseek-account/src/index.ts index 8dddec9074..739907057e 100644 --- a/packages/credentials/deepseek-account/src/index.ts +++ b/packages/account/deepseek-account/src/index.ts @@ -8,15 +8,14 @@ import { Context, Service } from '@deepseek-ai/cordis' import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' import Schema from '@deepseek-ai/schemastery' import { z } from 'zod' -import { installAccountTaskCancellation, isRunningAccountTask } from './account-tasks.ts' import { mergePlatformCookies, platformClientHeaders, platformWireLocale } from './client-metadata.ts' -import { type AccountNotification, type AccountNotificationBatch, type AccountNotificationEvent, type AccountNotificationId, type AccountClientMetadata, type AccountDetails, type AccountUserId, type AccountView, type AccountUpdate, type PlatformSession, type SignInAttemptId, type SignInAttemptView } from './types.ts' +import { type AccountNotification, type AccountNotificationBatch, type AccountNotificationEvent, type AccountNotificationId, type AccountClientMetadata, type AccountDetails, type AccountRequestCredential, type AccountUserId, type AccountView, type AccountUpdate, type PlatformSession, type SignInAttemptId, type SignInAttemptView } from './types.ts' import { credentialKey } from '@deepseek-ai/dsh-credentials' import type { AuthorizationSession } from '@deepseek-ai/dsh-authorization' import { profile, readAccountDetail } from './details.ts' import { readNotificationContent, readNotifications, sendNotificationEvent } from './notifications.ts' import { revokeAccount, type LogoutRetryPolicy } from './logout.ts' -import { AccountUnauthorizedError, PlatformAuthError, platformHeaders, platformOrigin, browserUrl, requestPlatform, initialization, exchange, loginOrigin } from './protocol.ts' +import { ACCOUNT_TOKEN_HEADER, AccountUnauthorizedError, PlatformAuthError, platformHeaders, platformOrigin, browserUrl, requestPlatform, initialization, exchange, loginOrigin } from './protocol.ts' export type * from './types.ts' @@ -122,6 +121,7 @@ export class DeepSeekAccount extends TypertRemoteService { private readonly revocations = new Set>() private attempt: Attempt | undefined private readonly listeners = new Set<(kind: 'snapshot' | 'credentials-changed' | 'identity') => void>() + private readonly runningTaskReports = new Set<() => boolean>() /** * Latest ready profile read and the grant token it was read with. Binding the token keeps a * cached identity from answering for a credential that has since changed. @@ -134,7 +134,6 @@ export class DeepSeekAccount extends TypertRemoteService { /** @param ctx - Host with authorization and credentials services. @param config - deployment options. */ constructor(ctx: Context, config: Config = {}) { super(ctx, 'deepseekAccount', { namespace: 'account' }) - installAccountTaskCancellation(ctx) const resolved = Config(config) this.embeddedPageDist = resolved.embeddedPageDist this.origin = platformOrigin(resolved.platformOrigin, resolved.allowLoopbackHttp, 'platformOrigin') @@ -469,6 +468,25 @@ export class DeepSeekAccount extends TypertRemoteService { return result.data.token } + /** + * Release the account credential for one request to `url` as the request + * carries it, together with its invalidation. Host-only. + * @param url - actual request destination or API base URL. + * @returns the request credential, or undefined for other origins or a signed-out account. + */ + async resolveRequestCredential(url: string): Promise { + const token = await this.resolveToken(url) + if (token === undefined) return undefined + return { + headers: { [ACCOUNT_TOKEN_HEADER]: token }, + value: token, + reject: async () => { + try { await this.rejectToken(token) } + catch (_credentialRemovalFailed) { /* The destination's rejection is the failure to report; the next rejection retries. */ } + }, + } + } + /** * Join an active attempt or start browser authorization. * @param client - identity of the requesting UI; a new attempt captures it, and joining retains the original attempt's identity. @@ -570,13 +588,26 @@ export class DeepSeekAccount extends TypertRemoteService { return this.removing } + /** + * Register a report of running work that signing out would interrupt. The + * plugin billing the account to a model route registers one from within + * `ctx.effect()`; without any report nothing is known to be running. + * @param report - answers whether such work is running now. + * @returns the disposer removing the report. + */ + registerRunningTaskReport(report: () => boolean): () => void { + this.runningTaskReports.add(report) + return () => { this.runningTaskReports.delete(report) } + } + /** * Inspect running work before sign-out. - * @returns whether a running task's latest request uses the account route; false when the optional agents service is absent. + * @returns whether a registered report says a running task uses the account; false without reports. */ @Remote hasRunningAccountTasks(): boolean { - return this.ctx.get('agents')?.list().some(isRunningAccountTask) ?? false + for (const report of this.runningTaskReports) if (report()) return true + return false } /** diff --git a/packages/credentials/deepseek-account/src/logout.ts b/packages/account/deepseek-account/src/logout.ts similarity index 100% rename from packages/credentials/deepseek-account/src/logout.ts rename to packages/account/deepseek-account/src/logout.ts diff --git a/packages/credentials/deepseek-account/src/notifications.ts b/packages/account/deepseek-account/src/notifications.ts similarity index 100% rename from packages/credentials/deepseek-account/src/notifications.ts rename to packages/account/deepseek-account/src/notifications.ts diff --git a/packages/credentials/deepseek-account/src/protocol.ts b/packages/account/deepseek-account/src/protocol.ts similarity index 95% rename from packages/credentials/deepseek-account/src/protocol.ts rename to packages/account/deepseek-account/src/protocol.ts index b7a6a234a6..2a0160e65e 100644 --- a/packages/credentials/deepseek-account/src/protocol.ts +++ b/packages/account/deepseek-account/src/protocol.ts @@ -66,7 +66,7 @@ export function platformHeaders(values: Record): Record() for (const [name, value] of Object.entries(values)) { const key = name.toLowerCase() - if (['authorization', 'x-dsh-auth-token', 'host', 'content-length', 'transfer-encoding', 'connection', 'content-type'].includes(key) + if (['authorization', ACCOUNT_TOKEN_HEADER, 'host', 'content-length', 'transfer-encoding', 'connection', 'content-type'].includes(key) || names.has(key)) throw new Error('account: requestHeaders contains a reserved or duplicate header') names.add(key) try { headers.set(name, value) } @@ -161,9 +161,12 @@ export function requestNotificationEvent(origin: string, token: string, id: Acco }, signal) } +/** Request header carrying the account token on every request the token authenticates. */ +export const ACCOUNT_TOKEN_HEADER = 'x-dsh-auth-token' + // The grant is provider-owned; deployment requestHeaders cannot override it or the client identity. function accountHeaders(headers: Record, token: string): Record { - return { ...headers, 'x-dsh-auth-token': token } + return { ...headers, [ACCOUNT_TOKEN_HEADER]: token } } /** @@ -177,7 +180,7 @@ function accountHeaders(headers: Record, token: string): Record< export async function logoutAccount(origin: string, token: string, signal: AbortSignal, headers: Record): Promise { await platformRequest(`${origin}/auth-api/v0/users/logout`, { - method: 'POST', headers: { ...headers, 'x-dsh-auth-token': token }, + method: 'POST', headers: { ...headers, [ACCOUNT_TOKEN_HEADER]: token }, }, signal) } @@ -196,7 +199,7 @@ async function platformRequest(url: string, init: RequestInit, signal: AbortSign if (!callerCancelled(signal)) console.error('[deepseek-account] request failed', { path, errorCode: 'no-response', aborted: signal.aborted }) throw new PlatformAuthError('no-response') } - if (response.status === 401 && new Headers(init.headers).has('x-dsh-auth-token')) { + if (response.status === 401 && new Headers(init.headers).has(ACCOUNT_TOKEN_HEADER)) { if (!callerCancelled(signal)) console.error('[deepseek-account] request failed', { path, status: response.status, errorCode: 'expired' }) await response.body?.cancel() throw new AccountUnauthorizedError() @@ -228,7 +231,7 @@ async function platformRequest(url: string, init: RequestInit, signal: AbortSign const responseCodes = z.object({ code: z.number().int(), data: z.object({ biz_code: z.number().int() }).optional() }).safeParse(payload) if (responseCodes.success) codes = responseCodes.data const authorization = z.object({ code: z.literal(40003) }).safeParse(payload) - if (authorization.success && new Headers(init.headers).has('x-dsh-auth-token')) { + if (authorization.success && new Headers(init.headers).has(ACCOUNT_TOKEN_HEADER)) { throw new AccountUnauthorizedError() } stage = 'envelope' diff --git a/packages/credentials/deepseek-account/src/types.ts b/packages/account/deepseek-account/src/types.ts similarity index 89% rename from packages/credentials/deepseek-account/src/types.ts rename to packages/account/deepseek-account/src/types.ts index 5ccd36303b..9a0f23c772 100644 --- a/packages/credentials/deepseek-account/src/types.ts +++ b/packages/account/deepseek-account/src/types.ts @@ -111,6 +111,24 @@ declare module '@deepseek-ai/cordis' { } } +/** + * The account credential released for one request destination, as the request + * carries it. Host-only: it holds the token and never crosses the Remote. + */ +export interface AccountRequestCredential { + /** Request headers carrying the account token. */ + readonly headers: Readonly> + /** The bare token. */ + readonly value: string + /** + * Remove the stored token after the destination rejected it, unless a newer + * sign-in replaced it. Storage failures are contained: the caller reports + * the destination's rejection, and the next rejection retries the removal. + * @returns settlement after the removal attempt. + */ + reject(): Promise +} + /** Host-only credentials for an embedded Platform document; never expose through account RPC. */ export interface PlatformSession { readonly origin: string diff --git a/packages/account/deepseek-account/tests/account-stub.ts b/packages/account/deepseek-account/tests/account-stub.ts new file mode 100644 index 0000000000..a04352bbac --- /dev/null +++ b/packages/account/deepseek-account/tests/account-stub.ts @@ -0,0 +1,35 @@ +/** `deepseekAccount` stand-ins for consumers of the account's request credential. */ +import type { DeepSeekAccount } from '../src/index.ts' +import { ACCOUNT_TOKEN_HEADER } from '../src/protocol.ts' + +/** Token policy and rejection observer of one stand-in. */ +export interface AccountStubOptions { + /** The token released for a destination; undefined or empty releases nothing, and a throw fails the read. */ + readonly token: (url: string) => string | undefined | Promise + /** Observes each rejected token; a throw is contained, as the service contains storage failures. */ + readonly reject?: (token: string) => void | Promise +} + +/** + * An account service releasing request credentials as the real one does: the token header, the bare token, and an + * invalidation that reports no failure. + * @param options - token policy and rejection observer. + * @returns the stand-in, typed as the service for `ctx.provide`. + */ +export function accountStub(options: AccountStubOptions): DeepSeekAccount { + const stub: Pick = { + async resolveRequestCredential(url) { + const token = await options.token(url) + if (token === undefined || token.length === 0) return undefined + return { + headers: { [ACCOUNT_TOKEN_HEADER]: token }, + value: token, + reject: async () => { + try { await options.reject?.(token) } + catch (_storageFailure) { /* The destination's rejection is the failure to report, as in the service. */ } + }, + } + }, + } + return stub as DeepSeekAccount +} diff --git a/packages/credentials/deepseek-account/tests/account.spec.ts b/packages/account/deepseek-account/tests/account.spec.ts similarity index 97% rename from packages/credentials/deepseek-account/tests/account.spec.ts rename to packages/account/deepseek-account/tests/account.spec.ts index 267616dab3..a5a1662868 100644 --- a/packages/credentials/deepseek-account/tests/account.spec.ts +++ b/packages/account/deepseek-account/tests/account.spec.ts @@ -306,6 +306,35 @@ it('allows real account credentials only on the exact official HTTPS origin', as } }) +it('releases the request credential for an allowed destination and removes the rejected token through it', async () => { + const f = await fixture(undefined, {}, false, {}, 'http://inference.example.test:8094') + f.exchangeResponse({ token: 'test-account-token' }) + await f.account.startSignIn(clientMetadata(), f.callbackOrigin, 'desktop') + await f.wait('waiting-browser') + await fetch(f.callback(), { redirect: 'manual' }) + await f.wait('succeeded') + const endpoint = 'http://inference.example.test:8094/v1/tools/search' + expect(await f.account.resolveRequestCredential('https://api.deepseek.com/v1/tools/search')).toBeUndefined() + const credential = await f.account.resolveRequestCredential(endpoint) + expect(credential).toMatchObject({ headers: { 'x-dsh-auth-token': 'test-account-token' }, value: 'test-account-token' }) + await credential!.reject() + expect((await f.account.getState()).status).toBe('signed-out') + expect(await f.account.resolveRequestCredential(endpoint)).toBeUndefined() +}) + +it('contains a storage failure while removing a rejected token', async () => { + const f = await fixture(undefined, {}, false, {}, 'http://inference.example.test:8094') + f.exchangeResponse({ token: 'test-account-token' }) + await f.account.startSignIn(clientMetadata(), f.callbackOrigin, 'desktop') + await f.wait('waiting-browser') + await fetch(f.callback(), { redirect: 'manual' }) + await f.wait('succeeded') + const credential = await f.account.resolveRequestCredential('http://inference.example.test:8094/v1/tools/search') + await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ kind: 'api-key', key: 'wrong-kind' })) + await expect(credential!.reject()).resolves.toBeUndefined() + await expect(f.account.rejectToken('test-account-token')).rejects.toThrow('account: storage') +}) + it('restricts platform destinations to the configured origin and route', () => { expect(() => platformOrigin('http://localhost:8081', false, 'platformOrigin')).toThrow() expect(platformOrigin('http://localhost:8081', true, 'platformOrigin')).toBe('http://localhost:8081') diff --git a/packages/credentials/deepseek-account/tests/authorization-response.spec.ts b/packages/account/deepseek-account/tests/authorization-response.spec.ts similarity index 100% rename from packages/credentials/deepseek-account/tests/authorization-response.spec.ts rename to packages/account/deepseek-account/tests/authorization-response.spec.ts diff --git a/packages/credentials/deepseek-account/tests/client-headers.spec.ts b/packages/account/deepseek-account/tests/client-headers.spec.ts similarity index 100% rename from packages/credentials/deepseek-account/tests/client-headers.spec.ts rename to packages/account/deepseek-account/tests/client-headers.spec.ts diff --git a/packages/credentials/deepseek-account/tests/details.spec.ts b/packages/account/deepseek-account/tests/details.spec.ts similarity index 100% rename from packages/credentials/deepseek-account/tests/details.spec.ts rename to packages/account/deepseek-account/tests/details.spec.ts diff --git a/packages/credentials/deepseek-account/tests/diagnostics.spec.ts b/packages/account/deepseek-account/tests/diagnostics.spec.ts similarity index 100% rename from packages/credentials/deepseek-account/tests/diagnostics.spec.ts rename to packages/account/deepseek-account/tests/diagnostics.spec.ts diff --git a/packages/credentials/deepseek-account/tests/expected/web-exchange-failure.txt b/packages/account/deepseek-account/tests/expected/web-exchange-failure.txt similarity index 100% rename from packages/credentials/deepseek-account/tests/expected/web-exchange-failure.txt rename to packages/account/deepseek-account/tests/expected/web-exchange-failure.txt diff --git a/packages/credentials/deepseek-account/tests/logout.spec.ts b/packages/account/deepseek-account/tests/logout.spec.ts similarity index 100% rename from packages/credentials/deepseek-account/tests/logout.spec.ts rename to packages/account/deepseek-account/tests/logout.spec.ts diff --git a/packages/credentials/deepseek-account/tests/notifications.spec.ts b/packages/account/deepseek-account/tests/notifications.spec.ts similarity index 100% rename from packages/credentials/deepseek-account/tests/notifications.spec.ts rename to packages/account/deepseek-account/tests/notifications.spec.ts diff --git a/packages/credentials/deepseek-account/tests/origins.spec.ts b/packages/account/deepseek-account/tests/origins.spec.ts similarity index 100% rename from packages/credentials/deepseek-account/tests/origins.spec.ts rename to packages/account/deepseek-account/tests/origins.spec.ts diff --git a/packages/credentials/deepseek-account/tests/remote.spec.ts b/packages/account/deepseek-account/tests/remote.spec.ts similarity index 84% rename from packages/credentials/deepseek-account/tests/remote.spec.ts rename to packages/account/deepseek-account/tests/remote.spec.ts index e33fc547da..7e1e162044 100644 --- a/packages/credentials/deepseek-account/tests/remote.spec.ts +++ b/packages/account/deepseek-account/tests/remote.spec.ts @@ -3,7 +3,6 @@ import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' -import type { Agent } from '@deepseek-ai/dsh-agent' import AuthorizationService from '@deepseek-ai/dsh-authorization' import { LocalCredentialProvider } from '@deepseek-ai/dsh-credentials-local' import { credentialKey } from '@deepseek-ai/dsh-credentials' @@ -70,18 +69,16 @@ it('delivers expiry only to current subscribers and stops on disconnect or provi expect(await reopened).toEqual({ done: true, value: undefined }) }) -it('reports running account requests and excludes absent, idle, and other-provider tasks', async () => { - const { ctx, account } = await fixture() +it('reports running account work through registered reports and forgets disposed ones', async () => { + const { account } = await fixture() expect(account.hasRunningAccountTasks()).toBe(false) - const active: Array> = [] - const task = (status: Agent['status'], provider?: string): Pick => ({ - status, session: { requestContext: () => provider === undefined ? undefined : { provider, model: 'model' } } as Agent['session'], - }) - ctx.provide('agents', { list: () => active } as Context['agents']) - active.push(task('running'), task('running', 'deepseek-official'), task('idle', 'deepseek-account')) + let running = false + const idle = account.registerRunningTaskReport(() => false) + const dispose = account.registerRunningTaskReport(() => running) expect(account.hasRunningAccountTasks()).toBe(false) - active.push(task('running', 'deepseek-account')) + running = true expect(account.hasRunningAccountTasks()).toBe(true) - active.pop() + dispose() expect(account.hasRunningAccountTasks()).toBe(false) + idle() }) diff --git a/packages/credentials/deepseek-account/tsconfig.json b/packages/account/deepseek-account/tsconfig.json similarity index 78% rename from packages/credentials/deepseek-account/tsconfig.json rename to packages/account/deepseek-account/tsconfig.json index e4add1d675..2c0bd9becb 100644 --- a/packages/credentials/deepseek-account/tsconfig.json +++ b/packages/account/deepseek-account/tsconfig.json @@ -18,16 +18,13 @@ "path": "../../util/brand" }, { - "path": "../../core/agent" + "path": "../../util/values" }, { - "path": "../../llm/llm" + "path": "../../credentials/authorization" }, { - "path": "../authorization" - }, - { - "path": "../credentials" + "path": "../../credentials/credentials" }, { "path": "../../../vendor/schemastery" diff --git a/packages/api/remotes/tsconfig.client.json b/packages/api/remotes/tsconfig.client.json index 2e82590c7a..bc8fc4f34d 100644 --- a/packages/api/remotes/tsconfig.client.json +++ b/packages/api/remotes/tsconfig.client.json @@ -113,7 +113,7 @@ "path": "../../document/office-kit" }, { - "path": "../../credentials/deepseek-account" + "path": "../../account/deepseek-account" }, { "path": "../../web/web" diff --git a/packages/api/remotes/tsconfig.host.json b/packages/api/remotes/tsconfig.host.json index 33a538658d..c05d497e60 100644 --- a/packages/api/remotes/tsconfig.host.json +++ b/packages/api/remotes/tsconfig.host.json @@ -90,7 +90,7 @@ "path": "../../host/plugin-inventory" }, { - "path": "../../credentials/deepseek-account" + "path": "../../account/deepseek-account" }, { "path": "../../web/web" diff --git a/packages/client/product-analytics/tsconfig.host.json b/packages/client/product-analytics/tsconfig.host.json index b4b4e831ab..e2d3803bd6 100644 --- a/packages/client/product-analytics/tsconfig.host.json +++ b/packages/client/product-analytics/tsconfig.host.json @@ -28,7 +28,7 @@ "path": "../../credentials/credentials" }, { - "path": "../../credentials/deepseek-account" + "path": "../../account/deepseek-account" }, { "path": "../../host/webserver" diff --git a/packages/client/ui-account-notifications/tsconfig.json b/packages/client/ui-account-notifications/tsconfig.json index 3d18f2dc37..6c2da05873 100644 --- a/packages/client/ui-account-notifications/tsconfig.json +++ b/packages/client/ui-account-notifications/tsconfig.json @@ -30,7 +30,7 @@ "path": "../ui-settings-account" }, { - "path": "../../credentials/deepseek-account" + "path": "../../account/deepseek-account" }, { "path": "../../host/webserver" diff --git a/packages/client/ui-settings-account/tsconfig.json b/packages/client/ui-settings-account/tsconfig.json index ac170f07db..d425a8cdea 100644 --- a/packages/client/ui-settings-account/tsconfig.json +++ b/packages/client/ui-settings-account/tsconfig.json @@ -36,7 +36,7 @@ "path": "../ui-theme/tsconfig.client.json" }, { - "path": "../../credentials/deepseek-account" + "path": "../../account/deepseek-account" }, { "path": "../ui-settings-models" diff --git a/packages/credentials/authorization/package.json b/packages/credentials/authorization/package.json index 8a9da04f8f..a3a4b26d5d 100644 --- a/packages/credentials/authorization/package.json +++ b/packages/credentials/authorization/package.json @@ -37,13 +37,13 @@ ], "license": "MIT", "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-credentials": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-credentials": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/credentials/authorization/src/index.ts b/packages/credentials/authorization/src/index.ts index f54e04896a..418c301543 100644 --- a/packages/credentials/authorization/src/index.ts +++ b/packages/credentials/authorization/src/index.ts @@ -28,7 +28,7 @@ import { Context, Service } from '@deepseek-ai/cordis' import type { CredentialKey, CredentialRecord } from '@deepseek-ai/dsh-credentials' -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' import type { AuthorizationEntry, AuthorizationMethod, AuthorizationNotice, AuthorizationOutcome, AuthorizationPrompt, diff --git a/packages/credentials/authorization/tsconfig.json b/packages/credentials/authorization/tsconfig.json index 414fd879c6..ec432a59c7 100644 --- a/packages/credentials/authorization/tsconfig.json +++ b/packages/credentials/authorization/tsconfig.json @@ -18,7 +18,7 @@ "path": "../credentials" }, { - "path": "../../llm/llm" + "path": "../../util/error" } ] } diff --git a/packages/credentials/credentials/README.i18n.yaml b/packages/credentials/credentials/README.i18n.yaml index 2b850ee561..1489c975f1 100644 --- a/packages/credentials/credentials/README.i18n.yaml +++ b/packages/credentials/credentials/README.i18n.yaml @@ -24,8 +24,8 @@ en: 8f3500119608f91b zh: 147fdb5389affbc0 /deepseek-ai-dsh-credentials/use-this-package/storing-checking-and-removing-keys: - en: 68096f3f256353ed - zh: 673608f5d5e66d66 + en: 9f6cf31d0fd281ac + zh: b20ac60e6cdd7527 /deepseek-ai-dsh-credentials/use-this-package/storing-updating-and-removing-records: en: 300c3f1f13abdca4 zh: ec7a6486ac88889c diff --git a/packages/credentials/credentials/README.md b/packages/credentials/credentials/README.md index 26e324c30b..845629e9e8 100644 --- a/packages/credentials/credentials/README.md +++ b/packages/credentials/credentials/README.md @@ -60,6 +60,8 @@ await ctx.credentials.unset(ref) // no-op when absent; an Store a key with `set`, remove it with `unset`, check its status with `describe`, and read the current value with `resolve` when an operation needs it. `describe` reports whether the key is set, where it comes from, and whether you can write to it — it never returns the value. Providers may disclose a masked stored-value preview through the optional `masked` field; the full value stays on the Host. +Consumers that must also work in compositions without a credentials service, such as the DeepSeek model and web providers, read references through `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`: a mounted service is authoritative, including when it holds no value, and only its absence makes them read the launch environment, where an empty value is absent. Store failures propagate, and callers validate the value's format. + ### Storing, updating, and removing records A plugin addresses each record by `/` — its own registered name plus an id it chooses, such as a provider route key — and reads, modifies, or removes what it holds: diff --git a/packages/credentials/credentials/README.zh.md b/packages/credentials/credentials/README.zh.md index 7aa8fc9d9e..bc03f641d7 100644 --- a/packages/credentials/credentials/README.zh.md +++ b/packages/credentials/credentials/README.zh.md @@ -60,6 +60,8 @@ await ctx.credentials.unset(ref) // no-op when absent; an 用 `set` 存储密钥、用 `unset` 移除、用 `describe` 检查状态、在操作需要时用 `resolve` 读取当前值。`describe` 报告密钥是否已设置、来自哪里、能否写入——它绝不返回值。提供方可通过可选的 `masked` 字段报告已保存值的脱敏预览;完整值留在 Host。 +必须在没有凭据服务的组合中也能工作的消费方(如 DeepSeek 模型与 Web 提供方)通过 `resolveCredentialRef(ctx, ref)` 和 `credentialRefConfigured(ctx, ref)` 读取引用:已挂载的服务具有权威性,包括它不持有值的情况;只有服务缺席时才读取启动环境,其中空值视为不存在。存储失败向上传播,值的格式由调用方校验。 + ### 存储、更新与移除记录 插件按 `/` 寻址每条记录——自身注册名加一个自选 id,例如提供方路由键——并读取、修改或移除它所持有的内容: diff --git a/packages/credentials/credentials/package.json b/packages/credentials/credentials/package.json index 4589152305..6c847e9587 100644 --- a/packages/credentials/credentials/package.json +++ b/packages/credentials/credentials/package.json @@ -35,10 +35,12 @@ ], "license": "MIT", "peerDependencies": { - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-launch-environment": "workspace:*" }, "devDependencies": { - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-launch-environment": "workspace:*" }, "dependencies": { "@deepseek-ai/dsh-brand": "workspace:*" diff --git a/packages/credentials/credentials/src/index.ts b/packages/credentials/credentials/src/index.ts index 8f6054a327..6190b7bc2a 100644 --- a/packages/credentials/credentials/src/index.ts +++ b/packages/credentials/credentials/src/index.ts @@ -10,6 +10,7 @@ import { Context, Service } from '@deepseek-ai/cordis' import { brandString } from '@deepseek-ai/dsh-brand' +import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' import type { CredentialInfo, CredentialKey, CredentialRecord, CredentialRef } from './types.ts' export type { @@ -151,6 +152,38 @@ declare module '@deepseek-ai/cordis' { } } +/** + * Read one reference's current value through the mounted credentials service, + * or through the launch environment when the composition mounts no service. A + * mounted service is authoritative, including when it holds no value: the + * environment is read only when there is no service to ask, which is how + * one-shot compositions without the store authenticate from their launching + * shell. Empty values are absent. Store failures propagate; callers validate + * the value's format. + * @param ctx - context providing the optional credentials service and the launch environment. + * @param ref - the reference to read. + * @returns the value, or `undefined` while unconfigured. + */ +export async function resolveCredentialRef(ctx: Context, ref: CredentialRef): Promise { + const credentials = ctx.get('credentials') + if (credentials !== undefined) return (await credentials.resolve(ref))?.value + const ambient = launchEnvironmentOf(ctx).get(ref)?.value + return ambient === undefined || ambient.length === 0 ? undefined : ambient +} + +/** + * Report whether a reference is configured without reading its value, through + * the same source {@link resolveCredentialRef} reads. Store failures propagate. + * @param ctx - context providing the optional credentials service and the launch environment. + * @param ref - the reference to inspect. + * @returns whether the authoritative source holds a value for the reference. + */ +export async function credentialRefConfigured(ctx: Context, ref: CredentialRef): Promise { + const credentials = ctx.get('credentials') + if (credentials !== undefined) return (await credentials.describe(ref)).configured + return (launchEnvironmentOf(ctx).get(ref)?.value.length ?? 0) > 0 +} + /** * Abstract credential service over two key spaces that answer two questions. * diff --git a/packages/credentials/credentials/tests/reference-fallback.spec.ts b/packages/credentials/credentials/tests/reference-fallback.spec.ts new file mode 100644 index 0000000000..3bfc12d435 --- /dev/null +++ b/packages/credentials/credentials/tests/reference-fallback.spec.ts @@ -0,0 +1,50 @@ +/** Reference reads fall back to the launch environment only when no credentials service is mounted. */ +import { Context } from '@deepseek-ai/cordis' +import { describe, expect, it, vi } from 'vitest' +import { createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY } from '@deepseek-ai/dsh-launch-environment' +import { credentialRef, credentialRefConfigured, resolveCredentialRef } from '../src/index.ts' +import { MemoryCredentials } from './memory.ts' + +const ref = credentialRef('TEST_PROVIDER_KEY') + +function context(value?: string): Context { + const ctx = new Context() + ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([ + { source: 'process', values: value === undefined ? {} : { [ref]: value } }, + ])) + return ctx +} + +describe('reference reads without a credentials service', () => { + it.each([undefined, '', 'ambient-key'])('read the launch environment, treating empty as absent: %j', async (value) => { + const ctx = context(value) + try { + await expect(resolveCredentialRef(ctx, ref)).resolves.toBe(value ? value : undefined) + await expect(credentialRefConfigured(ctx, ref)).resolves.toBe(Boolean(value)) + } finally { await ctx.fiber.dispose() } + }) +}) + +describe('reference reads with a credentials service', () => { + it('treat the service as authoritative, including its absence of a value', async () => { + const ctx = context('ambient-key') + const resolve = vi.fn(async () => undefined) + const describeRef = vi.fn(async () => ({ configured: false, writable: true })) + ctx.provide('credentials', { resolve, describe: describeRef } as never) + try { + await expect(credentialRefConfigured(ctx, ref)).resolves.toBe(false) + expect(resolve).not.toHaveBeenCalled() + await expect(resolveCredentialRef(ctx, ref)).resolves.toBeUndefined() + expect(resolve).toHaveBeenCalledExactlyOnceWith(ref) + } finally { await ctx.fiber.dispose() } + }) + + it('return the stored value verbatim on every read', async () => { + const ctx = context('ambient-key') + await ctx.plugin(MemoryCredentials, { [ref]: ' stored-key ' }) + try { + await expect(resolveCredentialRef(ctx, ref)).resolves.toBe(' stored-key ') + await expect(credentialRefConfigured(ctx, ref)).resolves.toBe(true) + } finally { await ctx.fiber.dispose() } + }) +}) diff --git a/packages/credentials/credentials/tsconfig.json b/packages/credentials/credentials/tsconfig.json index 342f636170..e984ba2b9d 100644 --- a/packages/credentials/credentials/tsconfig.json +++ b/packages/credentials/credentials/tsconfig.json @@ -16,6 +16,9 @@ }, { "path": "../../util/brand" + }, + { + "path": "../../util/launch-environment" } ] } diff --git a/packages/credentials/deepseek-account/src/account-tasks.ts b/packages/credentials/deepseek-account/src/account-tasks.ts deleted file mode 100644 index 6325571dd5..0000000000 --- a/packages/credentials/deepseek-account/src/account-tasks.ts +++ /dev/null @@ -1,35 +0,0 @@ -/** Account sign-out policy over the latest logged request route. */ -import type { Context } from '@deepseek-ai/cordis' -import { LlmError } from '@deepseek-ai/dsh-llm' -import type { Agent } from '@deepseek-ai/dsh-agent' -import type {} from './index.ts' - -/** - * Identify running work whose latest bound request used the account route. - * @param agent - live Agent with its durable request context. - * @returns whether account sign-out should interrupt this task. - */ -export function isRunningAccountTask(agent: Pick): boolean { - return agent.status === 'running' && agent.session.requestContext()?.provider === 'deepseek-account' -} - -/** - * Cancel signed-out account tasks and publish sign-in guidance for rejected requests. - * @param ctx - account provider lifetime; Agents may attach later. - */ -export function installAccountTaskCancellation(ctx: Context): void { - ctx.inject(['agents'], (scope) => { - scope.on('agent/error', ({ error }) => { - if (error instanceof LlmError && error.code === 'ACCOUNT_SIGN_IN_REQUIRED') { - scope.emit('deepseek-account/model-sign-in-required') - } - }) - scope.on('deepseek-account/signed-out', () => { - for (const agent of scope.agents.list()) { - if (isRunningAccountTask(agent)) { - agent.cancel({ kind: 'hook', reason: 'deepseek-account/signed-out' }, { keepInbox: true }) - } - } - }) - }) -} diff --git a/packages/experimental/translator/tests/paid-fixture.ts b/packages/experimental/translator/tests/paid-fixture.ts index 82d45d3a5d..bb2235c338 100644 --- a/packages/experimental/translator/tests/paid-fixture.ts +++ b/packages/experimental/translator/tests/paid-fixture.ts @@ -7,7 +7,6 @@ import * as JsonlPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import SqliteSessionQuery from '@deepseek-ai/dsh-session-query-sqlite' import * as Official from '@deepseek-ai/dsh-llm-deepseek-api-key' import * as Account from '@deepseek-ai/dsh-llm-deepseek-account' -import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' import DeepSeekLlmApiExtensionRegistry from '@deepseek-ai/dsh-deepseek-llm-api-extensions' import * as SessionLogDeepSeek from '@deepseek-ai/dsh-session-log-deepseek' import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' @@ -17,6 +16,7 @@ import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import Translator, { type Config } from '../src/index.ts' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' /** Provider-visible request, without credential values. */ export interface NativeRequest { @@ -170,9 +170,7 @@ export async function paidFixture(cleanups: Array<() => Promise>, options: describe: async () => ({ configured, writable: true }), resolve: async () => configured ? { value: 'fixture-native-key', source: 'fixture' } : undefined, } as never) - host.provide('deepseekAccount', { - resolveToken: async (_baseURL: string): Promise => signedIn ? 'fixture-account-token' : undefined, - } as DeepSeekAccount) + host.provide('deepseekAccount', accountStub({ token: () => signedIn ? 'fixture-account-token' : undefined })) }) let ctx = await start(), session: Session | undefined cleanups.push(async () => { await ctx.fiber.dispose() }) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index d0397ec2f8..ba605d4539 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1041,6 +1041,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'url', description: 'actual request destination or API base URL.' }], returns: 'stored token, or undefined for other origins or a signed-out account.', }, + { + signature: 'async resolveRequestCredential(url: string): Promise', + description: 'Release the account credential for one request to `url` as the request carries it, together with its invalidation. Host-only.', + parameters: [{ name: 'url', description: 'actual request destination or API base URL.' }], + returns: 'the request credential, or undefined for other origins or a signed-out account.', + }, { signature: '@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: \'web\' | \'desktop\'): Promise', description: 'Join an active attempt or start browser authorization.', @@ -1059,11 +1065,17 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'client', description: 'identity of the requesting UI, captured for the background revocation retries.' }], returns: 'the signed-out state after local removal; remote failures never restore the grant.', }, + { + signature: 'registerRunningTaskReport(report: () => boolean): () => void', + description: 'Register a report of running work that signing out would interrupt. The plugin billing the account to a model route registers one from within `ctx.effect()`; without any report nothing is known to be running.', + parameters: [{ name: 'report', description: 'answers whether such work is running now.' }], + returns: 'the disposer removing the report.', + }, { signature: '@Remote hasRunningAccountTasks(): boolean', description: 'Inspect running work before sign-out.', parameters: [], - returns: 'whether a running task\'s latest request uses the account route; false when the optional agents service is absent.', + returns: 'whether a registered report says a running task uses the account; false without reports.', }, { signature: '@Remote({ mode: \'stream\' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<\'session-expired\'>', @@ -2154,6 +2166,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'provider', description: 'registered provider route.' }, { name: 'model', description: 'exact model id.' }, { name: 'image', description: 'normalized image reference.' }], returns: 'dimensions and byte target used by the adapter\'s request serializer.', }, + { + signature: 'routeCredential(provider: string): RouteCredential | undefined', + description: 'Resolve the credential one registered route currently sends, through its owning adapter. An unregistered route answers `undefined` rather than throwing because callers ask about routes a conversation named earlier, which may no longer be mounted; a registered route whose configuration does not resolve propagates the adapter\'s failure.', + parameters: [{ name: 'provider', description: 'provider route whose credential is wanted.' }], + returns: 'the route credential, or `undefined` when the route is unregistered or publishes none.', + }, { signature: 'fileRequestText(ref: FileAttachmentRef): string', description: 'Resolve the exact text one durable file occurrence contributes to every provider request in the current execution environment.', @@ -5761,6 +5779,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'AccountProfile', declaration: 'export interface AccountProfile {\n readonly id: AccountUserId | null;\n readonly name: string | null;\n readonly contact: string | null;\n readonly avatarUrl?: string | null;\n}', }, + { + name: 'AccountRequestCredential', + declaration: 'export interface AccountRequestCredential {\n readonly headers: Readonly>;\n readonly value: string;\n reject(): Promise;\n}', + }, { name: 'AccountUpdate', declaration: 'export interface AccountUpdate {\n readonly type: \'snapshot\' | \'credentials-changed\';\n readonly state: AccountView;\n}', @@ -7375,7 +7397,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'LlmAdapter', - declaration: 'export abstract class LlmAdapter {\n providerInfo(provider: string): LlmProviderInfo;\n providerRetryPolicy(_provider: string): ResolvedRetryPolicy | undefined;\n imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget;\n listModels(_provider: string): Promise;\n resolveModel(provider: string, model: string, _signal?: AbortSignal): Promise;\n async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise;\n abstract stream(options: GenerateOptions): AsyncIterable;\n}', + declaration: 'export abstract class LlmAdapter {\n providerInfo(provider: string): LlmProviderInfo;\n providerRetryPolicy(_provider: string): ResolvedRetryPolicy | undefined;\n imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget;\n routeCredential(_provider: string): RouteCredential | undefined;\n listModels(_provider: string): Promise;\n resolveModel(provider: string, model: string, _signal?: AbortSignal): Promise;\n async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise;\n abstract stream(options: GenerateOptions): AsyncIterable;\n}', }, { name: 'LlmAttemptId', @@ -7397,6 +7419,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'LlmConfigurableProvider', declaration: 'export interface LlmConfigurableProvider {\n provider: string;\n displayName: string;\n settingsNs: string;\n settingsPath: readonly string[];\n declared?: boolean;\n defaultBaseURL?: string;\n baseURLEnv?: readonly string[];\n nativeAuth?: LlmNativeAuth;\n error?: string;\n}', }, + { + name: 'LlmCredentialKind', + declaration: 'export type LlmCredentialKind = LlmCredentialKindMap[keyof LlmCredentialKindMap];', + }, + { + name: 'LlmCredentialKindMap', + declaration: 'export interface LlmCredentialKindMap {\n \'api-key\': \'api-key\';\n account: \'account\';\n}', + }, { name: 'LlmDiscoveredModel', declaration: 'export interface LlmDiscoveredModel {\n id: string;\n name?: string;\n contextWindow?: number;\n maxTokens?: number;\n inputModalities?: readonly ModelModality[];\n}', @@ -7463,7 +7493,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'LlmRuntime', - declaration: 'export class LlmRuntime extends TypertRemoteService {\n constructor(ctx: Context);\n registerAdapter(providers: string[], adapter: LlmAdapter): AdapterRegistrationHandle;\n @Remote\n listProviders(): LlmProviderInfo[];\n registerConfigurableProviders(entries: readonly LlmConfigurableProvider[]): DirectoryRegistrationHandle;\n @Remote\n listConfigurableProviders(): LlmConfigurableProvider[];\n registerModelDiscovery(settingsNs: string, discover: (request: LlmModelDiscoveryRequest, signal?: AbortSignal) => Promise): () => void;\n async discoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal?: AbortSignal): Promise;\n @Remote(\'discoverModels\')\n async remoteDiscoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal: AbortSignal): Promise;\n providerRetryPolicy(provider: string): ResolvedRetryPolicy;\n imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget;\n fileRequestText(ref: FileAttachmentRef): string;\n async listModels(provider: string): Promise;\n async resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise;\n async resolveCallConfig(config: LlmCallConfig, signal?: AbortSignal): Promise;\n async prepareCall(conf /* …truncated — full shape in source */', + declaration: 'export class LlmRuntime extends TypertRemoteService {\n constructor(ctx: Context);\n registerAdapter(providers: string[], adapter: LlmAdapter): AdapterRegistrationHandle;\n @Remote\n listProviders(): LlmProviderInfo[];\n registerConfigurableProviders(entries: readonly LlmConfigurableProvider[]): DirectoryRegistrationHandle;\n @Remote\n listConfigurableProviders(): LlmConfigurableProvider[];\n registerModelDiscovery(settingsNs: string, discover: (request: LlmModelDiscoveryRequest, signal?: AbortSignal) => Promise): () => void;\n async discoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal?: AbortSignal): Promise;\n @Remote(\'discoverModels\')\n async remoteDiscoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal: AbortSignal): Promise;\n providerRetryPolicy(provider: string): ResolvedRetryPolicy;\n imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget;\n routeCredential(provider: string): RouteCredential | undefined;\n fileRequestText(ref: FileAttachmentRef): string;\n async listModels(provider: string): Promise;\n async resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise;\n async resolveCallConfig(config: LlmCallConfig, signa /* …truncated — full shape in source */', }, { name: 'LocalAtInput', @@ -8557,6 +8587,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ReviewVerdict', declaration: 'export type ReviewVerdict = \'approved\' | \'changes-requested\' | \'commented\' | \'dismissed\';', }, + { + name: 'RouteCredential', + declaration: 'export interface RouteCredential {\n readonly kind: LlmCredentialKind;\n readonly baseURL: string;\n readonly reference?: string;\n configured(endpoint: string): Promise;\n resolve(endpoint: string, signal?: AbortSignal): Promise;\n}', + }, + { + name: 'RouteCredentialGrant', + declaration: 'export interface RouteCredentialGrant {\n readonly headers: Readonly>;\n readonly value: string;\n reject?(): Promise;\n}', + }, { name: 'RpcId', declaration: 'export type RpcId = Branded<\'rpc-id\'>;', diff --git a/packages/llm/llm-deepseek-account/README.i18n.yaml b/packages/llm/llm-deepseek-account/README.i18n.yaml index ade47b1cf3..b2cab10d84 100644 --- a/packages/llm/llm-deepseek-account/README.i18n.yaml +++ b/packages/llm/llm-deepseek-account/README.i18n.yaml @@ -9,17 +9,17 @@ en: 8fa1148e0ee9d351 zh: 634ec9d79d5ffbf0 /deepseek-ai-dsh-llm-deepseek-account/summary: - en: b80e34cdfb51009d - zh: eda44bcc181793d8 + en: 90635454957391b0 + zh: 815bf79ba6056c3c /deepseek-ai-dsh-llm-deepseek-account/table-of-contents: en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 /deepseek-ai-dsh-llm-deepseek-account/use-this-package: - en: b1a9453e08198023 - zh: 630e7f566ad4d9db + en: 3d952599a9b0bf85 + zh: 231c0331a7d217e3 /deepseek-ai-dsh-llm-deepseek-account/understand-the-implementation: - en: 06629c312d0cb860 - zh: f33b2773b0ab1d25 + en: ee65c14a90dfa0dd + zh: 91778b3e940da7f7 /deepseek-ai-dsh-llm-deepseek-account/further-exploration: en: 30a69b9c66d89580 zh: fcc026a6373c1bee diff --git a/packages/llm/llm-deepseek-account/README.md b/packages/llm/llm-deepseek-account/README.md index d6397a8c5f..9b5ee9f706 100644 --- a/packages/llm/llm-deepseek-account/README.md +++ b/packages/llm/llm-deepseek-account/README.md @@ -11,7 +11,7 @@ English | [中文](README.zh.md) Register authentication, the account model listing, and model gating for `deepseek-account`. This plugin shares the [Messages transport](../llm-deepseek/README.md) and owns credential resolution, the account catalog, and model admission. -Authentication resolution returns `x-dsh-auth-token` and a failure callback capturing the same token. HTTP 401 classification and rejection stay in this provider; a rejected older request cannot clear a replacement login. +Authentication resolution returns the request credential the account service releases for the destination, carrying `x-dsh-auth-token`, with a failure callback that invalidates that same credential. HTTP 401 classification stays in this provider; a rejected older request cannot clear a replacement login. The route publishes the account credential through `ctx.llm.routeCredential('deepseek-account')` with its base URL, so the DeepSeek web providers send it to the same deployment. ## Table of Contents @@ -25,7 +25,7 @@ Authentication resolution returns `x-dsh-auth-token` and a failure callback capt ## Use this package -Only `deepseekAccount.resolveToken(url)` supplies the token; the account service validates the destination. Signed-out or ineligible requests fail with `ACCOUNT_SIGN_IN_REQUIRED` and discovery returns an empty catalog. The route never falls back to an API key. Other credential lookup errors propagate. +Only `deepseekAccount.resolveRequestCredential(url)` supplies the credential; the account service validates the destination. Signed-out or ineligible requests fail with `ACCOUNT_SIGN_IN_REQUIRED` and discovery returns an empty catalog. The route never falls back to an API key. Other credential lookup errors propagate. The route's catalog comes from the account's `GET /models` listing at the origin of the Messages `baseURL` (`https://api.deepseek.com/models` for the official endpoint); the listing endpoint is not configurable. Listing requests carry the account token in `x-dsh-auth-token` and the harness `User-Agent`, and reject redirects. @@ -56,14 +56,14 @@ An offered model shows the badge its listing entry declares under `client_metada | `modelsMaxAgeMs` | `600,000` | Automatic refresh interval after first use, also used after failure; `0` refreshes on access only | | `modelOverrides` | `{}` | Field overrides by model id | -An account request HTTP 401 maps to `ACCOUNT_TOKEN_INVALID` independently of the response body. The account service removes the credential only if it still matches the request token. HTTP 403 and other failures do not clear the login. The account module owns task cancellation after sign-out; this plugin does not inspect Agents. +An account request HTTP 401 maps to `ACCOUNT_TOKEN_INVALID` independently of the response body. The account service removes the credential only if it still matches the request token. HTTP 403 and other failures do not clear the login. After `deepseek-account/signed-out`, this plugin cancels running Agents whose latest bound request used this route, keeping their inboxes; it publishes `deepseek-account/model-sign-in-required` for a request that fails with `ACCOUNT_SIGN_IN_REQUIRED`, and registers a running-task report with the account service so its sign-out confirmation knows about that work. The settings namespace is the Cordis entry id, or the plugin name without an entry. Product profiles retain the official entry id `llm-deepseek` and use `llm-deepseek-account` for the account route. ## Understand the implementation -Account-token lookup and invalidation use the [shared credential helpers](../llm-deepseek/src/credential.ts); this plugin retains HTTP error classification. Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport, which the API-key route also uses; the cache lives in memory and is keyed by endpoint and a SHA-256 of the token. +Account credential lookup and invalidation go through the account service's `resolveRequestCredential`; this plugin retains HTTP error classification and owns the sign-out policy over running Agents in [`account-tasks.ts`](src/account-tasks.ts). Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport, which the API-key route also uses; the cache lives in memory and is keyed by endpoint and a SHA-256 of the token. A failed request the shared transport classifies as `QUOTA` is rewritten to `ACCOUNT_QUOTA` before it leaves this provider, covering an HTTP 402 response and an in-band SSE error alike. The shared transport and the `deepseek-official` route keep `QUOTA`, so the account route's top-up action never appears for an API-key or third-party failure. diff --git a/packages/llm/llm-deepseek-account/README.zh.md b/packages/llm/llm-deepseek-account/README.zh.md index a2407afbda..2f6958d366 100644 --- a/packages/llm/llm-deepseek-account/README.zh.md +++ b/packages/llm/llm-deepseek-account/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" 为 `deepseek-account` 注册鉴权、账号模型列表和模型门控。通过 [llm-deepseek](../llm-deepseek/README.zh.md) 共用 Messages 请求实现;本包负责凭据解析、账号目录和模型准入。 -鉴权解析返回 `x-dsh-auth-token` 和捕获同一 token 的失败回调。HTTP 401 的分类和凭据失效处理由此提供方负责;被拒绝的旧请求不能清除替换后的登录。 +鉴权解析返回账号服务为目标地址释放的请求凭据,携带 `x-dsh-auth-token`,并附带使同一凭据失效的失败回调。HTTP 401 的分类由此提供方负责;被拒绝的旧请求不能清除替换后的登录。路由通过 `ctx.llm.routeCredential('deepseek-account')` 连同其基础地址发布账号凭据,使 DeepSeek Web 提供方把它发往同一部署。 ## 目录 @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用此包 -账号 token 仅由 `deepseekAccount.resolveToken(url)` 提供,目标地址必须通过账号服务的来源校验。未登录或目标不允许账号鉴权时,请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,目录为空;不会回退到 API key。其他凭据查询错误继续向调用者报告。 +账号凭据仅由 `deepseekAccount.resolveRequestCredential(url)` 提供,目标地址必须通过账号服务的来源校验。未登录或目标不允许账号鉴权时,请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,目录为空;不会回退到 API key。其他凭据查询错误继续向调用者报告。 路由的目录来自账号的 `GET /models` 列表,地址为 Messages `baseURL` 的 origin 加 `/models`(官方端点即 `https://api.deepseek.com/models`),不可配置。列表请求用 `x-dsh-auth-token` 携带账号 token,带上 harness 的 `User-Agent`,并拒绝重定向。 @@ -56,14 +56,14 @@ kind: "package-reference" | `modelsMaxAgeMs` | `600,000` | 首次使用后的自动刷新间隔,失败后也按此间隔重试;`0` 表示只在访问时刷新 | | `modelOverrides` | `{}` | 按模型 id 的字段覆盖 | -账号请求的 HTTP 401 与响应正文无关:映射为 `ACCOUNT_TOKEN_INVALID`,并要求账号服务仅在当前 token 仍与请求所用 token 相同时清除凭据。403 和其他错误不会触发清除。账号模块负责退登后打断任务,本插件不遍历 Agent。 +账号请求的 HTTP 401 与响应正文无关:映射为 `ACCOUNT_TOKEN_INVALID`,并要求账号服务仅在当前 token 仍与请求所用 token 相同时清除凭据。403 和其他错误不会触发清除。`deepseek-account/signed-out` 之后,本插件取消最近一次绑定请求使用本路由的运行中 Agent 并保留其收件箱;请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败时发布 `deepseek-account/model-sign-in-required`,并向账号服务注册运行中任务报告,供其退登确认了解这些工作。 设置命名空间采用 Cordis entry id,没有 entry 时采用插件名。产品保留 official 的 `llm-deepseek` entry id,账号使用 `llm-deepseek-account`。 ## 理解实现 -账号 token 读取与作废使用[共享凭据函数](../llm-deepseek/src/credential.ts);本插件保留 HTTP 错误分类。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入目录和门控。列表请求、缓存和目录解析来自共享传输包,API key 路由也使用它们;缓存只在内存中,以端点和 token 的 SHA-256 为键。 +账号凭据的读取与作废经由账号服务的 `resolveRequestCredential`;本插件保留 HTTP 错误分类,并在 [`account-tasks.ts`](src/account-tasks.ts) 中拥有针对运行中 Agent 的退登策略。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入目录和门控。列表请求、缓存和目录解析来自共享传输包,API key 路由也使用它们;缓存只在内存中,以端点和 token 的 SHA-256 为键。 共享传输判定为 `QUOTA` 的失败请求离开本提供方前会被改写为 `ACCOUNT_QUOTA`,HTTP 402 响应与流内 SSE 错误都适用。共享传输与 `deepseek-official` 路由保留 `QUOTA`,因此账号路由的充值操作不会出现在 API Key 或第三方失败上。 diff --git a/packages/llm/llm-deepseek-account/package.json b/packages/llm/llm-deepseek-account/package.json index 96895b0c3d..3a3765d94c 100644 --- a/packages/llm/llm-deepseek-account/package.json +++ b/packages/llm/llm-deepseek-account/package.json @@ -41,7 +41,8 @@ "@deepseek-ai/dsh-llm-deepseek": "workspace:*", "@deepseek-ai/dsh-launch-environment": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", - "@deepseek-ai/cordis-plugin-loader": "workspace:~" + "@deepseek-ai/cordis-plugin-loader": "workspace:~", + "@deepseek-ai/dsh-agent": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", @@ -51,7 +52,8 @@ "@deepseek-ai/dsh-deepseek-account": "workspace:*", "@deepseek-ai/cordis-plugin-loader": "workspace:~", "@deepseek-ai/dsh-llm-deepseek-api-key": "workspace:*", - "@deepseek-ai/dsh-timeout": "workspace:*" + "@deepseek-ai/dsh-timeout": "workspace:*", + "@deepseek-ai/dsh-agent": "workspace:*" }, "peerDependenciesMeta": { "@deepseek-ai/dsh-deepseek-account": { @@ -59,6 +61,9 @@ }, "@deepseek-ai/cordis-plugin-loader": { "optional": true + }, + "@deepseek-ai/dsh-agent": { + "optional": true } } } diff --git a/packages/llm/llm-deepseek-account/src/account-tasks.ts b/packages/llm/llm-deepseek-account/src/account-tasks.ts new file mode 100644 index 0000000000..00843ce2be --- /dev/null +++ b/packages/llm/llm-deepseek-account/src/account-tasks.ts @@ -0,0 +1,40 @@ +/** Account sign-out policy over the latest logged request route of each running Agent. */ +import type { Context } from '@deepseek-ai/cordis' +import { LlmError } from '@deepseek-ai/dsh-llm' +import type { Agent } from '@deepseek-ai/dsh-agent' +import type {} from '@deepseek-ai/dsh-deepseek-account' + +/** Whether a running Agent's latest bound request used the account route `provider`. */ +function isRunningAccountTask(agent: Pick, provider: string): boolean { + return agent.status === 'running' && agent.session.requestContext()?.provider === provider +} + +/** + * Cancel signed-out account tasks, publish sign-in guidance for rejected + * requests, and report running account work to the account service's + * sign-out confirmation. Each listener attaches once the service it needs is + * mounted and detaches with this plugin. + * @param ctx - account route plugin lifetime; Agents and the account service may attach later. + * @param provider - the account route id this plugin registers. + */ +export function installAccountTaskCancellation(ctx: Context, provider: string): void { + ctx.inject(['agents'], (scope) => { + scope.on('agent/error', ({ error }) => { + if (error instanceof LlmError && error.code === 'ACCOUNT_SIGN_IN_REQUIRED') { + scope.emit('deepseek-account/model-sign-in-required') + } + }) + scope.on('deepseek-account/signed-out', () => { + for (const agent of scope.agents.list()) { + if (isRunningAccountTask(agent, provider)) { + agent.cancel({ kind: 'hook', reason: 'deepseek-account/signed-out' }, { keepInbox: true }) + } + } + }) + scope.inject(['deepseekAccount'], (reporting) => { + reporting.effect(() => reporting.deepseekAccount.registerRunningTaskReport( + () => reporting.agents.list().some(agent => isRunningAccountTask(agent, provider)), + ), 'llm-deepseek-account: running task report') + }) + }) +} diff --git a/packages/llm/llm-deepseek-account/src/index.ts b/packages/llm/llm-deepseek-account/src/index.ts index bda73bceda..e4d77e1e6e 100644 --- a/packages/llm/llm-deepseek-account/src/index.ts +++ b/packages/llm/llm-deepseek-account/src/index.ts @@ -2,22 +2,20 @@ import type {} from '@deepseek-ai/cordis-plugin-loader' import type { Context } from '@deepseek-ai/cordis' import { ACCOUNT_QUOTA_EXCEEDED_CODE, APP_IDENTITY, LlmError, QUOTA_EXCEEDED_CODE } from '@deepseek-ai/dsh-llm' -import type {} from '@deepseek-ai/dsh-deepseek-account' +import type { AccountRequestCredential } from '@deepseek-ai/dsh-deepseek-account' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' import { - catalogModelInfo, createModelListingCache, refuseListedModel, registerDeepSeekProvider, requestModelListing, resolveAdapterOptions, - resolveListedCatalog, rejectDeepSeekAccountToken, resolveDeepSeekAccountToken, + catalogModelInfo, createModelListingCache, refuseListedModel, registerDeepSeekProvider, resolveAdapterOptions, resolveListedCatalog, } from '@deepseek-ai/dsh-llm-deepseek' import type { DeepSeekRequestAuth, ListedCatalog, ListingView, ModelListing, ResolvedDeepSeekOptions } from '@deepseek-ai/dsh-llm-deepseek' +import { installAccountTaskCancellation } from './account-tasks.ts' import { Config, plainAccountOptions, resolveAccountOptions } from './config.ts' -export { Config, plainAccountOptions, resolveAccountOptions } from './config.ts' +export { Config } from './config.ts' export const name = 'llm-deepseek-account' export const inject = ['llm'] const PROVIDER = 'deepseek-account' -/** Header carrying the account token on Messages, Files, and model-listing requests. */ -const TOKEN_HEADER = 'x-dsh-auth-token' /** Console tag of listing diagnostics; product profiles mount no console exporter for `ctx.logger`. */ const LOG_TAG = '[llm-deepseek-account]' @@ -31,11 +29,14 @@ export function apply(ctx: Context, config: Config): void { const settings = () => resolveAccountOptions(plainAccountOptions(config), environment) settings() const supported = resolveAdapterOptions({}).models - const resolveAuth = async (connection: ResolvedDeepSeekOptions): Promise => { - const token = await resolveDeepSeekAccountToken(ctx, connection.baseURL) - if (token === undefined) throw new LlmError('Sign in to DeepSeek to use the account provider. The request destination must allow account authentication.', 'ACCOUNT_SIGN_IN_REQUIRED') + /** The account credential released for one destination; absent without an allowed signed-in account or without the account service. */ + const requestCredential = async (endpoint: string): Promise => + await ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint) + const resolveAuth = async (_connection: ResolvedDeepSeekOptions, endpoint: string): Promise => { + const credential = await requestCredential(endpoint) + if (credential === undefined) return undefined return { - headers: { [TOKEN_HEADER]: token }, + ...credential, onRequestError: async (error) => { if (!(error instanceof LlmError)) return error if (error.code === QUOTA_EXCEEDED_CODE) { @@ -43,15 +44,18 @@ export function apply(ctx: Context, config: Config): void { } if (error.failure.status !== 401) return error const rejected = new LlmError(error.message, 'ACCOUNT_TOKEN_INVALID', { ...error.failure, cause: error }) - await rejectDeepSeekAccountToken(ctx, token) + await credential.reject() return rejected }, } } + const missingCredential = () => new LlmError( + 'Sign in to DeepSeek to use the account provider. The request destination must allow account authentication.', + 'ACCOUNT_SIGN_IN_REQUIRED', + ) const catalog = createModelListingCache(ctx, name, PROVIDER, { settings: () => settings().catalog, - credential: url => resolveDeepSeekAccountToken(ctx, url), - load: (url, token, signal) => requestModelListing(url, { [TOKEN_HEADER]: token }, signal), + credential: async url => (await requestCredential(url))?.headers, }) let loggedListing: ModelListing | undefined /** Resolve the catalog, reporting each listing's hidden entries and dropped badges once. */ @@ -88,6 +92,11 @@ export function apply(ctx: Context, config: Config): void { options: () => connectionOf(catalog.current()), connect: async signal => connectionOf(await catalog.view(settings().catalog, signal)), resolveAuth, + missingCredential, + credential: { + kind: 'account', + configured: async (_connection, endpoint) => (await requestCredential(endpoint)) !== undefined, + }, admit: (connection, model) => { refuseListedModel(model, connection.catalog.refusals.get(model)) }, discoverModels: async (provider) => { const view = await catalog.view(settings().catalog) @@ -96,4 +105,5 @@ export function apply(ctx: Context, config: Config): void { return offered.map(model => catalogModelInfo(provider, model, badges.get(model.id))) }, }) + installAccountTaskCancellation(ctx, PROVIDER) } diff --git a/packages/llm/llm-deepseek-account/tests/account-quota.spec.ts b/packages/llm/llm-deepseek-account/tests/account-quota.spec.ts index 41bd00a4c0..81870b249c 100644 --- a/packages/llm/llm-deepseek-account/tests/account-quota.spec.ts +++ b/packages/llm/llm-deepseek-account/tests/account-quota.spec.ts @@ -1,7 +1,7 @@ /** Account-route quota classification stays separate from API-key and third-party quota. */ import { Context } from '@deepseek-ai/cordis' import { BlockAssembler, LlmRuntime } from '@deepseek-ai/dsh-llm' -import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' import * as ApiKey from '@deepseek-ai/dsh-llm-deepseek-api-key' import { afterEach, expect, it, vi } from 'vitest' import * as Account from '../src/index.ts' @@ -33,10 +33,7 @@ async function routeFor(token: string | undefined, provider: 'deepseek-account' const ctx = new Context() contexts.push(ctx) await ctx.plugin(LlmRuntime) - ctx.provide('deepseekAccount', { - resolveToken: async (_baseURL: string): Promise => token, - rejectToken: async (_token: string): Promise => {}, - } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => token })) await ctx.plugin(provider === 'deepseek-account' ? Account : ApiKey) return ctx } @@ -71,10 +68,7 @@ it('still expires the stored credential on an account-route 401', async () => { contexts.push(ctx) await ctx.plugin(LlmRuntime) const rejectToken = vi.fn(async (_token: string): Promise => {}) - ctx.provide('deepseekAccount', { - resolveToken: async (_baseURL: string): Promise => 'account-token', - rejectToken: (token: string): Promise => rejectToken(token), - } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => 'account-token', reject: rejectToken })) await ctx.plugin(Account) vi.spyOn(globalThis, 'fetch').mockImplementation(messagesOnly(() => new Response('Unauthorized', { status: 401 }))) await expect(finishOf(ctx, 'deepseek-account')).resolves.toMatchObject({ diff --git a/packages/credentials/deepseek-account/tests/account-tasks.spec.ts b/packages/llm/llm-deepseek-account/tests/account-tasks.spec.ts similarity index 78% rename from packages/credentials/deepseek-account/tests/account-tasks.spec.ts rename to packages/llm/llm-deepseek-account/tests/account-tasks.spec.ts index 14b9653b33..220f39cf37 100644 --- a/packages/credentials/deepseek-account/tests/account-tasks.spec.ts +++ b/packages/llm/llm-deepseek-account/tests/account-tasks.spec.ts @@ -1,4 +1,4 @@ -/** Account cancellation follows logged routes and the owning plugin lifetime. */ +/** Account cancellation and running-task reports follow logged routes and the owning plugin lifetime. */ import { Context } from '@deepseek-ai/cordis' import { LlmError } from '@deepseek-ai/dsh-llm' import { expect, it, vi } from 'vitest' @@ -16,9 +16,17 @@ it('cancels running account tasks with their inboxes retained and detaches with { status: 'running', session: { requestContext: () => undefined }, cancel: cancelOther }, ] ctx.provide('agents', { list: () => tasks } as never) - const owner = ctx.plugin((scope) => { installAccountTaskCancellation(scope) }) + const reports = new Set<() => boolean>() + ctx.provide('deepseekAccount', { + registerRunningTaskReport: (report: () => boolean) => { reports.add(report); return () => { reports.delete(report) } }, + } as never) + const owner = ctx.plugin((scope) => { installAccountTaskCancellation(scope, 'deepseek-account') }) try { await owner.await() + expect([...reports].map(report => report())).toEqual([true]) + tasks[0]!.status = 'idle' + expect([...reports].map(report => report())).toEqual([false]) + tasks[0]!.status = 'running' ctx.emit('deepseek-account/signed-out') expect(cancelAccount).toHaveBeenCalledExactlyOnceWith( { kind: 'hook', reason: 'deepseek-account/signed-out' }, { keepInbox: true }, @@ -34,6 +42,7 @@ it('cancels running account tasks with their inboxes retained and detaches with report(new LlmError('Sign in required', 'ACCOUNT_SIGN_IN_REQUIRED')) expect(notice).toHaveBeenCalledTimes(1) await owner.dispose() + expect(reports.size).toBe(0) report(new LlmError('Sign in required', 'ACCOUNT_SIGN_IN_REQUIRED')) expect(notice).toHaveBeenCalledTimes(1) ctx.emit('deepseek-account/signed-out') diff --git a/packages/llm/llm-deepseek-account/tests/provider.spec.ts b/packages/llm/llm-deepseek-account/tests/provider.spec.ts index 2ad19db785..5f4139eb91 100644 --- a/packages/llm/llm-deepseek-account/tests/provider.spec.ts +++ b/packages/llm/llm-deepseek-account/tests/provider.spec.ts @@ -4,7 +4,7 @@ import type { IncomingMessage, Server, ServerResponse } from 'node:http' import { afterEach, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import LlmRuntime, { ReasoningEffortId } from '@deepseek-ai/dsh-llm' -import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' import * as ApiKey from '@deepseek-ai/dsh-llm-deepseek-api-key' import * as Account from '../src/index.ts' @@ -50,9 +50,7 @@ async function host(origin: string, token: () => string | undefined = () => 'fix const ctx = new Context() contexts.push(ctx) await ctx.plugin(LlmRuntime) - ctx.provide('deepseekAccount', { - resolveToken: (url: string) => Promise.resolve(new URL(url).origin === origin ? token() : undefined), - } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: url => new URL(url).origin === origin ? token() : undefined })) return ctx } @@ -207,3 +205,34 @@ it('aborts an in-flight listing request when the plugin is disposed', async () = await closed await expect(pending).resolves.toEqual(expect.any(Array)) }) + +it('publishes the account credential for its consumers, asking the account for each endpoint', async () => { + const asked: string[] = [] + let token: string | undefined = 'fixture-account-token' + const ctx = new Context() + contexts.push(ctx) + await ctx.plugin(LlmRuntime) + ctx.provide('deepseekAccount', accountStub({ token: (url) => { asked.push(url); return token } })) + await ctx.plugin(Account, { baseURL: 'https://account.deepseek.test/anthropic' }) + const credential = ctx.llm.routeCredential('deepseek-account') + expect(credential).toMatchObject({ kind: 'account', baseURL: 'https://account.deepseek.test/anthropic' }) + expect(credential).not.toHaveProperty('reference') + const endpoint = 'https://account.deepseek.test/v1/tools/search' + await expect(credential!.configured(endpoint)).resolves.toBe(true) + await expect(credential!.resolve(endpoint)).resolves.toMatchObject({ headers: { 'x-dsh-auth-token': 'fixture-account-token' }, value: 'fixture-account-token' }) + token = undefined + await expect(credential!.configured(endpoint)).resolves.toBe(false) + await expect(credential!.resolve(endpoint)).resolves.toBeUndefined() + expect(asked).toEqual([endpoint, endpoint, endpoint, endpoint]) + expect(ctx.llm.routeCredential('deepseek-official')).toBeUndefined() +}) + +it('publishes a credential nobody holds without the account service', async () => { + const ctx = new Context() + contexts.push(ctx) + await ctx.plugin(LlmRuntime) + await ctx.plugin(Account, { baseURL: 'https://account.deepseek.test/anthropic' }) + const credential = ctx.llm.routeCredential('deepseek-account')! + await expect(credential.configured('https://account.deepseek.test/v1/tools/search')).resolves.toBe(false) + await expect(credential.resolve('https://account.deepseek.test/v1/tools/search')).resolves.toBeUndefined() +}) diff --git a/packages/llm/llm-deepseek-account/tsconfig.json b/packages/llm/llm-deepseek-account/tsconfig.json index 73803a4a6e..725d721c73 100644 --- a/packages/llm/llm-deepseek-account/tsconfig.json +++ b/packages/llm/llm-deepseek-account/tsconfig.json @@ -21,7 +21,7 @@ "path": "../../util/launch-environment" }, { - "path": "../../credentials/deepseek-account" + "path": "../../account/deepseek-account" }, { "path": "../../../vendor/loader" @@ -31,6 +31,9 @@ }, { "path": "../../../vendor/schemastery" + }, + { + "path": "../../core/agent" } ] } diff --git a/packages/llm/llm-deepseek-api-key/README.i18n.yaml b/packages/llm/llm-deepseek-api-key/README.i18n.yaml index dfb3bd13e8..68ac287b92 100644 --- a/packages/llm/llm-deepseek-api-key/README.i18n.yaml +++ b/packages/llm/llm-deepseek-api-key/README.i18n.yaml @@ -9,17 +9,17 @@ en: b6871195e386cc64 zh: 742b05a3ca80883c /deepseek-ai-dsh-llm-deepseek-api-key/summary: - en: f937052cf8ff4812 - zh: 899d61f5021136d6 + en: 69c60bbfb6aafb7a + zh: 1afe49ea9cdc3cd5 /deepseek-ai-dsh-llm-deepseek-api-key/table-of-contents: en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 /deepseek-ai-dsh-llm-deepseek-api-key/use-this-package: - en: 007427bed9bd469b - zh: 5089b5781746357f + en: 77aeaaf77e17245f + zh: 5b621a9a4aeea7d9 /deepseek-ai-dsh-llm-deepseek-api-key/understand-the-implementation: - en: 1b9584855817eddb - zh: feb2c883ca355d31 + en: 2fe0f32c15603cd9 + zh: 984ce05b82e8e679 /deepseek-ai-dsh-llm-deepseek-api-key/further-exploration: en: 347659458510940c zh: ccfb03e18b356a39 diff --git a/packages/llm/llm-deepseek-api-key/README.md b/packages/llm/llm-deepseek-api-key/README.md index aa6665824c..e646cb1ef2 100644 --- a/packages/llm/llm-deepseek-api-key/README.md +++ b/packages/llm/llm-deepseek-api-key/README.md @@ -11,7 +11,7 @@ English | [中文](README.zh.md) Register authentication, model discovery, and the official model listing for `deepseek-official`. This plugin shares the [Messages transport](../llm-deepseek/README.md) and owns credential resolution, catalog availability, and model admission. -Authentication resolution returns the validated API key in `x-api-key` for both Messages and Files requests. +Authentication resolution returns the validated API key in `x-api-key` for Messages, Files, and listing requests, and publishes the same key through `ctx.llm.routeCredential('deepseek-official')` with the route's base URL and `apiKeyEnv` reference, so the DeepSeek web providers send it as a bearer token to the same deployment. ## Table of Contents @@ -25,7 +25,7 @@ Authentication resolution returns the validated API key in `x-api-key` for both ## Use this package -`apiKeyEnv` defaults to `DEEPSEEK_API_KEY` and resolves per request and model discovery. When the credentials service exists, its precedence applies; only compositions without that service read the launch environment directly. Requests with missing credentials fail with `MISSING_CREDENTIAL`; malformed credentials fail with `INVALID_CREDENTIAL`. Model discovery returns an empty catalog when the credential is missing, hiding the route from model selectors while retaining its settings entry. Malformed credentials and other lookup failures propagate. Adding or removing a key affects the next discovery call. +`apiKeyEnv` defaults to `DEEPSEEK_API_KEY` and resolves per request and model discovery. It reads the key through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md): when the credentials service exists, its precedence applies, and only compositions without that service read the launch environment directly. Requests with missing credentials fail with `MISSING_CREDENTIAL`; malformed credentials fail with `INVALID_CREDENTIAL`. Model discovery returns an empty catalog when the credential is missing, hiding the route from model selectors while retaining its settings entry. Malformed credentials and other lookup failures propagate. Adding or removing a key affects the next discovery call. ```yaml - id: llm-deepseek @@ -55,7 +55,7 @@ The settings namespace is the Cordis entry id, or the plugin name without an ent ## Understand the implementation -API-key lookup calls `resolveDeepSeekApiKey` from the [shared credential module](../llm-deepseek/src/credential.ts). Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the listed catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport; the cache lives in memory and is keyed by endpoint and a SHA-256 of the key, so another key loads its own listing. A `loader/volatile-update` listener discards the cached listing whenever the route starts or stops following it. +API-key lookup calls `resolveCredentialRef` and `credentialRefConfigured` from `dsh-credentials` and validates the value with `assertUsableApiKey` from `dsh-llm`; the shared transport reads no credential. Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the listed catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport; the cache lives in memory and is keyed by endpoint and a SHA-256 of the key, so another key loads its own listing. A `loader/volatile-update` listener discards the cached listing whenever the route starts or stops following it. ## Further Exploration diff --git a/packages/llm/llm-deepseek-api-key/README.zh.md b/packages/llm/llm-deepseek-api-key/README.zh.md index 33ca8db1fa..b26da9ab8b 100644 --- a/packages/llm/llm-deepseek-api-key/README.zh.md +++ b/packages/llm/llm-deepseek-api-key/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" 为 `deepseek-official` 注册鉴权、模型发现和官方模型列表。通过 [llm-deepseek](../llm-deepseek/README.zh.md) 共用 Messages 请求实现;本包拥有凭据解析、目录可用性判断和模型准入。 -鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages 和 Files 请求共同使用。 +鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages、Files 和列表请求使用,并通过 `ctx.llm.routeCredential('deepseek-official')` 连同路由的基础地址和 `apiKeyEnv` 引用发布同一密钥,使 DeepSeek Web 提供方以 Bearer 令牌把它发往同一部署。 ## 目录 @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用此包 -`apiKeyEnv` 默认为 `DEEPSEEK_API_KEY`,在每次请求和模型发现时解析凭据。已组合 credentials 服务时,按其优先级解析;只有未组合该服务时才直接读取启动环境。请求时凭据缺失以 `MISSING_CREDENTIAL` 失败;格式错误以 `INVALID_CREDENTIAL` 失败。模型发现在凭据缺失时返回空目录,在模型选择器中隐藏该路由,但保留其设置入口。凭据格式错误和其他读取失败继续上报。添加或删除密钥会影响下一次模型发现。 +`apiKeyEnv` 默认为 `DEEPSEEK_API_KEY`,在每次请求和模型发现时解析凭据。密钥通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数读取:已组合 credentials 服务时,按其优先级解析;只有未组合该服务时才直接读取启动环境。请求时凭据缺失以 `MISSING_CREDENTIAL` 失败;格式错误以 `INVALID_CREDENTIAL` 失败。模型发现在凭据缺失时返回空目录,在模型选择器中隐藏该路由,但保留其设置入口。凭据格式错误和其他读取失败继续上报。添加或删除密钥会影响下一次模型发现。 ```yaml - id: llm-deepseek @@ -55,7 +55,7 @@ kind: "package-reference" ## 理解实现 -API key 读取调用[共享凭据模块](../llm-deepseek/src/credential.ts)的 `resolveDeepSeekApiKey`。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入列表目录和门控。列表请求、缓存和目录解析来自共享传输包;缓存只在内存中,以端点和 API key 的 SHA-256 为键,因此换一个 key 会加载它自己的列表。一个 `loader/volatile-update` 监听器在路由开始或停止使用列表时丢弃缓存的列表。 +API key 读取调用 `dsh-credentials` 的 `resolveCredentialRef` 与 `credentialRefConfigured`,并用 `dsh-llm` 的 `assertUsableApiKey` 校验值;共享传输层不读取任何凭据。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入列表目录和门控。列表请求、缓存和目录解析来自共享传输包;缓存只在内存中,以端点和 API key 的 SHA-256 为键,因此换一个 key 会加载它自己的列表。一个 `loader/volatile-update` 监听器在路由开始或停止使用列表时丢弃缓存的列表。 ## 进一步探索 diff --git a/packages/llm/llm-deepseek-api-key/src/index.ts b/packages/llm/llm-deepseek-api-key/src/index.ts index ac0f4753c5..9fa4f2a996 100644 --- a/packages/llm/llm-deepseek-api-key/src/index.ts +++ b/packages/llm/llm-deepseek-api-key/src/index.ts @@ -1,18 +1,18 @@ /** API-key authentication, credential-gated discovery, and the official model listing for the official DeepSeek route. */ import type { Context } from '@deepseek-ai/cordis' -import { APP_IDENTITY, LlmError } from '@deepseek-ai/dsh-llm' +import { APP_IDENTITY, assertUsableApiKey, LlmError } from '@deepseek-ai/dsh-llm' import type { LlmModelBadge } from '@deepseek-ai/dsh-llm' import type {} from '@deepseek-ai/cordis-plugin-loader' +import { credentialRefConfigured, resolveCredentialRef } from '@deepseek-ai/dsh-credentials' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' import { - catalogModelInfo, createModelListingCache, refuseListedModel, registerDeepSeekProvider, requestModelListing, resolveListedCatalog, - resolveDeepSeekApiKey, + catalogModelInfo, createModelListingCache, refuseListedModel, registerDeepSeekProvider, resolveListedCatalog, } from '@deepseek-ai/dsh-llm-deepseek' -import type { CatalogRefusal, DeepSeekCatalogModel, ListingView, ModelListing } from '@deepseek-ai/dsh-llm-deepseek' +import type { CatalogRefusal, DeepSeekCatalogModel, DeepSeekRequestAuth, ListingView, ModelListing } from '@deepseek-ai/dsh-llm-deepseek' import { Config, plainOptions, resolveAdapterOptions } from './config.ts' import type { ResolvedDeepSeekOptions } from './config.ts' -export { Config, plainOptions, resolveAdapterOptions } from './config.ts' +export { Config } from './config.ts' export type { Options, ResolvedDeepSeekOptions } from './config.ts' export const name = 'llm-deepseek-api-key' export const inject = ['llm'] @@ -34,28 +34,23 @@ interface OfficialConnection extends ResolvedDeepSeekOptions { export function apply(ctx: Context, config: Config): void { const options = () => resolveAdapterOptions(plainOptions(config), launchEnvironmentOf(ctx)) options() - const resolveApiKey = async (connection: ResolvedDeepSeekOptions): Promise => { - const ref = connection.apiKeyEnv - const key = await resolveDeepSeekApiKey(ctx, ref) - if (key !== undefined) return key - throw new LlmError( - `llm-deepseek: no API key for provider route "${PROVIDER}"; store ${ref} through the credentials` - + ` service (the web Models page writes it), or export ${ref} in the launching environment`, - 'MISSING_CREDENTIAL', - ) + /** The validated API key, or `undefined` when none is configured; store and format failures propagate. */ + const resolveApiKey = async (connection: ResolvedDeepSeekOptions): Promise => { + const value = await resolveCredentialRef(ctx, connection.apiKeyEnv) + return value === undefined ? undefined : assertUsableApiKey(value, 'llm-deepseek', connection.apiKeyEnv) } - /** The API key, or `undefined` when none is configured; other credential failures propagate. */ - const presentApiKey = async (connection: ResolvedDeepSeekOptions): Promise => { - try { return await resolveApiKey(connection) } - catch (error) { - if (error instanceof LlmError && error.code === 'MISSING_CREDENTIAL') return undefined - throw error - } + const resolveAuth = async (connection: ResolvedDeepSeekOptions): Promise => { + const key = await resolveApiKey(connection) + return key === undefined ? undefined : { headers: { 'x-api-key': key }, value: key } } + const missingCredential = (connection: ResolvedDeepSeekOptions) => new LlmError( + `llm-deepseek: no API key for provider route "${PROVIDER}"; store ${connection.apiKeyEnv} through the credentials` + + ` service (the web Models page writes it), or export ${connection.apiKeyEnv} in the launching environment`, + 'MISSING_CREDENTIAL', + ) const listings = createModelListingCache(ctx, name, PROVIDER, { settings: () => options().listing, - credential: async () => presentApiKey(options()), - load: (url, apiKey, signal) => requestModelListing(url, { 'x-api-key': apiKey }, signal), + credential: async () => (await resolveAuth(options()))?.headers, }) let reportedListing: ModelListing | undefined /** Resolve the catalog, reporting each listing's hidden entries and dropped badges once. */ @@ -96,12 +91,18 @@ export function apply(ctx: Context, config: Config): void { } return connectionOf(connection, view) }, - resolveAuth: async connection => ({ headers: { 'x-api-key': await resolveApiKey(connection) } }), + resolveAuth, + missingCredential, + credential: { + kind: 'api-key', + reference: connection => connection.apiKeyEnv, + configured: connection => credentialRefConfigured(ctx, connection.apiKeyEnv), + }, admit: (connection, model) => { refuseListedModel(model, connection.refusals.get(model)) }, discoverModels: async (provider) => { const connection = options() if (connection.listing === undefined) { - if (await presentApiKey(connection) === undefined) return [] + if (await resolveApiKey(connection) === undefined) return [] return connection.models.map(model => catalogModelInfo(provider, model)) } const view = await listings.view(connection.listing) diff --git a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts index 27f55f005b..528d332e2d 100644 --- a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts +++ b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts @@ -44,3 +44,26 @@ it('reports malformed credentials during discovery', async () => { vi.unstubAllEnvs() } }) + +it('publishes the route API key for its consumers from the credential planes it reads itself', async () => { + vi.stubEnv('DEEPSEEK_API_KEY', 'fixture-api-key') + const ctx = new Context() + try { + await ctx.plugin(LlmRuntime) + await ctx.plugin(ApiKey, { baseURL: 'https://route.deepseek.test/anthropic' }) + const credential = ctx.llm.routeCredential('deepseek-official') + expect(credential).toMatchObject({ kind: 'api-key', baseURL: 'https://route.deepseek.test/anthropic', reference: 'DEEPSEEK_API_KEY' }) + const endpoint = 'https://route.deepseek.test/v1/tools/search' + await expect(credential!.configured(endpoint)).resolves.toBe(true) + await expect(credential!.resolve(endpoint)).resolves.toEqual({ headers: { 'x-api-key': 'fixture-api-key' }, value: 'fixture-api-key' }) + vi.stubEnv('DEEPSEEK_API_KEY', '') + await expect(credential!.configured(endpoint)).resolves.toBe(false) + await expect(credential!.resolve(endpoint)).resolves.toBeUndefined() + vi.stubEnv('DEEPSEEK_API_KEY', 'invalid\nheader') + await expect(credential!.configured(endpoint)).resolves.toBe(true) + await expect(credential!.resolve(endpoint)).rejects.toMatchObject({ code: 'INVALID_CREDENTIAL' }) + } finally { + await ctx.fiber.dispose() + vi.unstubAllEnvs() + } +}) diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index 18c1efe0dc..68db96e254 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -27,8 +27,8 @@ en: 2a634ead5b47fe97 zh: 46f199ee79a8c5dc /deepseek-ai-dsh-llm-deepseek/use-this-package/account-credentials: - en: d3f232309f4963ef - zh: 2e0ccd028de26f3e + en: 98b9a8d297095e32 + zh: b8f8eb46038214cb /deepseek-ai-dsh-llm-deepseek/use-this-package/streaming-with-thinking-and-images: en: 81bf213499f015ba zh: e9107ef322213e56 diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 3c25fee26e..5333f68e3c 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -87,11 +87,11 @@ Messages sends text, thinking, tool calls, and tool results as content blocks, r ### Account credentials -`deepseek-official` resolves only its configured API-key reference. `deepseek-account` resolves only the stored grant from the [account service](../../credentials/deepseek-account/README.md), whose allowed `inferenceOrigin` defaults to `https://api.deepseek.com`. Neither route falls back to the other. Signing out removes the account grant and preserves API keys. +`deepseek-official` resolves only its configured API-key reference. `deepseek-account` resolves only the stored grant from the [account service](../../account/deepseek-account/README.md), whose allowed `inferenceOrigin` defaults to `https://api.deepseek.com`. Neither route falls back to the other. Signing out removes the account grant and preserves API keys. -Messages and Files requests send account tokens as `x-dsh-auth-token` without a Bearer prefix; API keys use `x-api-key`. Neither credential mode follows redirects. The account service owns HTTP 401 classification and credential invalidation; the transport passes failures to its callback. +Messages and Files requests send account tokens as `x-dsh-auth-token` without a Bearer prefix; API keys use `x-api-key`. Neither credential mode follows redirects. The account route owns HTTP 401 classification and the account service the credential invalidation; the transport passes failures to the credential's callback. -The [shared credential helpers](src/credential.ts) serve model routes and web providers without choosing request headers. `resolveDeepSeekApiKey(ctx, ref)` returns a normalized, validated key or `undefined`; an installed credentials service is authoritative, and only its absence enables launch-environment lookup. Store and key-format failures propagate. `deepSeekApiKeyConfigured(ctx, ref)` checks presence without reading stored key values. Account helpers delegate allowed-destination resolution and exact-token invalidation to the account service; invalidation contains storage failures so the original request error remains visible. +Provider plugins own credentials through three adapter hooks. `resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: the headers the Messages, Files, and listing requests send, the bare value, and an optional failure callback, or `undefined` when none is configured. `missingCredential(connection, provider)` names the failure of a request without one; the default is `MISSING_CREDENTIAL`. `credential` publishes the route's credential kind, optional reference, and presence check through `ctx.llm.routeCredential(provider)` together with the route's base URL, so web providers call the same deployment with the same credential without reading provider configuration. The plugins read API keys through the [credential reference helpers](../../credentials/credentials/README.md) of `dsh-credentials` and account credentials through the [account service](../../account/deepseek-account/README.md); this transport reads neither. ### Streaming with thinking and images diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index 3d1b6beeb4..8a83625697 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -87,11 +87,11 @@ Messages 以内容块发送文本、思考、工具调用和工具结果,以 ` ### 账号凭据 -`deepseek-official` 仅解析配置的 API Key 引用。`deepseek-account` 仅解析[账号服务](../../credentials/deepseek-account/README.zh.md)保存的授权,其允许的 `inferenceOrigin` 默认为 `https://api.deepseek.com`。两条路由均不回退到另一凭证。退出登录删除账号授权,保留 API Key。 +`deepseek-official` 仅解析配置的 API Key 引用。`deepseek-account` 仅解析[账号服务](../../account/deepseek-account/README.zh.md)保存的授权,其允许的 `inferenceOrigin` 默认为 `https://api.deepseek.com`。两条路由均不回退到另一凭证。退出登录删除账号授权,保留 API Key。 -Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 Bearer 前缀;API Key 使用 `x-api-key`。两种凭据模式均拒绝重定向。账号服务负责 HTTP 401 分类和凭据失效处理;传输层将错误交给其回调。 +Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 Bearer 前缀;API Key 使用 `x-api-key`。两种凭据模式均拒绝重定向。账号路由负责 HTTP 401 分类,账号服务负责凭据失效处理;传输层将错误交给凭据的回调。 -[共享凭据函数](src/credential.ts)为模型路由和 Web 提供方获取凭据,不决定请求头。`resolveDeepSeekApiKey(ctx, ref)` 返回规范化并校验后的密钥或 `undefined`;已安装的凭据服务具有权威性,仅在该服务缺席时读取启动环境。存储与密钥格式错误向上传播。`deepSeekApiKeyConfigured(ctx, ref)` 检查是否存在,不读取已存密钥值。账号函数将目标地址许可检查和精确 token 作废交给账号服务;作废时隔离存储失败,保留原请求错误。 +提供方插件通过三个适配器钩子拥有凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、裸凭据值以及可选的失败回调;未配置时返回 `undefined`。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。`credential` 通过 `ctx.llm.routeCredential(provider)` 发布路由的凭据种类、可选引用和存在性检查,并附带路由的基础地址,使 Web 提供方无需读取提供方配置即可用同一凭据调用同一部署。插件通过 `dsh-credentials` 的[凭据引用函数](../../credentials/credentials/README.zh.md)读取 API Key,通过[账号服务](../../account/deepseek-account/README.zh.md)读取账号凭据;本传输层两者都不读取。 ### 带 thinking 与图片的流式调用 diff --git a/packages/llm/llm-deepseek/src/adapter.ts b/packages/llm/llm-deepseek/src/adapter.ts index a6129f26fd..0020cf5cde 100644 --- a/packages/llm/llm-deepseek/src/adapter.ts +++ b/packages/llm/llm-deepseek/src/adapter.ts @@ -1,7 +1,7 @@ /** Direct Messages transport with one cancellable lifecycle per model request. */ import { attributionHeaders, LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm' -import type { GenerateOptions, ImageAttachmentAccessResolver, PreparedAdapterCall, StreamChunk } from '@deepseek-ai/dsh-llm' +import type { GenerateOptions, ImageAttachmentAccessResolver, PreparedAdapterCall, RouteCredential, StreamChunk } from '@deepseek-ai/dsh-llm' import type { DeepSeekLlmApiExtensionRequest, DeepSeekLlmApiJson } from '@deepseek-ai/dsh-deepseek-llm-api-extensions' import { idleWatchdog, timeoutOf } from '@deepseek-ai/dsh-timeout' import { modelInfo } from './model-info.ts' @@ -47,6 +47,23 @@ export class DeepSeekAdapter extends LlmAdapt if (entry === undefined) throw new LlmError(`DeepSeek model "${model}" has no declared image projection`, 'UNKNOWN_MODEL') return resolveRequestImageTarget(entry, image) } + override routeCredential(_provider: string): RouteCredential | undefined { + const publication = this.dependencies.credential + if (publication === undefined) return undefined + // One configuration generation serves the whole published object, as it does one model request. + const connection = this.dependencies.options() + const reference = publication.reference?.(connection) + return { + kind: publication.kind, + baseURL: connection.baseURL, + ...reference === undefined ? {} : { reference }, + configured: endpoint => publication.configured(connection, endpoint), + resolve: async (endpoint, signal) => { + signal?.throwIfAborted() + return await this.dependencies.resolveAuth(connection, endpoint) + }, + } + } override async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise { const connection = await this.connection(signal) this.dependencies.admit?.(connection, model) @@ -62,6 +79,11 @@ export class DeepSeekAdapter extends LlmAdapt return this.dependencies.connect?.(signal) ?? Promise.resolve(this.dependencies.options()) } + private missingCredential(connection: C, provider: string): LlmError { + return this.dependencies.missingCredential?.(connection, provider) + ?? new LlmError(`llm-deepseek: no credential for provider route "${provider}"`, 'MISSING_CREDENTIAL') + } + private async * generate(options: GenerateOptions, connection: C): AsyncGenerator { const consumer = new AbortController() const signal = options.signal === undefined ? consumer.signal : AbortSignal.any([consumer.signal, options.signal]) @@ -95,7 +117,8 @@ export class DeepSeekAdapter extends LlmAdapt const { messages, versions } = await prepareImages( options.messages, connection, options.model, this.dependencies.resolveAttachments?.(), this.imageAccess, signal, ) - const auth = await this.dependencies.resolveAuth(connection) + const auth = await this.dependencies.resolveAuth(connection, connection.baseURL) + if (auth === undefined) throw this.missingCredential(connection, options.provider) try { const files = new RequestFiles(this.files, { baseURL: connection.baseURL, headers: auth.headers, diff --git a/packages/llm/llm-deepseek/src/auth-headers.ts b/packages/llm/llm-deepseek/src/auth-headers.ts new file mode 100644 index 0000000000..e267691e81 --- /dev/null +++ b/packages/llm/llm-deepseek/src/auth-headers.ts @@ -0,0 +1,12 @@ +/** Deterministic serialization of credential headers for credential-scoped caches. @module dsh-llm-deepseek/auth-headers */ + +/** + * Serialize credential headers so caches scoped by credential digest the same + * credential to the same value whatever the header order. The result is hash + * input only: never persist or log it. + * @param headers - credential headers of one request. + * @returns a stable string representation of the headers. + */ +export function serializeAuthHeaders(headers: Readonly>): string { + return JSON.stringify(Object.entries(headers).sort(([left], [right]) => left.localeCompare(right))) +} diff --git a/packages/llm/llm-deepseek/src/credential.ts b/packages/llm/llm-deepseek/src/credential.ts deleted file mode 100644 index 0edcbb1107..0000000000 --- a/packages/llm/llm-deepseek/src/credential.ts +++ /dev/null @@ -1,58 +0,0 @@ -/** Credential values shared by DeepSeek model and web providers; callers own protocol headers and missing-key errors. */ -import type { Context } from '@deepseek-ai/cordis' -import type { CredentialRef } from '@deepseek-ai/dsh-credentials' -import type {} from '@deepseek-ai/dsh-deepseek-account' -import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' -import { assertUsableApiKey } from '@deepseek-ai/dsh-llm' - -/** - * Read and validate one API key. An installed credentials service is authoritative, including absence; - * only deployments without that service read the launch environment. Store and format failures propagate. - * @param ctx - context providing the credential and launch-environment services. - * @param ref - credential reference to resolve. - * @returns the validated key, or undefined when no key is configured. - */ -export async function resolveDeepSeekApiKey(ctx: Context, ref: CredentialRef): Promise { - const credentials = ctx.get('credentials') - if (credentials !== undefined) { - const hit = await credentials.resolve(ref) - return hit === undefined ? undefined : assertUsableApiKey(hit.value, 'llm-deepseek', ref) - } - const ambient = launchEnvironmentOf(ctx).get(ref) - return ambient === undefined || ambient.value.length === 0 ? undefined : assertUsableApiKey(ambient.value, 'llm-deepseek', ref) -} - -/** - * Check key presence without resolving a credential-store value or validating its format. Store failures propagate. - * @param ctx - context providing the credential and launch-environment services. - * @param ref - credential reference to inspect. - * @returns whether the authoritative credential source reports a configured key. - */ -export async function deepSeekApiKeyConfigured(ctx: Context, ref: CredentialRef): Promise { - const credentials = ctx.get('credentials') - return credentials === undefined - ? (launchEnvironmentOf(ctx).get(ref)?.value.length ?? 0) > 0 - : (await credentials.describe(ref)).configured -} - -/** - * Read an account token only for a destination allowed by the account service. Credential-store failures propagate. - * @param ctx - context providing the optional account service. - * @param endpoint - destination that would receive the token. - * @returns the token, or undefined without an allowed signed-in account. - */ -export async function resolveDeepSeekAccountToken(ctx: Context, endpoint: string): Promise { - return await ctx.get('deepseekAccount')?.resolveToken(endpoint) -} - -/** - * Invalidate the account token rejected by a request, without clearing a newer sign-in. Removal failure is contained - * so callers can report the original request failure; the account service owns in-memory invalidation and persistence. - * @param ctx - context providing the optional account service. - * @param token - exact token sent by the rejected request. - * @returns settlement after the invalidation attempt. - */ -export async function rejectDeepSeekAccountToken(ctx: Context, token: string): Promise { - try { await ctx.get('deepseekAccount')?.rejectToken(token) } - catch (_credentialRemovalFailed) { /* Storage failure cannot replace the request failure. */ } -} diff --git a/packages/llm/llm-deepseek/src/file-store.ts b/packages/llm/llm-deepseek/src/file-store.ts index da6f87654a..f89603c83c 100644 --- a/packages/llm/llm-deepseek/src/file-store.ts +++ b/packages/llm/llm-deepseek/src/file-store.ts @@ -6,6 +6,7 @@ import { DeepSeekFilesClient, isFilesQuotaError } from './files-api.ts' import type { DeepSeekFileId } from './file-id.ts' import { messagesApiRoot } from './messages-api.ts' import { deepSeekFileScope, DeepSeekUploadIndex } from './upload-index.ts' +import { serializeAuthHeaders } from './auth-headers.ts' import type { DeepSeekUploadRecord } from './upload-index.ts' /** Shared Files-store limit for each request image, including file-id references. */ @@ -47,10 +48,7 @@ interface SharedUpload { /** The Files resource's parent URL identifies the upload namespace. */ function fileScope(connection: DeepSeekFileConnection) { - return deepSeekFileScope( - messagesApiRoot(connection.baseURL), - JSON.stringify(Object.entries(connection.headers).sort(([left], [right]) => left.localeCompare(right))), - ) + return deepSeekFileScope(messagesApiRoot(connection.baseURL), serializeAuthHeaders(connection.headers)) } function abortReason(signal: AbortSignal): Error { diff --git a/packages/llm/llm-deepseek/src/host.ts b/packages/llm/llm-deepseek/src/host.ts index c9e89cad8e..202d9c2bef 100644 --- a/packages/llm/llm-deepseek/src/host.ts +++ b/packages/llm/llm-deepseek/src/host.ts @@ -8,6 +8,7 @@ import { getOrCreateAnonymousUserId, type AnonymousUserId } from '@deepseek-ai/d import { deepEqualJson } from '@deepseek-ai/dsh-util-values' import { DeepSeekAdapter } from './adapter.ts' import type { DeepSeekAdapterOptions, DeepSeekConnectionOptions } from './types.ts' +import { requestModelListing } from './listing.ts' import { ModelListingCache, type ListingCacheDependencies } from './listing-cache.ts' /** @@ -15,16 +16,17 @@ import { ModelListingCache, type ListingCacheDependencies } from './listing-cach * @param ctx - provider plugin lifetime. * @param owner - plugin name used in diagnostics. * @param provider - route whose catalog changes. - * @param dependencies - current configuration, credentials, and listing transport. + * @param dependencies - current configuration and credential headers; `load` defaults to the official `/models` request. * @returns the cache, disposed with the provider after its active work settles. */ export function createModelListingCache( ctx: Context, owner: string, provider: string, - dependencies: Pick, + dependencies: Pick & Partial>, ): ModelListingCache { const tag = `[${owner}]` const cache = new ModelListingCache({ ...dependencies, + load: dependencies.load ?? requestModelListing, now: () => Date.now(), // ACP reserves stdout for protocol messages, including during successful catalog loads. info: (message) => { console.error(tag, message) }, @@ -43,7 +45,7 @@ export function createModelListingCache( */ export function registerDeepSeekProvider( ctx: Context, provider: string, dependencies: Pick, - 'options' | 'resolveAuth' | 'providerName' | 'discoverModels' | 'connect' | 'admit'>): void { + 'options' | 'resolveAuth' | 'missingCredential' | 'credential' | 'providerName' | 'discoverModels' | 'connect' | 'admit'>): void { ctx.inject(['settings'], (child) => { child.effect(() => child.settings.configure({ auto: false }, ctx.fiber)) }) let userId: AnonymousUserId | undefined // These conditions repeat on every request of a route; log each first occurrence only. diff --git a/packages/llm/llm-deepseek/src/index.ts b/packages/llm/llm-deepseek/src/index.ts index c3ca109a93..0474969f60 100644 --- a/packages/llm/llm-deepseek/src/index.ts +++ b/packages/llm/llm-deepseek/src/index.ts @@ -1,5 +1,4 @@ /** DeepSeek Messages transport, request configuration, and model capabilities. */ -export { deepSeekApiKeyConfigured, rejectDeepSeekAccountToken, resolveDeepSeekAccountToken, resolveDeepSeekApiKey } from './credential.ts' export { catalogModelFields, deepSeekConfigFields, Config, isBuiltInCatalog, plainOptions, resolveAdapterOptions, PUBLIC_BASE_URL } from './config.ts' export type { Options, ResolvedDeepSeekOptions } from './config.ts' export { @@ -16,7 +15,7 @@ export { DEFAULT_STREAM_IDLE_TIMEOUT_MS, } from './defaults.ts' export { DeepSeekAdapter } from './adapter.ts' -export type { DeepSeekRequestAuth, DeepSeekAdapterOptions, DeepSeekCatalogModel, DeepSeekConnectionOptions } from './types.ts' +export type { DeepSeekRequestAuth, DeepSeekAdapterOptions, DeepSeekCatalogModel, DeepSeekConnectionOptions, DeepSeekRouteCredentialOptions } from './types.ts' export { DEFAULT_LOW_DETAIL_IMAGE_PIXEL_BUDGET, DEFAULT_MAX_IMAGES_PER_REQUEST, diff --git a/packages/llm/llm-deepseek/src/listing-cache.ts b/packages/llm/llm-deepseek/src/listing-cache.ts index 71173f509d..01c9a57da9 100644 --- a/packages/llm/llm-deepseek/src/listing-cache.ts +++ b/packages/llm/llm-deepseek/src/listing-cache.ts @@ -2,6 +2,7 @@ import { createHash } from 'node:crypto' import { deadline, MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { deepEqualJson } from '@deepseek-ai/dsh-util-values' +import { serializeAuthHeaders } from './auth-headers.ts' import type { ListingSettings } from './listing-config.ts' import { LISTING_TIMEOUT } from './listing.ts' import type { ModelListing } from './listing.ts' @@ -10,10 +11,10 @@ import type { ModelListing } from './listing.ts' export interface ListingCacheDependencies { /** Latest route configuration for automatic refresh; `undefined` stops following the listing. */ readonly settings: () => ListingSettings | undefined - /** The credential the route sends to `url`, or `undefined` when it has none. */ - readonly credential: (url: string) => Promise - /** Perform one listing request authenticated with `credential`; `signal` carries the {@link LISTING_TIMEOUT} request deadline. */ - readonly load: (url: string, credential: string, signal: AbortSignal) => Promise + /** Headers carrying the credential the route sends to `url`, or `undefined` when it has none. */ + readonly credential: (url: string) => Promise> | undefined> + /** Perform one listing request sending `headers`; `signal` carries the {@link LISTING_TIMEOUT} request deadline. */ + readonly load: (url: string, headers: Readonly>, signal: AbortSignal) => Promise /** Wall clock used for listing age. */ readonly now: () => number /** Report a loaded listing. */ @@ -80,14 +81,16 @@ export class ModelListingCache { * @returns the view after any first load of the scope settles. */ async view(settings: ListingSettings, signal?: AbortSignal): Promise { - const credential = await this.dependencies.credential(settings.url) + const headers = await this.dependencies.credential(settings.url) signal?.throwIfAborted() if (this.closed) return this.current() - const scope = credential === undefined ? undefined : `${settings.url}\n${createHash('sha256').update(credential).digest('hex')}` + const scope = headers === undefined + ? undefined + : `${settings.url}\n${createHash('sha256').update(serializeAuthHeaders(headers)).digest('hex')}` if (scope !== this.scope) this.rescope(scope) - if (credential !== undefined) { - if (this.settledAt === undefined) await abandonable(this.start(settings, credential), signal) - else if (this.dependencies.now() - this.settledAt >= settings.maxAgeMs) void this.start(settings, credential) + if (headers !== undefined) { + if (this.settledAt === undefined) await abandonable(this.start(settings, headers), signal) + else if (this.dependencies.now() - this.settledAt >= settings.maxAgeMs) void this.start(settings, headers) } return this.current() } @@ -120,7 +123,7 @@ export class ModelListingCache { this.generation += 1 } - private start(settings: ListingSettings, credential: string): Promise { + private start(settings: ListingSettings, headers: Readonly>): Promise { if (this.inflight !== undefined) return this.inflight clearTimeout(this.timer) this.generation += 1 @@ -128,7 +131,7 @@ export class ModelListingCache { const request = new AbortController() this.request = request const limit = deadline(request.signal, settings.timeoutMs, LISTING_TIMEOUT) - const run = this.dependencies.load(settings.url, credential, limit.signal) + const run = this.dependencies.load(settings.url, headers, limit.signal) .then((listing) => { if (generation !== this.generation) return const changed = !deepEqualJson(this.listing, listing) diff --git a/packages/llm/llm-deepseek/src/types.ts b/packages/llm/llm-deepseek/src/types.ts index c682bba792..a9f50b20a6 100644 --- a/packages/llm/llm-deepseek/src/types.ts +++ b/packages/llm/llm-deepseek/src/types.ts @@ -1,5 +1,8 @@ /** Model catalog and request-local dependencies for DeepSeek Messages. */ -import type { LlmModelInfo, ModelModality, SystemPromptUpdate, ToolUpdate, ResolvedRetryPolicy, ImageAttachmentAccess } from '@deepseek-ai/dsh-llm' +import type { + ImageAttachmentAccess, LlmCredentialKind, LlmError, LlmModelInfo, ModelModality, ResolvedRetryPolicy, RouteCredentialGrant, + SystemPromptUpdate, ToolUpdate, +} from '@deepseek-ai/dsh-llm' import type { AttachmentStore, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { AnonymousUserId } from '@deepseek-ai/dsh-anonymous-user-id' import type { DeepSeekLlmApiExtensionRequest, PreparedDeepSeekLlmApiExtensions } from '@deepseek-ai/dsh-deepseek-llm-api-extensions' @@ -81,14 +84,30 @@ export interface DeepSeekConnectionOptions { retryPolicy: ResolvedRetryPolicy } -/** Authentication captured by the provider for one request and its file operations. */ -export interface DeepSeekRequestAuth { - /** Credential headers sent unchanged to the resolved endpoint. */ - headers: Readonly> +/** + * Authentication released for one request and its file operations: the route + * credential grant the provider plugin builds, plus the request-failure + * classification bound to that credential. + */ +export interface DeepSeekRequestAuth extends RouteCredentialGrant { /** Classify a failure using the captured credential; callback failure preserves the original error. */ onRequestError?: (error: unknown) => Promise } +/** + * What `routeCredential()` publishes about the route's credential beside the + * request-path hooks, so consumers outside the model request path share the + * route's credential without reading its configuration. + */ +export interface DeepSeekRouteCredentialOptions { + /** Kind of credential the route sends. */ + kind: LlmCredentialKind + /** Credential reference the route resolves, named by diagnostics; omission publishes none. */ + reference?: (connection: Connection) => string | undefined + /** Report whether a credential exists for `endpoint` without reading its value. */ + configured: (connection: Connection, endpoint: string) => Promise +} + /** Constructor options for {@link DeepSeekAdapter}: the operation-local resolution hooks the plugin owns. */ export interface DeepSeekAdapterOptions { /** Report unusable native Messages replay metadata without exposing content or signatures. */ @@ -111,8 +130,20 @@ export interface DeepSeekAdapterOptions Promise /** Refuse a model before any network I/O by throwing an `LlmError`; omission admits every model. */ admit?: (connection: Connection, model: string) => void - /** Resolve authentication from this request's connection snapshot; never re-read the endpoint. */ - resolveAuth: (connection: Connection) => Promise + /** + * Release authentication for `endpoint` from this request's connection + * snapshot, or `undefined` when the route has no credential for it; never + * re-read the endpoint. Model requests pass the connection's own base URL; + * `routeCredential()` consumers pass theirs. + */ + resolveAuth: (connection: Connection, endpoint: string) => Promise + /** + * The failure a model request reports when {@link resolveAuth} releases no + * credential for the route's own endpoint; omission reports `MISSING_CREDENTIAL`. + */ + missingCredential?: (connection: Connection, provider: string) => LlmError + /** Publish the route's credential through `routeCredential()`; omission publishes none. */ + credential?: DeepSeekRouteCredentialOptions /** Resolve the harness-home anonymous id shared with telemetry and feedback. */ resolveUserId: () => AnonymousUserId /** Resolve the current durable attachment service; absence rejects image input. */ diff --git a/packages/llm/llm-deepseek/tests/account-routing.spec.ts b/packages/llm/llm-deepseek/tests/account-routing.spec.ts index 4a6cd8ddb8..94d2361d0c 100644 --- a/packages/llm/llm-deepseek/tests/account-routing.spec.ts +++ b/packages/llm/llm-deepseek/tests/account-routing.spec.ts @@ -1,8 +1,7 @@ /** Account route cancellation uses the real loop, registry, and tool lifecycle. */ import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native' import { afterEach, expect, it, vi } from 'vitest' -import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' -import { installAccountTaskCancellation } from '@deepseek-ai/dsh-deepseek-account/src/account-tasks.ts' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' import { Context } from '@deepseek-ai/cordis' import LlmRuntime, { createUserMessage, LlmAdapter, type GenerateOptions, type StreamChunk, ToolCallId } from '@deepseek-ai/dsh-llm' import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent' @@ -33,7 +32,6 @@ function listingRequest(input: string | URL | Request): Response | undefined { async function harness() { const ctx = new Context() contexts.push(ctx) - installAccountTaskCancellation(ctx) for (const plugin of [ LlmRuntime, SessionStore, SessionProjectionRegistry, SystemPrompt, ToolRuntime, NativeToolExecutor, AgentRegistry, ]) { @@ -186,7 +184,7 @@ it('never borrows an account token for a missing API key', async () => { const ctx = new Context() contexts.push(ctx) const resolveToken = vi.fn(async (_url: string) => 'fixture-account-token') - ctx.provide('deepseekAccount', { resolveToken: (url: string): Promise => resolveToken(url) } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: url => resolveToken(url) })) await ctx.plugin(LlmRuntime) await ctx.plugin(DeepSeek, {}) await ctx.plugin(AccountProvider, {}) @@ -200,7 +198,7 @@ it('never borrows an account token for a missing API key', async () => { it('propagates account sign-out to the HTTP request signal', async () => { const ctx = await harness() - ctx.provide('deepseekAccount', { resolveToken: async (_url: string) => 'fixture-account-token' } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => 'fixture-account-token' })) const started = Promise.withResolvers() vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => { const listed = listingRequest(url) @@ -254,7 +252,7 @@ it('lists each DeepSeek route only when its own credential is present', async () vi.stubGlobal('fetch', vi.fn((input: string | URL | Request) => Promise.resolve(listingRequest(input) ?? new Response(null, { status: 500 })))) const ctx = await harness() let token: string | undefined - ctx.provide('deepseekAccount', { resolveToken: async (url: string) => new URL(url).origin === 'https://api.deepseek.com' ? token : undefined } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: url => new URL(url).origin === 'https://api.deepseek.com' ? token : undefined })) expect(await ctx.llm.listModels('deepseek-account')).toEqual([]) expect(await ctx.llm.listModels('deepseek-official')).toEqual([]) token = 'fixture-account-token' @@ -269,7 +267,7 @@ it('lists each DeepSeek route only when its own credential is present', async () it('surfaces credential storage failures during catalog discovery', async () => { const ctx = await harness() - ctx.provide('deepseekAccount', { resolveToken: async (_url: string): Promise => { throw new Error('storage unavailable') } } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => { throw new Error('storage unavailable') } })) await expect(ctx.llm.listModels('deepseek-account')).rejects.toThrow('storage unavailable') }) diff --git a/packages/llm/llm-deepseek/tests/adapter.spec.ts b/packages/llm/llm-deepseek/tests/adapter.spec.ts index 9629892f70..6981f6c039 100644 --- a/packages/llm/llm-deepseek/tests/adapter.spec.ts +++ b/packages/llm/llm-deepseek/tests/adapter.spec.ts @@ -1,7 +1,6 @@ /** HTTP lifecycle, routing and optional Cordis services under real composition. */ import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native' -import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' -import { installAccountTaskCancellation } from '@deepseek-ai/dsh-deepseek-account/src/account-tasks.ts' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' import type { AnonymousUserId } from '@deepseek-ai/dsh-anonymous-user-id' import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' @@ -28,6 +27,7 @@ import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import { DeepSeekAdapter } from '../src/adapter.ts' import { object } from '../src/replay.ts' import { DeepSeekFileStore } from '../src/file-store.ts' +import { resolveAdapterOptions } from '../src/config.ts' import * as Messages from '@deepseek-ai/dsh-llm-deepseek-api-key' import * as AccountProvider from '@deepseek-ai/dsh-llm-deepseek-account' import { adapter, assemble, chunks, MODEL, options, prepareExtensions, server, sse, textEvents, user, sourceModuleLoader } from './helpers.ts' @@ -197,8 +197,8 @@ describe('direct Messages HTTP', () => { const prepare = vi.fn(async () => ({ fields: {}, accept })) const files = new DeepSeekFileStore() const llm = new DeepSeekAdapter({ - options: () => Messages.resolveAdapterOptions({ baseURL: source.url }), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' } }), resolveUserId: () => 'test-user' as AnonymousUserId, + options: () => resolveAdapterOptions({ baseURL: source.url }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' }, value: 'test-key' }), resolveUserId: () => 'test-user' as AnonymousUserId, resolveAttachments: () => undefined, resolveImageAccess: () => undefined, resolveFiles: () => files, prepareExtensions: prepare, }) @@ -213,11 +213,11 @@ describe('direct Messages HTTP', () => { it('freezes endpoint and defaults for a prepared call while the next call sees new settings', async () => { const first = await endpoint(), second = await endpoint() - let config = Messages.resolveAdapterOptions({ baseURL: first.url, maxTokens: 10, models: [{ id: MODEL, systemPromptUpdate: 'in-history' }] }) + let config = resolveAdapterOptions({ baseURL: first.url, maxTokens: 10, models: [{ id: MODEL, systemPromptUpdate: 'in-history' }] }) const files = new DeepSeekFileStore() - const llm = new DeepSeekAdapter({ options: () => config, resolveAuth: snapshot => Promise.resolve({ headers: { 'x-api-key': snapshot.maxTokens === 10 ? 'first' : 'second' } }), resolveUserId: () => 'user' as AnonymousUserId, resolveAttachments: () => undefined, resolveImageAccess: () => undefined, resolveFiles: () => files, prepareExtensions }) + const llm = new DeepSeekAdapter({ options: () => config, resolveAuth: snapshot => Promise.resolve({ headers: { 'x-api-key': snapshot.maxTokens === 10 ? 'first' : 'second' }, value: snapshot.maxTokens === 10 ? 'first' : 'second' }), resolveUserId: () => 'user' as AnonymousUserId, resolveAttachments: () => undefined, resolveImageAccess: () => undefined, resolveFiles: () => files, prepareExtensions }) const prepared = await llm.prepareCall('deepseek-official', MODEL) - config = Messages.resolveAdapterOptions({ baseURL: second.url, maxTokens: 20 }) + config = resolveAdapterOptions({ baseURL: second.url, maxTokens: 20 }) expect(prepared.model.systemPromptUpdate).toBe('in-history') expect((await llm.resolveModel('deepseek-official', MODEL)).systemPromptUpdate).toBeUndefined() await chunks(prepared.stream(options())) @@ -275,8 +275,8 @@ describe('direct Messages HTTP', () => { it('preserves the transport failure when a provider error callback rejects', async () => { vi.stubGlobal('fetch', async () => new Response('Unauthorized', { status: 401 })) const llm = new DeepSeekAdapter({ - options: () => Messages.resolveAdapterOptions({}), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'fixture-key' }, + options: () => resolveAdapterOptions({}), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'fixture-key' }, value: 'fixture-key', onRequestError: async () => { throw new Error('credential storage unavailable') }, }), resolveUserId: () => 'fixture-user' as import('@deepseek-ai/dsh-anonymous-user-id').AnonymousUserId, @@ -381,8 +381,7 @@ describe('Cordis provider composition', () => { response.end(body) }) const rejectToken = vi.fn(async (_token: string) => {}) - ctx.provide('deepseekAccount', { resolveToken: async (_url: string): Promise => 'fixture-token', - rejectToken: (token: string): Promise => rejectToken(token) } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => 'fixture-token', reject: rejectToken })) expect((await chunks(ctx.llm.stream(options({ provider })))).at(-1)).toMatchObject({ type: 'finish', reason: { kind: 'error', failure: { code: provider === 'deepseek-account' ? 'ACCOUNT_TOKEN_INVALID' : 'AUTH' } }, }) @@ -397,8 +396,7 @@ describe('Cordis provider composition', () => { response.end('Unauthorized') }) const rejectToken = vi.fn(async (_token: string) => {}) - ctx.provide('deepseekAccount', { resolveToken: async (_url: string): Promise => token, - rejectToken: (value: string): Promise => rejectToken(value) } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => token, reject: rejectToken })) await chunks(ctx.llm.stream(options({ provider: 'deepseek-account' }))) expect(token).toBe('replacement-login') expect(rejectToken).toHaveBeenCalledExactlyOnceWith('first-login') @@ -409,9 +407,7 @@ describe('Cordis provider composition', () => { response.writeHead(401) response.end(JSON.stringify({ error: { message: 'Authentication Fails (invalid dsh token)' } })) }) - ctx.provide('deepseekAccount', { resolveToken: async (_url: string): Promise => 'fixture-token', - rejectToken: async (_token: string): Promise => { ctx.emit('deepseek-account/signed-out') } } as DeepSeekAccount) - installAccountTaskCancellation(ctx) + ctx.provide('deepseekAccount', accountStub({ token: () => 'fixture-token', reject: () => { ctx.emit('deepseek-account/signed-out') } })) const agent = await ctx.agentLoop.create(SessionId('inference-account-expiry'), { provider: 'deepseek-account', model: MODEL }) agent.followup(user('hello')) await agent.whenIdle() @@ -425,8 +421,7 @@ describe('Cordis provider composition', () => { response.writeHead(401) response.end(JSON.stringify({ error: { message: 'Authentication Fails (invalid dsh token)' } })) }) - ctx.provide('deepseekAccount', { resolveToken: async (_url: string): Promise => 'fixture-token', - rejectToken: async (_token: string): Promise => { throw new Error('credential storage unavailable') } } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => 'fixture-token', reject: () => { throw new Error('credential storage unavailable') } })) expect((await chunks(ctx.llm.stream(options({ provider: 'deepseek-account' })))).at(-1)).toMatchObject({ type: 'finish', reason: { kind: 'error', failure: { code: 'ACCOUNT_TOKEN_INVALID' } }, }) @@ -444,8 +439,7 @@ describe('Cordis provider composition', () => { client_requirements: { 'deepseek-harness': { min_version: '99.0.0' } }, }, ] }) - ctx.provide('deepseekAccount', { resolveToken: async (_url: string): Promise => 'fixture-token', - rejectToken: async (_token: string): Promise => {} } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => 'fixture-token' })) expect((await ctx.llm.listModels('deepseek-account')).map(model => [model.id, model.name])).toEqual([['deepseek-flash', 'DeepSeek-V4.1-Flash']]) await expect(ctx.llm.prepareCall({ provider: 'deepseek-account', model: 'deepseek-v5' })) .rejects.toMatchObject({ code: 'CLIENT_UPGRADE_REQUIRED' }) @@ -459,8 +453,7 @@ describe('Cordis provider composition', () => { response.end(JSON.stringify({ error: { type: 'authentication_error', message: 'API key is invalid' } })) }) const rejectToken = vi.fn(async (_token: string) => {}) - ctx.provide('deepseekAccount', { resolveToken: async (_url: string): Promise => 'fixture-token', - rejectToken: (token: string): Promise => rejectToken(token) } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => 'fixture-token', reject: rejectToken })) expect((await chunks(ctx.llm.stream(options({ provider: 'deepseek-account' })))).at(-1)).toMatchObject({ type: 'finish', reason: { kind: 'error', failure: { code: 'AUTH' } }, }) @@ -637,7 +630,7 @@ describe('Cordis provider composition', () => { }) it('rejects invalid catalog context windows at the options resolver', () => { - expect(() => Messages.resolveAdapterOptions({ models: [{ id: 'invalid-window', contextWindow: 0 }] })).toThrow('contextWindow must be a positive integer') + expect(() => resolveAdapterOptions({ models: [{ id: 'invalid-window', contextWindow: 0 }] })).toThrow('contextWindow must be a positive integer') }) @@ -647,10 +640,8 @@ it.each([ ] as const)('selects account or API-key credentials from the actual endpoint %s', async (baseURL, expected) => { vi.stubEnv('DEEPSEEK_API_KEY', 'ambient-key') const { ctx } = await context() - // This consumer uses only resolveToken; the real provider owns origin validation in its own suite. - ctx.provide('deepseekAccount', { - resolveToken: (url: string) => Promise.resolve(url === 'https://api.deepseek.com' ? 'account-token' : undefined), - } as DeepSeekAccount) + // The stand-in releases the credential by exact destination; the real service owns origin validation in its own suite. + ctx.provide('deepseekAccount', accountStub({ token: url => url === 'https://api.deepseek.com' ? 'account-token' : undefined })) await ctx.plugin(LlmRuntime) await ctx.plugin(expected === 'account-token' ? AccountProvider : Messages, { baseURL }) const request = vi.fn((_input, init) => { diff --git a/packages/llm/llm-deepseek/tests/credential.spec.ts b/packages/llm/llm-deepseek/tests/credential.spec.ts deleted file mode 100644 index 6054a07c4f..0000000000 --- a/packages/llm/llm-deepseek/tests/credential.spec.ts +++ /dev/null @@ -1,71 +0,0 @@ -/** Shared credential resolution and metadata-only readiness across DeepSeek consumers. */ -import { Context } from '@deepseek-ai/cordis' -import { describe, expect, it, vi } from 'vitest' -import { credentialRef } from '@deepseek-ai/dsh-credentials' -import { createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY } from '@deepseek-ai/dsh-launch-environment' -import { deepSeekApiKeyConfigured, rejectDeepSeekAccountToken, resolveDeepSeekAccountToken, resolveDeepSeekApiKey } from '../src/credential.ts' - -const ref = credentialRef('TEST_DEEPSEEK_KEY') - -function context(value?: string): Context { - const ctx = new Context() - ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([ - { source: 'process', values: value === undefined ? {} : { [ref]: value } }, - ])) - return ctx -} - -describe('shared DeepSeek credentials', () => { - it.each([undefined, '', ' valid-key '])('reads the launch environment only without credentials: %j', async (value) => { - const ctx = context(value) - try { - await expect(resolveDeepSeekApiKey(ctx, ref)).resolves.toBe(value ? value.trim() : undefined) - await expect(deepSeekApiKeyConfigured(ctx, ref)).resolves.toBe(Boolean(value)) - } finally { await ctx.fiber.dispose() } - }) - - it('treats the installed service as authoritative and reads no value for configured', async () => { - const ctx = context('ambient-key') - const resolve = vi.fn(async () => undefined) - const describe = vi.fn(async () => ({ configured: false })) - ctx.provide('credentials', { resolve, describe } as never) - try { - await expect(deepSeekApiKeyConfigured(ctx, ref)).resolves.toBe(false) - expect(resolve).not.toHaveBeenCalled() - await expect(resolveDeepSeekApiKey(ctx, ref)).resolves.toBeUndefined() - expect(resolve).toHaveBeenCalledExactlyOnceWith(ref) - } finally { await ctx.fiber.dispose() } - }) - - it.each(['bad key', '非法密钥', 'bad\nkey', ' '])('rejects malformed environment keys without exposing the value: %j', async (value) => { - const ctx = context(value) - try { - await expect(resolveDeepSeekApiKey(ctx, ref)).rejects.toMatchObject({ code: 'INVALID_CREDENTIAL' }) - } finally { await ctx.fiber.dispose() } - }) - - it('validates and normalizes each stored key without caching it', async () => { - const ctx = context('ambient-key') - const resolve = vi.fn().mockResolvedValueOnce({ value: ' stored-key ' }).mockResolvedValueOnce({ value: 'bad key' }) - ctx.provide('credentials', { resolve } as never) - try { - await expect(resolveDeepSeekApiKey(ctx, ref)).resolves.toBe('stored-key') - await expect(resolveDeepSeekApiKey(ctx, ref)).rejects.toMatchObject({ code: 'INVALID_CREDENTIAL' }) - } finally { await ctx.fiber.dispose() } - }) - - it('delegates account destination checks and contains token-removal failures', async () => { - const ctx = context() - try { - await expect(resolveDeepSeekAccountToken(ctx, 'https://allowed.test')).resolves.toBeUndefined() - await expect(rejectDeepSeekAccountToken(ctx, 'old-token')).resolves.toBeUndefined() - const resolveToken = vi.fn(async () => 'account-token') - const rejectToken = vi.fn(async () => { throw new Error('storage failed') }) - ctx.provide('deepseekAccount', { resolveToken, rejectToken } as never) - await expect(resolveDeepSeekAccountToken(ctx, 'https://allowed.test')).resolves.toBe('account-token') - expect(resolveToken).toHaveBeenCalledExactlyOnceWith('https://allowed.test') - await expect(rejectDeepSeekAccountToken(ctx, 'old-token')).resolves.toBeUndefined() - expect(rejectToken).toHaveBeenCalledExactlyOnceWith('old-token') - } finally { await ctx.fiber.dispose() } - }) -}) diff --git a/packages/llm/llm-deepseek/tests/files.spec.ts b/packages/llm/llm-deepseek/tests/files.spec.ts index bb44326318..124830cb5b 100644 --- a/packages/llm/llm-deepseek/tests/files.spec.ts +++ b/packages/llm/llm-deepseek/tests/files.spec.ts @@ -39,7 +39,7 @@ function harness(config: Config = {}) { const prepare = vi.fn(prepareExtensions) const adapter = new DeepSeekAdapter({ options: () => resolveAdapterOptions(Object.assign({ baseURL: 'https://gateway.example/custom' }, config)), - resolveAuth: async () => ({ headers: { 'x-api-key': 'test-key' } }), resolveUserId: () => 'test-user' as AnonymousUserId, resolveAttachments: () => attachments, + resolveAuth: async () => ({ headers: { 'x-api-key': 'test-key' }, value: 'test-key' }), resolveUserId: () => 'test-user' as AnonymousUserId, resolveAttachments: () => attachments, resolveImageAccess: () => ({ readonlyPath: '/workspace/image.png' }), resolveFiles: () => files, prepareExtensions: prepare, }) return { adapter, ensureUploaded, invalidate, readImageRequest, prepare } diff --git a/packages/llm/llm-deepseek/tests/helpers.ts b/packages/llm/llm-deepseek/tests/helpers.ts index 77beea8f04..08af4080c5 100644 --- a/packages/llm/llm-deepseek/tests/helpers.ts +++ b/packages/llm/llm-deepseek/tests/helpers.ts @@ -45,7 +45,7 @@ export async function assemble(stream: AsyncIterable, model = MODEL } export function adapter(config: Config = {}, dependencies: Partial = {}) { const files = new DeepSeekFileStore() - return new DeepSeekAdapter({ options: () => resolveAdapterOptions(config), resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' } }), resolveUserId: () => 'test-user' as AnonymousUserId, resolveAttachments: () => undefined, resolveImageAccess: () => undefined, resolveFiles: () => files, prepareExtensions, ...dependencies }) + return new DeepSeekAdapter({ options: () => resolveAdapterOptions(config), resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' }, value: 'test-key' }), resolveUserId: () => 'test-user' as AnonymousUserId, resolveAttachments: () => undefined, resolveImageAccess: () => undefined, resolveFiles: () => files, prepareExtensions, ...dependencies }) } /** * Loopback Messages endpoint recording each model request. diff --git a/packages/llm/llm-deepseek/tests/listing-cache.spec.ts b/packages/llm/llm-deepseek/tests/listing-cache.spec.ts index cd6233745e..6b52e8bd8c 100644 --- a/packages/llm/llm-deepseek/tests/listing-cache.spec.ts +++ b/packages/llm/llm-deepseek/tests/listing-cache.spec.ts @@ -8,6 +8,11 @@ import type { ModelListing } from '../src/listing.ts' afterEach(() => { vi.useRealTimers() }) +/** Header the fixture route sends its credential under. */ +const TOKEN_HEADER = 'x-test-token' +const headersOf = (token: string | undefined): Readonly> | undefined => + token === undefined ? undefined : { [TOKEN_HEADER]: token } + const listing = (...ids: string[]): ModelListing => ({ skipped: 0, entries: ids.map(id => ({ id, requirement: { kind: 'none' }, capabilities: { usable: true, facts: { inputModalities: ['text'] } } })), @@ -16,20 +21,20 @@ const listing = (...ids: string[]): ModelListing => ({ function harness(timeoutMs = 60_000, honorsAbort = true) { let clock = 0 let token: string | undefined = 'token-a' - const loads: Array<{ token: string; signal: AbortSignal; settle: PromiseWithResolvers }> = [] + const loads: Array<{ token: string | undefined; signal: AbortSignal; settle: PromiseWithResolvers }> = [] const info = vi.fn() const warn = vi.fn() const changed = vi.fn() const settings: { -readonly [K in keyof ListingSettings]: ListingSettings[K] } = { url: 'https://api.example/models', timeoutMs, maxAgeMs: 100 } const resolveSettings = vi.fn<() => ListingSettings | undefined>(() => settings) - const resolveCredential = vi.fn(() => Promise.resolve(token)) + const resolveCredential = vi.fn(() => Promise.resolve(headersOf(token))) const cache = new ModelListingCache({ settings: resolveSettings, credential: resolveCredential, - load: (_url, value, signal) => { + load: (_url, headers, signal) => { const settle = Promise.withResolvers() if (honorsAbort) signal.addEventListener('abort', () => { settle.reject(signal.reason) }, { once: true }) - loads.push({ token: value, signal, settle }) + loads.push({ token: headers[TOKEN_HEADER], signal, settle }) return settle.promise }, now: () => clock, @@ -373,7 +378,7 @@ it('retains badges on credential lookup failures, reports the streak once, and r expect(catalog.current().listing).toEqual(badgedListing('New')) expect(changed).toHaveBeenCalledTimes(1) expect(warn).toHaveBeenCalledExactlyOnceWith(expect.stringContaining('check listing configuration and credentials')) - resolveCredential.mockResolvedValue('token-a') + resolveCredential.mockResolvedValue(headersOf('token-a')) advance(100) await vi.advanceTimersByTimeAsync(100) loads[1]!.settle.resolve(badgedListing('Back')) @@ -389,7 +394,7 @@ it.each(['resolve', 'reject'] as const)('awaits a pending automatic credential l await flush() loads[0]!.settle.resolve(listing('a')) await first - const credential = Promise.withResolvers() + const credential = Promise.withResolvers> | undefined>() resolveCredential.mockReturnValue(credential.promise) advance(100) await vi.advanceTimersByTimeAsync(100) @@ -397,7 +402,7 @@ it.each(['resolve', 'reject'] as const)('awaits a pending automatic credential l const disposal = catalog.dispose().then(() => { disposed = true }) await flush() expect(disposed).toBe(false) - if (outcome === 'resolve') credential.resolve('token-a') + if (outcome === 'resolve') credential.resolve(headersOf('token-a')) else credential.reject(new Error('lookup failed')) await disposal expect(loads).toHaveLength(1) diff --git a/packages/llm/llm-deepseek/tests/prepared-call.spec.ts b/packages/llm/llm-deepseek/tests/prepared-call.spec.ts index a54647ef7e..f4c35237d8 100644 --- a/packages/llm/llm-deepseek/tests/prepared-call.spec.ts +++ b/packages/llm/llm-deepseek/tests/prepared-call.spec.ts @@ -2,7 +2,8 @@ import { afterEach, expect, it } from 'vitest' import type { AnonymousUserId } from '@deepseek-ai/dsh-anonymous-user-id' import { DeepSeekAdapter } from '../src/index.ts' -import { Config, plainOptions, resolveAdapterOptions } from '@deepseek-ai/dsh-llm-deepseek-api-key' +import { Config } from '@deepseek-ai/dsh-llm-deepseek-api-key' +import { plainOptions, resolveAdapterOptions } from '@deepseek-ai/dsh-llm-deepseek-api-key/src/config.ts' import type { ResolvedDeepSeekOptions as DeepSeekConnectionOptions } from '@deepseek-ai/dsh-llm-deepseek-api-key' import { assemble, chunks, MODEL, options, server } from './helpers.ts' @@ -18,7 +19,7 @@ async function endpoint(...args: Parameters) { function adapter(connection: () => DeepSeekConnectionOptions) { return new DeepSeekAdapter({ options: connection, - resolveAuth: snapshot => Promise.resolve({ headers: { 'x-api-key': `key-for-${snapshot.apiKeyEnv}` } }), + resolveAuth: snapshot => Promise.resolve({ headers: { 'x-api-key': `key-for-${snapshot.apiKeyEnv}` }, value: `key-for-${snapshot.apiKeyEnv}` }), resolveUserId: () => '00000000-0000-4000-8000-000000000001' as AnonymousUserId, prepareExtensions: () => Promise.resolve({ fields: {}, accept: () => Promise.resolve() }), }) diff --git a/packages/llm/llm-deepseek/tests/provider-hooks.spec.ts b/packages/llm/llm-deepseek/tests/provider-hooks.spec.ts index 90a2d6f502..778cd5564b 100644 --- a/packages/llm/llm-deepseek/tests/provider-hooks.spec.ts +++ b/packages/llm/llm-deepseek/tests/provider-hooks.spec.ts @@ -23,7 +23,7 @@ async function route(hooks: Pick) { inject: ['llm'], apply: (child: Context) => { registerDeepSeekProvider(child, 'fixture-route', { - options: () => endpoint(), resolveAuth: () => Promise.resolve({ headers: {} }), ...hooks, + options: () => endpoint(), resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'fixture-key' }, value: 'fixture-key' }), ...hooks, }) }, }) @@ -59,7 +59,7 @@ it('refuses a model before a prepared call exists', async () => { it('refuses a model on a direct adapter stream', () => { const adapter = new DeepSeekAdapter({ options: () => endpoint(), - resolveAuth: () => Promise.resolve({ headers: {} }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'fixture-key' }, value: 'fixture-key' }), resolveUserId: () => 'fixture-user' as AnonymousUserId, prepareExtensions, admit: () => { throw new LlmError('blocked by fixture', 'MODEL_UNSUPPORTED') }, diff --git a/packages/llm/llm-deepseek/tests/route-credential.spec.ts b/packages/llm/llm-deepseek/tests/route-credential.spec.ts new file mode 100644 index 0000000000..8176bc65aa --- /dev/null +++ b/packages/llm/llm-deepseek/tests/route-credential.spec.ts @@ -0,0 +1,92 @@ +/** The adapter publishes a route credential only for providers that declare one, and refuses requests without a credential. */ +import { afterEach, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import LlmRuntime, { LlmError } from '@deepseek-ai/dsh-llm' +import type { AnonymousUserId } from '@deepseek-ai/dsh-anonymous-user-id' +import { DeepSeekAdapter, registerDeepSeekProvider, resolveAdapterOptions } from '../src/index.ts' +import type { DeepSeekAdapterOptions, DeepSeekRequestAuth, ResolvedDeepSeekOptions } from '../src/index.ts' +import { chunks, options as request, prepareExtensions } from './helpers.ts' + +const contexts: Context[] = [] +afterEach(async () => { + for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() + vi.unstubAllGlobals() +}) + +const BASE_URL = 'https://route.deepseek.test/anthropic' +const ALLOWED = 'https://route.deepseek.test/v1/tools/search' +const OTHER = 'https://route.deepseek.test/v1/tools/fetch' +const connection = () => resolveAdapterOptions({ baseURL: BASE_URL }) + +type Hooks = Partial> + +/** Mount the runtime and one fixture route whose credential hooks are `hooks`. */ +async function route(hooks: Hooks): Promise { + const ctx = new Context() + contexts.push(ctx) + await ctx.plugin(LlmRuntime) + await ctx.plugin({ + name: 'fixture-route', + inject: ['llm'], + apply: (child: Context) => { + registerDeepSeekProvider(child, 'fixture-route', { options: connection, resolveAuth: () => Promise.resolve(undefined), ...hooks }) + }, + }) + return ctx +} + +/** A direct adapter without a credential, failing requests through `missingCredential` when given. */ +function adapterWithout(missingCredential?: DeepSeekAdapterOptions['missingCredential']): DeepSeekAdapter { + return new DeepSeekAdapter({ + options: connection, + resolveAuth: () => Promise.resolve(undefined), + resolveUserId: () => 'fixture-user' as AnonymousUserId, + prepareExtensions, + ...missingCredential === undefined ? {} : { missingCredential }, + }) +} + +it('publishes no credential for a provider that declares none', async () => { + const ctx = await route({}) + expect(ctx.llm.routeCredential('fixture-route')).toBeUndefined() +}) + +it('publishes the declared credential from one configuration generation and resolves it per endpoint', async () => { + const resolveAuth = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string): Promise => + endpoint === ALLOWED ? { headers: { 'x-fixture': 'k' }, value: 'k' } : undefined) + const configured = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string) => endpoint === ALLOWED) + const ctx = await route({ resolveAuth, credential: { kind: 'api-key', reference: () => 'FIXTURE_KEY', configured } }) + const credential = ctx.llm.routeCredential('fixture-route') + expect(credential).toMatchObject({ kind: 'api-key', baseURL: BASE_URL, reference: 'FIXTURE_KEY' }) + await expect(credential!.configured(ALLOWED)).resolves.toBe(true) + await expect(credential!.configured(OTHER)).resolves.toBe(false) + await expect(credential!.resolve(ALLOWED)).resolves.toEqual({ headers: { 'x-fixture': 'k' }, value: 'k' }) + await expect(credential!.resolve(OTHER)).resolves.toBeUndefined() + await expect(credential!.resolve(ALLOWED, AbortSignal.abort(new Error('caller left')))).rejects.toThrow('caller left') + expect(resolveAuth).toHaveBeenCalledTimes(2) + expect(configured.mock.calls.map(([{ baseURL }]) => baseURL)).toEqual([BASE_URL, BASE_URL]) +}) + +it('omits the reference of a credential kind without one', async () => { + const ctx = await route({ credential: { kind: 'account', configured: () => Promise.resolve(false) } }) + const credential = ctx.llm.routeCredential('fixture-route') + expect(credential).toMatchObject({ kind: 'account', baseURL: BASE_URL }) + expect(credential).not.toHaveProperty('reference') +}) + +it('fails a request without a credential before any network I/O, with the default diagnostic', async () => { + const fetchMock = vi.fn() + vi.stubGlobal('fetch', fetchMock) + await expect(chunks(adapterWithout().stream(request({ provider: 'fixture-route' })))).rejects.toMatchObject({ + code: 'MISSING_CREDENTIAL', message: 'llm-deepseek: no credential for provider route "fixture-route"', + }) + expect(fetchMock).not.toHaveBeenCalled() +}) + +it('fails a request without a credential with the provider\'s own diagnostic', async () => { + vi.stubGlobal('fetch', vi.fn()) + const missing = adapterWithout((_connection, provider) => new LlmError(`sign in for ${provider}`, 'ACCOUNT_SIGN_IN_REQUIRED')) + await expect(chunks(missing.stream(request({ provider: 'fixture-route' })))).rejects.toMatchObject({ + code: 'ACCOUNT_SIGN_IN_REQUIRED', message: 'sign in for fixture-route', + }) +}) diff --git a/packages/llm/llm-deepseek/tests/runtime.spec.ts b/packages/llm/llm-deepseek/tests/runtime.spec.ts index 3c4676ba0d..5dde3d3f9a 100644 --- a/packages/llm/llm-deepseek/tests/runtime.spec.ts +++ b/packages/llm/llm-deepseek/tests/runtime.spec.ts @@ -78,7 +78,7 @@ function adapterOf( const { apiKey, ...rest } = config return new DeepSeekAdapter({ options: () => resolveAdapterOptions({ ...rest }), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': apiKey ?? 'k' } }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': apiKey ?? 'k' }, value: apiKey ?? 'k' }), resolveUserId: () => TEST_USER_ID, resolveAttachments: () => attachments, ...files === undefined ? {} : { resolveFiles: () => files }, @@ -192,7 +192,7 @@ describe('request image target', () => { const attachments = {} as AttachmentStore const adapter = new DeepSeekAdapter({ options: () => resolveAdapterOptions({ models: [{ id: 'vision', inputModalities: ['text', 'image'] }] }), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }), resolveUserId: () => TEST_USER_ID, resolveAttachments: () => attachments, resolveImageAccess: (store, ref) => (store === attachments && ref === imageRef @@ -215,7 +215,7 @@ describe('DeepSeekAdapter against a mock server', () => { })) const adapter = new DeepSeekAdapter({ options: () => resolveAdapterOptions({ baseURL: server.url }), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }), resolveUserId: () => TEST_USER_ID, prepareExtensions: prepareExtensions as never, }) @@ -230,7 +230,7 @@ describe('DeepSeekAdapter against a mock server', () => { const server = await mockServer([]) const base = { options: () => resolveAdapterOptions({ baseURL: server.url }), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }), resolveUserId: () => TEST_USER_ID, } const failed = new DeepSeekAdapter({ @@ -259,7 +259,7 @@ describe('DeepSeekAdapter against a mock server', () => { let signalSeen: AbortSignal | undefined const adapter = new DeepSeekAdapter({ options: () => resolveAdapterOptions({ baseURL: server.url }), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }), resolveUserId: () => TEST_USER_ID, prepareExtensions: ((request: { signal: AbortSignal }) => { signalSeen = request.signal @@ -324,7 +324,7 @@ describe('DeepSeekAdapter against a mock server', () => { const accept = vi.fn() const adapter = new DeepSeekAdapter({ options: () => resolveAdapterOptions({ baseURL: server.url }), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }), resolveUserId: () => TEST_USER_ID, prepareExtensions: () => Promise.resolve({ fields: { dsh_test: 1 }, accept: async () => { accept() } }) as never, }) @@ -342,7 +342,7 @@ describe('DeepSeekAdapter against a mock server', () => { const unaccepted = vi.fn() const base = { options: () => resolveAdapterOptions({ baseURL: server.url }), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }), resolveUserId: () => TEST_USER_ID, prepareExtensions: () => Promise.resolve({ fields: { dsh_test: 1 }, @@ -1142,7 +1142,7 @@ describe('DeepSeekAdapter against a mock server', () => { 'rejects image input for text-only model %s before credentials, image reads, or fetch', async (model) => { const server = await mockServer([]) - const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'k' } })) + const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' })) const attachments = attachmentStoreOf(ref => Promise.resolve(requestImage(ref))) const resolveAttachments = vi.fn(() => attachments.store) const adapter = new DeepSeekAdapter({ @@ -1169,7 +1169,7 @@ describe('DeepSeekAdapter against a mock server', () => { it('rejects vision input without an attachment provider before credentials or fetch', async () => { const server = await mockServer([]) - const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'k' } })) + const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' })) const adapter = new DeepSeekAdapter({ options: () => resolveAdapterOptions({ baseURL: server.url, @@ -2320,7 +2320,7 @@ describe('plugin registration and config', () => { it('resolves connection facts and the credential exactly once per stream call', async () => { const server = await mockServer([{ kind: 'sse', events: textEvents }]) const options = vi.fn(() => resolveAdapterOptions({ baseURL: server.url })) - const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'per-request-key' } })) + const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'per-request-key' }, value: 'per-request-key' })) const resolveUserId = vi.fn(() => TEST_USER_ID) const adapter = new DeepSeekAdapter({ options, resolveAuth, resolveUserId, prepareExtensions: noExtensions }) diff --git a/packages/llm/llm-deepseek/tsconfig.json b/packages/llm/llm-deepseek/tsconfig.json index 84c4ffe7a9..e307eab423 100644 --- a/packages/llm/llm-deepseek/tsconfig.json +++ b/packages/llm/llm-deepseek/tsconfig.json @@ -9,7 +9,7 @@ ], "references": [ { "path": "../../credentials/credentials" }, - { "path": "../../credentials/deepseek-account" }, + { "path": "../../account/deepseek-account" }, { "path": "../../../vendor/cosmokit" }, diff --git a/packages/llm/llm/src/index.ts b/packages/llm/llm/src/index.ts index 2f4299d8cd..113c698e0d 100644 --- a/packages/llm/llm/src/index.ts +++ b/packages/llm/llm/src/index.ts @@ -22,6 +22,7 @@ import type { LlmResolvedModelInfo, LlmProviderInfo, ModelModality, + RouteCredential, StreamChunk, SystemPromptUpdate, ToolSchema, @@ -264,6 +265,19 @@ export abstract class LlmAdapter { return { width: image.width, height: image.height, maxBytes: image.bytes } } + /** + * Describe the credential one owned route currently sends, for consumers that + * call the same deployment outside the model request path, such as web + * providers that share a route's credential and endpoint. The default + * publishes none. Implementations answer from one configuration generation + * per call and may throw when that configuration does not resolve. + * @param _provider - a route passed to `registerAdapter()` for this instance. + * @returns the route's current credential, or `undefined` when the route publishes none. + */ + routeCredential(_provider: string): RouteCredential | undefined { + return undefined + } + /** * List models this adapter can currently advertise for one owned provider. * Core routing accepts unlisted model ids; catalog-driven entry points such @@ -708,6 +722,19 @@ export class LlmRuntime extends TypertRemoteService { return this.registration(provider).adapter.imageRequestTarget(provider, model, image) } + /** + * Resolve the credential one registered route currently sends, through its + * owning adapter. An unregistered route answers `undefined` rather than + * throwing because callers ask about routes a conversation named earlier, + * which may no longer be mounted; a registered route whose configuration + * does not resolve propagates the adapter's failure. + * @param provider - provider route whose credential is wanted. + * @returns the route credential, or `undefined` when the route is unregistered or publishes none. + */ + routeCredential(provider: string): RouteCredential | undefined { + return this.adapters.get(provider)?.adapter.routeCredential(provider) + } + /** * Resolve the exact text one durable file occurrence contributes to every * provider request in the current execution environment. diff --git a/packages/llm/llm/src/types.ts b/packages/llm/llm/src/types.ts index 8a48b89895..53b0acb3e4 100644 --- a/packages/llm/llm/src/types.ts +++ b/packages/llm/llm/src/types.ts @@ -292,6 +292,87 @@ export interface LlmNativeAuth { oauth: boolean } +/** + * Merge-extensible vocabulary of the credential kinds a provider route sends. + * `api-key` is a provider key read from a credential reference or the launch + * environment; `account` is a grant obtained by signing in. An adapter that + * sends another kind declares it here. + */ +export interface LlmCredentialKindMap { + 'api-key': 'api-key' + account: 'account' +} + +/** Any declared credential kind. */ +export type LlmCredentialKind = LlmCredentialKindMap[keyof LlmCredentialKindMap] + +/** + * One credential released for one destination. Host-only: it carries the + * secret, so it never crosses a Remote boundary and never enters a log. + */ +export interface RouteCredentialGrant { + /** + * Request headers carrying the credential as the route's own protocol + * expects it, such as `x-api-key` for an API key. Consumers speaking that + * protocol send them unchanged. + */ + readonly headers: Readonly> + /** + * The bare credential value, for destinations whose protocol renders it + * differently from {@link headers}, such as `Authorization: Bearer`. + */ + readonly value: string + /** + * Invalidate this exact credential after the destination rejected it with + * HTTP 401 so no later request resends it. Absent for kinds without + * invalidation. The owner contains storage failures: the caller reports the + * destination's rejection, never a failure of this call. + * @returns settlement after the invalidation attempt. + */ + reject?(): Promise +} + +/** + * The credential one registered provider route currently sends, answered by + * the route's owning adapter so that consumers read no provider configuration + * and choose no header names. `ctx.llm.routeCredential()` resolves a new value + * per call from one configuration generation; a caller keeps it for one + * operation only. + */ +export interface RouteCredential { + /** Kind of credential the route sends. */ + readonly kind: LlmCredentialKind + /** + * The route's current request base URL as its configuration resolves it, + * environment fallbacks included: the destination this credential is meant + * for. Consumers derive sibling endpoints of the same deployment from it. + */ + readonly baseURL: string + /** + * Credential reference the route resolves, for diagnostics that tell the user + * where to configure the credential; absent for kinds without a stored + * reference, such as sign-in grants. + */ + readonly reference?: string + /** + * Whether {@link resolve} would release a credential for `endpoint`, checked + * without reading the credential's value, validating it, or contacting the + * destination. Store failures reject. + * @param endpoint - absolute URL the credential would be sent to. + * @returns whether a credential is configured for that destination. + */ + configured(endpoint: string): Promise + /** + * Release the credential for `endpoint`, or `undefined` when none is + * configured or the destination may not receive it. The caller chooses the + * failure it reports for `undefined`. Store and format failures reject. + * @param endpoint - absolute URL the credential will be sent to. + * @param signal - cancellation for the lookup. + * @returns the released credential, or `undefined`. + */ + resolve(endpoint: string, signal?: AbortSignal): Promise +} + /** * One interrogation of a provider endpoint that configuration has not stored * yet. Configuration surfaces send the draft a user is still editing, so the diff --git a/packages/llm/llm/tests/topology.spec.ts b/packages/llm/llm/tests/topology.spec.ts index 98b1be4920..7eddb69b35 100644 --- a/packages/llm/llm/tests/topology.spec.ts +++ b/packages/llm/llm/tests/topology.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import LlmRuntime, { LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm' -import type { GenerateOptions, LlmConfigurableProvider, StreamChunk } from '@deepseek-ai/dsh-llm' +import type { GenerateOptions, LlmConfigurableProvider, RouteCredential, StreamChunk } from '@deepseek-ai/dsh-llm' class NoopAdapter extends LlmAdapter { @@ -339,3 +339,25 @@ describe('imageRequestPricing resolution', () => { expect(ctx.llm.imageRequestPricing('a', 'vision')).toBeUndefined() }) }) + +describe('routeCredential resolution', () => { + it('forwards to the owning adapter and answers undefined everywhere else', async () => { + const ctx = await setup() + const credential: RouteCredential = { + kind: 'api-key', baseURL: 'https://a.example/v1', + configured: () => Promise.resolve(true), + resolve: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }), + } + class CredentialAdapter extends NoopAdapter { + override routeCredential(provider: string) { return provider === 'a' ? credential : undefined } + } + const dispose = ctx.llm.registerAdapter(['a', 'b'], new CredentialAdapter()) + ctx.llm.registerAdapter(['plain'], new NoopAdapter()) + expect(ctx.llm.routeCredential('a')).toBe(credential) + expect(ctx.llm.routeCredential('b')).toBeUndefined() + expect(ctx.llm.routeCredential('plain')).toBeUndefined() + expect(ctx.llm.routeCredential('missing')).toBeUndefined() + dispose() + expect(ctx.llm.routeCredential('a')).toBeUndefined() + }) +}) diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md index 489d3c98ce..0f1a47d350 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -4,6 +4,12 @@ This file is GENERATED from workspace manifests (`scripts/gen-plugin-packages.ts Every package below exports a Cordis plugin that a bundle patch can name in a Loader row. `Config` marks packages whose row accepts a `config` mapping; read the mounted schema from `Config.listConfigs` through `cordis_inspect_query` (filter by `name`, then query the `entry` id) when available, otherwise from the package README. Packages under `experimental` are pre-stable. +## account + +| Package | Config | Description | +|---|---|---| +| `@deepseek-ai/dsh-deepseek-account` | yes | Sign in to DeepSeek and manage account credentials and notifications | + ## acp | Package | Config | Description | @@ -171,7 +177,6 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo |---|---|---| | `@deepseek-ai/dsh-authorization` | no | Authorization seam (ctx.authorization): plugin-owned flows that obtain a credential through a conversation with the human | | `@deepseek-ai/dsh-credentials-local` | yes | File-backed credentials provider ($DSH_HOME/.env under the live process environment) for the DeepSeek Harness | -| `@deepseek-ai/dsh-deepseek-account` | yes | Sign in to DeepSeek and manage account credentials and notifications | ## deliverables diff --git a/packages/subagent/subagent/tests/continuation-messages-adapter.spec.ts b/packages/subagent/subagent/tests/continuation-messages-adapter.spec.ts index 7c031ca554..260215b12d 100644 --- a/packages/subagent/subagent/tests/continuation-messages-adapter.spec.ts +++ b/packages/subagent/subagent/tests/continuation-messages-adapter.spec.ts @@ -38,7 +38,7 @@ it('continues the parent through default Messages after a reasoning-bearing cont const connection = resolveAdapterOptions({ baseURL: http.url }) const adapter = new DeepSeekAdapter({ options: () => connection, - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' } }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' }, value: 'test-key' }), resolveUserId: () => '00000000-0000-4000-8000-000000000001' as AnonymousUserId, prepareExtensions: () => Promise.resolve({ fields: {}, accept: () => Promise.resolve() }), }) diff --git a/packages/web/web-deepseek-api/README.i18n.yaml b/packages/web/web-deepseek-api/README.i18n.yaml index 5fcfc042a3..42582881ec 100644 --- a/packages/web/web-deepseek-api/README.i18n.yaml +++ b/packages/web/web-deepseek-api/README.i18n.yaml @@ -18,14 +18,14 @@ en: 673ba23a4e608cf2 zh: 042afa607aaf4335 /deepseek-ai-dsh-web-deepseek-api/use-this-package/authentication: - en: b25cbe2a7894c03e - zh: db47f20dffe77a30 + en: 8923728d77eb1256 + zh: 85d1b8408cf1f325 /deepseek-ai-dsh-web-deepseek-api/use-this-package/results-and-failures: en: 7dbb34d960c1344c zh: 51a1459415857ab5 /deepseek-ai-dsh-web-deepseek-api/understand-the-implementation: - en: 71549e32f0a69c81 - zh: 9cafbeb60bdf0114 + en: 597dab3fe52fa59d + zh: 4370d01d5a58f2f9 /deepseek-ai-dsh-web-deepseek-api/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 @@ -54,8 +54,8 @@ en: 14f9af39f3be4fac zh: 3c7139fba0f17862 /deepseek-ai-dsh-web-deepseek-api/known-limitations-and-deferred-work: - en: 689b26b5f3af8861 - zh: 02cc62856a83cf48 + en: 3880e7c032129fb7 + zh: ad1450509e3473ab /deepseek-ai-dsh-web-deepseek-api/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 zh: 9f56528562c7c914 diff --git a/packages/web/web-deepseek-api/README.md b/packages/web/web-deepseek-api/README.md index 63a945d4a4..a653aadad9 100644 --- a/packages/web/web-deepseek-api/README.md +++ b/packages/web/web-deepseek-api/README.md @@ -59,16 +59,16 @@ Run the real API tests with `DEEPSEEK_API_KEY` and `DEEPSEEK_SEARCH_API_TEST_BAS Search and Fetch each resolve their endpoint and credential from one settings snapshot per operation, so a saved setting, a model-provider change, a sign-in, or a stored key applies to the next operation. The conversation's route is the `provider` of the initiating Session's latest request context; `ready()` uses the route of the model request being prepared. - **Own settings.** A capability with a non-empty `*BaseURL` or `*ApiKeyEnv` sends only the key under its `*ApiKeyEnv` (`DEEPSEEK_API_KEY` when unset) as `Authorization: Bearer` to its `*BaseURL` (`https://api.deepseek.com/v1/tools` when unset) on every route, and never the account token. Without the key, the operation fails with a diagnostic that names the reference and the `*ApiKeyEnv` field. -- **Account token.** The operation sends the token that `ctx.deepseekAccount` releases for the dispatch endpoint as `x-dsh-auth-token`; the public Search and Fetch routes accepted it on 2026-10-16. The endpoint is under the origin of the active Loader entry of `@deepseek-ai/dsh-llm-deepseek-account` at the entry root that the model provider directory lists for `deepseek-account`; without that entry, it is under the origin of that route's default base URL (`https://api.deepseek.com`, or the `DEEPSEEK_BASE_URL` origin). No sign-in, no account service, or an empty token means no token. A failed account-token read fails the operation without trying another credential. An active entry whose settings the route's own resolver rejects fails the operation before that account token is read when the operation reaches this source. -- **API key.** The operation sends the key under the `apiKeyEnv` of the active `@deepseek-ai/dsh-llm-deepseek-api-key` entry the directory lists for `deepseek-official` (`DEEPSEEK_API_KEY` by default) as `Authorization: Bearer` to that route's origin, resolving its options as the route does. Without that entry, or with an inactive one, it sends `DEEPSEEK_API_KEY` to `https://api.deepseek.com/v1/tools`. An active entry whose settings the route's own resolver rejects fails each operation that needs the key, before the key is read; the operation never substitutes the official endpoint or `DEEPSEEK_API_KEY`. -- **`auto` billing** follows the conversation. On the `deepseek-account` route it sends the account token, and without one the API key; without the account route entry, only the API key. On the `deepseek-official` route it sends only the API key. On any other route or outside a Session it sends the API key, and without a key the account token; without a key, a mounted account route entry whose settings do not resolve fails the operation. -- **`account` billing** sends only the account token on every route, and **`api-key` billing** only the API key; neither falls back to the other credential. +- **Account credential.** The operation sends the credential `ctx.deepseekAccount` releases for the dispatch endpoint as `x-dsh-auth-token`; the public Search and Fetch routes accepted it on 2026-10-16. With the `deepseek-account` model route mounted, the endpoint is under the origin of the base URL that route publishes through `ctx.llm.routeCredential`; without that route, it is under the origin `DEEPSEEK_BASE_URL` names, `https://api.deepseek.com` by default. No sign-in or no account service means no credential. A failed credential read fails the operation without trying another credential. A mounted route whose settings do not resolve, or a `DEEPSEEK_BASE_URL` that is not an HTTP(S) URL without credentials, fails the operation before the credential is read when the operation reaches this source. +- **API key.** With the `deepseek-official` model route mounted, the operation sends the key that route publishes through `ctx.llm.routeCredential`, read under the route's `apiKeyEnv` (`DEEPSEEK_API_KEY` by default), as `Authorization: Bearer` to the origin of the route's base URL. Without that route, it sends `DEEPSEEK_API_KEY` to `https://api.deepseek.com/v1/tools`. A mounted route whose settings do not resolve fails each operation that needs the key, before the key is read; the operation never substitutes the official endpoint or `DEEPSEEK_API_KEY`. +- **`auto` billing** follows the conversation. On the `deepseek-account` route it sends the account credential, and without one the API key; without the account route, only the API key. On the `deepseek-official` route it sends only the API key. On any other route or outside a Session it sends the API key, and without a key the account credential; without a key, a mounted account route whose settings do not resolve fails the operation. +- **`account` billing** sends only the account credential on every route, and **`api-key` billing** only the API key; neither falls back to the other credential. Without a credential, the operation fails with a diagnostic for its billing that names the missing sign-in or the Models page and the key reference, and the `*Billing` field on the Web search and fetch settings page. -References use the [shared DeepSeek credential helpers](../../llm/llm-deepseek/README.md#account-credentials): `ctx.credentials` is authoritative, with launch-environment lookup only when that service is absent. Route and own keys receive the same whitespace normalization and format validation as model requests; malformed keys fail before dispatch. +Keys the operation reads itself, `DEEPSEEK_API_KEY` without the API-key route and the own `*ApiKeyEnv`, go through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md): `ctx.credentials` is authoritative, with launch-environment lookup only when that service is absent. Route keys and own keys receive the same whitespace normalization and format validation as model requests; malformed keys fail before dispatch. -Each provider's `ready()` answers whether its next operation for that route has a credential, in the order its billing resolves them: a non-empty account token, or a key that `ctx.credentials.describe` reports configured (without that service, the launch environment must carry it). A failed account-token or credential-store read, or a needed route entry whose settings do not resolve, answers false. While these providers are selected, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and `web_fetch` with their prompt guidance from each request for which they answer false. Only presence is checked: a wrong key counts as ready and fails each call. +Each provider's `ready()` answers whether its next operation for that route has a credential, in the order its billing resolves them: a route credential its route reports configured for the endpoint, an account credential the account service releases for the endpoint, or a key that `ctx.credentials.describe` reports configured (without that service, the launch environment must carry it). A failed credential or credential-store read, or a needed route whose settings do not resolve, answers false. While these providers are selected, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and `web_fetch` with their prompt guidance from each request for which they answer false. Only presence is checked: a wrong key counts as ready and fails each call. ### Results and failures @@ -84,7 +84,7 @@ An unparseable own base URL makes that capability's provider unavailable; and a
Implementation internals — click to expand -The [plugin](src/index.ts) reads its settings once per operation, registers both providers, and turns one capability's settings snapshot, the conversation's route, and the active model route entries into the operation's ordered credentials, each bound to the API base it is sent to. The [Search provider](src/search.ts) validates response JSON before returning service results; the [Fetch provider](src/fetch.ts) validates the Markdown body. The [transport](src/transport.ts) reads those credentials in order, sends one request with the first present one, and owns cancellation, redirect rejection, and failure guidance; a recording hook runs before dispatch and prevents it by throwing. Search and Fetch API calls emit no auxiliary request event. The [Messages search provider](../web-search-deepseek/README.md) owns its `web/deepseek-search-llm-request` Session event declaration and recording. Tool calls and results retain their normal Session logging. +The [plugin](src/index.ts) reads its settings once per operation, registers both providers, and turns one capability's settings snapshot, the conversation's route, and the credentials the mounted DeepSeek model routes publish through `ctx.llm.routeCredential` into the operation's ordered credentials, each bound to the API base it is sent to. The [Search provider](src/search.ts) validates response JSON before returning service results; the [Fetch provider](src/fetch.ts) validates the Markdown body. The [transport](src/transport.ts) reads those credentials in order, sends one request with the first present one, and owns cancellation, redirect rejection, and failure guidance; a recording hook runs before dispatch and prevents it by throwing. Search and Fetch API calls emit no auxiliary request event. The [Messages search provider](../web-search-deepseek/README.md) owns its `web/deepseek-search-llm-request` Session event declaration and recording. Tool calls and results retain their normal Session logging. See the [web subsystem](../../../docs/subsystems/web.md) for service types and [tool-web](../tool-web/README.md) for bounded model output. @@ -132,7 +132,7 @@ A returning or removed web tool changes the declared tools as [`dsh-tool-web`](. - API query and URL constraints are enforced by the remote service. An unresolvable Fetch target returned HTTP 500 rather than the documented 404 on 2026-10-16, and its failure carries the same endpoint guidance as an endpoint failure. Fetch exposes neither the target status nor the final redirect URL, so results report HTTP 200 and the requested URL; the provider discards the API's page title. - `available()` cannot query asynchronous credential stores; `ready()` does, so model steps withhold the tools when the store lacks the key. A direct `ctx.web.search()` or `ctx.web.fetch()` call can still fail with a missing-credential error. - Search pacing limits send times within one plugin instance. Other processes and clients on the same account share the account-wide 5 QPS limit without coordination, and network jitter can still bunch arrivals; an HTTP 429 fails that search, and `dsh-tool-web` then fails the whole multi-query call. Fetch is not paced, so parallel `web_fetch` calls can exceed the Fetch limit. -- Route endpoints and keys follow only the Loader entries of `@deepseek-ai/dsh-llm-deepseek-api-key` and `@deepseek-ai/dsh-llm-deepseek-account` at the entry root; another package registering the same provider id, such as a test replay adapter, counts as no route, so its conversations use `DEEPSEEK_API_KEY` and the official base. +- Route endpoints and credentials follow what the adapter registered as `deepseek-official` or `deepseek-account` publishes through `ctx.llm.routeCredential`; an adapter that publishes no credential, such as a test replay adapter, counts as no route, so its conversations use `DEEPSEEK_API_KEY` and the official base. ### Dev Note diff --git a/packages/web/web-deepseek-api/README.zh.md b/packages/web/web-deepseek-api/README.zh.md index 8c5a5cc2f6..c59eeb474a 100644 --- a/packages/web/web-deepseek-api/README.zh.md +++ b/packages/web/web-deepseek-api/README.zh.md @@ -59,16 +59,16 @@ kind: "package-reference" Search 与 Fetch 每次操作各自从同一份设置快照解析端点和凭据,因此保存的设置、模型提供方变更、登录或存入的密钥从下一次操作开始生效。会话的路由是发起会话最近一次请求上下文的 `provider`;`ready()` 使用正在准备的模型请求的路由。 - **单独配置。** 设置了非空 `*BaseURL` 或 `*ApiKeyEnv` 的能力在任何路由上都只以 `Authorization: Bearer` 把其 `*ApiKeyEnv`(未设置时为 `DEEPSEEK_API_KEY`)下的密钥发往其 `*BaseURL`(未设置时为 `https://api.deepseek.com/v1/tools`),从不发送账号令牌。没有该密钥时,操作失败,诊断信息点名该引用和 `*ApiKeyEnv` 字段。 -- **账号令牌。** 操作通过 `x-dsh-auth-token` 发送 `ctx.deepseekAccount` 为请求端点给出的令牌;2026-10-16 公网 Search 与 Fetch 路由已接受该令牌。端点位于模型提供方目录为 `deepseek-account` 列出的、入口根部活动的 `@deepseek-ai/dsh-llm-deepseek-account` Loader 条目的 origin 下;没有该条目时,位于该路由默认基础地址的 origin(`https://api.deepseek.com`,或 `DEEPSEEK_BASE_URL` 的 origin)下。没有登录、没有账号服务或令牌为空都算没有令牌。账号令牌读取失败时操作失败,不再尝试其他凭据。条目活动但其设置被该路由自身的解析器拒绝时,操作在轮到该来源时失败,不读取该账号令牌。 -- **API 密钥。** 操作以 `Authorization: Bearer` 把目录为 `deepseek-official` 列出的活动 `@deepseek-ai/dsh-llm-deepseek-api-key` 条目的 `apiKeyEnv`(默认 `DEEPSEEK_API_KEY`)下的密钥发往该路由的 origin,并按该路由的方式解析其选项。没有该条目或条目未激活时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。条目活动但其设置被该路由自身的解析器拒绝时,每个需要该密钥的操作都在读取密钥前失败,绝不改用官方端点或 `DEEPSEEK_API_KEY`。 -- **`auto` 计费**跟随会话。在 `deepseek-account` 路由上先发送账号令牌,没有令牌时发送 API 密钥;没有账号路由条目时只发送 API 密钥。在 `deepseek-official` 路由上只发送 API 密钥。在其他路由上或会话之外先发送 API 密钥,没有密钥时发送账号令牌;没有密钥且已挂载的账号路由条目设置无法解析时,操作失败。 -- **`account` 计费**在任何路由上只发送账号令牌,**`api-key` 计费**只发送 API 密钥;两者都不回退到另一种凭据。 +- **账号凭据。** 操作通过 `x-dsh-auth-token` 发送 `ctx.deepseekAccount` 为请求端点释放的凭据;2026-10-16 公网 Search 与 Fetch 路由已接受该凭据。挂载了 `deepseek-account` 模型路由时,端点位于该路由通过 `ctx.llm.routeCredential` 发布的基础地址的 origin 下;没有该路由时,位于 `DEEPSEEK_BASE_URL` 所指 origin 下,默认 `https://api.deepseek.com`。没有登录或没有账号服务都算没有凭据。凭据读取失败时操作失败,不再尝试其他凭据。已挂载路由的设置无法解析,或 `DEEPSEEK_BASE_URL` 不是不含凭据的 HTTP(S) URL 时,操作在轮到该来源时于读取凭据前失败。 +- **API 密钥。** 挂载了 `deepseek-official` 模型路由时,操作以 `Authorization: Bearer` 把该路由通过 `ctx.llm.routeCredential` 发布的密钥(按路由的 `apiKeyEnv` 读取,默认 `DEEPSEEK_API_KEY`)发往该路由基础地址的 origin。没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。已挂载路由的设置无法解析时,每个需要该密钥的操作都在读取密钥前失败,绝不改用官方端点或 `DEEPSEEK_API_KEY`。 +- **`auto` 计费**跟随会话。在 `deepseek-account` 路由上先发送账号凭据,没有凭据时发送 API 密钥;没有账号路由时只发送 API 密钥。在 `deepseek-official` 路由上只发送 API 密钥。在其他路由上或会话之外先发送 API 密钥,没有密钥时发送账号凭据;没有密钥且已挂载的账号路由设置无法解析时,操作失败。 +- **`account` 计费**在任何路由上只发送账号凭据,**`api-key` 计费**只发送 API 密钥;两者都不回退到另一种凭据。 没有凭据时,操作失败,诊断信息按计费方式点名缺少的登录或模型页面与密钥引用,以及网页搜索与获取设置页上的 `*Billing` 字段。 -引用使用[共享 DeepSeek 凭据函数](../../llm/llm-deepseek/README.zh.md#account-credentials):`ctx.credentials` 具有权威性,仅在该服务缺席时读取启动环境。路由密钥与单独配置的密钥均接受与模型请求相同的首尾空白规范化和格式校验;格式错误在发送请求前失败。 +操作自行读取的密钥——没有 API 密钥路由时的 `DEEPSEEK_API_KEY` 和单独配置的 `*ApiKeyEnv`——通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数读取:`ctx.credentials` 具有权威性,仅在该服务缺席时读取启动环境。路由密钥与单独配置的密钥均接受与模型请求相同的首尾空白规范化和格式校验;格式错误在发送请求前失败。 -每个提供者的 `ready()` 按其计费方式的解析顺序回答其在该路由上的下一次操作是否有凭据:非空账号令牌,或 `ctx.credentials.describe` 报告已配置的密钥(没有该服务时,启动环境必须包含它)。账号令牌或凭据存储读取失败,或所需路由条目的设置无法解析时,回答 false。这两个提供者被选中时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它们回答 false 的每个请求中撤下 `web_search` 与 `web_fetch` 及其提示词指引。只检查是否存在:错误的密钥仍算就绪,并使每次调用失败。 +每个提供者的 `ready()` 按其计费方式的解析顺序回答其在该路由上的下一次操作是否有凭据:路由报告为该端点已配置的路由凭据、账号服务为该端点释放的账号凭据,或 `ctx.credentials.describe` 报告已配置的密钥(没有该服务时,启动环境必须包含它)。凭据或凭据存储读取失败,或所需路由的设置无法解析时,回答 false。这两个提供者被选中时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它们回答 false 的每个请求中撤下 `web_search` 与 `web_fetch` 及其提示词指引。只检查是否存在:错误的密钥仍算就绪,并使每次调用失败。 ### 结果与失败 @@ -84,7 +84,7 @@ Search API 接收 `query`、`count`(配置的结果数,或请求中更小的
实现细节 — 点击展开 -[插件](src/index.ts)在每次操作时读取一次设置,注册两个提供者,并把一个能力的设置快照、会话的路由和活动的模型路由条目转换为该操作的有序凭据,每个凭据都绑定其发往的 API 基础地址。[Search 提供者](src/search.ts)在返回服务结果前校验响应 JSON;[Fetch 提供者](src/fetch.ts)校验 Markdown 正文。[传输层](src/transport.ts)按顺序读取这些凭据,用第一个存在的凭据发送一次请求,并负责取消、重定向拒绝和失败指引;记录钩子在发送前运行,抛出异常即阻止发送。Search 与 Fetch API 调用不产生辅助请求事件。[Messages 搜索提供方](../web-search-deepseek/README.zh.md)负责声明和记录自身的 `web/deepseek-search-llm-request` 会话事件。工具调用和结果仍按常规记录到会话。 +[插件](src/index.ts)在每次操作时读取一次设置,注册两个提供者,并把一个能力的设置快照、会话的路由,以及已挂载的 DeepSeek 模型路由通过 `ctx.llm.routeCredential` 发布的凭据转换为该操作的有序凭据,每个凭据都绑定其发往的 API 基础地址。[Search 提供者](src/search.ts)在返回服务结果前校验响应 JSON;[Fetch 提供者](src/fetch.ts)校验 Markdown 正文。[传输层](src/transport.ts)按顺序读取这些凭据,用第一个存在的凭据发送一次请求,并负责取消、重定向拒绝和失败指引;记录钩子在发送前运行,抛出异常即阻止发送。Search 与 Fetch API 调用不产生辅助请求事件。[Messages 搜索提供方](../web-search-deepseek/README.zh.md)负责声明和记录自身的 `web/deepseek-search-llm-request` 会话事件。工具调用和结果仍按常规记录到会话。 服务类型见 [Web 子系统](../../../docs/subsystems/web.zh.md),受限的模型输出见 [tool-web](../tool-web/README.zh.md)。 @@ -132,7 +132,7 @@ Search API 接收 `query`、`count`(配置的结果数,或请求中更小的 - 查询和 URL 约束由远端服务执行。2026-10-16 抓取无法解析的目标域名时返回 HTTP 500,而非文档所述的 404,其失败信息与端点失败附带相同的端点指引。Fetch 既不暴露目标状态,也不暴露最终重定向 URL,因此结果报告 HTTP 200 和请求 URL;提供者丢弃 API 返回的页面标题。 - `available()` 无法查询异步凭据存储;`ready()` 可以,因此凭据存储缺少密钥时,模型步骤会撤下这两个工具。直接调用 `ctx.web.search()` 或 `ctx.web.fetch()` 仍可能因凭据缺失失败。 - Search 限速只约束单个插件实例内的发送时间。同一账号下的其他进程和客户端共享账号级 5 QPS 限制,彼此不协调,网络抖动也可能使请求集中到达;HTTP 429 会使该次搜索失败,随后 `dsh-tool-web` 会使整个多查询调用失败。Fetch 不限速,因此并行的 `web_fetch` 调用可能超过 Fetch 限制。 -- 路由端点与密钥只认入口根部的 `@deepseek-ai/dsh-llm-deepseek-api-key` 与 `@deepseek-ai/dsh-llm-deepseek-account` Loader 条目;以相同提供方 id 注册的其他包(例如测试回放适配器)视为没有路由,其会话使用 `DEEPSEEK_API_KEY` 与官方基础地址。 +- 路由端点与凭据只认以 `deepseek-official` 或 `deepseek-account` 注册的适配器通过 `ctx.llm.routeCredential` 发布的内容;不发布凭据的适配器(例如测试回放适配器)视为没有路由,其会话使用 `DEEPSEEK_API_KEY` 与官方基础地址。 ### 开发备注 diff --git a/packages/web/web-deepseek-api/package.json b/packages/web/web-deepseek-api/package.json index 1c9209b89c..ed155bec20 100644 --- a/packages/web/web-deepseek-api/package.json +++ b/packages/web/web-deepseek-api/package.json @@ -32,39 +32,33 @@ ], "license": "MIT", "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-credentials": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", "@deepseek-ai/dsh-launch-environment": "workspace:*", - "@deepseek-ai/dsh-llm-deepseek": "workspace:*", - "@deepseek-ai/dsh-session": "workspace:*", - "@deepseek-ai/dsh-web": "workspace:*", - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/cordis-plugin-loader": "workspace:~", "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/dsh-llm-deepseek-api-key": "workspace:*", - "@deepseek-ai/dsh-llm-deepseek-account": "workspace:*" + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-web": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~" }, "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-app-boot": "workspace:*", "@deepseek-ai/dsh-credentials": "workspace:*", "@deepseek-ai/dsh-credentials-local": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", + "@deepseek-ai/dsh-http-proxy": "workspace:*", "@deepseek-ai/dsh-launch-environment": "workspace:*", - "@deepseek-ai/dsh-llm-deepseek": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-llm-deepseek-account": "workspace:*", + "@deepseek-ai/dsh-llm-deepseek-api-key": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", - "@deepseek-ai/dsh-web": "workspace:*", - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-http-proxy": "workspace:*", - "@deepseek-ai/cordis-plugin-loader": "workspace:~", - "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/dsh-llm-deepseek-api-key": "workspace:*", - "@deepseek-ai/dsh-llm-deepseek-account": "workspace:*", - "@deepseek-ai/dsh-app-boot": "workspace:*" + "@deepseek-ai/dsh-web": "workspace:*" }, "peerDependenciesMeta": { "@deepseek-ai/dsh-deepseek-account": { diff --git a/packages/web/web-deepseek-api/src/index.ts b/packages/web/web-deepseek-api/src/index.ts index 555bab178b..0b610ce7ab 100644 --- a/packages/web/web-deepseek-api/src/index.ts +++ b/packages/web/web-deepseek-api/src/index.ts @@ -1,36 +1,28 @@ /** - * Register the DeepSeek Search and Fetch APIs in `ctx.web` as `deepseek-search-api` - * and `deepseek-fetch-api`. Each operation is one direct API request without an - * auxiliary model request. `web.searchProvider` and `web.fetchProvider` select them. Each capability's billing setting - * chooses its credential. `auto` follows the conversation: a Session whose latest model request used the - * `deepseek-account` route sends the account token to that route's origin and otherwise the API key; one on the - * `deepseek-official` route sends the API key; any other operation sends the API key and, without a key, the signed-in - * account's token. `account` sends only the account token and `api-key` only the API key. The API key is that of the - * DeepSeek API-key route, sent to its origin, or `DEEPSEEK_API_KEY` sent to the official base without that route. The - * account token goes to the account route's origin, or outside an account conversation without that route to the origin - * of its default base URL. An operation that needs a mounted route whose settings do not resolve fails instead of - * changing its endpoint or credential. A capability with its own `*BaseURL` or `*ApiKeyEnv` uses only that endpoint and - * key instead, whatever its billing + * Register the DeepSeek Search and Fetch APIs in `ctx.web` as `deepseek-search-api` and `deepseek-fetch-api`. Each + * operation is one direct API request without an auxiliary model request. `web.searchProvider` and `web.fetchProvider` + * select them. Each capability's billing setting chooses its credential. `auto` follows the conversation: a Session + * whose latest model request used the `deepseek-account` route sends the account credential to that route's origin and + * otherwise the API key; one on the `deepseek-official` route sends the API key; any other operation sends the API key + * and, without a key, the signed-in account's credential. `account` sends only the account credential and `api-key` + * only the API key. Each mounted DeepSeek model route publishes its credential and base URL through + * `ctx.llm.routeCredential()`: the API key is that of the `deepseek-official` route, sent to its origin, or + * `DEEPSEEK_API_KEY` sent to the official base without that route; the account credential is that of the + * `deepseek-account` route, sent to its origin, or outside an account conversation without that route the signed-in + * account's credential sent to the origin `DEEPSEEK_BASE_URL` names, by default the official one. An operation that + * needs a mounted route whose settings do not resolve fails instead of changing its endpoint or credential. A capability + * with its own `*BaseURL` or `*ApiKeyEnv` uses only that endpoint and key instead, whatever its billing * ([rationale](../../../../.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md#credential-resolution)). * Both providers report themselves not ready when their next operation would have no credential. * @module @deepseek-ai/dsh-web-deepseek-api */ -import { FiberState, type Context, type Volatile } from '@deepseek-ai/cordis' -import type {} from '@deepseek-ai/cordis-plugin-loader' +import type { Context, Volatile } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-agent' -import { credentialRef, type CredentialRef } from '@deepseek-ai/dsh-credentials' +import { credentialRef, credentialRefConfigured, resolveCredentialRef, type CredentialRef } from '@deepseek-ai/dsh-credentials' +import type {} from '@deepseek-ai/dsh-deepseek-account' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' -import type {} from '@deepseek-ai/dsh-llm' -import { - deepSeekApiKeyConfigured, rejectDeepSeekAccountToken, resolveDeepSeekAccountToken, resolveDeepSeekApiKey, -} from '@deepseek-ai/dsh-llm-deepseek' -import { - plainAccountOptions, resolveAccountOptions, type Config as AccountRouteConfig, -} from '@deepseek-ai/dsh-llm-deepseek-account' -import { - plainOptions as plainOfficialOptions, resolveAdapterOptions as resolveOfficialOptions, type Config as OfficialRouteConfig, -} from '@deepseek-ai/dsh-llm-deepseek-api-key' +import { assertUsableApiKey, type RouteCredential } from '@deepseek-ai/dsh-llm' import type { Session } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-web' import { DeepSeekFetchApiProvider } from './fetch.ts' @@ -114,9 +106,6 @@ type Capability = 'search' | 'fetch' /** Credential choice of one capability without its own endpoint settings. */ type Billing = Config['searchBilling'] extends Volatile ? B : never -/** Model route whose settings an operation can depend on. */ -type RouteName = keyof typeof ROUTE_PACKAGES - /** * Rule that ordered an operation's credentials: `auto` billing in a conversation on the account route, on the API-key * route, or anywhere else, or an explicit billing. @@ -135,11 +124,14 @@ const ACCOUNT_PROVIDER = 'deepseek-account' /** Provider id of the DeepSeek API-key route. */ const OFFICIAL_PROVIDER = 'deepseek-official' -/** Loader package that registers each model route. */ -const ROUTE_PACKAGES = { - [OFFICIAL_PROVIDER]: '@deepseek-ai/dsh-llm-deepseek-api-key', - [ACCOUNT_PROVIDER]: '@deepseek-ai/dsh-llm-deepseek-account', -} as const +/** Model route whose published credential an operation can send. */ +type RouteName = typeof ACCOUNT_PROVIDER | typeof OFFICIAL_PROVIDER + +/** + * Launch-environment variable naming the DeepSeek deployment the model routes default to. Without the account route, + * its origin receives the signed-in account's credential. + */ +const DEEPSEEK_BASE_URL_ENV = 'DEEPSEEK_BASE_URL' /** Display names, configuration prefix, and operation path of each capability. */ const CAPABILITY = { @@ -203,8 +195,8 @@ export function apply(ctx: Context, config: Config): void { /** * Resolve the ordered credentials and endpoint guidance of one capability without reading credential values. Route - * endpoints use the origin of the route's resolved Messages base URL with `/v1/tools`. - * @param ctx - context with the model, loader, credential, and account services. + * endpoints use the origin of the route's published base URL with `/v1/tools`. + * @param ctx - context with the model, credential, and account services. * @param capability - the capability being resolved. * @param own - the capability's own base URL and credential reference, where empty values count as unset, and its * billing. @@ -233,85 +225,133 @@ function resolveTarget( : llmProvider === ACCOUNT_PROVIDER ? 'account-conversation' : llmProvider === OFFICIAL_PROVIDER ? 'official-conversation' : 'other-conversation' const sources = ruleSources(ctx, capability, rule) - const [ref = DEEPSEEK_API_KEY] = sources.flatMap(row => row.kind === 'api-key' && typeof row.key !== 'string' ? [row.key.ref] : []) + const ref: string = sources.flatMap(keyReference)[0] ?? DEEPSEEK_API_KEY return { guidance: guidance(false), auth: { sources, missingCredentialMessage: missingMessage(capability, rule, ref) } } } /** * The credentials one rule tries, in order. - * @param ctx - context with the model, loader, credential, and account services. + * @param ctx - context with the model, credential, and account services. * @param capability - the capability whose diagnostics misconfigured sources name. * @param rule - the rule. * @returns the sources; the account source is absent in an account conversation without a mounted account route. */ function ruleSources(ctx: Context, capability: Capability, rule: Rule): DeepSeekWebAuthSource[] { - const accountConfig = routeConfig(ctx, ACCOUNT_PROVIDER) as AccountRouteConfig | undefined switch (rule) { - case 'account-conversation': return accountConfig === undefined - ? [officialSource(ctx, capability)] : [accountSource(ctx, capability, accountConfig), officialSource(ctx, capability)] + case 'account-conversation': { + const account = routeSource(ctx, capability, ACCOUNT_PROVIDER) + return account === undefined ? [officialSource(ctx, capability)] : [account, officialSource(ctx, capability)] + } case 'official-conversation': case 'api-key': return [officialSource(ctx, capability)] - case 'other-conversation': return [officialSource(ctx, capability), accountSource(ctx, capability, accountConfig)] - case 'account': return [accountSource(ctx, capability, accountConfig)] + case 'other-conversation': return [officialSource(ctx, capability), accountSource(ctx, capability)] + case 'account': return [accountSource(ctx, capability)] /* v8 ignore next -- the switch is exhaustive. */ default: return assertNever(rule) } } /** - * The API key of the active DeepSeek API-key route, sent to its origin, or `DEEPSEEK_API_KEY` sent to the official base - * without that route. - * @returns the source, or a misconfigured source when the route's resolver rejects its settings. + * The credential a mounted model route publishes, sent to the Search and Fetch APIs under the origin of the route's + * base URL. + * @param ctx - context with the optional model service. + * @param capability - the capability whose diagnostics a misconfigured source names. + * @param provider - the route. + * @returns the source; undefined when no mounted route publishes a credential as `provider`; a misconfigured source + * when the route's settings do not resolve. */ -function officialSource(ctx: Context, capability: Capability): DeepSeekWebAuthSource { - const config = routeConfig(ctx, OFFICIAL_PROVIDER) as OfficialRouteConfig | undefined - if (config === undefined) return apiKeySource(ctx, DEEPSEEK_WEB_API_BASE_URL, DEEPSEEK_API_KEY) - let resolved: { baseURL: string; apiKeyEnv: CredentialRef } - try { resolved = resolveOfficialOptions(plainOfficialOptions(config), launchEnvironmentOf(ctx)) } - catch (error: unknown) { return misconfigured(capability, OFFICIAL_PROVIDER, error) } - return apiKeySource(ctx, toolsBase(resolved.baseURL), resolved.apiKeyEnv) +function routeSource(ctx: Context, capability: Capability, provider: RouteName): DeepSeekWebAuthSource | undefined { + let credential: RouteCredential | undefined + try { credential = ctx.get('llm')?.routeCredential(provider) } + catch (error: unknown) { return misconfigured(capability, provider, error) } + return credential === undefined ? undefined : { kind: 'route', baseURL: toolsBase(credential.baseURL), credential } } /** - * The account token sent to the origin of the account route, or without that route to the origin of its default base - * URL, including `DEEPSEEK_BASE_URL`. The account service releases the token only for destinations it allows. - * @param config - the active account route's settings, or undefined for the defaults. - * @returns the source, or a misconfigured source when the route's resolver rejects its settings. + * The API key of the DeepSeek API-key route sent to its origin, or `DEEPSEEK_API_KEY` sent to the official base + * without that route. + * @returns the source, or a misconfigured source when the route's settings do not resolve. */ -function accountSource(ctx: Context, capability: Capability, config: AccountRouteConfig | undefined): DeepSeekWebAuthSource { - let baseURL: string - try { - baseURL = resolveAccountOptions(config === undefined ? {} : plainAccountOptions(config), launchEnvironmentOf(ctx)).protocol.baseURL - } catch (error: unknown) { return misconfigured(capability, ACCOUNT_PROVIDER, error) } - return { - kind: 'account', baseURL: toolsBase(baseURL), - resolveToken: endpoint => resolveDeepSeekAccountToken(ctx, endpoint), - rejectToken: token => rejectDeepSeekAccountToken(ctx, token), - } +function officialSource(ctx: Context, capability: Capability): DeepSeekWebAuthSource { + return routeSource(ctx, capability, OFFICIAL_PROVIDER) ?? apiKeySource(ctx, DEEPSEEK_WEB_API_BASE_URL, DEEPSEEK_API_KEY) } -/** The key under `ref`, read through the shared DeepSeek credential helpers, sent to `baseURL`. */ +/** + * The account credential of the DeepSeek account route sent to its origin, or without that route the signed-in + * account's credential sent to the origin `DEEPSEEK_BASE_URL` names, by default the official one. The account service + * releases its credential only for destinations it allows. + * @returns the source, or a misconfigured source when the route's settings or `DEEPSEEK_BASE_URL` do not resolve. + */ +function accountSource(ctx: Context, capability: Capability): DeepSeekWebAuthSource { + const route = routeSource(ctx, capability, ACCOUNT_PROVIDER) + if (route !== undefined) return route + const configured = nonEmpty(launchEnvironmentOf(ctx).get(DEEPSEEK_BASE_URL_ENV)?.value) + let baseURL = DEEPSEEK_WEB_API_BASE_URL + if (configured !== undefined) { + try { baseURL = toolsBase(deploymentURL(configured)) } + catch (error: unknown) { return misconfiguredDeployment(capability, error) } + } + return { kind: 'route', baseURL, credential: { + kind: 'account', + configured: async endpoint => (await ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint)) !== undefined, + resolve: endpoint => ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint) ?? Promise.resolve(undefined), + } } +} + +/** The key under `ref`, read from the credentials service or the launch environment, sent to `baseURL`. */ function apiKeySource(ctx: Context, baseURL: string, ref: CredentialRef): DeepSeekWebAuthSource { return { kind: 'api-key', baseURL, key: { - ref, configured: () => deepSeekApiKeyConfigured(ctx, ref), resolve: () => resolveDeepSeekApiKey(ctx, ref), + ref, + configured: () => credentialRefConfigured(ctx, ref), + resolve: async () => { + const value = await resolveCredentialRef(ctx, ref) + return value === undefined ? undefined : assertUsableApiKey(value, name, ref) + }, } } } +/** The credential reference an API-key source names in missing-credential diagnostics. */ +function keyReference(source: DeepSeekWebAuthSource): string[] { + switch (source.kind) { + case 'api-key': return [source.key.ref] + case 'route': return source.credential.kind === 'api-key' && source.credential.reference !== undefined ? [source.credential.reference] : [] + case 'misconfigured': return [] + /* v8 ignore next -- the switch is exhaustive. */ + default: return assertNever(source) + } +} + /** * The source of a credential whose model route settings do not resolve. * @param capability - the capability that stops. * @param route - the route whose settings failed. - * @param error - the route resolver's failure. + * @param error - the route's failure. * @returns the source whose diagnostic names the route and both recoveries. */ function misconfigured(capability: Capability, route: RouteName, error: unknown): DeepSeekWebAuthSource { - const { subject, prefix } = CAPABILITY[capability] const provider = route === ACCOUNT_PROVIDER ? 'DeepSeek account model provider' : 'DeepSeek API-key model provider' const credential = route === ACCOUNT_PROVIDER ? 'the DeepSeek account sign-in' : 'that provider\'s API key' - return { kind: 'misconfigured', message: `DeepSeek ${subject} API sends ${credential} to the origin of the ${provider}, and` - + ` that provider's settings do not resolve: ${errorMessage(error)}. ${subject} did not send the request. Guide the user` - + ' to correct that provider\'s settings on the Models page or in the deployment configuration, or to set' - + ` ${name}.${prefix}BaseURL and ${name}.${prefix}ApiKeyEnv so ${subject} uses its own endpoint.` } + return unresolvedSource(capability, `${credential} to the origin of the ${provider}, and that provider's settings do not resolve`, + error, 'correct that provider\'s settings on the Models page or in the deployment configuration') +} + +/** + * The source of the signed-in account's credential when `DEEPSEEK_BASE_URL` is not an HTTP(S) URL. + * @param capability - the capability that stops. + * @param error - the URL failure. + * @returns the source whose diagnostic names the variable and both recoveries. + */ +function misconfiguredDeployment(capability: Capability, error: unknown): DeepSeekWebAuthSource { + return unresolvedSource(capability, `the DeepSeek account sign-in to the origin of ${DEEPSEEK_BASE_URL_ENV}, and that value does not resolve`, + error, `correct ${DEEPSEEK_BASE_URL_ENV} in the launching environment`) +} + +/** A misconfigured source whose diagnostic names what the operation sends where, the failure, and both recoveries. */ +function unresolvedSource(capability: Capability, destination: string, error: unknown, recovery: string): DeepSeekWebAuthSource { + const { subject, prefix } = CAPABILITY[capability] + return { kind: 'misconfigured', message: `DeepSeek ${subject} API sends ${destination}: ${errorMessage(error)}. ${subject} did not` + + ` send the request. Guide the user to ${recovery}, or to set ${name}.${prefix}BaseURL and ${name}.${prefix}ApiKeyEnv so` + + ` ${subject} uses its own endpoint.` } } /** @@ -321,7 +361,7 @@ function misconfigured(capability: Capability, route: RouteName, error: unknown) * @param keyRef - the reference of the API key the rule tries, or `DEEPSEEK_API_KEY` when it tries none. * @returns the diagnostic naming the missing credentials and their recoveries. */ -function missingMessage(capability: Capability, rule: Rule, keyRef: CredentialRef): string { +function missingMessage(capability: Capability, rule: Rule, keyRef: string): string { const { subject, prefix } = CAPABILITY[capability] const ref = JSON.stringify(keyRef) const addKey = `add the DeepSeek API key on the Models page or export ${ref} in the launching environment` @@ -358,17 +398,17 @@ function errorMessage(error: unknown): string { } /** - * Find the effective config of the active loader entry that registers `provider`, as the model provider directory - * names it. A route registered by another package, nested settings, or an inactive entry counts as absent. + * Accept a deployment base URL that may receive the account credential: HTTP(S) without embedded credentials. + * @param value - the configured URL. + * @returns the value. + * @throws {Error} when the value is not such a URL. */ -function routeConfig(ctx: Context, provider: RouteName): unknown { - const llm = ctx.get('llm'), loader = ctx.get('loader') - if (llm === undefined || loader === undefined || !llm.listProviders().some(row => row.id === provider)) return undefined - const directory = llm.listConfigurableProviders().find(row => row.provider === provider) - if (directory === undefined || directory.settingsPath.length !== 0) return undefined - const entry = [...loader.entries()].find(row => row.options.id === directory.settingsNs && row.options.name === ROUTE_PACKAGES[provider]) - if (entry?.fiber?.state !== FiberState.ACTIVE) return undefined - return entry.fiber.effectiveConfig +function deploymentURL(value: string): string { + const url = new URL(value) + if (!/^https?:$/u.test(url.protocol) || url.username.length > 0 || url.password.length > 0) { + throw new Error(`${DEEPSEEK_BASE_URL_ENV} must be an HTTP(S) URL without credentials`) + } + return value } /** The Search and Fetch API base under the origin of a Messages base URL. */ diff --git a/packages/web/web-deepseek-api/src/transport.ts b/packages/web/web-deepseek-api/src/transport.ts index 1f61e36381..f8c841bb60 100644 --- a/packages/web/web-deepseek-api/src/transport.ts +++ b/packages/web/web-deepseek-api/src/transport.ts @@ -5,15 +5,13 @@ * @module @deepseek-ai/dsh-web-deepseek-api/transport */ import type { CredentialRef } from '@deepseek-ai/dsh-credentials' +import type { LlmCredentialKind, RouteCredential } from '@deepseek-ai/dsh-llm' import { WebError } from '@deepseek-ai/dsh-web' const USER_AGENT = 'deepseek-harness/0.0.1' -/** - * API key of one {@link DeepSeekWebAuthSource}: a literal value, where an empty string means no key, or a credential - * reference read once per use without retention. - */ -export type DeepSeekWebApiKey = string | { +/** API key of one {@link DeepSeekWebAuthSource}: a credential reference read once per use without retention. */ +export interface DeepSeekWebApiKey { /** Credential reference the key is stored under. */ ref: CredentialRef /** Report key presence without reading or validating its value; store failures reject. */ @@ -27,15 +25,16 @@ export type DeepSeekWebApiKey = string | { * `/search`, to `baseURL`. */ export type DeepSeekWebAuthSource = - /** The account token released for the dispatch endpoint, sent as `x-dsh-auth-token`. */ + /** + * A credential released per use for the dispatch endpoint, as a DeepSeek model route publishes it. An API key is + * sent as `Authorization: Bearer`; any other kind is sent through the headers of its grant. + */ | { - kind: 'account' - /** API base the token is sent to, including its path prefix. */ + kind: 'route' + /** API base the credential is sent to, including its path prefix. */ baseURL: string - /** Read the token released for a dispatch endpoint; undefined or empty means no token, and read failures reject. */ - resolveToken: (endpoint: string) => Promise - /** Invalidate the exact token rejected by HTTP 401; failures must not replace the request error. */ - rejectToken: (token: string) => Promise + /** The credential's owner: it answers presence and releases a grant for an endpoint, and read failures reject. */ + credential: Omit } /** An API key, sent as `Authorization: Bearer`. */ | { @@ -86,7 +85,7 @@ interface DeepSeekWebRequest { body: object /** Protocol headers without credentials. */ headers?: Readonly> - /** Additional API-key headers; not applied to account tokens. */ + /** Additional headers sent beside an API key; other credential kinds send only their grant's headers. */ apiKeyHeaders?: (key: string) => Readonly> /** Validate and project the response. */ decode: (payload: unknown) => T @@ -101,18 +100,19 @@ interface DeepSeekWebRequest { /** * Check synchronously whether an operation has a source to try, without reading credentials. * @param auth - Sources for the operation. - * @returns Whether any source is an account, a credential reference, a non-empty literal key, or a misconfigured source - * the operation reports. + * @returns Whether any source exists: a route credential, a credential reference, or a misconfigured source the + * operation reports. */ export function hasDeepSeekWebCredential(auth: DeepSeekWebAuth): boolean { - return auth.sources.some(source => source.kind !== 'api-key' || typeof source.key !== 'string' || source.key.length > 0) + return auth.sources.length > 0 } /** * Check whether an operation would find a credential, reading the sources in the order {@link dispatchDeepSeekWeb} - * does. An account source reads its token for the operation's endpoint; a referenced key is only checked for presence, - * so a malformed or wrong key counts as ready. A misconfigured source or a failed read answers false without reading - * later sources, because the operation fails there too. Nothing is sent and nothing is retained. + * does. A route source asks its credential whether one is configured for the operation's endpoint; a referenced key is + * only checked for presence, so a malformed or wrong key counts as ready. A misconfigured source or a failed read + * answers false without reading later sources, because the operation fails there too. Nothing is sent and nothing is + * retained. * @param auth - Sources for the operation. * @param path - Operation path appended to each source's base. * @returns Whether a source before any misconfigured or unreadable one is present. @@ -121,20 +121,13 @@ export async function isDeepSeekWebAuthReady(auth: DeepSeekWebAuth, path: '/sear for (const source of auth.sources) { switch (source.kind) { case 'misconfigured': return false - case 'account': { - let token: string | undefined - try { token = await source.resolveToken(joinPath(source.baseURL, path)) } - catch (_unreadableGrant) { return false /* The operation fails on this read before it tries another source. */ } - if (token !== undefined && token.length > 0) return true + case 'route': { + try { if (await source.credential.configured(joinPath(source.baseURL, path))) return true } + catch (_unreadableCredential) { return false /* The operation fails on this read before it tries another source. */ } break } case 'api-key': { - const { key } = source - if (typeof key === 'string') { - if (key.length > 0) return true - break - } - try { if (await key.configured()) return true } + try { if (await source.key.configured()) return true } catch (_unreadableStore) { return false /* The operation fails on this read before it tries another source. */ } break } @@ -160,15 +153,15 @@ export function invalidResponse(): WebError { return new WebError('DeepSeek returned an invalid response body', 'WEB_PROVIDER_ERROR') } -/** Authentication headers and endpoint for one operation, tagged by the credential that produced them. */ +/** Authentication headers and endpoint for one operation, tagged by the kind of credential that produced them. */ interface SearchAuth { - /** `account` for a DeepSeek account token, `api-key` for an API key. */ - readonly kind: 'account' | 'api-key' + /** Kind of the credential sent; an API-key source sends `api-key`. */ + readonly kind: LlmCredentialKind /** Absolute dispatch URL under the base of the source. */ readonly endpoint: string /** Headers carrying the credential. */ readonly headers: Readonly> - /** Request-bound invalidation, present only when an account token was sent. */ + /** Request-bound invalidation of the sent credential, present when its grant offers one. */ readonly reject?: () => Promise } @@ -234,14 +227,13 @@ export async function dispatchDeepSeekWeb( // malformed/non-JSON error body (normal for gateway 5xx/429s) can only // cost a richer provider message, never the real error. } - // The account service released this token only for its inference - // origin, so the endpoint is not what the user must change. - if (status === 401 && auth.kind === 'account') { + if (status === 401) { // Invalidation can cancel this Session; finish reading the HTTP failure before it does. A cancelled read still - // invalidates the token the status rejected. - try { await auth.reject?.() } - catch (_credentialRemovalFailed) { /* Report the original failure even if credential removal fails. */ } - throw aborted ?? accountRejectedError(message) + // invalidates the credential the status rejected. + await auth.reject?.() + // The account service released its credential only for its inference origin, so the endpoint is not what the + // user must change. + if (auth.kind === 'account') throw aborted ?? accountRejectedError(message) } if (aborted !== undefined) throw aborted throw searchEndpointError(guidance, endpoint, message) @@ -315,21 +307,20 @@ async function authHeaders( throwIfSearchAborted(signal) switch (source.kind) { case 'misconfigured': throw new WebError(source.message, 'WEB_PROVIDER_MISCONFIGURED') - case 'account': { + case 'route': { const endpoint = joinPath(source.baseURL, request.path) - const token = await resolveCredential(() => source.resolveToken(endpoint), signal) - if (token !== undefined && token.length > 0) return { - kind: 'account', endpoint, headers: { 'x-dsh-auth-token': token }, - reject: async () => { await source.rejectToken(token) }, + const grant = await resolveCredential(() => source.credential.resolve(endpoint, signal), signal) + if (grant === undefined) break + const { kind } = source.credential + const invalidate = grant.reject?.bind(grant) + return { + kind, endpoint, + headers: kind === 'api-key' ? { ...request.apiKeyHeaders?.(grant.value), authorization: `Bearer ${grant.value}` } : grant.headers, + ...invalidate === undefined ? {} : { reject: invalidate }, } - break } case 'api-key': { - const { key } = source - // A conditional await in a ternary can produce negative branch counts in V8-to-Istanbul mapping. - let apiKey: string | undefined - if (typeof key === 'string') apiKey = key - else apiKey = await resolveCredential(key.resolve, signal) + const apiKey = await resolveCredential(source.key.resolve, signal) if (apiKey !== undefined && apiKey.length > 0) return { kind: 'api-key', endpoint: joinPath(source.baseURL, request.path), headers: { ...request.apiKeyHeaders?.(apiKey), 'authorization': `Bearer ${apiKey}`, @@ -367,9 +358,7 @@ function assertNever(value: never): never { * @returns the resolved credential, or undefined when the resolver supplied none. * @throws {@link WebError} `WEB_ABORTED` on cancellation, `WEB_PROVIDER_ERROR` when the resolver fails. */ -async function resolveCredential( - resolve: () => Promise, signal?: AbortSignal, -): Promise { +async function resolveCredential(resolve: () => Promise, signal?: AbortSignal): Promise { throwIfSearchAborted(signal) try { return await abortable(resolve(), signal) diff --git a/packages/web/web-deepseek-api/tests/composition.spec.ts b/packages/web/web-deepseek-api/tests/composition.spec.ts index ba93f108bc..71f01ee2b9 100644 --- a/packages/web/web-deepseek-api/tests/composition.spec.ts +++ b/packages/web/web-deepseek-api/tests/composition.spec.ts @@ -10,13 +10,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { Context } from '@deepseek-ai/cordis' import type { ModuleLoaderV2 } from '@deepseek-ai/cordis-plugin-loader' import { boot } from '@deepseek-ai/dsh-app-boot' -import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' import LlmRuntime from '@deepseek-ai/dsh-llm' import * as Account from '@deepseek-ai/dsh-llm-deepseek-account' import * as Official from '@deepseek-ai/dsh-llm-deepseek-api-key' import WebRuntime from '@deepseek-ai/dsh-web' import * as webApiPlugin from '@deepseek-ai/dsh-web-deepseek-api' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' const cleanups: Array<() => Promise> = [] @@ -83,7 +83,7 @@ async function bootComposition(web: Record, environment: Record } host.loader.internal = modules host.provide('launchEnvironment', createLaunchEnvironmentSnapshot([{ source: 'process', values: environment }])) - host.provide('deepseekAccount', { resolveToken: async () => 'account-token' } as Pick as DeepSeekAccount) + host.provide('deepseekAccount', accountStub({ token: () => 'account-token' })) }) cleanups.push(async () => { await ctx.fiber.dispose() }) const sent = (): Sent[] => fetchMock.mock.calls.flatMap(([endpoint, init]) => { diff --git a/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts b/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts index 741ebde66e..abd6896b76 100644 --- a/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts +++ b/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts @@ -4,10 +4,11 @@ * operation would send. */ import { afterEach, describe, expect, it, vi } from 'vitest' -import { Context, FiberState } from '@deepseek-ai/cordis' +import { Context } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' import { DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' @@ -15,20 +16,6 @@ import WebRuntime from '@deepseek-ai/dsh-web' import * as webApiPlugin from '@deepseek-ai/dsh-web-deepseek-api' import { provideRoutes, type RouteRow } from './routes.ts' -/** A value the API-key route resolver throws instead of resolving; undefined lets it resolve normally. */ -const resolverThrow = vi.hoisted(() => ({ value: undefined as string | undefined })) - -vi.mock('@deepseek-ai/dsh-llm-deepseek-api-key', async (importOriginal) => { - const original = await importOriginal() - return { - ...original, - resolveAdapterOptions: (...args: Parameters) => { - if (resolverThrow.value !== undefined) throw resolverThrow.value - return original.resolveAdapterOptions(...args) - }, - } -}) - type Operation = 'search' | 'fetch' const OPERATIONS: readonly Operation[] = ['search', 'fetch'] @@ -41,7 +28,6 @@ const mounted: Context[] = [] afterEach(async () => { vi.unstubAllGlobals() - resolverThrow.value = undefined await Promise.all(mounted.splice(0).map(ctx => ctx.fiber.dispose())) }) @@ -53,7 +39,7 @@ interface Setup { /** Model routes the provider directory lists. */ routes?: readonly RouteRow[] /** Account service stand-in. */ - account?: Pick & Partial> + account?: DeepSeekAccount /** Credentials service stand-in. */ credentials?: object /** API response status. */ @@ -81,7 +67,7 @@ async function mount(setup: Setup): Promise<{ ctx: Context; sent: () => Sent[] } const ctx = new Context() mounted.push(ctx) ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([{ source: 'process', values: setup.environment ?? {} }])) - if (setup.account !== undefined) ctx.provide('deepseekAccount', setup.account as DeepSeekAccount) + if (setup.account !== undefined) ctx.provide('deepseekAccount', setup.account) if (setup.credentials !== undefined) ctx.provide('credentials', setup.credentials as never) if (setup.routes !== undefined) provideRoutes(ctx, setup.routes) await ctx.plugin(SessionStore) @@ -121,10 +107,14 @@ function ready(ctx: Context, operation: Operation, route: string | undefined): P return operation === 'search' ? ctx.web.searchReady(route) : ctx.web.fetchReady(route) } -/** The account service of a signed-in user, recording the URLs it is asked for. */ -function signedIn(asked: string[] = []): Pick { - return { resolveToken: async (url: string) => { asked.push(url); return 'account-token' } } +/** The account service of a signed-in user, recording the URLs it is asked for and the tokens it is told to reject. */ +function signedIn(asked: string[] = [], reject?: (token: string) => Promise): DeepSeekAccount { + return accountStub({ token: (url) => { asked.push(url); return 'account-token' }, ...reject === undefined ? {} : { reject } }) } +/** The account service of a signed-out user. */ +const signedOut = (): DeepSeekAccount => accountStub({ token: () => undefined }) +/** An account service whose stored grant cannot be read. */ +const unreadable = (): DeepSeekAccount => accountStub({ token: () => Promise.reject(new Error('grant unreadable')) }) const officialRoute = (config: Record = { baseURL: 'https://route.deepseek.test/anthropic' }): RouteRow => ({ provider: 'deepseek-official', config }) @@ -151,8 +141,8 @@ describe.each(OPERATIONS)('%s in a conversation on the DeepSeek account route', }) it('invalidates the token the API rejects with 401', async () => { - const rejectToken = vi.fn(async () => {}) - const { ctx } = await mount({ routes: bothRoutes, account: { ...signedIn(), rejectToken }, status: 401 }) + const rejectToken = vi.fn(async (_token: string) => {}) + const { ctx } = await mount({ routes: bothRoutes, account: signedIn([], rejectToken), status: 401 }) const failure = operate(ctx, operation, 'deepseek-account') await expect(failure).rejects.toMatchObject({ code: 'WEB_PROVIDER_ERROR' }) await expect(failure).rejects.toThrow('HTTP 401') @@ -160,8 +150,7 @@ describe.each(OPERATIONS)('%s in a conversation on the DeepSeek account route', }) it.each<[string, Setup['account']]>([ - ['the user is not signed in', { resolveToken: async () => undefined }], - ['the account releases an empty token', { resolveToken: async () => '' }], + ['the user is not signed in', signedOut()], ['no account service is mounted', undefined], ])('sends the API key to the API-key endpoint when %s', async (_label, account) => { const { ctx, sent } = await mount({ @@ -174,7 +163,7 @@ describe.each(OPERATIONS)('%s in a conversation on the DeepSeek account route', it('is not ready and names both recoveries when neither a sign-in nor the key is available', async () => { const subject = operation === 'search' ? 'Search' : 'Fetch' - const { ctx, sent } = await mount({ routes: bothRoutes, account: { resolveToken: async () => undefined } }) + const { ctx, sent } = await mount({ routes: bothRoutes, account: signedOut() }) expect(await ready(ctx, operation, 'deepseek-account')).toBe(false) await expect(operate(ctx, operation, 'deepseek-account')).rejects.toMatchObject({ code: 'WEB_PROVIDER_CREDENTIAL_MISSING', @@ -228,7 +217,7 @@ describe.each(OPERATIONS)('%s in a conversation on the DeepSeek account route', it('fails instead of sending DEEPSEEK_API_KEY when there is no sign-in and the API-key route settings do not resolve', async () => { const { ctx, sent } = await mount({ routes: [officialRoute({ thinking: 'disabled', reasoningEffort: 'high' }), accountRoute()], - account: { resolveToken: async () => undefined }, environment: { DEEPSEEK_API_KEY: 'chat-key' }, + account: signedOut(), environment: { DEEPSEEK_API_KEY: 'chat-key' }, }) expect(await ready(ctx, operation, 'deepseek-account')).toBe(false) await expect(operate(ctx, operation, 'deepseek-account')).rejects.toMatchObject({ code: 'WEB_PROVIDER_MISCONFIGURED' }) @@ -237,7 +226,7 @@ describe.each(OPERATIONS)('%s in a conversation on the DeepSeek account route', it('is not ready and fails without trying the key when the account grant cannot be read', async () => { const { ctx, sent } = await mount({ - routes: bothRoutes, account: { resolveToken: () => Promise.reject(new Error('grant unreadable')) }, + routes: bothRoutes, account: unreadable(), environment: { DEEPSEEK_API_KEY: 'chat-key' }, }) expect(await ready(ctx, operation, 'deepseek-account')).toBe(false) @@ -302,7 +291,7 @@ describe.each(OPERATIONS)('%s in any other conversation', (operation) => { it('is not ready and names both recoveries without a key and a sign-in', async () => { const subject = operation === 'search' ? 'Search' : 'Fetch' - for (const account of [{ resolveToken: async () => undefined }, undefined]) { + for (const account of [signedOut(), undefined]) { const { ctx, sent } = await mount({ routes: bothRoutes, ...account === undefined ? {} : { account } }) expect(await ready(ctx, operation, 'moonshotai')).toBe(false) await expect(operate(ctx, operation, 'moonshotai')).rejects.toMatchObject({ @@ -364,10 +353,9 @@ describe.each(OPERATIONS)('%s in any other conversation', (operation) => { }) it.each<[string, readonly RouteRow[] | undefined]>([ - ['no model provider directory is mounted', undefined], - ['the route entry is not active', [{ provider: 'deepseek-official', config: { apiKeyEnv: 'TEAM_KEY' }, state: FiberState.DISPOSED }]], - ['another package registers the route', [{ provider: 'deepseek-official', config: { apiKeyEnv: 'TEAM_KEY' }, name: '@example/other-llm' }]], - ['the route settings are nested', [{ provider: 'deepseek-official', config: { apiKeyEnv: 'TEAM_KEY' }, settingsPath: ['routes', 'official'] }]], + ['no model service is mounted', undefined], + ['no route registers deepseek-official', [accountRoute()]], + ['the registered deepseek-official adapter publishes no credential', [{ provider: 'deepseek-official', config: { apiKeyEnv: 'TEAM_KEY' }, withoutCredential: true }]], ])('sends DEEPSEEK_API_KEY to the official base when %s', async (_label, routes) => { const { ctx, sent } = await mount({ ...routes === undefined ? {} : { routes }, @@ -470,8 +458,7 @@ describe.each(OPERATIONS)('%s billed to the signed-in DeepSeek account', (operat }) it.each<[string, Setup['account']]>([ - ['the user is not signed in', { resolveToken: async () => undefined }], - ['the account releases an empty token', { resolveToken: async () => '' }], + ['the user is not signed in', signedOut()], ['no account service is mounted', undefined], ])('is not ready and never sends the key when %s', async (_label, account) => { const { ctx, sent } = await mount({ @@ -503,18 +490,31 @@ describe.each(OPERATIONS)('%s billed to the signed-in DeepSeek account', (operat expect(asked).toEqual([]) }) - it('is not ready and fails without a token when the default account settings do not resolve', async () => { - const { ctx, sent } = await mount({ - config, account: signedIn(), environment: { DEEPSEEK_BASE_URL: 'https://user:secret@internal.deepseek.test/anthropic' }, - }) - expect(await ready(ctx, operation, undefined)).toBe(false) - await expect(operate(ctx, operation)).rejects.toMatchObject({ code: 'WEB_PROVIDER_MISCONFIGURED' }) + it('is not ready and never sends the key without the account route and the account service', async () => { + const { ctx, sent } = await mount({ config, routes: [officialRoute()], environment: { DEEPSEEK_API_KEY: 'chat-key' } }) + expect(await ready(ctx, operation, 'moonshotai')).toBe(false) + await expect(operate(ctx, operation, 'moonshotai')).rejects.toMatchObject({ code: 'WEB_PROVIDER_CREDENTIAL_MISSING' }) expect(sent()).toEqual([]) }) + it.each(['https://user:secret@internal.deepseek.test/anthropic', 'https://:secret@internal.deepseek.test/anthropic', 'ftp://internal.deepseek.test/anthropic', 'not a url'])( + 'is not ready and fails without a token when DEEPSEEK_BASE_URL is %s and no account route is mounted', async (baseURL) => { + const asked: string[] = [] + const { ctx, sent } = await mount({ config, account: signedIn(asked), environment: { DEEPSEEK_BASE_URL: baseURL } }) + expect(await ready(ctx, operation, undefined)).toBe(false) + const failure = operate(ctx, operation) + await expect(failure).rejects.toMatchObject({ code: 'WEB_PROVIDER_MISCONFIGURED' }) + await expect(failure).rejects.toThrow(`DeepSeek ${subject} API sends the DeepSeek account sign-in to the origin of DEEPSEEK_BASE_URL,` + + ' and that value does not resolve: ') + await expect(failure).rejects.toThrow('Guide the user to correct DEEPSEEK_BASE_URL in the launching environment, or to set') + expect(sent()).toEqual([]) + expect(asked).toEqual([]) + }, + ) + it('is not ready and fails when the account grant cannot be read', async () => { const { ctx, sent } = await mount({ - config, routes: bothRoutes, account: { resolveToken: () => Promise.reject(new Error('grant unreadable')) }, + config, routes: bothRoutes, account: unreadable(), environment: { DEEPSEEK_API_KEY: 'chat-key' }, }) expect(await ready(ctx, operation, 'moonshotai')).toBe(false) @@ -523,8 +523,8 @@ describe.each(OPERATIONS)('%s billed to the signed-in DeepSeek account', (operat }) it('invalidates the token the API rejects with 401', async () => { - const rejectToken = vi.fn(async () => {}) - const { ctx } = await mount({ config, routes: bothRoutes, account: { ...signedIn(), rejectToken }, status: 401 }) + const rejectToken = vi.fn(async (_token: string) => {}) + const { ctx } = await mount({ config, routes: bothRoutes, account: signedIn([], rejectToken), status: 401 }) await expect(operate(ctx, operation, 'moonshotai')).rejects.toThrow('HTTP 401') expect(rejectToken).toHaveBeenCalledExactlyOnceWith('account-token') }) @@ -677,10 +677,11 @@ describe('independent capabilities', () => { }) }) -describe('route resolver failures', () => { +describe('route credential failures', () => { it('reports a thrown non-Error value as its string', async () => { - const { ctx, sent } = await mount({ routes: [officialRoute()], environment: { DEEPSEEK_API_KEY: 'chat-key' } }) - resolverThrow.value = 'route resolver unavailable' + const { ctx, sent } = await mount({ + routes: [{ provider: 'deepseek-official', throws: 'route resolver unavailable' }], environment: { DEEPSEEK_API_KEY: 'chat-key' }, + }) const failure = operate(ctx, 'search', 'deepseek-official') await expect(failure).rejects.toMatchObject({ code: 'WEB_PROVIDER_MISCONFIGURED' }) await expect(failure).rejects.toThrow('that provider\'s settings do not resolve: route resolver unavailable. Search did not send') diff --git a/packages/web/web-deepseek-api/tests/egress.spec.ts b/packages/web/web-deepseek-api/tests/egress.spec.ts index c47a3c07ba..cbe81aac8c 100644 --- a/packages/web/web-deepseek-api/tests/egress.spec.ts +++ b/packages/web/web-deepseek-api/tests/egress.spec.ts @@ -1,6 +1,7 @@ import { createServer, type Server } from 'node:http' import type { AddressInfo } from 'node:net' import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { credentialRef } from '@deepseek-ai/dsh-credentials' import { installProxyFromEnvironment } from '@deepseek-ai/dsh-http-proxy' import { customGuidance } from './guidance.ts' @@ -35,7 +36,7 @@ async function observe(run: () => Promise): Promise { import { DeepSeekSearchApiProvider } from '../src/search.ts' describe('deepseek search api egress', () => { it('goes through the proxy', async () => { - const p = new DeepSeekSearchApiProvider(() => ({ auth: { sources: [{ kind: 'api-key', baseURL: 'http://dsk-probe.invalid/api/v1/tools', key: 'probe' }] }, count: 10, requestsPerSecond: 5, guidance: customGuidance('search') })) + const p = new DeepSeekSearchApiProvider(() => ({ auth: { sources: [{ kind: 'api-key', baseURL: 'http://dsk-probe.invalid/api/v1/tools', key: { ref: credentialRef('PROBE_KEY'), configured: async () => true, resolve: async () => 'probe' } }] }, count: 10, requestsPerSecond: 5, guidance: customGuidance('search') })) expect(await observe(() => p.search({ query: 'probe' }))).toEqual(['REQ http://dsk-probe.invalid/api/v1/tools/search']) }) }) diff --git a/packages/web/web-deepseek-api/tests/fetch.spec.ts b/packages/web/web-deepseek-api/tests/fetch.spec.ts index 060725780a..31ef9f6e14 100644 --- a/packages/web/web-deepseek-api/tests/fetch.spec.ts +++ b/packages/web/web-deepseek-api/tests/fetch.spec.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' +import { credentialRef } from '@deepseek-ai/dsh-credentials' import WebRuntime from '@deepseek-ai/dsh-web' import { DeepSeekFetchApiProvider, type DeepSeekFetchApiOptions } from '@deepseek-ai/dsh-web-deepseek-api' import * as webApiPlugin from '@deepseek-ai/dsh-web-deepseek-api' @@ -7,7 +8,8 @@ import { DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot } from '@de import { customGuidance } from './guidance.ts' const fetchProvider = (options: DeepSeekFetchApiOptions) => new DeepSeekFetchApiProvider(() => options) const BASE = 'https://api.deepseek.test/api/v1/tools' -const auth = (key: string, baseURL = BASE): DeepSeekFetchApiOptions['auth'] => ({ sources: [{ kind: 'api-key', baseURL, key }] }) +const auth = (key: string, baseURL = BASE): DeepSeekFetchApiOptions['auth'] => + ({ sources: [{ kind: 'api-key', baseURL, key: { ref: credentialRef('TEST_KEY'), configured: async () => key.length > 0, resolve: async () => key.length > 0 ? key : undefined } }] }) const options = { auth: auth('ds-key'), guidance: customGuidance('fetch') } function jsonResponse(body: unknown, init: ResponseInit = {}): Response { return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' }, ...init }) @@ -57,7 +59,8 @@ describe('DeepSeek Fetch API', () => { }) it('is available only with a credential source and a parseable base', () => { expect(fetchProvider(options).available()).toBe(true) - expect(fetchProvider({ ...options, auth: auth('') }).available()).toBe(false) + expect(fetchProvider({ ...options, auth: { sources: [] } }).available()).toBe(false) + expect(fetchProvider({ ...options, auth: auth('') }).available()).toBe(true) expect(fetchProvider({ ...options, auth: auth('ds-key', 'not a url') }).available()).toBe(false) }) it('unregisters both providers with its plugin fiber', async () => { diff --git a/packages/web/web-deepseek-api/tests/redirect.spec.ts b/packages/web/web-deepseek-api/tests/redirect.spec.ts index 6453872aa8..f1985a350e 100644 --- a/packages/web/web-deepseek-api/tests/redirect.spec.ts +++ b/packages/web/web-deepseek-api/tests/redirect.spec.ts @@ -6,6 +6,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { createServer, type IncomingMessage, type Server } from 'node:http' import type { AddressInfo } from 'node:net' +import { credentialRef } from '@deepseek-ai/dsh-credentials' import { customGuidance } from './guidance.ts' import { dispatchDeepSeekWeb } from '../src/transport.ts' @@ -47,7 +48,7 @@ afterAll(async () => { describe('dispatchDeepSeekWeb redirect policy', () => { it.each([301, 302, 303, 307, 308])('rejects HTTP %i before contacting Location', async (status) => { targetRequests.length = 0 - await expect(dispatchDeepSeekWeb({ sources: [{ kind: 'api-key', baseURL: redirectOrigin, key: TEST_API_KEY }] }, { + await expect(dispatchDeepSeekWeb({ sources: [{ kind: 'api-key', baseURL: redirectOrigin, key: { ref: credentialRef('TEST_API_KEY'), configured: async () => true, resolve: async () => TEST_API_KEY } }] }, { path: `/${status}`, body: { query: TEST_QUERY }, decode: value => value, apiKeyHeaders: key => ({ 'x-api-key': key }), guidance: customGuidance('search'), @@ -57,8 +58,9 @@ describe('dispatchDeepSeekWeb redirect policy', () => { it('rejects a redirect of an account-token request before contacting Location', async () => { targetRequests.length = 0 + const grant = { headers: { 'x-dsh-auth-token': 'redirect-test-token' }, value: 'redirect-test-token' } await expect(dispatchDeepSeekWeb({ sources: [{ - kind: 'account', baseURL: redirectOrigin, resolveToken: async () => 'redirect-test-token', rejectToken: async () => {}, + kind: 'route', baseURL: redirectOrigin, credential: { kind: 'account', configured: async () => true, resolve: async () => grant }, }] }, { path: '/307', body: { query: TEST_QUERY }, decode: value => value, guidance: customGuidance('search'), diff --git a/packages/web/web-deepseek-api/tests/routes.ts b/packages/web/web-deepseek-api/tests/routes.ts index a6592cea45..620a3b87f5 100644 --- a/packages/web/web-deepseek-api/tests/routes.ts +++ b/packages/web/web-deepseek-api/tests/routes.ts @@ -1,48 +1,61 @@ -/** Stand-in model and loader services that expose DeepSeek model routes the way the provider directory does. */ -import { FiberState, type Context } from '@deepseek-ai/cordis' +/** A stand-in model service publishing DeepSeek route credentials the way the route plugins do. */ +import type { Context } from '@deepseek-ai/cordis' +import { credentialRefConfigured, resolveCredentialRef } from '@deepseek-ai/dsh-credentials' +import type {} from '@deepseek-ai/dsh-deepseek-account' +import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' +import type { RouteCredential } from '@deepseek-ai/dsh-llm' import { Config as AccountConfig } from '@deepseek-ai/dsh-llm-deepseek-account' +import { plainAccountOptions, resolveAccountOptions } from '@deepseek-ai/dsh-llm-deepseek-account/src/config.ts' import { Config as OfficialConfig } from '@deepseek-ai/dsh-llm-deepseek-api-key' +import { plainOptions, resolveAdapterOptions } from '@deepseek-ai/dsh-llm-deepseek-api-key/src/config.ts' /** One model route row. */ export interface RouteRow { /** Provider id the route registers. */ provider: 'deepseek-official' | 'deepseek-account' - /** Route plugin config, parsed by the route package's own schema. */ + /** Route plugin config; the route package's own resolver turns it into the published base URL and key reference. */ config?: Record - /** Loader package name; defaults to the package that registers the provider. */ - name?: string - /** Loader fiber state; defaults to active. */ - state?: FiberState - /** Provider directory settings path; defaults to the entry root. */ - settingsPath?: string[] + /** Publish no credential, as an adapter another package registers under this id does. Defaults to false. */ + withoutCredential?: boolean + /** Value `routeCredential()` throws instead of publishing. */ + throws?: unknown } -const PACKAGES = { - 'deepseek-official': '@deepseek-ai/dsh-llm-deepseek-api-key', - 'deepseek-account': '@deepseek-ai/dsh-llm-deepseek-account', -} as const +/** The credential `route` publishes, resolved from its config as the route plugin resolves it on each call. */ +function credentialOf(ctx: Context, route: RouteRow): RouteCredential { + const environment = launchEnvironmentOf(ctx) + if (route.provider === 'deepseek-official') { + const resolved = resolveAdapterOptions(plainOptions(OfficialConfig(route.config ?? {})), environment) + const ref = resolved.apiKeyEnv + return { + kind: 'api-key', baseURL: resolved.baseURL, reference: ref, + configured: () => credentialRefConfigured(ctx, ref), + resolve: async () => { + const key = await resolveCredentialRef(ctx, ref) + return key === undefined ? undefined : { headers: { 'x-api-key': key }, value: key } + }, + } + } + const resolved = resolveAccountOptions(plainAccountOptions(AccountConfig(route.config ?? {})), environment) + return { + kind: 'account', baseURL: resolved.protocol.baseURL, + configured: async endpoint => (await ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint)) !== undefined, + resolve: endpoint => ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint) ?? Promise.resolve(undefined), + } +} /** - * Provide `llm` and `loader` stand-ins whose rows describe `routes`. + * Provide an `llm` stand-in whose `routeCredential()` answers for `routes`. * @param ctx - the root context. - * @param routes - route rows; each gets its own loader entry. + * @param routes - route rows, one per provider id. */ export function provideRoutes(ctx: Context, routes: readonly RouteRow[]): void { - const rows = routes.map((route, index) => ({ - route, - entry: { - options: { id: `route-${String(index)}`, name: route.name ?? PACKAGES[route.provider] }, - fiber: { - state: route.state ?? FiberState.ACTIVE, - effectiveConfig: route.provider === 'deepseek-official' ? OfficialConfig(route.config ?? {}) : AccountConfig(route.config ?? {}), - }, - }, - })) ctx.provide('llm', { - listProviders: () => rows.map(({ route }) => ({ id: route.provider })), - listConfigurableProviders: () => rows.map(({ route, entry }) => ({ - provider: route.provider, settingsNs: entry.options.id, settingsPath: route.settingsPath ?? [], - })), + routeCredential: (provider: string): RouteCredential | undefined => { + const route = routes.find(row => row.provider === provider) + if (route === undefined || route.withoutCredential === true) return undefined + if (route.throws !== undefined) throw route.throws + return credentialOf(ctx, route) + }, } as never) - ctx.provide('loader', { entries: () => rows.map(({ entry }) => entry).values() } as never) } diff --git a/packages/web/web-deepseek-api/tests/search.spec.ts b/packages/web/web-deepseek-api/tests/search.spec.ts index 6840c90493..17d3eccfa7 100644 --- a/packages/web/web-deepseek-api/tests/search.spec.ts +++ b/packages/web/web-deepseek-api/tests/search.spec.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' +import { credentialRef } from '@deepseek-ai/dsh-credentials' import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import type { Session } from '@deepseek-ai/dsh-session' @@ -20,7 +21,8 @@ const searchProvider = (options: DeepSeekSearchApiOptions): DeepSeekSearchApiPro new DeepSeekSearchApiProvider(() => options) const BASE = 'https://api.deepseek.test/api/v1/tools' -const auth = (key: string, baseURL = BASE): DeepSeekSearchApiOptions['auth'] => ({ sources: [{ kind: 'api-key', baseURL, key }] }) +const auth = (key: string, baseURL = BASE): DeepSeekSearchApiOptions['auth'] => + ({ sources: [{ kind: 'api-key', baseURL, key: { ref: credentialRef('TEST_KEY'), configured: async () => key.length > 0, resolve: async () => key.length > 0 ? key : undefined } }] }) const options = { auth: auth('ds-key'), @@ -74,16 +76,18 @@ describe('mapSearchResponse', () => { }) describe('DeepSeekSearchApiProvider availability', () => { - it('is unavailable without a key', () => { - expect(searchProvider({ ...options, auth: auth('') }).available()).toBe(false) + it('is unavailable without a source, and available with a referenced key whose presence only ready() reads', () => { + expect(searchProvider({ ...options, auth: { sources: [] } }).available()).toBe(false) + expect(searchProvider({ ...options, auth: auth('') }).available()).toBe(true) }) it('is available with a key', () => { expect(searchProvider(options).available()).toBe(true) }) - it('is available with only an account token resolver', () => { - expect(searchProvider({ ...options, auth: { sources: [{ kind: 'account', baseURL: BASE, resolveToken: async () => 'account-token', rejectToken: async () => {} }] } }).available()).toBe(true) + it('is available with only a route credential', () => { + const credential = { kind: 'account', configured: async () => true, resolve: async () => undefined } as const + expect(searchProvider({ ...options, auth: { sources: [{ kind: 'route', baseURL: BASE, credential }] } }).available()).toBe(true) }) it('is available with only a misconfigured source, which the search reports', () => { diff --git a/packages/web/web-deepseek-api/tests/transport.spec.ts b/packages/web/web-deepseek-api/tests/transport.spec.ts index 5296e4eb42..c6620a9d13 100644 --- a/packages/web/web-deepseek-api/tests/transport.spec.ts +++ b/packages/web/web-deepseek-api/tests/transport.spec.ts @@ -9,18 +9,39 @@ import { const API_BASE = 'https://api.deepseek.test/v1/tools' const ACCOUNT_BASE = 'https://account.deepseek.test/v1/tools' /** An API-key source on {@link API_BASE}. */ -function keySource(key: DeepSeekWebApiKey = 'ds-key'): DeepSeekWebAuthSource { +function keySource(key: DeepSeekWebApiKey = keyRef(async () => 'ds-key')): DeepSeekWebAuthSource { return { kind: 'api-key', baseURL: API_BASE, key } } /** A referenced key whose presence check and read are the given functions. */ function keyRef(resolve: () => Promise, configured: () => Promise = async () => true): DeepSeekWebApiKey { return { ref: credentialRef('TEST_KEY'), configured, resolve } } -/** An account source on {@link ACCOUNT_BASE}. */ +/** + * A route source on {@link ACCOUNT_BASE} whose account credential releases `resolveToken(endpoint)` as the token header; + * an empty token releases nothing. `rejectToken` observes each invalidated token, and its failures are contained as the + * account service contains them. + */ function accountSource( resolveToken: (endpoint: string) => Promise, rejectToken: (token: string) => Promise = async () => {}, ): DeepSeekWebAuthSource { - return { kind: 'account', baseURL: ACCOUNT_BASE, resolveToken, rejectToken } + const grant = async (endpoint: string) => { + const token = await resolveToken(endpoint) + if (token === undefined || token.length === 0) return undefined + return { headers: { 'x-dsh-auth-token': token }, value: token, reject: async () => { + try { await rejectToken(token) } catch (_storageFailure) { /* Contained as the account service contains it. */ } + } } + } + return { kind: 'route', baseURL: ACCOUNT_BASE, credential: { + kind: 'account', configured: async endpoint => (await grant(endpoint)) !== undefined, resolve: grant, + } } +} +/** A route source on {@link API_BASE} whose API-key credential releases `key`, sent as a bearer token. */ +function keyRouteSource(key: string | undefined, reference = 'ROUTE_KEY'): DeepSeekWebAuthSource { + return { kind: 'route', baseURL: API_BASE, credential: { + kind: 'api-key', reference, + configured: async () => key !== undefined, + resolve: async () => key === undefined ? undefined : { headers: { 'x-api-key': key }, value: key }, + } } } const misconfigured: DeepSeekWebAuthSource = { kind: 'misconfigured', message: 'route settings do not resolve' } /** Search once with the given sources, in order. */ @@ -101,9 +122,24 @@ describe('DeepSeek web credential order', () => { .toEqual([[`${API_BASE}/search`, 'ds-key', undefined]]) }) + it('sends a route API key as a bearer token with the request\'s API-key headers, never the route\'s own headers', async () => { + const { sent } = captureFetch() + await search([keyRouteSource('route-key')]) + const [request] = sent() + expect(request?.url).toBe(`${API_BASE}/search`) + expect(request?.headers).toMatchObject({ 'authorization': 'Bearer route-key', 'x-api-key': 'route-key' }) + expect(request?.headers).not.toHaveProperty('x-dsh-auth-token') + }) + + it('moves past a route whose API key is absent', async () => { + const { sent } = captureFetch() + await search([keyRouteSource(undefined), accountSource(async () => 'account-token')]) + expect(sent().map(row => [row.url, row.headers['x-dsh-auth-token']])).toEqual([[`${ACCOUNT_BASE}/search`, 'account-token']]) + }) + it.each<[string, readonly DeepSeekWebAuthSource[]]>([ ['no sources', []], - ['an empty literal key', [keySource('')]], + ['a referenced key that resolves empty', [keySource(keyRef(async () => ''))]], ['a missing referenced key and no account token', [keySource(keyRef(async () => undefined)), accountSource(async () => undefined)]], ])('fails with the caller diagnostic and sends nothing for %s', async (_label, sources) => { const { fetchMock } = captureFetch() @@ -161,7 +197,7 @@ describe('DeepSeek web credential order', () => { describe('DeepSeek web credential availability and readiness', () => { it.each<[boolean, readonly DeepSeekWebAuthSource[]]>([ [false, []], - [false, [keySource('')]], + [true, [keySource(keyRef(async () => undefined, async () => false))]], [true, [keySource()]], [true, [keySource(keyRef(async () => undefined))]], [true, [accountSource(async () => undefined)]], @@ -184,8 +220,8 @@ describe('DeepSeek web credential availability and readiness', () => { it.each<[string, readonly DeepSeekWebAuthSource[], boolean]>([ ['no sources', [], false], - ['an empty literal key', [keySource('')], false], - ['a literal key', [keySource()], true], + ['an unconfigured referenced key', [keySource(keyRef(async () => undefined, async () => false))], false], + ['a configured referenced key', [keySource()], true], ['a configured key before the account', [keySource(keyRef(async () => undefined)), accountSource(async () => undefined)], true], ['neither credential', [accountSource(async () => ''), keySource(keyRef(async () => undefined, async () => false))], false], ])('answers for %s', async (_label, sources, expected) => { @@ -215,7 +251,7 @@ describe('DeepSeek web account authentication', () => { }) }) - it.each([false, true])('invalidates the sent account token on 401 and preserves the HTTP error when removal fails: %s', async (fails) => { + it.each([false, true])('invalidates the sent account token on 401 and preserves the HTTP error whether or not removal fails: %s', async (fails) => { const rejectToken = vi.fn(async (_token: string) => { if (fails) throw new Error('storage failed') }) vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: 'invalid token' }, { status: 401 }))) const error = await rejectedWebError(search([accountSource(async () => 'sent-token', rejectToken)])) @@ -249,6 +285,14 @@ describe('DeepSeek web account authentication', () => { expect(rejectToken).not.toHaveBeenCalled() }) + it('keeps endpoint guidance for a 401 on a route API key, which has no invalidation', async () => { + vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: 'invalid key' }, { status: 401 }))) + const error = await rejectedWebError(search([keyRouteSource('route-key')])) + expect(error.message).toContain('DeepSeek API error (HTTP 401): invalid key') + expect(error.message).toContain('If that endpoint is not intended') + expect(error.message).not.toContain('sign in') + }) + it('retains the HTTP failure when account invalidation cancels the requesting Session', async () => { const controller = new AbortController() const response = jsonResponse({ error: 'invalid token' }, { status: 401 }) diff --git a/packages/web/web-deepseek-api/tests/web-deepseek-api.e2e.ts b/packages/web/web-deepseek-api/tests/web-deepseek-api.e2e.ts index 86f76ffab3..84d2cfc65e 100644 --- a/packages/web/web-deepseek-api/tests/web-deepseek-api.e2e.ts +++ b/packages/web/web-deepseek-api/tests/web-deepseek-api.e2e.ts @@ -1,11 +1,15 @@ import { describe, expect, it } from 'vitest' +import { credentialRef } from '@deepseek-ai/dsh-credentials' import { DeepSeekFetchApiProvider, DeepSeekSearchApiProvider } from '@deepseek-ai/dsh-web-deepseek-api' import { customGuidance } from './guidance.ts' /** Real Search and Fetch API probes; the base names the deployment the key authenticates. */ const apiKey = process.env.DEEPSEEK_API_KEY const baseURL = process.env.DEEPSEEK_SEARCH_API_TEST_BASE_URL ?? '' -const auth = { sources: [{ kind: 'api-key', baseURL, key: apiKey ?? '' }] } as const +const auth = { sources: [{ + kind: 'api-key', baseURL, + key: { ref: credentialRef('DEEPSEEK_API_KEY'), configured: async () => apiKey !== undefined, resolve: async () => apiKey }, +}] } as const const maybe = apiKey !== undefined && apiKey.length > 0 && baseURL.length > 0 ? describe : describe.skip maybe('DeepSeek Search and Fetch real API', () => { diff --git a/packages/web/web-deepseek-api/tsconfig.json b/packages/web/web-deepseek-api/tsconfig.json index 0fb683fb97..01466b7c23 100644 --- a/packages/web/web-deepseek-api/tsconfig.json +++ b/packages/web/web-deepseek-api/tsconfig.json @@ -8,7 +8,6 @@ "src" ], "references": [ - { "path": "../../llm/llm-deepseek" }, { "path": "../../util/launch-environment" }, @@ -34,22 +33,13 @@ "path": "../../credentials/credentials" }, { - "path": "../../credentials/deepseek-account" + "path": "../../account/deepseek-account" }, { "path": "../../util/http-proxy" }, - { - "path": "../../../vendor/loader" - }, { "path": "../../llm/llm" - }, - { - "path": "../../llm/llm-deepseek-api-key" - }, - { - "path": "../../llm/llm-deepseek-account" } ] } diff --git a/packages/web/web-search-deepseek/README.i18n.yaml b/packages/web/web-search-deepseek/README.i18n.yaml index 6ff6e2b7d0..d83724b59e 100644 --- a/packages/web/web-search-deepseek/README.i18n.yaml +++ b/packages/web/web-search-deepseek/README.i18n.yaml @@ -24,8 +24,8 @@ en: 3ed88edabdf63c8d zh: c66176c8a7c9a434 /deepseek-ai-dsh-web-search-deepseek/use-this-package/authentication: - en: 7a765ba931329067 - zh: 6fc14edcc378684a + en: 7e625c9a31ecad31 + zh: 19088d0014d51b24 /deepseek-ai-dsh-web-search-deepseek/use-this-package/what-a-search-returns: en: e30442c90365357b zh: 9c9e2f1182963a8a @@ -39,14 +39,14 @@ en: 9842c69ad3636bb3 zh: 3cdc3f816cbdd0cb /deepseek-ai-dsh-web-search-deepseek/understand-the-implementation/design-philosophy: - en: 1b1760efbf4568c1 - zh: fca06c959e51ce16 + en: 76d5fb7c1e00079c + zh: 6f0e835157a3c982 /deepseek-ai-dsh-web-search-deepseek/understand-the-implementation/source-map: en: 6488e1c85646339f zh: 2b5ca1c6b5939a8c /deepseek-ai-dsh-web-search-deepseek/understand-the-implementation/request-flow: - en: d6c3f30b70a5f4b5 - zh: ab7c5b7d6fc3cae6 + en: a45785f95dbde10a + zh: 399bd28592d34721 /deepseek-ai-dsh-web-search-deepseek/further-exploration: en: 3a650478cf33d792 zh: ab4247c4c31f4a90 diff --git a/packages/web/web-search-deepseek/README.md b/packages/web/web-search-deepseek/README.md index 7f7fb0815b..230f4cc63e 100644 --- a/packages/web/web-search-deepseek/README.md +++ b/packages/web/web-search-deepseek/README.md @@ -58,11 +58,11 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a ### Authentication -A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names the `deepseek-account` provider route and `ctx.deepseekAccount` resolves a token for the search endpoint. The account service resolves one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the token that search sent: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. +A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names a model route that publishes an account credential through `ctx.llm.routeCredential`, the `deepseek-account` route, and that credential resolves for the search endpoint. The account service releases one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only the credential's headers, `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the credential that search sent through the credential's own invalidation: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. -The provider's `ready()` answers whether the search a model request would make has a credential, on any model route: the request's route is `deepseek-account` and `ctx.deepseekAccount` resolves a token for the configured search endpoint, or a literal `apiKey` is set or `ctx.credentials.describe` reports the `apiKeyEnv` reference configured (without that service, the process environment must carry it). It checks them in the order a search resolves them, and a failed account-token or credential-store read answers false, because the search fails on that read instead of trying the next credential. While this provider is the selected search provider, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and its prompt guidance from each request for which it answers false. Only presence is checked: a wrong key, or an endpoint that does not serve the native `web_search_20250305` server tool, counts as ready and fails each call. A call that still arrives resolves credentials when it runs. +The provider's `ready()` answers whether the search a model request would make has a credential, on any model route: the request's route publishes an account credential that reports itself configured for the configured search endpoint, or a literal `apiKey` is set or `ctx.credentials.describe` reports the `apiKeyEnv` reference configured (without that service, the process environment must carry it). It checks them in the order a search resolves them, and a route whose settings do not resolve or a failed account-credential or credential-store read answers false, because the search fails there instead of trying the next credential. While this provider is the selected search provider, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and its prompt guidance from each request for which it answers false. Only presence is checked: a wrong key, or an endpoint that does not serve the native `web_search_20250305` server tool, counts as ready and fails each call. A call that still arrives resolves credentials when it runs. -Referenced keys use the [shared DeepSeek credential helpers](../../llm/llm-deepseek/README.md#account-credentials), including the same whitespace normalization and format validation as model requests. A malformed referenced key fails before dispatch; readiness remains a presence-only check. +Referenced keys go through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md) and receive the same whitespace normalization and format validation as model requests. A malformed referenced key fails before dispatch; readiness remains a presence-only check. ### What a search returns @@ -91,7 +91,7 @@ This section explains the design decisions behind the provider; the observable b The provider is built on two commitments: - **Structured blocks only.** DeepSeek runs the search server-side and returns structured `web_search_tool_result` blocks; the provider parses those blocks and never scrapes URLs out of model prose. In strict mode, a response with no such block throws `WEB_PROVIDER_ERROR` instead of degrading. -- **Conversation credentials, resolved per search.** The provider adds no secret: a search from a Session on the account route uses that account's token, and every other search reuses the `DEEPSEEK_API_KEY` reference. The auxiliary request endpoint stays independent through `$DEEPSEEK_SEARCH_BASE_URL`. A mounted credentials service is authoritative; without one the provider falls back to the launching process environment. Resolving per call means a key stored or rotated in the Web Models page, or an account sign-in, reaches the next search without a restart. +- **Conversation credentials, resolved per search.** The provider adds no secret: a search from a Session on a route that publishes an account credential uses that credential, and every other search reuses the `DEEPSEEK_API_KEY` reference. The auxiliary request endpoint stays independent through `$DEEPSEEK_SEARCH_BASE_URL`. A mounted credentials service is authoritative; without one the provider falls back to the launching process environment. Resolving per call means a key stored or rotated in the Web Models page, or an account sign-in, reaches the next search without a restart. ### Source map @@ -103,9 +103,9 @@ The provider is built on two commitments: ### Request flow -Each search captures the current Config values into provider options — endpoint, model, key reference, limits — then asks `ctx.deepseekAccount` for a token when the initiating Session uses the account route, otherwise resolves the credential reference through `ctx.credentials` (or the environment), appends the log-only session event, and dispatches the Messages request with the native `web_search` server tool. The response's `web_search_tool_result` blocks become `sources[]`; `cited_text` entries from text blocks are joined to their URLs as snippets; results are deduplicated by URL; and the service enforces the requested source bound on the way back. +Each search captures the current Config values into provider options — endpoint, model, key reference, limits — then asks the initiating Session's model route for its account credential through `ctx.llm.routeCredential` when it publishes one, otherwise resolves the credential reference through `ctx.credentials` (or the environment), appends the log-only session event, and dispatches the Messages request with the native `web_search` server tool. The response's `web_search_tool_result` blocks become `sources[]`; `cited_text` entries from text blocks are joined to their URLs as snippets; results are deduplicated by URL; and the service enforces the requested source bound on the way back. -Readiness captures the same options but reads no API key value: on the account route it first asks `ctx.deepseekAccount` for a token, then checks the literal key or asks `ctx.credentials.describe()` (or the environment) whether the key reference is configured. +Readiness captures the same options but reads no API key value: on a route publishing an account credential it first asks that credential whether it is configured for the search endpoint, then checks the literal key or asks `ctx.credentials.describe()` (or the environment) whether the key reference is configured.
diff --git a/packages/web/web-search-deepseek/README.zh.md b/packages/web/web-search-deepseek/README.zh.md index f27c5367b3..a55dc76495 100644 --- a/packages/web/web-search-deepseek/README.zh.md +++ b/packages/web/web-search-deepseek/README.zh.md @@ -58,11 +58,11 @@ kind: "package-reference" ### 鉴权 -当发起会话最近的 `request/context` 事件指明 `deepseek-account` 提供方路由,且 `ctx.deepseekAccount` 为搜索端点解析出 token 时,搜索使用 DeepSeek 账号鉴权。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)解析 token。这类搜索只发送 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并只作废该搜索实际发送的 token:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。 +当发起会话最近的 `request/context` 事件指明的模型路由通过 `ctx.llm.routeCredential` 发布账号凭据(即 `deepseek-account` 路由),且该凭据为搜索端点解析成功时,搜索使用 DeepSeek 账号鉴权。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)释放凭据。这类搜索只发送该凭据的请求头 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并通过凭据自身的失效操作只作废该搜索实际发送的凭据:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。 -提供方的 `ready()` 回答模型请求将发起的搜索是否有凭据,不论模型路由:该请求的路由是 `deepseek-account` 且 `ctx.deepseekAccount` 为配置的搜索端点解析出 token,或者设置了字面 `apiKey`,或 `ctx.credentials.describe` 报告 `apiKeyEnv` 引用已配置(没有该服务时,进程环境中必须存在该变量)。它按搜索解析凭据的顺序检查,读取账号 token 或凭据存储失败时回答 false,因为搜索会在该次读取上失败,而不会尝试下一种凭据。本提供方是选中的搜索提供方时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它回答 false 的每个请求中撤下 `web_search` 及其提示词说明。这里只检查凭据是否存在:错误的密钥,或不提供原生 `web_search_20250305` 服务器工具的端点,都视为就绪并使每次调用失败。仍然到达的调用会在运行时解析凭据。 +提供方的 `ready()` 回答模型请求将发起的搜索是否有凭据,不论模型路由:该请求的路由发布的账号凭据报告自身已为配置的搜索端点配置,或者设置了字面 `apiKey`,或 `ctx.credentials.describe` 报告 `apiKeyEnv` 引用已配置(没有该服务时,进程环境中必须存在该变量)。它按搜索解析凭据的顺序检查;路由设置无法解析,或读取账号凭据或凭据存储失败时回答 false,因为搜索会在那里失败,而不会尝试下一种凭据。本提供方是选中的搜索提供方时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它回答 false 的每个请求中撤下 `web_search` 及其提示词说明。这里只检查凭据是否存在:错误的密钥,或不提供原生 `web_search_20250305` 服务器工具的端点,都视为就绪并使每次调用失败。仍然到达的调用会在运行时解析凭据。 -引用密钥使用[共享 DeepSeek 凭据函数](../../llm/llm-deepseek/README.zh.md#account-credentials),接受与模型请求相同的首尾空白规范化和格式校验。引用密钥格式错误会在发送请求前失败;就绪判断仍只检查是否存在。 +引用密钥通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数读取,接受与模型请求相同的首尾空白规范化和格式校验。引用密钥格式错误会在发送请求前失败;就绪判断仍只检查是否存在。 ### 搜索返回什么 @@ -91,7 +91,7 @@ kind: "package-reference" 本提供方建立在两项承诺之上: - **只取结构化块。** DeepSeek 在服务端执行搜索并返回结构化的 `web_search_tool_result` 块;提供方解析这些块,绝不从模型文本中抓取 URL。严格模式下,没有此类块的响应会抛出 `WEB_PROVIDER_ERROR`,而非降级。 -- **会话凭据,逐次解析。** 提供方不新增密钥:来自账号路由会话的搜索使用该账号的 token,其余搜索复用 `DEEPSEEK_API_KEY` 引用。辅助请求端点通过 `$DEEPSEEK_SEARCH_BASE_URL` 保持独立。已挂载的凭据服务具有权威性;没有该服务时回退到启动进程的环境。按次解析意味着在 Web 的 Models 页中存储或轮换的密钥,或一次账号登录,无需重启即可用于下一次搜索。 +- **会话凭据,逐次解析。** 提供方不新增密钥:来自发布账号凭据的路由会话的搜索使用该凭据,其余搜索复用 `DEEPSEEK_API_KEY` 引用。辅助请求端点通过 `$DEEPSEEK_SEARCH_BASE_URL` 保持独立。已挂载的凭据服务具有权威性;没有该服务时回退到启动进程的环境。按次解析意味着在 Web 的 Models 页中存储或轮换的密钥,或一次账号登录,无需重启即可用于下一次搜索。 ### 源码地图 @@ -103,9 +103,9 @@ kind: "package-reference" ### 请求流程 -每次搜索先把当前 Config 段投影为提供方选项——端点、模型、密钥引用、上限——然后在发起会话使用账号路由时向 `ctx.deepseekAccount` 请求 token,否则通过 `ctx.credentials`(或环境)解析凭据引用,追加仅用于日志的会话事件,并以原生 `web_search` 服务器工具分发 Messages 请求。响应中的 `web_search_tool_result` 块变为 `sources[]`;文本块中的 `cited_text` 条目按其 URL 拼接为 snippet;结果按 URL 去重;服务在返回路径上强制执行请求的来源上限。 +每次搜索先把当前 Config 段投影为提供方选项——端点、模型、密钥引用、上限——然后在发起会话的模型路由通过 `ctx.llm.routeCredential` 发布账号凭据时向其索取该凭据,否则通过 `ctx.credentials`(或环境)解析凭据引用,追加仅用于日志的会话事件,并以原生 `web_search` 服务器工具分发 Messages 请求。响应中的 `web_search_tool_result` 块变为 `sources[]`;文本块中的 `cited_text` 条目按其 URL 拼接为 snippet;结果按 URL 去重;服务在返回路径上强制执行请求的来源上限。 -就绪判断捕获相同的选项,但不读取 API 密钥的值:账号路由先向 `ctx.deepseekAccount` 请求 token,再检查字面密钥,或询问 `ctx.credentials.describe()`(或环境)密钥引用是否已配置。 +就绪判断捕获相同的选项,但不读取 API 密钥的值:发布账号凭据的路由先询问该凭据是否已为搜索端点配置,再检查字面密钥,或询问 `ctx.credentials.describe()`(或环境)密钥引用是否已配置。
diff --git a/packages/web/web-search-deepseek/package.json b/packages/web/web-search-deepseek/package.json index cf3d5b11ec..671c5ca268 100644 --- a/packages/web/web-search-deepseek/package.json +++ b/packages/web/web-search-deepseek/package.json @@ -32,33 +32,28 @@ ], "license": "MIT", "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-credentials": "workspace:*", - "@deepseek-ai/dsh-deepseek-account": "workspace:*", "@deepseek-ai/dsh-launch-environment": "workspace:*", - "@deepseek-ai/dsh-llm-deepseek": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", - "@deepseek-ai/dsh-web": "workspace:*", - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/dsh-web": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~" }, "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-credentials": "workspace:*", "@deepseek-ai/dsh-credentials-local": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", + "@deepseek-ai/dsh-http-proxy": "workspace:*", "@deepseek-ai/dsh-launch-environment": "workspace:*", - "@deepseek-ai/dsh-llm-deepseek": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-llm-deepseek-account": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", - "@deepseek-ai/dsh-web": "workspace:*", - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-http-proxy": "workspace:*" - }, - "peerDependenciesMeta": { - "@deepseek-ai/dsh-deepseek-account": { - "optional": true - } + "@deepseek-ai/dsh-web": "workspace:*" } } diff --git a/packages/web/web-search-deepseek/src/index.ts b/packages/web/web-search-deepseek/src/index.ts index af7fad61a5..da16c7c2a6 100644 --- a/packages/web/web-search-deepseek/src/index.ts +++ b/packages/web/web-search-deepseek/src/index.ts @@ -1,10 +1,11 @@ /** * Register a DeepSeek-backed provider in `ctx.web`. It calls the Anthropic-compatible Messages API - * with native `web_search_20250305`. A search initiated by a Session on the DeepSeek account route - * authenticates with the account token when the account service allows the search endpoint; - * every other search reuses `DEEPSEEK_API_KEY`. The provider does not reuse `DEEPSEEK_BASE_URL`; - * auxiliary search has its own endpoint configuration. The provider reports itself not ready for a - * model request whose search would have no credential. + * with native `web_search_20250305`. A search initiated by a Session whose latest model request used + * a route that publishes an account credential through `ctx.llm.routeCredential()` authenticates with + * that credential when its owner allows the search endpoint; every other search reuses + * `DEEPSEEK_API_KEY`. The provider does not reuse `DEEPSEEK_BASE_URL`; auxiliary search has its own + * endpoint configuration. The provider reports itself not ready for a model request whose search + * would have no credential. * @module @deepseek-ai/dsh-web-search-deepseek */ import type { Volatile } from '@deepseek-ai/cordis' @@ -12,13 +13,11 @@ import type { Volatile } from '@deepseek-ai/cordis' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-agent' -import { credentialRef } from '@deepseek-ai/dsh-credentials' +import { credentialRef, credentialRefConfigured, resolveCredentialRef } from '@deepseek-ai/dsh-credentials' import type { CredentialRef } from '@deepseek-ai/dsh-credentials' -import type {} from '@deepseek-ai/dsh-deepseek-account' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' -import { - deepSeekApiKeyConfigured, rejectDeepSeekAccountToken, resolveDeepSeekAccountToken, resolveDeepSeekApiKey, -} from '@deepseek-ai/dsh-llm-deepseek' +import { assertUsableApiKey } from '@deepseek-ai/dsh-llm' +import type { RouteCredential } from '@deepseek-ai/dsh-llm' import type {} from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-web' import { @@ -87,20 +86,29 @@ export const Config = z.object({ */ const SEARCH_BASE_URL_ENV = 'DEEPSEEK_SEARCH_BASE_URL' -/** Provider route id `dsh-llm-deepseek-account` registers; `request/context` events record it per Session. */ -const ACCOUNT_PROVIDER = 'deepseek-account' - /** Settings namespace carrying this provider's endpoint, model, and key reference. */ export const WEB_SEARCH_DEEPSEEK_SETTINGS_NAMESPACE = 'web-search-deepseek' /** Options for one search, with the key reference the readiness check reads. */ type SearchOptions = DeepSeekSearchProviderOptions & { readonly apiKeyEnv: CredentialRef } +/** + * The account credential the model route `route` publishes, when it publishes one of that kind. + * @param ctx - plugin context supplying the optional model service. + * @param route - provider route of a model request; undefined names none. + * @returns the route's account credential, or undefined for another kind, no credential, or no route. + * @throws when the route's settings do not resolve. + */ +function accountCredentialOf(ctx: Context, route: string | undefined): RouteCredential | undefined { + const credential = route === undefined ? undefined : ctx.get('llm')?.routeCredential(route) + return credential?.kind === 'account' ? credential : undefined +} + /** * Project one resolved section into the options the provider serves its next * search with. Environment fallbacks stay here rather than in the provider: * every value it reads is already fully defaulted. - * @param ctx - plugin context supplying the credential and environment planes. + * @param ctx - plugin context supplying the credential, model, and environment planes. * @param config - the currently authoritative section. * @returns options for one search. */ @@ -113,15 +121,16 @@ function resolveOptions( : undefined return { ...literalApiKey === undefined ? {} : { apiKey: literalApiKey }, - resolveAccountToken: async (endpoint) => { + resolveAccountCredential: async (endpoint) => { // The latest request context names the route that served the model // request which called this search, as account sign-out reads it. - const provider = ctx.get('agents')?.currentInitiator()?.session.requestContext()?.provider - if (provider !== ACCOUNT_PROVIDER) return undefined - return await resolveDeepSeekAccountToken(ctx, endpoint) + const credential = accountCredentialOf(ctx, ctx.get('agents')?.currentInitiator()?.session.requestContext()?.provider) + return credential === undefined ? undefined : await credential.resolve(endpoint) + }, + resolveApiKey: async () => { + const value = await resolveCredentialRef(ctx, apiKeyEnv) + return value === undefined ? undefined : assertUsableApiKey(value, name, apiKeyEnv) }, - rejectAccountToken: token => rejectDeepSeekAccountToken(ctx, token), - resolveApiKey: () => resolveDeepSeekApiKey(ctx, apiKeyEnv), apiKeyEnv, baseURL: config.baseURL ?? launchEnvironmentOf(ctx).get(SEARCH_BASE_URL_ENV)?.value @@ -141,27 +150,28 @@ function resolveOptions( /** * Whether the search a model request on `route` would make has a credential, checked in the order - * the search resolves them: the account token first on the account route, then the API key. A failed - * read answers false, because the search fails on that read instead of trying the next credential. - * Only presence is checked: the API key's value is not read and the endpoint is not contacted, so a - * wrong key or an endpoint without native search still counts as configured. - * @param ctx - plugin context supplying the account, credential, and environment planes. + * the search resolves them: the account credential the route publishes first, then the API key. A + * route whose settings do not resolve or a failed read answers false, because the search fails there + * instead of trying the next credential. Only presence is checked: the API key's value is not read + * and the endpoint is not contacted, so a wrong key or an endpoint without native search still + * counts as configured. + * @param ctx - plugin context supplying the model, credential, and environment planes. * @param options - options the next search would use. * @param route - provider route of the model request being assembled. - * @returns whether the account token or an API key is available to that search. + * @returns whether the account credential or an API key is available to that search. */ async function searchConfigured( ctx: Context, options: SearchOptions, route: string | undefined, ): Promise { - const account = ctx.get('deepseekAccount') - if (route === ACCOUNT_PROVIDER && account !== undefined) { - let token: string | undefined - try { token = await account.resolveToken(`${options.baseURL}/messages`) } + let account: RouteCredential | undefined + try { account = accountCredentialOf(ctx, route) } + catch (_unresolvedRoute) { return false /* The search fails on this route before it reads any credential. */ } + if (account !== undefined) { + try { if (await account.configured(`${options.baseURL}/messages`)) return true } catch (_unreadableGrant) { return false /* The search fails on this read before it tries the API key. */ } - if (token !== undefined && token.length > 0) return true } if (options.apiKey !== undefined) return true - try { return await deepSeekApiKeyConfigured(ctx, options.apiKeyEnv) } + try { return await credentialRefConfigured(ctx, options.apiKeyEnv) } catch (_unreadableStore) { return false /* A store that cannot be read supplies no key to the search either. */ } } diff --git a/packages/web/web-search-deepseek/src/provider.ts b/packages/web/web-search-deepseek/src/provider.ts index 32c973946d..ccc14b9f3d 100644 --- a/packages/web/web-search-deepseek/src/provider.ts +++ b/packages/web/web-search-deepseek/src/provider.ts @@ -14,6 +14,7 @@ import type { WebSearchSource, } from '@deepseek-ai/dsh-web' import type { CredentialRef } from '@deepseek-ai/dsh-credentials' +import type { RouteCredentialGrant } from '@deepseek-ai/dsh-llm' import type {} from '@deepseek-ai/dsh-session' import type { AnthropicError, @@ -93,13 +94,11 @@ declare module '@deepseek-ai/dsh-session/types' { /** Resolved provider options (the plugin's `apply` supplies credential and constant defaults). */ export interface DeepSeekSearchProviderOptions { /** - * Resolve the DeepSeek account token for one search endpoint. A token takes - * precedence over every API key and is sent only as `x-dsh-auth-token`; - * `undefined` selects API-key authentication. + * Resolve the DeepSeek account credential for one search endpoint. A credential takes + * precedence over every API key and is sent only through the headers of its grant, which + * also invalidates it after HTTP 401; `undefined` selects API-key authentication. */ - resolveAccountToken?: (endpoint: string) => Promise - /** Invalidate the exact account token rejected by HTTP 401; failures must not replace the search error. */ - rejectAccountToken?: (token: string) => Promise + resolveAccountCredential?: (endpoint: string) => Promise /** Literal DeepSeek API key; when present it wins over {@link resolveApiKey}. */ apiKey?: string /** Resolve the current DeepSeek API key for one search operation. */ @@ -189,11 +188,11 @@ export function mapAnthropicResponse(response: AnthropicResponse): WebSearchResu /** Authentication headers for one search, tagged by the credential that produced them. */ interface SearchAuth { - /** `account` for a DeepSeek account token, `api-key` for an API key. */ + /** `account` for a DeepSeek account credential, `api-key` for an API key. */ readonly kind: 'account' | 'api-key' /** Headers carrying the credential. */ readonly headers: Readonly> - /** Request-bound invalidation, present only when an account token was sent. */ + /** Request-bound invalidation, present when the sent account credential offers one. */ readonly reject?: () => Promise } @@ -226,7 +225,7 @@ export class DeepSeekSearchProvider implements WebSearchProvider { available(): boolean { const options = this.resolveOptions() - return ((options.apiKey?.length ?? 0) > 0 || options.resolveApiKey !== undefined || options.resolveAccountToken !== undefined) + return ((options.apiKey?.length ?? 0) > 0 || options.resolveApiKey !== undefined || options.resolveAccountCredential !== undefined) && URL.canParse(options.baseURL) && isPositiveInteger(options.maxTokens) && isPositiveInteger(options.maxUses) @@ -297,13 +296,12 @@ export class DeepSeekSearchProvider implements WebSearchProvider { // malformed/non-JSON error body (normal for gateway 5xx/429s) can only // cost a richer provider message, never the real error. } - // The account service released this token only for its inference + // The account service released this credential only for its inference // origin, so the endpoint is not what the user must change. if (status === 401 && auth.kind === 'account') { // Invalidation can cancel this Session; finish reading the HTTP failure before it does. A cancelled read - // still invalidates the token the status rejected. - try { await auth.reject?.() } - catch (_credentialRemovalFailed) { /* Report the original failure even if credential removal fails. */ } + // still invalidates the credential the status rejected. + await auth.reject?.() throw aborted ?? accountRejectedError(message) } if (aborted !== undefined) throw aborted @@ -327,18 +325,18 @@ export class DeepSeekSearchProvider implements WebSearchProvider { * @param options - the caller's snapshot, so the credential and the endpoint it is sent to come from one section. * @param endpoint - the Messages endpoint this operation dispatches to. * @param signal - abort signal for the surrounding search. - * @returns the account-token header when one resolves, otherwise the API-key headers, tagged by credential kind. + * @returns the account credential's headers when one resolves, otherwise the API-key headers, tagged by credential kind. */ private async authHeaders( options: DeepSeekSearchProviderOptions, endpoint: string, signal?: AbortSignal, ): Promise { - const { resolveAccountToken, rejectAccountToken } = options - const token = resolveAccountToken === undefined + const { resolveAccountCredential } = options + const credential = resolveAccountCredential === undefined ? undefined - : await resolveCredential(() => resolveAccountToken(endpoint), signal) - if (token !== undefined && token.length > 0) return { - kind: 'account', headers: { 'x-dsh-auth-token': token }, - ...rejectAccountToken === undefined ? {} : { reject: () => rejectAccountToken(token) }, + : await resolveCredential(() => resolveAccountCredential(endpoint), signal) + if (credential !== undefined) { + const invalidate = credential.reject?.bind(credential) + return { kind: 'account', headers: credential.headers, ...invalidate === undefined ? {} : { reject: invalidate } } } const apiKey = await this.apiKey(options, signal) // Official DeepSeek expects `x-api-key`; an Anthropic-compatible proxy @@ -377,9 +375,7 @@ export class DeepSeekSearchProvider implements WebSearchProvider { * @returns the resolved credential, or undefined when the resolver supplied none. * @throws {@link WebError} `WEB_ABORTED` on cancellation, `WEB_PROVIDER_ERROR` when the resolver fails. */ -async function resolveCredential( - resolve: () => Promise, signal?: AbortSignal, -): Promise { +async function resolveCredential(resolve: () => Promise, signal?: AbortSignal): Promise { throwIfSearchAborted(signal) try { return await abortable(resolve(), signal) diff --git a/packages/web/web-search-deepseek/tests/deepseek.spec.ts b/packages/web/web-search-deepseek/tests/deepseek.spec.ts index 3b52fc139a..a1feb29aba 100644 --- a/packages/web/web-search-deepseek/tests/deepseek.spec.ts +++ b/packages/web/web-search-deepseek/tests/deepseek.spec.ts @@ -11,6 +11,9 @@ import { credentialRef } from '@deepseek-ai/dsh-credentials' import LocalCredentialProvider from '@deepseek-ai/dsh-credentials-local' import { createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY } from '@deepseek-ai/dsh-launch-environment' import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' +import LlmRuntime from '@deepseek-ai/dsh-llm' +import type { RouteCredentialGrant } from '@deepseek-ai/dsh-llm' +import * as AccountRoute from '@deepseek-ai/dsh-llm-deepseek-account' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import WebRuntime, { WebError, type WebSearchResult } from '@deepseek-ai/dsh-web' import { @@ -20,6 +23,7 @@ import { import * as deepseekPlugin from '@deepseek-ai/dsh-web-search-deepseek' import { citationSnippets, mapAnthropicResponse } from '../src/provider.ts' import type { AnthropicResponse } from '@deepseek-ai/dsh-web-search-deepseek/src/types.ts' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' /** Construct the provider over a fixed options value; production passes a live thunk. */ import type { DeepSeekSearchProviderOptions } from '@deepseek-ai/dsh-web-search-deepseek' @@ -27,6 +31,22 @@ import type { DeepSeekSearchProviderOptions } from '@deepseek-ai/dsh-web-search- const searchProvider = (options: DeepSeekSearchProviderOptions): DeepSeekSearchProvider => new DeepSeekSearchProvider(() => options) +/** + * The account credential resolver a route publishes over `token`, with `reject` observing each invalidated token; + * a throwing observer is contained as the account service contains storage failures. + */ +function accountCredential( + token: (endpoint: string) => Promise, reject?: (token: string) => Promise, +): (endpoint: string) => Promise { + return async (endpoint) => { + const value = await token(endpoint) + if (value === undefined || value.length === 0) return undefined + return { headers: { 'x-dsh-auth-token': value }, value, ...reject === undefined ? {} : { reject: async () => { + try { await reject(value) } catch (_storageFailure) { /* Contained as the account service contains it. */ } + } } } + } +} + /** Return the provider's rejected WebError, or propagate an unexpected outcome. */ async function rejectedWebError(operation: Promise): Promise { try { @@ -173,7 +193,7 @@ describe('DeepSeekSearchProvider availability', () => { }) it('is available with only an account token resolver', () => { - expect(searchProvider({ ...options, apiKey: '', resolveAccountToken: async () => 'account-token' }).available()).toBe(true) + expect(searchProvider({ ...options, apiKey: '', resolveAccountCredential: accountCredential(async () => 'account-token') }).available()).toBe(true) }) it('is misconfigured when the base URL is unparseable', () => { @@ -259,7 +279,7 @@ describe('DeepSeekSearchProvider account authentication', () => { const { first } = captureFetch() const resolveAccountToken = vi.fn(async (_endpoint: string) => 'account-token') const resolveApiKey = vi.fn(async () => 'resolved-key') - await searchProvider({ ...options, resolveAccountToken, resolveApiKey }).search({ query: 'q' }) + await searchProvider({ ...options, resolveAccountCredential: accountCredential(resolveAccountToken), resolveApiKey }).search({ query: 'q' }) const { url, headers } = first() expect(resolveAccountToken).toHaveBeenCalledWith(url) expect(resolveApiKey).not.toHaveBeenCalled() @@ -270,7 +290,7 @@ describe('DeepSeekSearchProvider account authentication', () => { it.each([undefined, ''])('falls back to the API key when the account resolves %j', async (token) => { const { first } = captureFetch() - await searchProvider({ ...options, resolveAccountToken: async () => token }).search({ query: 'q' }) + await searchProvider({ ...options, resolveAccountCredential: accountCredential(async () => token) }).search({ query: 'q' }) const { headers } = first() expect(headers['x-api-key']).toBe('ds-key') expect(headers).not.toHaveProperty('x-dsh-auth-token') @@ -280,7 +300,7 @@ describe('DeepSeekSearchProvider account authentication', () => { const { fetchMock } = captureFetch() await expect(searchProvider({ ...options, - resolveAccountToken: () => Promise.reject(new Error('account storage failed')), + resolveAccountCredential: accountCredential(() => Promise.reject(new Error('account storage failed'))), }).search({ query: 'q' })) .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR', @@ -293,7 +313,7 @@ describe('DeepSeekSearchProvider account authentication', () => { vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: { message: 'invalid token' } }, { status: 401 }))) const error = await rejectedWebError(searchProvider({ ...options, - resolveAccountToken: async () => 'account-token', + resolveAccountCredential: accountCredential(async () => 'account-token'), }).search({ query: 'q' })) expect(error).toMatchObject({ code: 'WEB_PROVIDER_ERROR', @@ -303,11 +323,11 @@ describe('DeepSeekSearchProvider account authentication', () => { }) }) - it.each([false, true])('invalidates the sent account token on 401 and keeps the sign-in guidance when removal fails: %s', async (fails) => { + it.each([false, true])('invalidates the sent account token on 401 and keeps the sign-in guidance whether or not removal fails: %s', async (fails) => { const rejectAccountToken = vi.fn(async (_token: string) => { if (fails) throw new Error('storage failed') }) vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: 'invalid token' }, { status: 401 }))) const error = await rejectedWebError(searchProvider({ - ...options, resolveAccountToken: async () => 'sent-token', rejectAccountToken, + ...options, resolveAccountCredential: accountCredential(async () => 'sent-token', rejectAccountToken), }).search({ query: 'q' })) expect(error.code).toBe('WEB_PROVIDER_ERROR') expect(error.message).toBe('DeepSeek API error (HTTP 401): invalid token\n\n' @@ -320,7 +340,7 @@ describe('DeepSeekSearchProvider account authentication', () => { const rejectAccountToken = vi.fn(async (_token: string) => {}) vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({}, { status }))) const error = await rejectedWebError(searchProvider({ - ...options, resolveAccountToken: async () => token, rejectAccountToken, + ...options, resolveAccountCredential: accountCredential(async () => token, rejectAccountToken), }).search({ query: 'q' })) expect(error.code).toBe('WEB_PROVIDER_ERROR') expect(rejectAccountToken).not.toHaveBeenCalled() @@ -336,7 +356,7 @@ describe('DeepSeekSearchProvider account authentication', () => { vi.stubGlobal('fetch', vi.fn(async () => response)) const rejectAccountToken = vi.fn(async (_token: string) => {}) const error = await rejectedWebError(searchProvider({ - ...options, resolveAccountToken: async () => 'sent-token', rejectAccountToken, + ...options, resolveAccountCredential: accountCredential(async () => 'sent-token', rejectAccountToken), }).search({ query: 'q' }, controller.signal)) expect(error.code).toBe('WEB_ABORTED') expect(rejectAccountToken).toHaveBeenCalledExactlyOnceWith('sent-token') @@ -346,7 +366,7 @@ describe('DeepSeekSearchProvider account authentication', () => { vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({}, { status: 503 }))) const error = await rejectedWebError(searchProvider({ ...options, - resolveAccountToken: async () => 'account-token', + resolveAccountCredential: accountCredential(async () => 'account-token'), }).search({ query: 'q' })) expect(error.message).toContain('Search endpoint configuration is separate from chat.') }) @@ -355,7 +375,7 @@ describe('DeepSeekSearchProvider account authentication', () => { const { fetchMock } = captureFetch() await expect(searchProvider({ ...options, - resolveAccountToken: () => { throw new Error('account service threw') }, + resolveAccountCredential: accountCredential(() => { throw new Error('account service threw') }), }).search({ query: 'q' })) .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR', @@ -369,7 +389,7 @@ describe('DeepSeekSearchProvider account authentication', () => { const resolveApiKey = vi.fn(async () => 'resolved-key') const controller = new AbortController() controller.abort(new Error('caller stopped')) - await expect(searchProvider({ ...options, apiKey: '', resolveAccountToken, resolveApiKey }) + await expect(searchProvider({ ...options, apiKey: '', resolveAccountCredential: accountCredential(resolveAccountToken), resolveApiKey }) .search({ query: 'q' }, controller.signal)) .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' })) expect(resolveAccountToken).not.toHaveBeenCalled() @@ -382,10 +402,10 @@ describe('DeepSeekSearchProvider account authentication', () => { await expect(searchProvider({ ...options, apiKey: '', - resolveAccountToken: async () => { + resolveAccountCredential: accountCredential(async () => { controller.abort(new Error('caller stopped')) return undefined - }, + }), resolveApiKey, }).search({ query: 'q' }, controller.signal)) .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' })) @@ -397,7 +417,7 @@ describe('DeepSeekSearchProvider account authentication', () => { const controller = new AbortController() const search = searchProvider({ ...options, - resolveAccountToken: () => new Promise(() => {}), + resolveAccountCredential: accountCredential(() => new Promise(() => {})), }).search({ query: 'q' }, controller.signal) controller.abort(new Error('deadline')) await expect(search).rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' })) @@ -764,9 +784,9 @@ describe('web-search-deepseek account route selection', () => { await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) - ctx.provide('deepseekAccount', { - resolveToken: async (url: string) => { asked.push(url); return 'account-token' }, - } as DeepSeekAccount) + await ctx.plugin(LlmRuntime) + await ctx.plugin(AccountRoute, {}) + ctx.provide('deepseekAccount', accountStub({ token: (url) => { asked.push(url); return 'account-token' } })) await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' }) const session = ctx.sessions.create(SessionId(`web-search-account-${provider ?? 'none'}`)) session.append('turn/start', { turn: 1 }) @@ -801,8 +821,9 @@ describe('web-search-deepseek account route selection', () => { await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) - const account: Pick = { resolveToken: async () => current, rejectToken } - ctx.provide('deepseekAccount', account as DeepSeekAccount) + await ctx.plugin(LlmRuntime) + await ctx.plugin(AccountRoute, {}) + ctx.provide('deepseekAccount', accountStub({ token: () => current, reject: rejectToken })) await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' }) const session = ctx.sessions.create(SessionId('web-search-account-late-401')) session.append('turn/start', { turn: 1 }) @@ -816,7 +837,7 @@ describe('web-search-deepseek account route selection', () => { } }) - it.each(['deepseek-official', undefined])('keeps API-key authentication for route %j', async (provider) => { + it.each(['deepseek-official', undefined])('keeps API-key authentication for route %j, whose published credential is no account', async (provider) => { const { headers, asked } = await searchAs(provider) expect(asked).toEqual([]) expect(headers['x-api-key']).toBe('ds-key') @@ -841,7 +862,7 @@ describe('web-search-deepseek search readiness', () => { interface Setup { config?: Record - account?: Pick + account?: DeepSeekAccount credentialsDir?: string } @@ -851,17 +872,16 @@ describe('web-search-deepseek search readiness', () => { * @param asked - receives every URL the account is asked to authenticate. * @returns the account double. */ - function officialOriginAccount(asked: string[] = []): Pick { - return { - resolveToken: (url: string) => { - asked.push(url) - return Promise.resolve(new URL(url).origin === 'https://api.deepseek.com' ? 'account-token' : undefined) - }, - } + function officialOriginAccount(asked: string[] = []): DeepSeekAccount { + return accountStub({ token: (url) => { + asked.push(url) + return new URL(url).origin === 'https://api.deepseek.com' ? 'account-token' : undefined + } }) } /** - * Mount the web seam with the DeepSeek provider selected for search. + * Mount the web seam with the DeepSeek provider selected for search, beside the account model route whose + * published credential the account route answers with. * @param setup - provider config, account double, and credential store. * @returns the composed context. */ @@ -869,10 +889,12 @@ describe('web-search-deepseek search readiness', () => { const ctx = new Context() mounted.push(ctx) await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) + await ctx.plugin(LlmRuntime) + await ctx.plugin(AccountRoute, {}) if (setup.credentialsDir !== undefined) { await ctx.plugin(LocalCredentialProvider, { path: join(setup.credentialsDir, '.credentials.yaml'), watch: false }) } - if (setup.account !== undefined) ctx.provide('deepseekAccount', setup.account as DeepSeekAccount) + if (setup.account !== undefined) ctx.provide('deepseekAccount', setup.account) await ctx.plugin(deepseekPlugin, setup.config ?? {}) return ctx } @@ -922,9 +944,8 @@ describe('web-search-deepseek search readiness', () => { it.each<[string, Setup]>([ ['a search endpoint outside the account origin', { config: { baseURL: 'https://gateway.test/anthropic/v1' }, account: officialOriginAccount() }], - ['a signed-out account', { account: { resolveToken: () => Promise.resolve(undefined) } }], - ['an empty account token', { account: { resolveToken: () => Promise.resolve('') } }], - ['an unreadable account grant', { account: { resolveToken: () => Promise.reject(new Error('unreadable grant')) } }], + ['a signed-out account', { account: accountStub({ token: () => undefined }) }], + ['an unreadable account grant', { account: accountStub({ token: () => Promise.reject(new Error('unreadable grant')) }) }], ['no account service', {}], ])('is not ready on the account route with %s and no search key', async (_label, setup) => { const ctx = await compose(setup) @@ -967,6 +988,28 @@ describe('web-search-deepseek search readiness', () => { } }) + it('is not ready and fails the search when the initiating route\'s settings do not resolve, despite a literal key', async () => { + const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init: RequestInit = {}) => jsonResponse(searchResponse())) + vi.stubGlobal('fetch', fetchMock) + const ctx = new Context() + mounted.push(ctx) + await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) + ctx.provide('llm', { routeCredential: () => { throw new Error('route settings do not resolve') } } as never) + await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' }) + expect(await ctx.web.searchReady('deepseek-account')).toBe(false) + expect(await ctx.web.searchReady(undefined)).toBe(true) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(AgentRegistry) + const session = ctx.sessions.create(SessionId('web-search-unresolved-route')) + session.append('turn/start', { turn: 1 }) + session.append('request/context', { provider: 'deepseek-account', model: 'deepseek-v4-flash' }) + const failure = await rejectedWebError(ctx.agents.withInitiator({ session } as Agent, () => ctx.web.search({ query: 'q' }))) + expect(failure.code).toBe('WEB_PROVIDER_ERROR') + expect(failure.message).toContain('route settings do not resolve') + expect(fetchMock).not.toHaveBeenCalled() + }) + it.each<[string, Setup, string | undefined]>([ ['a literal key', { config: { apiKey: 'ds-key' } }, undefined], ['a launch environment key', {}, 'env-key'], @@ -974,7 +1017,7 @@ describe('web-search-deepseek search readiness', () => { if (envKey !== undefined) process.env.DEEPSEEK_API_KEY = envKey const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init: RequestInit = {}) => jsonResponse(searchResponse())) vi.stubGlobal('fetch', fetchMock) - const ctx = await compose({ ...setup, account: { resolveToken: () => Promise.reject(new Error('account storage unreadable')) } }) + const ctx = await compose({ ...setup, account: accountStub({ token: () => Promise.reject(new Error('account storage unreadable')) }) }) expect(await ctx.web.searchReady('deepseek-account')).toBe(false) // A search on that route reads the same grant before any key and fails instead of trying the key. await ctx.plugin(SessionStore) diff --git a/packages/web/web-search-deepseek/tsconfig.json b/packages/web/web-search-deepseek/tsconfig.json index c3f7eec093..bb371f359c 100644 --- a/packages/web/web-search-deepseek/tsconfig.json +++ b/packages/web/web-search-deepseek/tsconfig.json @@ -8,7 +8,6 @@ "src" ], "references": [ - { "path": "../../llm/llm-deepseek" }, { "path": "../../util/launch-environment" }, @@ -34,10 +33,10 @@ "path": "../../credentials/credentials" }, { - "path": "../../credentials/deepseek-account" + "path": "../../util/http-proxy" }, { - "path": "../../util/http-proxy" + "path": "../../llm/llm" } ] } diff --git a/packages/web/web/package.json b/packages/web/web/package.json index 93ce48d033..bf55c66663 100644 --- a/packages/web/web/package.json +++ b/packages/web/web/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-web", - "description": "Abstract web access capability seam (ctx.web) for the DeepSeek Harness — search/fetch provider registry, registration-order-independent selection, request/result vocabulary, and the WebError taxonomy", + "description": "Abstract web access capability seam (ctx.web) for the DeepSeek Harness \u2014 search/fetch provider registry, registration-order-independent selection, request/result vocabulary, and the WebError taxonomy", "version": "0.2.2-rc.1", "publishConfig": { "access": "public" @@ -50,8 +50,8 @@ ], "license": "MIT", "peerDependencies": { - "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@deepseek-ai/dsh-package-manifest": "workspace:*", @@ -59,7 +59,7 @@ "@deepseek-ai/dsh-typert-protocol": "workspace:*" }, "devDependencies": { - "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/web/web/src/types.ts b/packages/web/web/src/types.ts index ff632770a4..772c3b368a 100644 --- a/packages/web/web/src/types.ts +++ b/packages/web/web/src/types.ts @@ -5,7 +5,7 @@ * @module @deepseek-ai/dsh-web/types */ -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' declare module '@deepseek-ai/cordis' { diff --git a/packages/web/web/tsconfig.json b/packages/web/web/tsconfig.json index 601a3e4241..c442590c24 100644 --- a/packages/web/web/tsconfig.json +++ b/packages/web/web/tsconfig.json @@ -18,7 +18,7 @@ "path": "../../../vendor/schemastery" }, { - "path": "../../llm/llm" + "path": "../../util/error" }, { "path": "../../typert/protocol" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0e5a012628..37b70ac998 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -763,7 +763,7 @@ importers: version: link:../../packages/client/ui-theme '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../packages/credentials/deepseek-account + version: link:../../packages/account/deepseek-account '@deepseek-ai/dsh-home-paths': specifier: workspace:* version: link:../../packages/util/home-paths @@ -862,7 +862,7 @@ importers: version: link:../../packages/client/connection '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../packages/credentials/deepseek-account + version: link:../../packages/account/deepseek-account '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../../packages/host/webserver @@ -1247,6 +1247,37 @@ importers: native/system/packages/linux-x64: {} + packages/account/deepseek-account: + dependencies: + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery + zod: + specifier: 4.6.6 + version: 4.6.6 + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-authorization': + specifier: workspace:* + version: link:../../credentials/authorization + '@deepseek-ai/dsh-brand': + specifier: workspace:* + version: link:../../util/brand + '@deepseek-ai/dsh-credentials': + specifier: workspace:* + version: link:../../credentials/credentials + '@deepseek-ai/dsh-host-webserver': + specifier: workspace:* + version: link:../../host/webserver + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol + '@deepseek-ai/dsh-util-values': + specifier: workspace:* + version: link:../../util/values + packages/acp/acp: dependencies: '@agentclientprotocol/sdk': @@ -1502,7 +1533,7 @@ importers: version: link:../../credentials/credentials '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-file-reference': specifier: workspace:* version: link:../../context/file-reference @@ -2438,7 +2469,7 @@ importers: version: link:../../credentials/credentials-local '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-deepseek-llm-api-extensions': specifier: workspace:* version: link:../../llm/deepseek-llm-api-extensions @@ -3606,7 +3637,7 @@ importers: version: link:../../compaction/compaction '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-host-product-telemetry-otel': specifier: workspace:* version: link:../../host/product-telemetry-otel @@ -3728,7 +3759,7 @@ importers: version: link:../ui-slots '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../../host/webserver @@ -5777,7 +5808,7 @@ importers: version: link:../ui-theme '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../../host/webserver @@ -8176,9 +8207,9 @@ importers: '@deepseek-ai/dsh-credentials': specifier: workspace:* version: link:../credentials - '@deepseek-ai/dsh-llm': + '@deepseek-ai/dsh-error': specifier: workspace:* - version: link:../../llm/llm + version: link:../../util/error packages/credentials/credentials: dependencies: @@ -8189,6 +8220,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis + '@deepseek-ai/dsh-launch-environment': + specifier: workspace:* + version: link:../../util/launch-environment packages/credentials/credentials-local: dependencies: @@ -8218,43 +8252,6 @@ importers: specifier: workspace:* version: link:../../util/launch-environment - packages/credentials/deepseek-account: - dependencies: - '@deepseek-ai/schemastery': - specifier: link:../../../vendor/schemastery - version: link:../../../vendor/schemastery - zod: - specifier: 4.6.6 - version: 4.6.6 - devDependencies: - '@deepseek-ai/cordis': - specifier: workspace:~ - version: link:../../../vendor/cordis - '@deepseek-ai/dsh-agent': - specifier: workspace:* - version: link:../../core/agent - '@deepseek-ai/dsh-authorization': - specifier: workspace:* - version: link:../authorization - '@deepseek-ai/dsh-brand': - specifier: workspace:* - version: link:../../util/brand - '@deepseek-ai/dsh-credentials': - specifier: workspace:* - version: link:../credentials - '@deepseek-ai/dsh-host-webserver': - specifier: workspace:* - version: link:../../host/webserver - '@deepseek-ai/dsh-llm': - specifier: workspace:* - version: link:../../llm/llm - '@deepseek-ai/dsh-typert-protocol': - specifier: workspace:* - version: link:../../typert/protocol - '@deepseek-ai/dsh-util-values': - specifier: workspace:* - version: link:../../util/values - packages/deliverables/deliverable-file-references: devDependencies: '@deepseek-ai/cordis': @@ -11608,7 +11605,7 @@ importers: version: link:../../credentials/credentials '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-deepseek-llm-api-extensions': specifier: workspace:* version: link:../../llm/deepseek-llm-api-extensions @@ -13334,7 +13331,7 @@ importers: version: link:../../credentials/credentials-local '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-deepseek-llm-api-extensions': specifier: workspace:* version: link:../deepseek-llm-api-extensions @@ -13408,9 +13405,12 @@ importers: '@deepseek-ai/cordis-plugin-loader': specifier: workspace:~ version: link:../../../vendor/loader + '@deepseek-ai/dsh-agent': + specifier: workspace:* + version: link:../../core/agent '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-launch-environment': specifier: workspace:* version: link:../../util/launch-environment @@ -18069,9 +18069,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis - '@deepseek-ai/dsh-llm': + '@deepseek-ai/dsh-error': specifier: workspace:* - version: link:../../llm/llm + version: link:../../util/error packages/web/web-deepseek-api: dependencies: @@ -18082,9 +18082,6 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis - '@deepseek-ai/cordis-plugin-loader': - specifier: workspace:~ - version: link:../../../vendor/loader '@deepseek-ai/dsh-agent': specifier: workspace:* version: link:../../core/agent @@ -18099,7 +18096,7 @@ importers: version: link:../../credentials/credentials-local '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-http-proxy': specifier: workspace:* version: link:../../util/http-proxy @@ -18109,9 +18106,6 @@ importers: '@deepseek-ai/dsh-llm': specifier: workspace:* version: link:../../llm/llm - '@deepseek-ai/dsh-llm-deepseek': - specifier: workspace:* - version: link:../../llm/llm-deepseek '@deepseek-ai/dsh-llm-deepseek-account': specifier: workspace:* version: link:../../llm/llm-deepseek-account @@ -18170,16 +18164,19 @@ importers: version: link:../../credentials/credentials-local '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-http-proxy': specifier: workspace:* version: link:../../util/http-proxy '@deepseek-ai/dsh-launch-environment': specifier: workspace:* version: link:../../util/launch-environment - '@deepseek-ai/dsh-llm-deepseek': + '@deepseek-ai/dsh-llm': specifier: workspace:* - version: link:../../llm/llm-deepseek + version: link:../../llm/llm + '@deepseek-ai/dsh-llm-deepseek-account': + specifier: workspace:* + version: link:../../llm/llm-deepseek-account '@deepseek-ai/dsh-session': specifier: workspace:* version: link:../../core/session @@ -18497,7 +18494,7 @@ importers: version: link:../../packages/credentials/credentials '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../packages/credentials/deepseek-account + version: link:../../packages/account/deepseek-account '@deepseek-ai/dsh-deepseek-llm-api-extensions': specifier: workspace:* version: link:../../packages/llm/deepseek-llm-api-extensions diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 88fc939459..665df52875 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -87,7 +87,7 @@ export const SERVICE_PAGE: Record = { compaction: 'compaction.md', cordisInspect: 'extensions.md', authorization: 'credentials.md', - deepseekAccount: 'credentials.md', + deepseekAccount: 'account.md', credentials: 'credentials.md', credentialsController: 'credentials.md', settingsController: 'settings.md', @@ -248,7 +248,7 @@ export const EVENT_SCOPE_PAGE: Record = { 'cordis': 'extensions.md', 'authorization': 'credentials.md', 'credentials': 'credentials.md', - 'deepseek-account': 'credentials.md', + 'deepseek-account': 'account.md', 'domain': 'storage.md', 'forge': 'forge.md', 'fs': 'filesystem.md', @@ -475,6 +475,7 @@ export const LINK_MAP: Readonly> = { LlmResolvedModelInfo: 'llm-streaming.md', LlmFailure: 'llm-streaming.md', LlmImageRequestPricing: 'llm-streaming.md', + RouteCredential: 'llm-streaming.md', LlmModelInfo: 'llm-streaming.md', LlmProviderInfo: 'llm-streaming.md', LlmConfigurableProvider: 'llm-streaming.md', @@ -894,18 +895,19 @@ export const LINK_MAP: Readonly> = { AuthorizationMethod: 'credentials.md', AuthorizationNotice: 'credentials.md', AuthorizationOutcome: 'credentials.md', - AccountView: 'credentials.md', - AccountUpdate: 'credentials.md', - AccountDetails: 'credentials.md', - AccountClientMetadata: 'credentials.md', - AccountNotificationBatch: 'credentials.md', - AccountNotificationId: 'credentials.md', - AccountNotification: 'credentials.md', - AccountNotificationAction: 'credentials.md', - AccountNotificationEvent: 'credentials.md', - AccountUserId: 'credentials.md', - PlatformSession: 'credentials.md', - SignInAttemptId: 'credentials.md', + AccountView: 'account.md', + AccountUpdate: 'account.md', + AccountDetails: 'account.md', + AccountClientMetadata: 'account.md', + AccountNotificationBatch: 'account.md', + AccountNotificationId: 'account.md', + AccountNotification: 'account.md', + AccountNotificationAction: 'account.md', + AccountNotificationEvent: 'account.md', + AccountRequestCredential: 'account.md', + AccountUserId: 'account.md', + PlatformSession: 'account.md', + SignInAttemptId: 'account.md', AuthorizationPrompt: 'credentials.md', AuthorizationRequest: 'credentials.md', AuthorizationSession: 'credentials.md', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 6643bd5b44..8bcf3227f4 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -296,8 +296,8 @@ const SERVICE_ROLES: ServiceRole[] = [ title: 'LLM adapter registry', mode: 'seam', implementations: ['llm-deepseek', 'llm-pi-ai', 'llm-replay'], - consumers: ['agent-loop', 'compaction-basic'], - note: 'Adapters register provider implementations; the loop and compaction call the provider-neutral stream service.', + consumers: ['agent-loop', 'compaction-basic', 'web-deepseek-api', 'web-search-deepseek'], + note: 'Adapters register provider implementations; the loop and compaction call the provider-neutral stream service, and the DeepSeek web providers read the credential a route publishes.', }, { key: 'sessionLogDeepSeek', @@ -486,7 +486,7 @@ const SERVICE_ROLES: ServiceRole[] = [ title: 'Credential seam', mode: 'seam', implementations: ['credentials-local'], - consumers: ['api-settings-controller', 'llm-deepseek', 'llm-pi-ai'], + consumers: ['api-settings-controller', 'llm-deepseek-api-key', 'llm-pi-ai', 'web-deepseek-api', 'web-search-deepseek'], note: 'Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the settings controller exposes value-free views and write-only storage.', }, { @@ -495,8 +495,8 @@ const SERVICE_ROLES: ServiceRole[] = [ title: 'DeepSeek account', mode: 'service', implementations: [], - consumers: ['llm-deepseek'], - note: 'The Host owns browser authorization and local credentials; UI consumers receive state without tokens.', + consumers: ['llm-deepseek-account', 'web-deepseek-api'], + note: 'The Host owns browser authorization and local credentials and releases per-request credentials to the account model route and the web providers; UI consumers receive state without tokens.', }, { key: 'authorization', diff --git a/scripts/plugin-entry-existing-exports.ts b/scripts/plugin-entry-existing-exports.ts index 70a12fd14b..4966421efe 100644 --- a/scripts/plugin-entry-existing-exports.ts +++ b/scripts/plugin-entry-existing-exports.ts @@ -109,8 +109,6 @@ export const EXISTING_PLUGIN_ENTRY_EXPORTS = { 'projectToolUpdates', 'requestImageHandleText', 'requiredImageOffload', 'resolveImageAttachmentAccess', 'resolveRetryPolicy', 'runFirstTokenTime', 'runFirstVisibleTime', 'textOnlyImageText', 'userAgent', ], - '@deepseek-ai/dsh-llm-deepseek-account': ['plainAccountOptions', 'resolveAccountOptions'], - '@deepseek-ai/dsh-llm-deepseek-api-key': ['plainOptions', 'resolveAdapterOptions'], '@deepseek-ai/dsh-llm-pi-ai': ['PiAiAdapter', 'recordKeyFor', 'supportedProtocols'], '@deepseek-ai/dsh-llm-replay': [ 'deriveReplayScript', 'installLlmReplay', 'loadReplayScript', 'loadSessionScripts', 'parseSessionHeader', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 43725880bf..1435978ba4 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -1842,6 +1842,16 @@ "symbol": "LlmNativeAuth", "source": "packages/llm/llm/src/types.ts" }, + { + "doc": "docs/subsystems/llm-streaming.md", + "symbol": "RouteCredentialGrant", + "source": "packages/llm/llm/src/types.ts" + }, + { + "doc": "docs/subsystems/llm-streaming.md", + "symbol": "RouteCredential", + "source": "packages/llm/llm/src/types.ts" + }, { "doc": "docs/subsystems/permission-presets.md", "symbol": "Config", diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index 6424868d38..c3c54ca0f5 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -88,7 +88,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/computer-use/computer-use': { kind: 'none', reason: 'The registry only reserves provider names; providers own all model-facing tools and guidance.' }, 'packages/document/office-kit': { kind: 'indirect', reason: 'The provider returns rendered and converted bytes; the Office tools own their model-visible results.' }, - 'packages/credentials/deepseek-account': { kind: 'none', reason: 'Account authorization registers no model context or tools; credentials affect HTTP authentication only.' }, + 'packages/account/deepseek-account': { kind: 'none', reason: 'Account authorization registers no model context or tools; credentials affect HTTP authentication only.' }, 'packages/client/ui-settings-account': { kind: 'none', reason: 'Account authorization registers no model context or tools; credentials affect HTTP authentication only.' }, 'packages/client/ui-account-notifications': { kind: 'none', reason: 'Account notification presentation and polling add no model input or Session events.' }, diff --git a/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs b/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs index a3891bc5b0..c2fcfcf89b 100644 --- a/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs +++ b/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs @@ -34,8 +34,9 @@ function transportInput(input, transportEndpoint) { /** Provide the signed-in account and start the Search endpoint; both end with the plugin fiber. */ export async function apply(ctx) { ctx.provide('deepseekAccount', { - resolveToken: async endpoint => endpoint.startsWith('https://api.deepseek.com/') ? ACCOUNT_TOKEN : undefined, - rejectToken: async () => {}, + resolveRequestCredential: async endpoint => endpoint.startsWith('https://api.deepseek.com/') + ? { headers: { 'x-dsh-auth-token': ACCOUNT_TOKEN }, value: ACCOUNT_TOKEN, reject: async () => {} } + : undefined, }) let restoreFetch = () => {} await applyLoopbackServerEffect(ctx, { diff --git a/tsconfig.base.json b/tsconfig.base.json index cbceac1a3f..56d6cbd202 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -52,9 +52,9 @@ "@deepseek-ai/dsh-client-ui-settings-account": ["./packages/client/ui-settings-account/src/index.ts"], "@deepseek-ai/dsh-client-ui-settings-account/client": ["./packages/client/ui-settings-account/src/client/index.ts"], "@deepseek-ai/dsh-api-gateway/stream-protocol": ["./packages/api/gateway/src/stream-protocol.ts"], - "@deepseek-ai/dsh-deepseek-account": ["./packages/credentials/deepseek-account/src/index.ts"], - "@deepseek-ai/dsh-deepseek-account/types": ["./packages/credentials/deepseek-account/src/types.ts"], - "@deepseek-ai/dsh-deepseek-account/client-metadata": ["./packages/credentials/deepseek-account/src/client-metadata.ts"], + "@deepseek-ai/dsh-deepseek-account": ["./packages/account/deepseek-account/src/index.ts"], + "@deepseek-ai/dsh-deepseek-account/types": ["./packages/account/deepseek-account/src/types.ts"], + "@deepseek-ai/dsh-deepseek-account/client-metadata": ["./packages/account/deepseek-account/src/client-metadata.ts"], "@deepseek-ai/dsh-experimental-speech-to-text": ["./packages/experimental/speech-to-text/src/index.ts"], "@deepseek-ai/dsh-experimental-translator": ["./packages/experimental/translator/src/index.ts"], "@deepseek-ai/dsh-experimental-translator/types": ["./packages/experimental/translator/src/types.ts"], diff --git a/tsconfig.host.json b/tsconfig.host.json index c2eb718f3a..bdec67243a 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -333,7 +333,7 @@ { "path": "./packages/document/office-kit" }, { "path": "./packages/document/tool-office" }, - { "path": "./packages/credentials/deepseek-account" }, + { "path": "./packages/account/deepseek-account" }, { "path": "./packages/client/ui-deliverables/tsconfig.host.json" }, { "path": "./vendor/cosmokit" }, { "path": "./vendor/schemastery" }, From 2ba494e53395ad2af75500a6e7ae9446d10b6a25 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Tue, 10 Nov 2026 20:08:25 +0800 Subject: [PATCH 07/48] refactor(llm): drop stale credential references from the llm-deepseek project --- packages/llm/llm-deepseek/tsconfig.json | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/llm/llm-deepseek/tsconfig.json b/packages/llm/llm-deepseek/tsconfig.json index e307eab423..d7b5af77a3 100644 --- a/packages/llm/llm-deepseek/tsconfig.json +++ b/packages/llm/llm-deepseek/tsconfig.json @@ -8,8 +8,6 @@ "src" ], "references": [ - { "path": "../../credentials/credentials" }, - { "path": "../../account/deepseek-account" }, { "path": "../../../vendor/cosmokit" }, From 48a20b9d0379f1e26b780c5ec04ff8820f09a012 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Wed, 11 Nov 2026 12:54:18 +0800 Subject: [PATCH 08/48] docs(upgrade-guide): move the route credential guide to v0.2.2-rc.2 --- .../2026-11-10-llm-route-credential-seam.i18n.yaml | 4 ++-- .../architecture/2026-11-10-llm-route-credential-seam.md | 2 +- .../architecture/2026-11-10-llm-route-credential-seam.zh.md | 2 +- .../llm-route-credential/guide.i18n.yaml | 6 +++--- .../llm-route-credential/guide.md | 0 .../llm-route-credential/guide.zh.md | 0 6 files changed, 7 insertions(+), 7 deletions(-) rename docs/upgrade-guide/{v0.2.2-rc.1 => v0.2.2-rc.2}/llm-route-credential/guide.i18n.yaml (87%) rename docs/upgrade-guide/{v0.2.2-rc.1 => v0.2.2-rc.2}/llm-route-credential/guide.md (100%) rename docs/upgrade-guide/{v0.2.2-rc.1 => v0.2.2-rc.2}/llm-route-credential/guide.zh.md (100%) diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index 2d080f2a52..957eb36d50 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -15,5 +15,5 @@ en: 8177946a6bfa1a6d zh: f523f9057b4b47c5 /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/consequences: - en: e558492c672907dc - zh: 3748557528dc3055 + en: f96508aa7cea1e87 + zh: 3eb61bdce43590bc diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md index 9e73be3c88..f3af0daf41 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -34,4 +34,4 @@ The web providers consume publications. `web-deepseek-api` builds each operation ## Consequences -Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `routeCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`. +Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `routeCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`. diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index 663d216dff..497aec414d 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -34,4 +34,4 @@ Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.route ## 后果 -新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `routeCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 +新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `routeCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml similarity index 87% rename from docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.i18n.yaml rename to docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml index 752379e39f..feb25c5ab8 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml @@ -1,13 +1,13 @@ # Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading # section, a hash of its English and Chinese blocks outside code blocks and generated regions. # After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md /: en: f0cf30e5430471e8 zh: 2e6e871797dfdd6b /deepseek-routes-publish-the-credential-web-consumers-reuse: - en: d7412a58aadc57a0 - zh: 82243a8cd8563083 + en: f0139803159ee9c9 + zh: 73bd5dfd53ed8d36 /deepseek-routes-publish-the-credential-web-consumers-reuse/change: en: 7a63f24e07fb3d33 zh: 99c64684a589088e diff --git a/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md similarity index 100% rename from docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md rename to docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md diff --git a/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md similarity index 100% rename from docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.zh.md rename to docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md From 3895609baad1dee2d92f50ef50d5e31ac6086195 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Wed, 11 Nov 2026 13:38:59 +0800 Subject: [PATCH 09/48] refactor(session): list Workspace sessions from member headers Drop contain_subagent from list_session: discovering subagents of a Workspace needs either a corpus scan or the parent subagent catalog, so this version lists only non-subagent sessions. A workspace_id call now reads its members' headers from the Workspace registry index through the new Workspace.sessionHeaders, so its work grows with the member count instead of enumerating every stored Session. Unscoped calls still enumerate the corpus headers. --- docs/subsystems/workspace.md | 7 +++ docs/subsystems/workspace.zh.md | 7 +++ docs/tool-catalog.i18n.yaml | 4 +- docs/tool-catalog.md | 8 +-- docs/tool-catalog.zh.md | 8 +-- .../extensions/tool-cordis/src/api-catalog.ts | 2 +- .../tool-session-list/README.i18n.yaml | 24 +++---- .../session-query/tool-session-list/README.md | 14 ++--- .../tool-session-list/README.zh.md | 14 ++--- .../tool-session-list/src/index.ts | 5 +- .../tool-session-list/src/list.ts | 63 +++++-------------- .../tests/tool-session-list.spec.ts | 51 +++++++-------- packages/workspace/workspace/README.i18n.yaml | 4 +- packages/workspace/workspace/README.md | 2 +- packages/workspace/workspace/README.zh.md | 2 +- packages/workspace/workspace/src/entity.ts | 14 ++++- packages/workspace/workspace/src/index.ts | 8 +++ packages/workspace/workspace/src/types.ts | 9 ++- .../workspace/tests/workspace.spec.ts | 2 + .../session-list-tools/session.v4.jsonl | 6 +- .../tool-schemas.expected.json | 8 +-- 21 files changed, 129 insertions(+), 133 deletions(-) diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index 046f0b9924..ba01258c94 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -63,6 +63,13 @@ interface Workspace { */ readonly sessionIds: readonly SessionId[] + /** + * Stored headers of {@link sessionIds}, in the same order. Read from the + * registry's startup and attach-time header index without persistence I/O; + * headers are immutable, so an indexed header never goes stale. + */ + readonly sessionHeaders: readonly SessionHeader[] + /** * Replace the display title durably. * @param title - New title; any string, duplicates across workspaces allowed. diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index 95983eb846..55b4bd531d 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -63,6 +63,13 @@ interface Workspace { */ readonly sessionIds: readonly SessionId[] + /** + * Stored headers of {@link sessionIds}, in the same order. Read from the + * registry's startup and attach-time header index without persistence I/O; + * headers are immutable, so an indexed header never goes stale. + */ + readonly sessionHeaders: readonly SessionHeader[] + /** * Replace the display title durably. * @param title - New title; any string, duplicates across workspaces allowed. diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index a8129d0f23..e154e39f30 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -243,8 +243,8 @@ en: 6d68942100dd76e7 zh: 6d68942100dd76e7 /tool-schema-catalog/deepseek-ai-dsh-tool-session-list/list-session: - en: fa3ac1878f21c149 - zh: dfd5759772f99d13 + en: 8a04c79a2d8ef256 + zh: 06e93b69aa95c6e9 /tool-schema-catalog/deepseek-ai-dsh-tool-session-list/list-workspace: en: 7b1f0bed364dfcd2 zh: c907d8ff78f54268 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index 3d4070cdaf..93f4b36c3e 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -1923,7 +1923,7 @@ Source: [`packages/skill/tool-skill/src/index.ts`](../packages/skill/tool-skill/ ### `list_session` -List sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null. +List non-subagent sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null. ```json { @@ -1931,11 +1931,7 @@ List sessions by latest human prompt time, newest first, then by ID. Returns IDs "properties": { "workspace_id": { "type": "string", - "description": "Workspace ID from list_workspace. Includes its members and, when requested, subagents belonging through their nearest member ancestor. Omit to list all accessible sessions." - }, - "contain_subagent": { - "type": "boolean", - "description": "Include subagent sessions. Defaults to false." + "description": "Workspace ID from list_workspace. Lists only its member sessions. Omit to list sessions in every workspace and outside all workspaces." }, "archived": { "type": "boolean", diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index 4847ac26c1..4b91662eb7 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -1929,7 +1929,7 @@ lsp 工具将提供方选择和语言服务器子进程置于 ctx.lsp 之后, ### `list_session` -按最近人工提示词时间从新到旧列出会话,时间相同时按 ID 排列。返回 ID、可用标题以及 ISO 创建时间和更新时间。缺少活动元数据时使用创建时间;标题不可用时为 null。 +按最近人工提示词时间从新到旧列出非 subagent 会话,时间相同时按 ID 排列。返回 ID、可用标题以及 ISO 创建时间和更新时间。缺少活动元数据时使用创建时间;标题不可用时为 null。 ```json { @@ -1937,11 +1937,7 @@ lsp 工具将提供方选择和语言服务器子进程置于 ctx.lsp 之后, "properties": { "workspace_id": { "type": "string", - "description": "Workspace ID from list_workspace. Includes its members and, when requested, subagents belonging through their nearest member ancestor. Omit to list all accessible sessions." - }, - "contain_subagent": { - "type": "boolean", - "description": "Include subagent sessions. Defaults to false." + "description": "Workspace ID from list_workspace. Lists only its member sessions. Omit to list sessions in every workspace and outside all workspaces." }, "archived": { "type": "boolean", diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 55c63b384c..d3a55d0b3a 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -10676,7 +10676,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'Workspace', - declaration: 'export interface Workspace {\n readonly id: WorkspaceId;\n readonly path: string;\n readonly title: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n readonly sessionIds: readonly SessionId[];\n setTitle(title: string): Promise;\n attachSession(sessionId: SessionId): Promise;\n insertSessionBefore(sessionId: SessionId, beforeSessionId?: SessionId): Promise;\n detachSession(sessionId: SessionId): Promise;\n status(): Promise<\'ok\' | \'missing-dir\'>;\n}', + declaration: 'export interface Workspace {\n readonly id: WorkspaceId;\n readonly path: string;\n readonly title: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n readonly sessionIds: readonly SessionId[];\n readonly sessionHeaders: readonly SessionHeader[];\n setTitle(title: string): Promise;\n attachSession(sessionId: SessionId): Promise;\n insertSessionBefore(sessionId: SessionId, beforeSessionId?: SessionId): Promise;\n detachSession(sessionId: SessionId): Promise;\n status(): Promise<\'ok\' | \'missing-dir\'>;\n}', }, { name: 'WorkspaceArchiveSessionRequest', diff --git a/packages/session-query/tool-session-list/README.i18n.yaml b/packages/session-query/tool-session-list/README.i18n.yaml index 53c6e0e891..362ea0c6c0 100644 --- a/packages/session-query/tool-session-list/README.i18n.yaml +++ b/packages/session-query/tool-session-list/README.i18n.yaml @@ -9,8 +9,8 @@ en: 963f03d1ba483ea9 zh: 4809b66477752fe9 /deepseek-ai-dsh-tool-session-list/summary: - en: c643c299cff0602e - zh: a4e0d8d3cb039859 + en: e4e61ecb4f56e250 + zh: 815fd87f03e766f1 /deepseek-ai-dsh-tool-session-list/table-of-contents: en: d152484eb41ac6b4 zh: 5acc0d3807846b6e @@ -21,17 +21,17 @@ en: 0bf65fbc8660134a zh: f4f7b3a0049d3196 /deepseek-ai-dsh-tool-session-list/use-this-package/listing-behavior: - en: 77a4b342a8be5311 - zh: eb166df6d600df90 + en: bd85d03043393832 + zh: 9c57bdd92461c1e1 /deepseek-ai-dsh-tool-session-list/use-this-package/failures: - en: be4dd03d3877e2ed - zh: 27c38df3c449dde9 + en: 95ee3e3c0ecedadd + zh: 933d267402ceec74 /deepseek-ai-dsh-tool-session-list/understand-the-implementation: - en: a9a0e5d116579be4 - zh: 1b78e7f73b639f85 + en: 730fef413ce5a404 + zh: 325a5700a9edbda1 /deepseek-ai-dsh-tool-session-list/further-exploration: - en: 2a147ada18753beb - zh: d9aa75491c8fc0b7 + en: 06d8fa5cb2d63b6b + zh: 2635b93fccf3dbc9 /deepseek-ai-dsh-tool-session-list/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 @@ -48,8 +48,8 @@ en: 0e201fbbe37798d8 zh: fd4bd41e7393c234 /deepseek-ai-dsh-tool-session-list/known-limitations-and-deferred-work: - en: 103c746911f87efd - zh: 58f101c6b129c9e8 + en: f0b57c2f2e7a0984 + zh: ed80800cb0d021c8 /deepseek-ai-dsh-tool-session-list/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/session-query/tool-session-list/README.md b/packages/session-query/tool-session-list/README.md index a8eda14d56..3a17a6f125 100644 --- a/packages/session-query/tool-session-list/README.md +++ b/packages/session-query/tool-session-list/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Discover workspaces and sessions without resuming an agent or reading cold conversation logs. List empty workspaces, find sessions in a workspace, or include subagents and archived sessions. Results contain identifiers and lightweight metadata, with bounded page sizes. Enable these tools when callers may inspect the metadata of the whole mounted runtime. +Discover workspaces and sessions without resuming an agent or reading cold conversation logs. List empty workspaces, find sessions in a workspace, or list archived sessions. Results contain identifiers and lightweight metadata, with bounded page sizes. Enable these tools when callers may inspect the metadata of the whole mounted runtime. ## Table of Contents @@ -47,15 +47,15 @@ When the composition already mounts `workspaceRegistry`, add only the tool row. Both tools return an array directly. The [tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-tool-session-list) defines arguments. Pagination follows filtering and ordering; each call defaults to 20 entries, accepts at most 100, and starts at offset zero. Increase the offset by the number of returned entries to continue; an empty array ends the traversal. -`list_workspace` preserves registry order and includes workspaces with no sessions. `list_session` includes unarchived ordinary sessions by default, including sessions outside every Workspace when no `workspace_id` is supplied. Explicit Workspace selection uses recorded membership, not a matching working directory. With subagents included, a directly assigned Workspace wins; otherwise the nearest recorded member ancestor determines membership. Ordinary forked sessions do not inherit membership through their parents. Archival matches each Session's own ID, independently of its ancestors. +`list_workspace` preserves registry order and includes workspaces with no sessions. `list_session` never returns subagent sessions. It includes unarchived sessions by default, including sessions outside every Workspace when no `workspace_id` is supplied. Explicit Workspace selection uses recorded membership, not a matching working directory. Archival matches each Session's own ID. Session order is descending `updated_at`, then ascending Session ID for ties. Activity time is the later of creation and the latest human-authored prompt; assistant activity and title changes do not advance it. Titles come from live projections or persisted projection metadata. Unavailable titles are `null`, and unavailable activity metadata falls back to creation time. Timestamps are ISO 8601 strings. Pin order and manual sidebar order do not affect the results. -After header enumeration, filtering, metadata reads, and sorting run synchronously. The call does not promise prompt handling of new cancellation requests during this work or one snapshot across all Sessions. +With `workspace_id`, the call reads its members' headers from the Workspace registry index without persistence I/O, so its work grows with the member count. Without `workspace_id`, it first enumerates every stored and live Session header. Filtering, metadata reads, and sorting then run synchronously. The call does not promise prompt handling of new cancellation requests during this work or one snapshot across all Sessions. ### Failures -Invalid pagination and an unknown `workspace_id` fail with `ToolArgsError` (`INVALID_ARGS`); use `list_workspace` to find a registered ID. Query and storage failures fail the call, and cyclic subagent ancestry encountered during Workspace selection fails with `SESSION_QUERY_INVALID_LINEAGE`. Cancellation returns no partial result. These failures leave sessions and Workspace records untouched. +Invalid pagination and an unknown `workspace_id` fail with `ToolArgsError` (`INVALID_ARGS`); use `list_workspace` to find a registered ID. Query and storage failures fail the call. Cancellation returns no partial result. These failures leave sessions and Workspace records untouched. ----- @@ -65,7 +65,7 @@ Invalid pagination and an unknown `workspace_id` fail with `ToolArgsError` (`INV
Implementation internals — click to expand -The tools combine the existing header-only query listing with Workspace membership and projected metadata. The shared `registerSessionListMetadata` helper acquires the same projection unit used by the Session API; each consumer releases its own registration when disposed. The title projection remains owned by `dsh-session-title`. Cold rows read the projection cache without opening the underlying log, including on a cache miss. No Session Controller or Agent activation is required. +A Workspace selection reads `Workspace.sessionHeaders`; an unscoped call uses the existing header-only query listing. Both combine headers with projected metadata. The shared `registerSessionListMetadata` helper acquires the same projection unit used by the Session API; each consumer releases its own registration when disposed. The title projection remains owned by `dsh-session-title`. Cold rows read the projection cache without opening the underlying log, including on a cache miss. No Session Controller or Agent activation is required. | File | Role | |---|---| @@ -80,7 +80,7 @@ The tools combine the existing header-only query listing with Workspace membersh ## Further Exploration - [Workspace registry](../../workspace/workspace/README.md) — recorded membership, registry order, and archival. -- [Session query](../session-query/README.md) — header enumeration and the shared list metadata reader. +- [Session query](../session-query/README.md) — corpus header enumeration and the shared list metadata reader. - [Session projection cache](../../session/session-projection-cache/README.md) — persisted metadata and cache availability. - [Session query package map](../README.md) — adjacent retrieval capabilities. @@ -110,7 +110,7 @@ The schemas remain stable while tool availability is unchanged. Calls append ord These constraints affect consumers of the lists. - **Cold metadata can be missing or stale** — listing never rebuilds it by reading the full log. A `null` title can mean either no title or unavailable title metadata. -- **Pagination is not a stable snapshot** — concurrent registry or Session changes can move entries between calls. Session listing enumerates candidates before selecting a page, so the page size does not bound total scan work. +- **Pagination is not a stable snapshot** — concurrent registry or Session changes can move entries between calls. Session listing reads every candidate before selecting a page, so the page size does not bound total work; an unscoped call scales with the Session count. - **Metadata access is runtime-wide** — callers needing per-agent Workspace authorization require a separately defined access policy before these tools are enabled for them. diff --git a/packages/session-query/tool-session-list/README.zh.md b/packages/session-query/tool-session-list/README.zh.md index 65492ef42b..a6dbcf8786 100644 --- a/packages/session-query/tool-session-list/README.zh.md +++ b/packages/session-query/tool-session-list/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -无需恢复 agent(智能体)运行或读取冷会话的日志,即可发现工作区和会话。可以列出空工作区、查找某工作区中的会话,或包含 subagent 和已归档会话。结果包含标识符及轻量元数据,并限制每页条目数。当调用者可以查看整个已挂载运行时的元数据时,启用这些工具。 +无需恢复 agent(智能体)运行或读取冷会话的日志,即可发现工作区和会话。可以列出空工作区、查找某工作区中的会话,或列出已归档会话。结果包含标识符及轻量元数据,并限制每页条目数。当调用者可以查看整个已挂载运行时的元数据时,启用这些工具。 ## 目录 @@ -47,15 +47,15 @@ kind: "package-reference" 两个工具都直接返回数组。[工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-session-list)定义参数。先过滤和排序,再分页;每次调用默认返回 20 条,最多接受 100 条,起始偏移为零。继续遍历时,将偏移增加已返回的条目数;空数组表示遍历结束。 -`list_workspace` 保留注册表顺序,并包含没有会话的工作区。`list_session` 默认包含未归档的普通会话;没有指定 `workspace_id` 时,也包含不属于任何 Workspace 的会话。显式选择 Workspace 时使用已记录的成员关系,而非相同的工作目录。包含 subagent 时,直接分配的 Workspace 优先;否则由最近的已记录成员祖先确定归属。普通 fork 会话不会通过父级继承成员关系。归档筛选匹配每个 Session 自身的 ID,与祖先无关。 +`list_workspace` 保留注册表顺序,并包含没有会话的工作区。`list_session` 从不返回 subagent 会话。它默认包含未归档会话;没有指定 `workspace_id` 时,也包含不属于任何 Workspace 的会话。显式选择 Workspace 时使用已记录的成员关系,而非相同的工作目录。归档筛选匹配每个 Session 自身的 ID。 会话按 `updated_at` 降序排列,时间相同则按 Session ID 升序排列。活动时间取创建时间与最近人工提示词时间的较晚值;助手活动和标题变化不会推进它。标题来自实时投影或持久化投影元数据。标题不可用时为 `null`,活动元数据不可用时回退到创建时间。时间戳使用 ISO 8601 字符串。置顶顺序和侧边栏手动顺序不影响结果。 -header 枚举之后,筛选、元数据读取和排序同步执行。调用不承诺在这段工作中及时处理新收到的取消请求,也不承诺所有 Session 共享同一个快照。 +指定 `workspace_id` 时,调用从 Workspace 注册表索引读取成员 header,不做持久化 I/O,因此工作量随成员数增长。不指定 `workspace_id` 时,先枚举所有已存储和 live Session 的 header。随后的筛选、元数据读取和排序同步执行。调用不承诺在这段工作中及时处理新收到的取消请求,也不承诺所有 Session 共享同一个快照。 ### 失败 -无效分页参数或未知的 `workspace_id` 以 `ToolArgsError`(`INVALID_ARGS`)失败;使用 `list_workspace` 查找已注册的 ID。查询和存储故障使调用失败,按 Workspace 筛选时遇到循环的 subagent 祖先关系则以 `SESSION_QUERY_INVALID_LINEAGE` 失败。取消不返回部分结果。这些失败不会修改会话或 Workspace 记录。 +无效分页参数或未知的 `workspace_id` 以 `ToolArgsError`(`INVALID_ARGS`)失败;使用 `list_workspace` 查找已注册的 ID。查询和存储故障使调用失败。取消不返回部分结果。这些失败不会修改会话或 Workspace 记录。 ----- @@ -65,7 +65,7 @@ header 枚举之后,筛选、元数据读取和排序同步执行。调用不
实现细节——点击展开 -工具将现有的仅 header 查询列表与 Workspace 成员关系及投影元数据结合。共享的 `registerSessionListMetadata` 辅助函数获取 Session API 使用的同一个投影单元;每个消费方在释放时只移除自己的注册。标题投影仍由 `dsh-session-title` 拥有。冷条目读取投影缓存,不打开底层日志,缓存未命中时也一样。不需要 Session 控制器,也不会激活 agent。 +选定 Workspace 时读取 `Workspace.sessionHeaders`;不指定范围时使用现有的仅 header 查询列表。两者都把 header 与投影元数据结合。共享的 `registerSessionListMetadata` 辅助函数获取 Session API 使用的同一个投影单元;每个消费方在释放时只移除自己的注册。标题投影仍由 `dsh-session-title` 拥有。冷条目读取投影缓存,不打开底层日志,缓存未命中时也一样。不需要 Session 控制器,也不会激活 agent。 | 文件 | 职责 | |---|---| @@ -80,7 +80,7 @@ header 枚举之后,筛选、元数据读取和排序同步执行。调用不 ## 进一步探索 - [Workspace 注册表](../../workspace/workspace/README.zh.md)——已记录的成员关系、注册表顺序与归档。 -- [Session 查询](../session-query/README.zh.md)——header 枚举与共享列表元数据读取函数。 +- [Session 查询](../session-query/README.zh.md)——全量 header 枚举与共享列表元数据读取函数。 - [Session 投影缓存](../../session/session-projection-cache/README.zh.md)——持久化元数据与缓存可用性。 - [Session 查询包映射](../README.zh.md)——相邻的检索能力。 @@ -110,7 +110,7 @@ header 枚举之后,筛选、元数据读取和排序同步执行。调用不 以下约束影响列表消费方。 - **冷元数据可能缺失或过期**——列表不会通过读取完整日志重建它。标题为 `null` 可能表示没有标题,也可能表示标题元数据不可用。 -- **分页不是稳定快照**——并发的注册表或 Session 变化可能让条目在多次调用间移动。会话列表先枚举候选项,再选取一页,因此每页大小不限制总扫描工作量。 +- **分页不是稳定快照**——并发的注册表或 Session 变化可能让条目在多次调用间移动。会话列表先读取全部候选项,再选取一页,因此每页大小不限制总工作量;不指定范围的调用随 Session 总数增长。 - **元数据访问覆盖整个运行时**——需要逐 agent Workspace 授权的调用者,必须先定义独立的访问策略,再为其启用这些工具。 diff --git a/packages/session-query/tool-session-list/src/index.ts b/packages/session-query/tool-session-list/src/index.ts index f3e2ed47c7..a7d17b0bab 100644 --- a/packages/session-query/tool-session-list/src/index.ts +++ b/packages/session-query/tool-session-list/src/index.ts @@ -52,10 +52,9 @@ export async function apply(ctx: Context): Promise { })) ctx.tools.register(defineTool({ name: 'list_session', - description: 'List sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null.', + description: 'List non-subagent sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null.', parameters: { - workspace_id: { type: 'string', description: 'Workspace ID from list_workspace. Includes its members and, when requested, subagents belonging through their nearest member ancestor. Omit to list all accessible sessions.' }, - contain_subagent: { type: 'boolean', description: 'Include subagent sessions. Defaults to false.' }, + workspace_id: { type: 'string', description: 'Workspace ID from list_workspace. Lists only its member sessions. Omit to list sessions in every workspace and outside all workspaces.' }, archived: { type: 'boolean', description: 'Return only archived sessions when true, otherwise only unarchived sessions. Defaults to false.' }, ...pagination, }, diff --git a/packages/session-query/tool-session-list/src/list.ts b/packages/session-query/tool-session-list/src/list.ts index 68fed14528..2de007a6eb 100644 --- a/packages/session-query/tool-session-list/src/list.ts +++ b/packages/session-query/tool-session-list/src/list.ts @@ -2,7 +2,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { Session, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' -import { SessionQueryError, type SessionListMetadata } from '@deepseek-ai/dsh-session-query' +import type { SessionListMetadata } from '@deepseek-ai/dsh-session-query' import type {} from '@deepseek-ai/dsh-session-projection-cache' import type {} from '@deepseek-ai/dsh-session-title' import { ToolArgsError } from '@deepseek-ai/dsh-tools' @@ -17,7 +17,6 @@ export interface PageInput { /** Optional Session selection arguments. */ export interface SessionListInput extends PageInput { readonly workspace_id?: string - readonly contain_subagent?: boolean readonly archived?: boolean } @@ -74,6 +73,8 @@ export function listWorkspaces(ctx: Context, input: PageInput, signal: AbortSign /** * List live and persisted Session metadata without opening cold logs or activating Agents. + * A Workspace selection reads only its members' indexed headers; an unscoped call enumerates + * the corpus headers. Subagent Sessions are excluded. * @param ctx - context providing query, Workspace, and projection services. * @param readLiveMetadata - ready reader owned by this plugin's registration. * @param input - filters and pagination arguments. @@ -88,30 +89,22 @@ export async function listSessions( ): Promise { const { limit, offset } = resolvePage(input) signal.throwIfAborted() - const workspaceId = input.workspace_id === undefined ? undefined : WorkspaceId(input.workspace_id) - if (workspaceId !== undefined && ctx.workspaceRegistry.get(workspaceId) === undefined) { - throw new ToolArgsError([`workspace_id ${JSON.stringify(workspaceId)} is not registered; use list_workspace to find a workspace`]) - } - const records = await ctx.sessionQuery.listSessions(signal) - signal.throwIfAborted() - const archived = new Set(ctx.workspaceRegistry.archivedSessionIds) - const ownership = new Map() - if (workspaceId !== undefined) { - for (const workspace of ctx.workspaceRegistry.list()) { - for (const id of workspace.sessionIds) ownership.set(id, workspace.id) - } - } - const headers = new Map(records.map(record => [record.header.id, record.header])) - const nearestWorkspace = ancestorWorkspaceReader(headers, ownership) - const items = [] - for (const { header } of records) { + let headers: readonly SessionHeader[] + if (input.workspace_id === undefined) { + headers = (await ctx.sessionQuery.listSessions(signal)).map(record => record.header) signal.throwIfAborted() - if (!input.contain_subagent && header.origin === 'subagent') continue - if (archived.has(header.id) !== (input.archived ?? false)) continue - if (workspaceId !== undefined) { - const owner = header.origin === 'subagent' ? nearestWorkspace(header) : ownership.get(header.id) - if (owner !== workspaceId) continue + } else { + const workspace = ctx.workspaceRegistry.get(WorkspaceId(input.workspace_id)) + if (workspace === undefined) { + throw new ToolArgsError([`workspace_id ${JSON.stringify(input.workspace_id)} is not registered; use list_workspace to find a workspace`]) } + headers = workspace.sessionHeaders + } + const archived = new Set(ctx.workspaceRegistry.archivedSessionIds) + const items = [] + for (const header of headers) { + if (header.origin === 'subagent') continue + if (archived.has(header.id) !== (input.archived ?? false)) continue const metadata = readListMetadata(ctx, header, readLiveMetadata) items.push({ session_id: header.id, @@ -122,7 +115,6 @@ export async function listSessions( } items.sort((left, right) => right.updatedAt - left.updatedAt || (left.session_id < right.session_id ? -1 : 1)) - signal.throwIfAborted() return items.slice(offset, offset + limit).map(({ updatedAt, ...item }) => ({ ...item, updated_at: new Date(updatedAt).toISOString(), @@ -149,24 +141,3 @@ function readListMetadata( lastPromptAt: snapshot?.values.sessionListMetadata?.lastPromptAt ?? null, } } - -function ancestorWorkspaceReader( - headers: ReadonlyMap, - ownership: ReadonlyMap, -): (header: SessionHeader) => WorkspaceId | undefined { - const resolved = new Map(ownership) - return (header) => { - const visited = new Set() - let current: SessionHeader | undefined = header - while (current !== undefined && !resolved.has(current.id)) { - if (visited.has(current.id)) { - throw new SessionQueryError(`Session ${header.id} has cyclic parent ancestry`, 'SESSION_QUERY_INVALID_LINEAGE') - } - visited.add(current.id) - current = current.parentSession === undefined ? undefined : headers.get(current.parentSession) - } - const workspace = current === undefined ? undefined : resolved.get(current.id) - for (const id of visited) resolved.set(id, workspace) - return workspace - } -} diff --git a/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts index 87dd7fcac7..6777822aef 100644 --- a/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts +++ b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts @@ -233,9 +233,7 @@ describe('read-only Session list tools', () => { }) await mounted.ctx.workspaceRegistry.pinSession(SessionId('z')) expect(value(await mounted.call('list_session', { limit: 1, offset: 1 }))).toEqual([item('b', 100)]) - expect(value(await mounted.call('list_session', { contain_subagent: true }))).toEqual([ - item('child', 200), item('a', 100), item('b', 100), item('z', 100), - ]) + expect(value(await mounted.call('list_session'))).toEqual([item('a', 100), item('b', 100), item('z', 100)]) expect(value(await mounted.call('list_session', { archived: true }))).toEqual([item('archived', 500)]) expect(value(await mounted.call('list_session', { archived: true, offset: 1 }))).toEqual([]) }) @@ -248,33 +246,36 @@ describe('read-only Session list tools', () => { ]) }) - it('inherits explicit Workspace membership only for subagents and stops at the nearest assigned ancestor', async () => { + it('lists recorded non-subagent Workspace members from indexed headers without enumerating the corpus', async () => { const path = await directory() const otherPath = join(path, 'other') await mkdir(otherPath) const mounted = await mount({ headers: [ header('parent', 10, { cwd: path }), - header('same-cwd', 20, { cwd: path }), - header('child', 30, { cwd: path, origin: 'subagent', parentSession: SessionId('parent') }), - header('grandchild', 40, { origin: 'subagent', parentSession: SessionId('child') }), - header('fork', 50, { cwd: path, parentSession: SessionId('parent') }), - header('assigned-child', 60, { cwd: otherPath, origin: 'subagent', parentSession: SessionId('parent') }), - header('assigned-grandchild', 70, { origin: 'subagent', parentSession: SessionId('assigned-child') }), - header('orphan', 80, { origin: 'subagent', parentSession: SessionId('absent') }), - header('unassigned-child', 90, { origin: 'subagent', parentSession: SessionId('same-cwd') }), + header('member', 20, { cwd: path }), + header('same-cwd', 30, { cwd: path }), + header('child', 40, { cwd: path, origin: 'subagent', parentSession: SessionId('parent') }), + header('assigned-child', 50, { cwd: path, origin: 'subagent', parentSession: SessionId('parent') }), + header('other-member', 60, { cwd: otherPath }), + ], + workspaces: [ + ['primary', workspace(path, ['parent', 'member', 'assigned-child'])], + ['other', workspace(otherPath, ['other-member'])], ], - workspaces: [['primary', workspace(path, ['parent'])], ['other', workspace(otherPath, ['assigned-child'])]], archived: ['parent'], }) - expect(value(await mounted.call('list_session', { workspace_id: 'primary', contain_subagent: true }))).toEqual([ - item('grandchild', 40), item('child', 30), - ]) + const corpus = vi.spyOn(mounted.ctx.sessionQuery, 'listSessions') + // Registry startup already listed the stored headers; only later listings matter. + const stored = vi.spyOn(mounted.ctx.sessionPersistence, 'list') + stored.mockClear() + expect(value(await mounted.call('list_session', { workspace_id: 'primary' }))).toEqual([item('member', 20)]) expect(value(await mounted.call('list_session', { workspace_id: 'primary', archived: true }))).toEqual([item('parent', 10)]) - expect(value(await mounted.call('list_session', { workspace_id: 'other', contain_subagent: true }))).toEqual([ - item('assigned-grandchild', 70), item('assigned-child', 60), - ]) - expect(value(await mounted.call('list_session', { workspace_id: 'primary' }))).toEqual([]) + expect(value(await mounted.call('list_session', { workspace_id: 'other' }))).toEqual([item('other-member', 60)]) + expect(corpus).not.toHaveBeenCalled() + expect(stored).not.toHaveBeenCalled() + expect(value(await mounted.call('list_session'))).toEqual([item('other-member', 60), item('same-cwd', 30), item('member', 20)]) + expect(corpus).toHaveBeenCalledOnce() }) it('defaults to twenty rows and accepts the upper page limit', async () => { @@ -295,16 +296,10 @@ describe('read-only Session list tools', () => { } }) - it('rejects an unknown Workspace and corrupt subagent ancestry with typed failures', async () => { - const path = await directory() - const mounted = await mount({ - headers: [header('cycle-a', 10, { origin: 'subagent', parentSession: SessionId('cycle-b') }), header('cycle-b', 20, { origin: 'subagent', parentSession: SessionId('cycle-a') })], - workspaces: [['known', workspace(path)]], - }) + it('rejects an unknown Workspace with a typed failure', async () => { + const mounted = await mount() expect((await mounted.call('list_session', { workspace_id: 'absent' })).error?.info) .toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) - expect((await mounted.call('list_session', { workspace_id: 'known', contain_subagent: true })).error?.info) - .toMatchObject({ name: 'SessionQueryError', code: 'SESSION_QUERY_INVALID_LINEAGE' }) expect(mounted.open).not.toHaveBeenCalled() }) diff --git a/packages/workspace/workspace/README.i18n.yaml b/packages/workspace/workspace/README.i18n.yaml index d90b57b56d..56af9d261a 100644 --- a/packages/workspace/workspace/README.i18n.yaml +++ b/packages/workspace/workspace/README.i18n.yaml @@ -39,8 +39,8 @@ en: 447ced401b3b14a8 zh: 3ce2105605223945 /deepseek-ai-dsh-workspace/understand-the-implementation/design-philosophy: - en: e969314497b99389 - zh: 82eafc832617a1eb + en: 512431b309ba0051 + zh: 206c77de2022a541 /deepseek-ai-dsh-workspace/understand-the-implementation/api-behavior: en: 8fcd81ee32f3c01e zh: 08ac92d085bb8147 diff --git a/packages/workspace/workspace/README.md b/packages/workspace/workspace/README.md index bafe861a81..23d8e88804 100644 --- a/packages/workspace/workspace/README.md +++ b/packages/workspace/workspace/README.md @@ -91,7 +91,7 @@ This section explains the design decisions behind the feature and points at the ### Design philosophy - **One record per canonical path.** `fs.realpath` is the single uniqueness canon: paths are stored canonicalized, so a symlink to an owned directory collides, and uniqueness is string equality of canonical paths. -- **Membership starts from the recorded account.** The header index validates ordered `sessionIds`; missing-directory candidates retain their account, while other invalid candidates are filtered on read and pruned by the next mutation. The strict canonical-path index used for history bootstrap includes existing directories only. +- **Membership starts from the recorded account.** The header index validates ordered `sessionIds`; missing-directory candidates retain their account, while other invalid candidates are filtered on read and pruned by the next mutation. `sessionHeaders` returns the indexed headers of `sessionIds` in the same order without persistence I/O. The strict canonical-path index used for history bootstrap includes existing directories only. - **Header-only reads.** Bootstrap and attach validation read `SessionHeader` fields only; event bodies are never loaded. - **Two-write mutations with an explicit marker.** Create and delete persist a `pendingMutation` marker before the record/order pair can diverge, so startup completes exactly the interrupted operation and unmarked divergence fails loud as corruption. - **Serialized writes.** Registry operations run on one operation chain; entity mutations go through `table.update` on the domain write chain, stamping `updatedAt` and deciding membership at their chain slot. diff --git a/packages/workspace/workspace/README.zh.md b/packages/workspace/workspace/README.zh.md index c894d3264a..02bf670648 100644 --- a/packages/workspace/workspace/README.zh.md +++ b/packages/workspace/workspace/README.zh.md @@ -91,7 +91,7 @@ Workspace 注册不意味着拥有其目录。未来的破坏性文件系统操 ### 设计理念 - **每个规范路径一条记录。** `fs.realpath` 是唯一的一套唯一性规范:路径以规范化形式存储,因此指向已有记录目录的符号链接会与之冲突,唯一性即规范路径的字符串相等。 -- **成员资格以已记录的归属为起点。** 头部索引校验有序的 `sessionIds`;目录缺失的候选保留归属,其他无效候选在读取时过滤,并在下一次变更时剪除。历史引导使用的严格规范路径索引只包含现存目录。 +- **成员资格以已记录的归属为起点。** 头部索引校验有序的 `sessionIds`;目录缺失的候选保留归属,其他无效候选在读取时过滤,并在下一次变更时剪除。`sessionHeaders` 按相同顺序返回 `sessionIds` 的已索引 header,不做持久化 I/O。历史引导使用的严格规范路径索引只包含现存目录。 - **仅读取头部。** 引导与 attach 校验只读取 `SessionHeader` 字段;事件正文绝不加载。 - **两次写入的变更带显式标记。** 创建与删除在记录/顺序对可能分叉之前先持久化 `pendingMutation` 标记,因此启动只补全被中断的操作,未标记的分叉作为损坏明确报错。 - **串行化写入。** 注册表操作跑在同一条操作链上;实体变更通过领域写链上的 `table.update` 执行,写入 `updatedAt`,并在其所在的链位置决定成员资格。 diff --git a/packages/workspace/workspace/src/entity.ts b/packages/workspace/workspace/src/entity.ts index 0d687e8c94..cecd435181 100644 --- a/packages/workspace/workspace/src/entity.ts +++ b/packages/workspace/workspace/src/entity.ts @@ -29,7 +29,8 @@ export class WorkspaceMoveInvalidError extends Error { /** * The registry-owned machinery an entity mutates through. Entities never see * the registry itself — only the open table, the canonical session-path - * index backing the `sessionIds` projection, and attach-time header reads. + * index backing the `sessionIds` projection, its header index, and + * attach-time header reads. */ export interface WorkspaceEntityHost { /** @@ -55,6 +56,13 @@ export interface WorkspaceEntityHost { */ readSessionHeader(id: SessionId): Promise + /** + * Read the indexed header of a session that {@link candidateMatches} accepted. + * @param id - Session currently returned by `sessionIds`. + * @returns the immutable indexed header. + */ + sessionHeader(id: SessionId): SessionHeader + /** * Publish a successfully validated canonical cwd to the projection index. * @param id - Validated session id. @@ -103,6 +111,10 @@ export class WorkspaceEntity implements Workspace { return this.record.sessionIds.filter(id => this.host.candidateMatches(id, this.record.path)) } + get sessionHeaders(): readonly SessionHeader[] { + return this.sessionIds.map(id => this.host.sessionHeader(id)) + } + async setTitle(title: string): Promise { await this.mutate(record => ({ ...record, title })) } diff --git a/packages/workspace/workspace/src/index.ts b/packages/workspace/workspace/src/index.ts index 825cb0491a..a8c0e498df 100644 --- a/packages/workspace/workspace/src/index.ts +++ b/packages/workspace/workspace/src/index.ts @@ -200,6 +200,14 @@ export class WorkspaceRegistry extends Service { table: () => this.requireTable(), candidateMatches: (id, path) => this.sessionPaths.get(id) === path || this.missingSessionPaths.has(id), readSessionHeader: id => this.readSessionHeader(id), + sessionHeader: (id) => { + const header = this.headers.get(id) + /* v8 ignore next 3 -- every path that admits a candidate indexes its header first. */ + if (header === undefined) { + throw new Error(`workspace member '${id}' has no indexed session header`) + } + return header + }, rememberSessionPath: (id, path) => { this.sessionPaths.set(id, path) this.missingSessionPaths.delete(id) diff --git a/packages/workspace/workspace/src/types.ts b/packages/workspace/workspace/src/types.ts index 1b09bef969..bd3ae0a3e4 100644 --- a/packages/workspace/workspace/src/types.ts +++ b/packages/workspace/workspace/src/types.ts @@ -6,7 +6,7 @@ */ import type { Branded } from '@deepseek-ai/dsh-brand' -import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session/types' import type { TypertResource } from '@deepseek-ai/dsh-typert-protocol' /** @@ -99,6 +99,13 @@ export interface Workspace { */ readonly sessionIds: readonly SessionId[] + /** + * Stored headers of {@link sessionIds}, in the same order. Read from the + * registry's startup and attach-time header index without persistence I/O; + * headers are immutable, so an indexed header never goes stale. + */ + readonly sessionHeaders: readonly SessionHeader[] + /** * Replace the display title durably. * @param title - New title; any string, duplicates across workspaces allowed. diff --git a/packages/workspace/workspace/tests/workspace.spec.ts b/packages/workspace/workspace/tests/workspace.spec.ts index 7c0a9e99e7..ddba94bb49 100644 --- a/packages/workspace/workspace/tests/workspace.spec.ts +++ b/packages/workspace/workspace/tests/workspace.spec.ts @@ -667,6 +667,7 @@ describe('Workspace session ordering', () => { expect(workspace.sessionIds).toEqual(['s2', 's1']) await workspace.attachSession(SessionId('s1')) expect(workspace.sessionIds).toEqual(['s2', 's1']) + expect(workspace.sessionHeaders).toEqual([header('s2', dir, 2), header('s1', dir, 1)]) expect(storedRecord(result.pool, workspace.id).sessionIds).toEqual(['s2', 's1']) }) @@ -890,6 +891,7 @@ describe('header-validated membership projection', () => { onTestFinished(() => result.ctx.fiber.dispose()) const workspace = result.registry.get(id)! expect(workspace.sessionIds).toEqual(['missing-dir']) + expect(workspace.sessionHeaders).toEqual([header('missing-dir', missing)]) await workspace.setTitle('Validated') expect(storedRecord(pool, id).sessionIds).toEqual(['missing-dir']) }) diff --git a/snapshots/session/session-list-tools/session.v4.jsonl b/snapshots/session/session-list-tools/session.v4.jsonl index 18b6788ea5..bd34f510b8 100644 --- a/snapshots/session/session-list-tools/session.v4.jsonl +++ b/snapshots/session/session-list-tools/session.v4.jsonl @@ -27,9 +27,9 @@ {"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"list-3"},"toolCallId":"list-3","content":[{"type":"text","text":"[{\"session_id\":\"list-beta\",\"title\":null,\"created_at\":\"1970-01-01T00:00:02.000Z\",\"updated_at\":\"1970-01-01T00:00:02.000Z\"},{\"session_id\":\"list-alpha\",\"title\":\"Alpha\",\"created_at\":\"1970-01-01T00:00:01.000Z\",\"updated_at\":\"1970-01-01T00:00:01.000Z\"}]"}],"isError":false,"id":"{{message:9}}"}},"sourceEventSeqs":[24],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} -{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"contain_subagent\":true,\"limit\":2}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"contain_subagent\":true,\"limit\":2}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":4,"callId":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"contain_subagent\":true,\"limit\":2}"}} -{"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"list-4"},"toolCallId":"list-4","content":[{"type":"text","text":"[{\"session_id\":\"list-child\",\"title\":null,\"created_at\":\"1970-01-01T00:00:04.000Z\",\"updated_at\":\"1970-01-01T00:00:04.000Z\"},{\"session_id\":\"list-beta\",\"title\":null,\"created_at\":\"1970-01-01T00:00:02.000Z\",\"updated_at\":\"1970-01-01T00:00:02.000Z\"}]"}],"isError":false,"id":"{{message:11}}"}},"sourceEventSeqs":[29],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":4,"callId":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1}"}} +{"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"list-4"},"toolCallId":"list-4","content":[{"type":"text","text":"[{\"session_id\":\"list-beta\",\"title\":null,\"created_at\":\"1970-01-01T00:00:02.000Z\",\"updated_at\":\"1970-01-01T00:00:02.000Z\"}]"}],"isError":false,"id":"{{message:11}}"}},"sourceEventSeqs":[29],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":4}} {"type":"step/start","data":{"turn":1,"step":5}} {"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-5","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"archived\":true}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-5","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"archived\":true}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/session-list-tools/tool-schemas.expected.json b/snapshots/session/session-list-tools/tool-schemas.expected.json index 0cc0d307b3..a7f800a4ac 100644 --- a/snapshots/session/session-list-tools/tool-schemas.expected.json +++ b/snapshots/session/session-list-tools/tool-schemas.expected.json @@ -249,17 +249,13 @@ }, { "name": "list_session", - "description": "List sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null.", + "description": "List non-subagent sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null.", "parameters": { "type": "object", "properties": { "workspace_id": { "type": "string", - "description": "Workspace ID from list_workspace. Includes its members and, when requested, subagents belonging through their nearest member ancestor. Omit to list all accessible sessions." - }, - "contain_subagent": { - "type": "boolean", - "description": "Include subagent sessions. Defaults to false." + "description": "Workspace ID from list_workspace. Lists only its member sessions. Omit to list sessions in every workspace and outside all workspaces." }, "archived": { "type": "boolean", From cd329ad22a64040116e2404989a06283b556e54e Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Wed, 11 Nov 2026 14:31:42 +0800 Subject: [PATCH 10/48] fix(session): align list tool release version and rescope skip Match the new package to the merged 0.2.2-rc.2 release version, and add the cua agent-scopes test to the exact-path rescope exceptions for its cordis preset id. --- packages/session-query/tool-session-list/package.json | 2 +- scripts/rescope-vendor.ts | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/session-query/tool-session-list/package.json b/packages/session-query/tool-session-list/package.json index 26ac358141..0c24c7fcae 100644 --- a/packages/session-query/tool-session-list/package.json +++ b/packages/session-query/tool-session-list/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tool-session-list", "description": "Read-only paginated Workspace and Session metadata tools", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/scripts/rescope-vendor.ts b/scripts/rescope-vendor.ts index 62259636b2..47cc146745 100644 --- a/scripts/rescope-vendor.ts +++ b/scripts/rescope-vendor.ts @@ -103,6 +103,7 @@ const GENERIC_SKIPS: readonly GenericSkip[] = [ { file: 'apps/web/tests/agent-preset-authoring.e2e.ts', upstream: ['cordis'] }, { file: 'apps/web/tests/creator-persona.e2e.ts', upstream: ['cordis'] }, { file: 'packages/preset/agent-preset-registry/tests/session.spec.ts', upstream: ['cordis'] }, + { file: 'packages/experimental/cua/tests/agent-scopes.spec.ts', upstream: ['cordis'] }, { file: 'packages/experimental/creation-recommendations/src/index.ts', upstream: ['cordis'] }, { file: 'packages/experimental/creation-recommendations/tests/creation.spec.ts', upstream: ['cordis'] }, { file: 'packages/experimental/creation-recommendations/tests/loader-composition.spec.ts', upstream: ['cordis'] }, From bb383263d8d244994cd709b42c61af49cf36f209 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Wed, 11 Nov 2026 14:17:28 +0800 Subject: [PATCH 11/48] refactor(llm): share extractTextContent across text consumers --- docs/config-catalog.md | 16 ++++---- docs/config-catalog.zh.md | 16 ++++---- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- docs/module-graph.md | 3 +- docs/module-graph.zh.md | 3 +- docs/persistence-catalog.i18n.yaml | 8 ++-- docs/persistence-catalog.md | 4 +- docs/persistence-catalog.zh.md | 4 +- docs/persistence-schema.json | 2 +- packages/bundle/headless/src/index.ts | 6 +-- .../src/client/conversation-nodes/command.ts | 5 +-- .../src/client/contract/system-prompt.ts | 3 +- .../src/client/queue/QueueDock.tsx | 5 ++- .../src/client/tool/toolviews/office-row.tsx | 3 +- .../session-reference/src/projection.ts | 10 ++--- packages/core/tool-executor-ptc/src/ptc.ts | 3 +- .../claude-code-mods/src/host-ops.ts | 9 ++-- .../claude-code-mods/src/index.ts | 11 ++--- .../client-ui-stats/src/client/stats-fold.ts | 12 ++---- .../experimental/forge-session/package.json | 1 + .../forge-session/src/projection.ts | 4 +- .../forge-session/src/reference-lookup.ts | 4 +- .../hooks-claude-code/src/index.ts | 10 ++--- .../experimental/hooks-codex/src/index.ts | 12 ++---- .../src/index.ts | 8 ++-- packages/llm/llm-deepseek/src/serialize.ts | 6 +-- packages/llm/llm-pi-ai/src/context.ts | 20 +++------ packages/llm/llm/README.i18n.yaml | 8 ++-- packages/llm/llm/README.md | 3 +- packages/llm/llm/README.zh.md | 3 +- packages/llm/llm/src/index.ts | 6 ++- packages/llm/llm/src/message.ts | 15 ++++++- packages/llm/llm/tests/message.spec.ts | 41 +++++++++++++++++++ packages/sdk/server/src/query-activity.ts | 4 +- .../src/index.ts | 8 ++-- packages/session/session-title/src/index.ts | 6 +-- packages/web/web-deepseek-api/src/index.ts | 5 ++- .../workflow/workflow-ptc/src/guest-source.ts | 2 +- packages/workflow/workflow-ptc/src/runtime.ts | 12 +----- 40 files changed, 166 insertions(+), 139 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 778476c08b..66b4ce105e 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1046,7 +1046,7 @@ export interface StagehandModelConfig { ## `@deepseek-ai/dsh-experimental-claude-code-mods` - `inject`: `workingDirectory` · `agents` -- `source`: [`packages/experimental/claude-code-mods/src/index.ts:53`](../packages/experimental/claude-code-mods/src/index.ts) +- `source`: [`packages/experimental/claude-code-mods/src/index.ts:54`](../packages/experimental/claude-code-mods/src/index.ts) ```ts config-catalog /** Plugin config: the limits mod hooks run under. */ @@ -1714,7 +1714,7 @@ export interface Config { - `inject`: `agentDefaultModel` · `agents` · `sessions` - `refs`: [`ApprovalPolicy`](subsystems/approval.md) -- `source`: [`packages/bundle/headless/src/index.ts:48`](../packages/bundle/headless/src/index.ts) +- `source`: [`packages/bundle/headless/src/index.ts:49`](../packages/bundle/headless/src/index.ts) ```ts config-catalog /** Plugin config: the task and run options resolved from this app's injected provider service. */ @@ -1762,7 +1762,7 @@ export interface HmrConfig extends ChokidarOptions { ## `@deepseek-ai/dsh-hooks-claude-code` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:50`](../packages/experimental/hooks-claude-code/src/index.ts) +- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:51`](../packages/experimental/hooks-claude-code/src/index.ts) ```ts config-catalog /** Plugin config: where the CC hook config lives + substitution roots. */ @@ -1801,7 +1801,7 @@ export interface Config { ## `@deepseek-ai/dsh-hooks-codex` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-codex/src/index.ts:49`](../packages/experimental/hooks-codex/src/index.ts) +- `source`: [`packages/experimental/hooks-codex/src/index.ts:50`](../packages/experimental/hooks-codex/src/index.ts) ```ts config-catalog /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */ @@ -3399,7 +3399,7 @@ export enum SessionTelemetryMode { ## `@deepseek-ai/dsh-session-title` - `inject`: `sessions` · `sessionProjections` · `agents` -- `source`: [`packages/session/session-title/src/index.ts:56`](../packages/session/session-title/src/index.ts) +- `source`: [`packages/session/session-title/src/index.ts:57`](../packages/session/session-title/src/index.ts) ```ts config-catalog /** Required deterministic fallback and accepted-title limits. */ @@ -3421,7 +3421,7 @@ export interface Config { - `inject`: `sessionTitle` · `llm` · `sessions` - `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts) -- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:28`](../packages/experimental/session-title-all-prompts-llm/src/index.ts) +- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:29`](../packages/experimental/session-title-all-prompts-llm/src/index.ts) ```ts config-catalog /** Required execution controls plus this provider's title-length targets; no defaults. */ @@ -3441,7 +3441,7 @@ export interface Config extends SessionTitleLlmConfig { - `inject`: `sessionTitle` · `llm` · `sessions` - `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts) -- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:28`](../packages/session/session-title-first-prompt-llm/src/index.ts) +- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:29`](../packages/session/session-title-first-prompt-llm/src/index.ts) ```ts config-catalog /** Required execution controls plus this provider's title-length targets; no defaults. */ @@ -4884,7 +4884,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-deepseek-api/src/index.ts:64`](../packages/web/web-deepseek-api/src/index.ts) +- `source`: [`packages/web/web-deepseek-api/src/index.ts:65`](../packages/web/web-deepseek-api/src/index.ts) ```ts config-catalog /** diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 29944e53bb..4df36f8825 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1048,7 +1048,7 @@ export interface StagehandModelConfig { ## `@deepseek-ai/dsh-experimental-claude-code-mods` - `inject`: `workingDirectory` · `agents` -- `source`: [`packages/experimental/claude-code-mods/src/index.ts:53`](../packages/experimental/claude-code-mods/src/index.ts) +- `source`: [`packages/experimental/claude-code-mods/src/index.ts:54`](../packages/experimental/claude-code-mods/src/index.ts) ```ts config-catalog /** Plugin config: the limits mod hooks run under. */ @@ -1716,7 +1716,7 @@ export interface Config { - `inject`: `agentDefaultModel` · `agents` · `sessions` - `refs`: [`ApprovalPolicy`](subsystems/approval.zh.md) -- `source`: [`packages/bundle/headless/src/index.ts:48`](../packages/bundle/headless/src/index.ts) +- `source`: [`packages/bundle/headless/src/index.ts:49`](../packages/bundle/headless/src/index.ts) ```ts config-catalog /** Plugin config: the task and run options resolved from this app's injected provider service. */ @@ -1764,7 +1764,7 @@ export interface HmrConfig extends ChokidarOptions { ## `@deepseek-ai/dsh-hooks-claude-code` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:50`](../packages/experimental/hooks-claude-code/src/index.ts) +- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:51`](../packages/experimental/hooks-claude-code/src/index.ts) ```ts config-catalog /** Plugin config: where the CC hook config lives + substitution roots. */ @@ -1803,7 +1803,7 @@ export interface Config { ## `@deepseek-ai/dsh-hooks-codex` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-codex/src/index.ts:49`](../packages/experimental/hooks-codex/src/index.ts) +- `source`: [`packages/experimental/hooks-codex/src/index.ts:50`](../packages/experimental/hooks-codex/src/index.ts) ```ts config-catalog /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */ @@ -3401,7 +3401,7 @@ export enum SessionTelemetryMode { ## `@deepseek-ai/dsh-session-title` - `inject`: `sessions` · `sessionProjections` · `agents` -- `source`: [`packages/session/session-title/src/index.ts:56`](../packages/session/session-title/src/index.ts) +- `source`: [`packages/session/session-title/src/index.ts:57`](../packages/session/session-title/src/index.ts) ```ts config-catalog /** Required deterministic fallback and accepted-title limits. */ @@ -3423,7 +3423,7 @@ export interface Config { - `inject`: `sessionTitle` · `llm` · `sessions` - `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts) -- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:28`](../packages/experimental/session-title-all-prompts-llm/src/index.ts) +- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:29`](../packages/experimental/session-title-all-prompts-llm/src/index.ts) ```ts config-catalog /** Required execution controls plus this provider's title-length targets; no defaults. */ @@ -3443,7 +3443,7 @@ export interface Config extends SessionTitleLlmConfig { - `inject`: `sessionTitle` · `llm` · `sessions` - `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts) -- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:28`](../packages/session/session-title-first-prompt-llm/src/index.ts) +- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:29`](../packages/session/session-title-first-prompt-llm/src/index.ts) ```ts config-catalog /** Required execution controls plus this provider's title-length targets; no defaults. */ @@ -4886,7 +4886,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-deepseek-api/src/index.ts:64`](../packages/web/web-deepseek-api/src/index.ts) +- `source`: [`packages/web/web-deepseek-api/src/index.ts:65`](../packages/web/web-deepseek-api/src/index.ts) ```ts config-catalog /** diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index aa42c78c51..17f0edb61c 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -60,7 +60,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index bdda966741..58d3f9819c 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -62,7 +62,7 @@ | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | diff --git a/docs/module-graph.md b/docs/module-graph.md index 623e1664ff..3e59e9c953 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -1147,6 +1147,7 @@ flowchart TD pkg_experimental_auto_review --> pkg_tools pkg_experimental_auto_review --> pkg_working_directory pkg_experimental_forge_session --> pkg_experimental_forge + pkg_experimental_forge_session --> pkg_llm pkg_experimental_forge_session --> pkg_sandbox_policy pkg_experimental_forge_session --> pkg_session pkg_experimental_forge_session --> pkg_session_projection @@ -1877,7 +1878,7 @@ flowchart TD | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | | [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | +| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | | [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | | [`tool-cordis`](../packages/extensions/tool-cordis) | `extensions` | [`agent`](../packages/core/agent), [`app-boot`](../packages/boot/app-boot), [`cordis-host-runner`](../packages/extensions/cordis-host-runner), [`tools`](../packages/core/tools) | | [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`brand`](../packages/util/brand), [`typert-protocol`](../packages/typert/protocol) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index fd754de0b4..311c6d06e6 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -1149,6 +1149,7 @@ flowchart TD pkg_experimental_auto_review --> pkg_tools pkg_experimental_auto_review --> pkg_working_directory pkg_experimental_forge_session --> pkg_experimental_forge + pkg_experimental_forge_session --> pkg_llm pkg_experimental_forge_session --> pkg_sandbox_policy pkg_experimental_forge_session --> pkg_session pkg_experimental_forge_session --> pkg_session_projection @@ -1879,7 +1880,7 @@ flowchart TD | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | | [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | +| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | | [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | | [`tool-cordis`](../packages/extensions/tool-cordis) | `extensions` | [`agent`](../packages/core/agent), [`app-boot`](../packages/boot/app-boot), [`cordis-host-runner`](../packages/extensions/cordis-host-runner), [`tools`](../packages/core/tools) | | [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`brand`](../packages/util/brand), [`typert-protocol`](../packages/typert/protocol) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index f2294edff6..15315a1b41 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -183,8 +183,8 @@ en: 20645a60e921f012 zh: 7141cafe3a0e71d7 /session-persistence-event-catalog/events/session/session-title-log-only: - en: 6c6a27578dff5828 - zh: 9a5add2bc0df2d0a + en: 5775e52a72c0ce94 + zh: fa211a35b4660c10 /session-persistence-event-catalog/events/session/session-title-llm-request-log-only: en: 59b02baa2be32ca0 zh: 3637c99652ca89cf @@ -1368,8 +1368,8 @@ en: 4147b170f52814af zh: e78991ac1c41ebec /session-persistence-event-catalog/resolved-persistence-types/string: - en: ef89e74973f4a575 - zh: 0bb1564a0418501c + en: 396943de139bab31 + zh: 59c676f614b39c2a /session-persistence-event-catalog/resolved-persistence-types/string~2: en: 0089620bf4638263 zh: 1922bef1713094bb diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 33d9aa4395..3713b7f10c 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -865,7 +865,7 @@ Source: [`packages/core/session/src/types.ts:435`](../packages/core/session/src/ Types: [SessionTitleEventData](subsystems/session-title.md) -Source: [`packages/session/session-title/src/index.ts:77`](../packages/session/session-title/src/index.ts) +Source: [`packages/session/session-title/src/index.ts:78`](../packages/session/session-title/src/index.ts) @@ -5659,7 +5659,7 @@ Array of `number`. SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -Sources: [`packages/api/session-controller/src/types.ts:391`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:391`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:43`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 5047ebc659..8da066bf73 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -867,7 +867,7 @@ export type SessionEvent = { 类型:[SessionTitleEventData](subsystems/session-title.zh.md) -来源:[`packages/session/session-title/src/index.ts:77`](../packages/session/session-title/src/index.ts) +来源:[`packages/session/session-title/src/index.ts:78`](../packages/session/session-title/src/index.ts) @@ -5661,7 +5661,7 @@ SHA-256: `5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78` SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -来源:[`packages/api/session-controller/src/types.ts:391`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:391`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:43`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index a2832eb98c..b753ba4cb8 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -259,7 +259,7 @@ {"digest":"4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731","names":["packages/llm/llm/src/message.ts#ToolResultMessage"],"sources":["packages/llm/llm/src/message.ts:173"]}, {"digest":"4b7ddaf3710b88ff9b8df66304f5f97bf03688fd19730eedc2e9535203c820ea","names":[],"sources":[]}, {"digest":"4bb451330ff699f36b45539ceb0eb2606ead72084e2c5bb637c36cc80e2252db","names":[],"sources":["packages/core/session/src/types.ts:198"]}, - {"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/index.ts#SessionTitleProviderId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/team/agent-team/src/types.ts#TeamId","packages/team/agent-team/src/types.ts#TeamMessageId","packages/team/agent-team/src/types.ts#TeamTaskId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:391","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:31","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:19","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/index.ts:42","packages/session/session-title/src/types.ts:17","packages/team/agent-team/src/types.ts:20","packages/team/agent-team/src/types.ts:32","packages/team/agent-team/src/types.ts:8","packages/workflow/workflow/src/types.ts:13"]}, + {"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/index.ts#SessionTitleProviderId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/team/agent-team/src/types.ts#TeamId","packages/team/agent-team/src/types.ts#TeamMessageId","packages/team/agent-team/src/types.ts#TeamTaskId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:391","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:31","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:19","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/index.ts:43","packages/session/session-title/src/types.ts:17","packages/team/agent-team/src/types.ts:20","packages/team/agent-team/src/types.ts:32","packages/team/agent-team/src/types.ts:8","packages/workflow/workflow/src/types.ts:13"]}, {"digest":"4d60dddaa65d3da8d4cd014d85ce3d2c2875664dd0433e331d8e9d395289686b","names":["packages/experimental/liveshare/src/host/viewer-principal.ts#ShareViewerPrincipal"],"sources":["packages/experimental/liveshare/src/host/viewer-principal.ts:24"]}, {"digest":"4e011753f8263f436efaabfbb3b4db53a98fc55342c5ded2daf7208b217be159","names":[],"sources":[]}, {"digest":"4e44c9118152f6829634bfd508e47669ab0497caffa380c94b4be91f9390d35d","names":[],"sources":[]}, diff --git a/packages/bundle/headless/src/index.ts b/packages/bundle/headless/src/index.ts index bc98d7ae6b..69b40ac06a 100644 --- a/packages/bundle/headless/src/index.ts +++ b/packages/bundle/headless/src/index.ts @@ -18,6 +18,7 @@ import type { Agent, AgentOptions } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-agent-default-model' import { installModelSelection } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-fs' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { APPROVAL_POLICIES, setApprovalPolicy, type ApprovalPolicy } from '@deepseek-ai/dsh-user-approval' import { assertNever } from '@deepseek-ai/dsh-util-values' @@ -99,10 +100,7 @@ function summarize(session: Session, firstSeq: SessionLogOffset): RunOutcome { } if (!started) continue if (event.type === 'assistant/message') { - const joined = event.data.message.content - .filter(block => block.type === 'text') - .map(block => block.text) - .join('') + const joined = extractTextContent(event.data.message.content) if (joined !== '') text = joined } if (event.type === 'turn/end') reason = event.data.reason diff --git a/packages/client/ui-chat/src/client/conversation-nodes/command.ts b/packages/client/ui-chat/src/client/conversation-nodes/command.ts index a52b877552..de407aa354 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/command.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/command.ts @@ -1,3 +1,4 @@ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { Context } from '@deepseek-ai/cordis' import type { CommandNode, CompactionSummaryNode, ConversationMatch, ConversationNodeContext, ConversationNodeDefinition, @@ -105,9 +106,7 @@ function compactSummary(match: ConversationMatch | undefined, checkpoint: Conver if (match?.event.type === 'compaction/summary') { const data = match.event.data if (Array.isArray(data.summary)) { - const text = data.summary - .map(block => block.type === 'text' ? block.text : '') - .join('') + const text = extractTextContent(data.summary) summary = text.trim() === '' ? null : text } shadowedItemCount = Array.isArray(data.shadowedSeqs) diff --git a/packages/client/ui-conversation/src/client/contract/system-prompt.ts b/packages/client/ui-conversation/src/client/contract/system-prompt.ts index e61b35d81b..3ac1fadcc7 100644 --- a/packages/client/ui-conversation/src/client/contract/system-prompt.ts +++ b/packages/client/ui-conversation/src/client/contract/system-prompt.ts @@ -1,4 +1,5 @@ /** Immutable system-only interpretation of the loaded Session surface. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { SessionEvent } from '@deepseek-ai/dsh-session/types' import { isSurfaceEvent } from '@deepseek-ai/dsh-session/surface' import type { SystemPromptNode } from './request-inspection.ts' @@ -61,7 +62,7 @@ export function inspectSystemPrompt(previous: SystemPromptState | undefined, eve time: event.time, turn: event.data.turn, step: event.data.step, - text: event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join(''), + text: extractTextContent(event.data.message.content), update: op === 'append' && previous?.nodes.some(item => item.node.text !== '') === true, } : undefined diff --git a/packages/client/ui-conversation/src/client/queue/QueueDock.tsx b/packages/client/ui-conversation/src/client/queue/QueueDock.tsx index 6396387a91..420dcff49f 100644 --- a/packages/client/ui-conversation/src/client/queue/QueueDock.tsx +++ b/packages/client/ui-conversation/src/client/queue/QueueDock.tsx @@ -1,3 +1,4 @@ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { Context } from '@deepseek-ai/cordis' import { useEffect, useId, useMemo, useState } from 'react' import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' @@ -23,7 +24,7 @@ const QUEUE_TEXT_FACTS: Readonly> = { function textOf(content: InboxState['next-turn'][number]['content']): string | null { if (!content.every(block => block.type === 'text')) return null - return content.map(block => block.text).join('') + return extractTextContent(content) } /** Queue operations injected by the session-scoped registration. */ @@ -228,7 +229,7 @@ export function QueueDock({ useSession, useProjection, updateQueue, notify, load )} {renderFactorySlot('conversation.user.text', { - text: row.content.filter(block => block.type === 'text').map(block => block.text).join(''), + text: extractTextContent(row.content), facts: QUEUE_TEXT_FACTS, interactive: false, ellipsis: true, })} diff --git a/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx b/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx index e52ff7d10f..c3e14750fe 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx +++ b/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx @@ -1,6 +1,7 @@ // Office toolview links target the input, not the temporary output. Rows show the // result's text blocks; rendered page images reach the model but are not displayed. +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { IconBrowseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { Context } from '@deepseek-ai/cordis' import { toolFileInject } from '../file-menu.ts' @@ -26,7 +27,7 @@ export function OfficeRow({ const row = toolRowModel(toolName, block, cwd, home) // Image blocks flatten to JSON attachment references, so a settled result with only images shows no body. const output = 'kind' in block - ? block.content.flatMap(part => part.type === 'text' ? [part.text] : []).join('\n') || null + ? extractTextContent(block.content, { separator: '\n' }) || null : row.output const path = office.filePath return ( diff --git a/packages/context/session-reference/src/projection.ts b/packages/context/session-reference/src/projection.ts index 196c75b4e1..f747f242c3 100644 --- a/packages/context/session-reference/src/projection.ts +++ b/packages/context/session-reference/src/projection.ts @@ -1,5 +1,7 @@ /** Current-surface projection and byte-bounded rendering. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import { isCompactCheckpointSource } from '@deepseek-ai/dsh-compaction' import type { SessionSurfaceSnapshot } from '@deepseek-ai/dsh-session-query' import { TextRetainer } from '@deepseek-ai/dsh-output-retention' @@ -42,12 +44,12 @@ function projectSessionConversation(snapshot: SessionSurfaceSnapshot): Projected case 'user/message': { const checkpoint = isCompactCheckpointSource(event.data.source) if (!checkpoint && event.data.source.kind !== 'user') break - const text = textContent(event.data.content) + const text = extractTextContent(event.data.content, { separator: '\n' }) if (text !== '') conversation.push({ role: 'user', text, checkpoint, originalText: text, omittedBytes: 0 }) break } case 'assistant/message': { - const text = textContent(event.data.message.content) + const text = extractTextContent(event.data.message.content, { separator: '\n' }) if (text !== '') conversation.push({ role: 'assistant', text, checkpoint: false, originalText: text, omittedBytes: 0 }) break } @@ -145,10 +147,6 @@ export function retainReferencedSession( } } -function textContent(content: readonly { type: string; text?: string }[]): string { - return content.flatMap(block => block.type === 'text' && typeof block.text === 'string' ? [block.text] : []).join('\n') -} - function truncateWithNotice(text: string, maxOutputBytes: number): { text: string; omittedBytes: number } { /* v8 ignore next -- callers invoke this only with a target smaller than the selected original text. */ if (Buffer.byteLength(text, 'utf8') <= maxOutputBytes) return { text, omittedBytes: 0 } diff --git a/packages/core/tool-executor-ptc/src/ptc.ts b/packages/core/tool-executor-ptc/src/ptc.ts index 7fa2b79c78..ce3202e2b9 100644 --- a/packages/core/tool-executor-ptc/src/ptc.ts +++ b/packages/core/tool-executor-ptc/src/ptc.ts @@ -10,6 +10,7 @@ import { isDeepStrictEqual } from 'node:util' import type { PtcDispatchLog } from './runtime-types.ts' import { symbols, type Context } from '@deepseek-ai/cordis' import { brandString } from '@deepseek-ai/dsh-brand' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage, HarnessError, resolveImageAttachmentAccess } from '@deepseek-ai/dsh-llm' import type { ContentBlock, ToolCallId, ToolSchema } from '@deepseek-ai/dsh-llm' @@ -704,7 +705,7 @@ export function createRunCodeTransport( if (first !== undefined && images.length === 1) return programImage(first.attachment) if (outcome.imageRemoved) { throw new Error('Image output was removed by a tool output policy.\n' - + outcome.content.filter(block => block.type === 'text').map(block => block.text).join('\n')) + + extractTextContent(outcome.content, { separator: '\n' })) } if (name === 'read_image' || images.length > 1) throw new Error('Image-producing tools must return exactly one image') } diff --git a/packages/experimental/claude-code-mods/src/host-ops.ts b/packages/experimental/claude-code-mods/src/host-ops.ts index 47bf900671..0968717709 100644 --- a/packages/experimental/claude-code-mods/src/host-ops.ts +++ b/packages/experimental/claude-code-mods/src/host-ops.ts @@ -14,6 +14,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-subprocess' import type { CommandDefinition } from '@deepseek-ai/dsh-commands' import type { FileSystem, FsTarget } from '@deepseek-ai/dsh-fs' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage, ToolCallId } from '@deepseek-ai/dsh-llm' import type { ContentBlock, Message } from '@deepseek-ai/dsh-llm' import { scopeOf } from '@deepseek-ai/dsh-scope' @@ -106,17 +107,13 @@ function requireAgent(context: OpContext, op: string): Agent { return agent } -function textOf(content: readonly ContentBlock[]): string { - return content.filter((block): block is Extract => block.type === 'text').map(block => block.text).join('') -} - /** * Project one tool outcome onto Claude Code's `tool.call` result. * @param result - the harness tool outcome. * @returns its text as `result`, with `isError` on a failure. */ export function toolCallResultOf(result: ToolExecutionResult): ToolCallResult { - return result.isError ? { result: textOf(result.content), isError: true } : { result: textOf(result.content) } + return result.isError ? { result: extractTextContent(result.content), isError: true } : { result: extractTextContent(result.content) } } /** The model's raw JSON arguments as an object; an unparsable string is an empty input. */ @@ -136,7 +133,7 @@ function sessionMessages(messages: readonly Message[], aliases: ToolNameAliases) const toolUses = message.content .filter((block): block is Extract => block.type === 'tool-call') .map(block => ({ tool_use_id: block.id, tool: aliases.toMod(block.name), input: argumentsOf(block.arguments) })) - out.push({ role: message.role, text: textOf(message.content), toolUses }) + out.push({ role: message.role, text: extractTextContent(message.content), toolUses }) } return out } diff --git a/packages/experimental/claude-code-mods/src/index.ts b/packages/experimental/claude-code-mods/src/index.ts index bcce9050c3..61a2f52435 100644 --- a/packages/experimental/claude-code-mods/src/index.ts +++ b/packages/experimental/claude-code-mods/src/index.ts @@ -15,7 +15,8 @@ import type {} from '@deepseek-ai/dsh-working-directory' import z from '@deepseek-ai/schemastery' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' -import type { AssistantMessage, ContentBlock, TokenUsage } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' +import { type AssistantMessage, type ContentBlock, type TokenUsage } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' import type { UserMessage } from '@deepseek-ai/dsh-session' import { scopeOf } from '@deepseek-ai/dsh-scope' @@ -77,10 +78,6 @@ function assertPositive(field: string, value: number): void { if (!Number.isFinite(value) || value <= 0) throw new Error(`claude-code-mods: ${field} must be a positive number of milliseconds`) } -function textOf(blocks: readonly ContentBlock[]): string { - return blocks.filter((block): block is Extract => block.type === 'text').map(block => block.text).join('') -} - /** The human's own messages among a claim: the prompt a `prompt.submit` hook sees and may rewrite. */ function promptMessages(claimed: readonly UserMessage[]): UserMessage[] { return claimed.filter(message => message.source.kind === 'user') @@ -140,7 +137,7 @@ interface TurnRecord { /** Fold one committed assistant message into the turn's answer and usage. */ function foldAssistantMessage(turnRecord: TurnRecord, data: { message: AssistantMessage; usage?: TokenUsage }): void { - turnRecord.answer = textOf(data.message.content) + turnRecord.answer = extractTextContent(data.message.content) if (data.usage === undefined) return const { model } = data.message.source const usage = turnRecord.usage ?? { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, model } @@ -348,7 +345,7 @@ export class ClaudeCodeMods extends TypertRemoteService { const first = !started.has(turn) started.add(turn) const prompt = promptMessages(messages) - const text = textOf(prompt.flatMap(message => message.content)) + const text = extractTextContent(prompt.flatMap(message => message.content)) let submitted: PromptSubmitResult = { text } // A batch of injected context alone is not a prompt: Claude Code raises prompt.submit for typed prompts. if (prompt.length > 0) { diff --git a/packages/experimental/client-ui-stats/src/client/stats-fold.ts b/packages/experimental/client-ui-stats/src/client/stats-fold.ts index 365a7873f1..fd7c6d78e8 100644 --- a/packages/experimental/client-ui-stats/src/client/stats-fold.ts +++ b/packages/experimental/client-ui-stats/src/client/stats-fold.ts @@ -1,5 +1,6 @@ /** Event folding and per-step metric derivation for the Statistics table. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { SessionEventLike } from '@deepseek-ai/dsh-api-session-controller/client' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { AssistantMessage, ContentBlock, StreamChunk, UserMessage } from '@deepseek-ai/dsh-llm' @@ -267,10 +268,7 @@ const OPAQUE_SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9 export function triggerSenderOf(message: UserMessage): string | null { const kind: string = message.source.kind if (kind !== 'agent-message' && kind !== 'team-message') return null - let text = '' - for (const block of message.content) { - if (block.type === 'text') text += block.text - } + const text = extractTextContent(message.content) const team = TEAM_MESSAGE_PREFIX.exec(text) /* v8 ignore next -- a matched capture group is always present. */ if (team !== null) return team[1]?.trim() ?? null @@ -291,11 +289,7 @@ function answerOf(message: AssistantMessage): { body: string truncated: boolean } | null { - const parts: string[] = [] - for (const block of message.content) { - if (block.type === 'text') parts.push(block.text) - } - const text = parts.join('\n').trim() + const text = extractTextContent(message.content, { separator: '\n' }).trim() if (text === '') return null return { preview: text.length > ANSWER_LIMIT ? text.slice(0, ANSWER_LIMIT) : text, diff --git a/packages/experimental/forge-session/package.json b/packages/experimental/forge-session/package.json index 18d8274446..8819ada7bb 100644 --- a/packages/experimental/forge-session/package.json +++ b/packages/experimental/forge-session/package.json @@ -43,6 +43,7 @@ }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-experimental-forge": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", diff --git a/packages/experimental/forge-session/src/projection.ts b/packages/experimental/forge-session/src/projection.ts index 1f1ab54a43..0a285de34d 100644 --- a/packages/experimental/forge-session/src/projection.ts +++ b/packages/experimental/forge-session/src/projection.ts @@ -1,5 +1,7 @@ /** Projection that folds shell results and binding records into one Session's change request bindings, and shows clients the bindings. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import { z } from 'zod' import { pluginRecordOf, SessionSeq } from '@deepseek-ai/dsh-session' import type { SessionEvent, SessionEventMap } from '@deepseek-ai/dsh-session' @@ -105,7 +107,7 @@ function applyResult(state: ForgeChangeRequestsState, result: SessionEventMap['t if (pending === undefined) return state const rest = state.pending.filter(entry => entry !== pending) if (result.message.isError === true) return { ...state, pending: rest } - const text = result.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n') + const text = extractTextContent(result.message.content, { separator: '\n' }) const printed = pending.urls === 'created' ? changeRequestUrls(text) : ownChangeRequestUrls(text) return { pending: rest, diff --git a/packages/experimental/forge-session/src/reference-lookup.ts b/packages/experimental/forge-session/src/reference-lookup.ts index 7cce3eb6dc..b648911c58 100644 --- a/packages/experimental/forge-session/src/reference-lookup.ts +++ b/packages/experimental/forge-session/src/reference-lookup.ts @@ -1,5 +1,7 @@ /** Resolve unqualified CLI references in the shell execution world and persist only confirmed URLs. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import type { Context } from '@deepseek-ai/cordis' import type { Session } from '@deepseek-ai/dsh-session' import type { ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools' @@ -53,7 +55,7 @@ export function observeReferences(ctx: Context, timeoutMs: number, record: (sess const argumentsResult = shellArguments.safeParse(exec.arguments) const shell = completedShell.safeParse(result.value) if (!argumentsResult.success || !shell.success) return - const printed = result.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n') + const printed = extractTextContent(result.content, { separator: '\n' }) if (ownChangeRequestUrls(printed).length > 0) return const lookups = ghReferences(argumentsResult.data.command).flatMap(reference => reference.lookup === null ? [] : [reference.lookup]) const agent = exec.agent diff --git a/packages/experimental/hooks-claude-code/src/index.ts b/packages/experimental/hooks-claude-code/src/index.ts index 5e2b59d3d8..2541297e3d 100644 --- a/packages/experimental/hooks-claude-code/src/index.ts +++ b/packages/experimental/hooks-claude-code/src/index.ts @@ -13,6 +13,7 @@ import { readFileSync } from 'node:fs' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' declare module '@deepseek-ai/dsh-llm' { @@ -319,11 +320,6 @@ function lastTurn(ctx: Context, agent: Agent | undefined): number { return ctx.agents.turnBoundaryOf(agent.session).lastTurn } -/** Flatten content blocks to the text a hook payload carries (the common case). */ -function blocksToText(content: ContentBlock[]): string { - return content.filter((b): b is Extract => b.type === 'text').map(b => b.text).join('') -} - function base(agent: Agent | undefined, event: string): Record { return { session_id: agent?.session.header.id ?? '', @@ -338,13 +334,13 @@ function sessionStartPayload(agent: Agent, source: string): Record { - return { ...base(agent, 'UserPromptSubmit'), prompt: blocksToText(content) } + return { ...base(agent, 'UserPromptSubmit'), prompt: extractTextContent(content) } } function preToolPayload(exec: ToolExecution): Record { return { ...base(exec.agent, 'PreToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId } } function postToolPayload(exec: ToolExecution, result: ToolExecutionResult): Record { - return { ...base(exec.agent, 'PostToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId, tool_response: blocksToText(result.content) } + return { ...base(exec.agent, 'PostToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId, tool_response: extractTextContent(result.content) } } function stopPayload(agent: Agent): Record { return { ...base(agent, 'Stop'), stop_hook_active: false } diff --git a/packages/experimental/hooks-codex/src/index.ts b/packages/experimental/hooks-codex/src/index.ts index 2d9b3c3daf..6d86ae79f3 100644 --- a/packages/experimental/hooks-codex/src/index.ts +++ b/packages/experimental/hooks-codex/src/index.ts @@ -16,6 +16,7 @@ import { readFileSync } from 'node:fs' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' declare module '@deepseek-ai/dsh-llm' { @@ -203,7 +204,7 @@ export function apply(ctx: Context, config: Config): void { const payload = { ...base(agent, 'UserPromptSubmit', model), turn_id: String(turn), - prompt: blocksToText(messages.flatMap(message => message.content)), + prompt: extractTextContent(messages.flatMap(message => message.content)), } const merged = await runPoint('UserPromptSubmit', '', payload, { agent, turn, plainStdoutAsContext: true, signal, @@ -275,17 +276,12 @@ export function apply(ctx: Context, config: Config): void { // --- Codex DIALECT payloads: snake_case, model on every event, turn_id on // turn-scoped events. --- -// These small payload helpers intentionally remain next to the dialect shape; -// sharing them would pull bridge-only agent/LLM dependencies into hook-protocol. +// Shared hook-protocol code has no Agent dependency, so turn lookup stays in the bridge. /* jscpd:ignore-start */ function lastTurn(ctx: Context, agent: Agent | undefined): number { if (!agent) return 0 return ctx.agents.turnBoundaryOf(agent.session).lastTurn } - -function blocksToText(content: ContentBlock[]): string { - return content.filter((b): b is Extract => b.type === 'text').map(b => b.text).join('') -} /* jscpd:ignore-end */ /** Base fields on every Codex payload (no turn_id). */ @@ -324,5 +320,5 @@ function preToolPayload(ctx: Context, exec: ToolExecution, model: string): Recor } function postToolPayload(ctx: Context, exec: ToolExecution, result: ToolExecutionResult, model: string): Record { - return { ...turnBase(ctx, exec.agent, 'PostToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId, tool_response: blocksToText(result.content) } + return { ...turnBase(ctx, exec.agent, 'PostToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId, tool_response: extractTextContent(result.content) } } diff --git a/packages/experimental/session-title-all-prompts-llm/src/index.ts b/packages/experimental/session-title-all-prompts-llm/src/index.ts index a88ba63695..5b48816e9c 100644 --- a/packages/experimental/session-title-all-prompts-llm/src/index.ts +++ b/packages/experimental/session-title-all-prompts-llm/src/index.ts @@ -3,7 +3,8 @@ /* jscpd:ignore-start -- both shipped providers import the same shared packages. */ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import type { LlmResolvedModelInfo, ReasoningEffortId } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' +import { type LlmResolvedModelInfo, type ReasoningEffortId } from '@deepseek-ai/dsh-llm' import { assertNever } from '@deepseek-ai/dsh-util-values' import { normalizeSessionTitle, @@ -136,10 +137,7 @@ function titleFromResponse(response: SessionTitleLlmResponse): string { if (response.blocks.some(block => block.type === 'tool-call')) { throw new Error('session-title-llm: title output must contain text only') } - const text = response.blocks - .filter((block): block is Extract<(typeof response.blocks)[number], { type: 'text' }> => block.type === 'text') - .map(block => block.text) - .join(' ') + const text = extractTextContent(response.blocks, { separator: ' ' }) const title = normalizeSessionTitle(titleFromOutput(text), Number.MAX_SAFE_INTEGER) if (title.length === 0) throw new Error('session-title-llm: title model produced no text') return title diff --git a/packages/llm/llm-deepseek/src/serialize.ts b/packages/llm/llm-deepseek/src/serialize.ts index f08412c0e9..ab5e0f75d7 100644 --- a/packages/llm/llm-deepseek/src/serialize.ts +++ b/packages/llm/llm-deepseek/src/serialize.ts @@ -1,5 +1,6 @@ /** Map system snapshots, tool changes, and conversation turns to Messages using the configured route capability. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { LlmError, requestImageHandleText } from '@deepseek-ai/dsh-llm' import type { ContentBlock, GenerateOptions, ImageAttachmentAccessResolver, Message, RequestMessage } from '@deepseek-ai/dsh-llm' import type { ImageAttachmentRef, RequestImageAttachment } from '@deepseek-ai/dsh-attachment' @@ -104,9 +105,8 @@ export function serialize( return unsupported('tool-change blocks outside developer messages') } if (message.role === 'system') { - const texts = message.content.filter(block => block.type === 'text') - if (texts.length !== message.content.length) return unsupported('non-text system message') - const text = texts.map(block => block.text).join('') + if (message.content.some(block => block.type !== 'text')) return unsupported('non-text system message') + const text = extractTextContent(message.content) if (inHistory && messages.length > 0) { if (text.length === 0) return unsupported('empty in-history system update') systemUpdates.push({ role: 'system', content: [{ type: 'text', text }] }) diff --git a/packages/llm/llm-pi-ai/src/context.ts b/packages/llm/llm-pi-ai/src/context.ts index b77fda933c..95179f5ab1 100644 --- a/packages/llm/llm-pi-ai/src/context.ts +++ b/packages/llm/llm-pi-ai/src/context.ts @@ -5,6 +5,7 @@ */ import { brandString } from '@deepseek-ai/dsh-brand' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { contentHasImage, IMAGE_OFFLOAD_REQUIRED_CODE, LlmError, offloadedImageText, projectOffloadedImages, requestImageHandleText, requiredImageOffload } from '@deepseek-ai/dsh-llm' import type { ContentBlock, GenerateOptions, ImageAttachmentAccessResolver, Message, RequestMessage, ToolCallId } from '@deepseek-ai/dsh-llm' import type { @@ -20,15 +21,6 @@ import type { PrefixDigests } from './prefix-binding.ts' import { requestImageDimensions } from '@deepseek-ai/dsh-attachment' import { DEFAULT_REQUEST_IMAGE_MAX_BYTES, DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET } from './config.ts' -/** Join the text blocks of a harness message. */ -function flattenText(message: RequestMessage): string { - return message.content - .filter(block => block.type === 'text') - .map(block => block.text) - .join('') -} - - /** Recover the pi-ai toolResult message for one harness tool-role message. */ function toolResultOf( message: Extract, @@ -94,7 +86,7 @@ function userContent( break } } - if (content.every(block => block.type === 'text')) return content.map(block => block.text).join('') + if (content.every(block => block.type === 'text')) return extractTextContent(content) return content } @@ -151,7 +143,7 @@ function splitSystemPrompt(options: GenerateOptions): SystemPromptSplit { let end = 0 for (const message of options.messages) { if (message.role !== 'system') break - text.push(flattenText(message)) + text.push(extractTextContent(message.content)) end++ } const systemPrompt = text.filter(Boolean).join('\n\n') @@ -230,7 +222,7 @@ function appendSharedHistory( return true } if (message.role === 'system') { - const content = flattenText(message) + const content = extractTextContent(message.content) if (content.length > 0) { if (supportsMidConvoSystemMessages) { messages.push({ role: 'system', content, timestamp: 0 }) @@ -264,10 +256,10 @@ function textOnlyContext( } if (appendSharedHistory(message, options, messages, toolNames, supportsMidConvoSystemMessages, onReplayDegrade, prefixDigests)) continue if (message.role === 'tool') { - messages.push(toolResultOf(message, toolNames, flattenText(message))) + messages.push(toolResultOf(message, toolNames, extractTextContent(message.content))) continue } - messages.push({ role: 'user', content: flattenText(message), timestamp: 0 }) + messages.push({ role: 'user', content: extractTextContent(message.content), timestamp: 0 }) } return piContext(split.systemPrompt, options, messages) } diff --git a/packages/llm/llm/README.i18n.yaml b/packages/llm/llm/README.i18n.yaml index d131c176a8..a740cc3d2e 100644 --- a/packages/llm/llm/README.i18n.yaml +++ b/packages/llm/llm/README.i18n.yaml @@ -24,8 +24,8 @@ en: cf221d60fb42a278 zh: 0ea17503495d386b /deepseek-ai-dsh-llm/use-this-package/what-you-can-do: - en: dc61eb86585f6e0d - zh: 9c0d6b240dfd2cda + en: cb9f0c6ee3203ab3 + zh: 8513340a40192513 /deepseek-ai-dsh-llm/use-this-package/failures-and-recovery: en: 47f4dab3c377a4cd zh: 49ac1c366de19136 @@ -36,8 +36,8 @@ en: 12d0444c18a397c7 zh: 9d4a5468b4bb7fcd /deepseek-ai-dsh-llm/understand-the-implementation/source-map: - en: ae1618577f4e8364 - zh: a6e8ab1563c08dfb + en: 8ec1ca8903e09bc0 + zh: 77c7bc3413cbab1c /deepseek-ai-dsh-llm/understand-the-implementation/main-flow: en: c95d4947745e39bb zh: ec37b969f27629e2 diff --git a/packages/llm/llm/README.md b/packages/llm/llm/README.md index 25718cdca3..ddba38e4da 100644 --- a/packages/llm/llm/README.md +++ b/packages/llm/llm/README.md @@ -83,6 +83,7 @@ const configure = (maxTokens: number): ConfigureCall => ### What you can do +- **Extract content text** — `extractTextContent(content, options?)` from `@deepseek-ai/dsh-llm/message` joins only `text` blocks in order, preserving whitespace and empty text blocks while omitting all other block types without placeholders. The optional `options.separator` defaults to `''`. It accepts read-only content and returns `''` when no text blocks exist. - **Stream one model call** — `ctx.llm.stream(options)` yields raw chunks (token-level deltas) for any registered provider and model; consumers assemble them with `BlockAssembler`. - **Register provider adapters** — an adapter owns one or more provider routes, and its registration captures that route's retry policy; registering the same route twice fails with `DUPLICATE_ADAPTER`. - **Expose and activate providers through configuration** — adapters declare configurable-provider routes plus a settings namespace, so configuration surfaces can activate dormant providers and edit connection facts without a restart. `LlmConfigurableProvider.error` reports a configuration diagnostic for repair; unaffected models can remain serviceable. An entry can also carry `defaultBaseURL`, the endpoint the adapter uses when the profile sets none, and `nativeAuth`, the environment variables and OAuth sign-in that the adapter's authentication reads when the profile names no credential reference; `baseURLEnv` lists environment variables used to configure the endpoint. Configuration UIs read these fields from the directory without calling the adapter. @@ -114,7 +115,7 @@ The service is built on one separation: **the logical contract is provider-neutr |---|---| | [`src/index.ts`](src/index.ts) | The `LlmRuntime` service: adapter registry, configurable-provider directory, model discovery, call preparation, and the streaming boundary | | [`src/types.ts`](src/types.ts) | The `StreamChunk` protocol, content-block map, finish reasons, and shared vocabulary | -| [`src/message.ts`](src/message.ts) | Immutable message constructors shared by delivery, history, and requests | +| [`src/message.ts`](src/message.ts) | Content text extraction and immutable message constructors shared by delivery, history, and requests | | [`src/assembler.ts`](src/assembler.ts) | `BlockAssembler`: incremental chunk-to-block assembly | | [`src/assistant-stream.ts`](src/assistant-stream.ts) | Compact timed Assistant stream accumulation, strict validation, exact expansion, and record-level readers | | [`src/call-config.ts`](src/call-config.ts) | Call-config validation, adapter-default materialization, and request freezing | diff --git a/packages/llm/llm/README.zh.md b/packages/llm/llm/README.zh.md index ee45bdbb9f..8373531ba5 100644 --- a/packages/llm/llm/README.zh.md +++ b/packages/llm/llm/README.zh.md @@ -83,6 +83,7 @@ const configure = (maxTokens: number): ConfigureCall => ### 你可以做什么 +- **提取内容文本**——从 `@deepseek-ai/dsh-llm/message` 导入的 `extractTextContent(content, options?)` 按顺序仅拼接 `text` 块,保留空白与空文本块,忽略所有其他块类型且不生成占位符。可选的 `options.separator` 默认为 `''`。它接受只读内容,没有文本块时返回 `''`。 - **流式发起一次模型调用**——`ctx.llm.stream(options)` 为任何已注册提供方与模型产出原始分片(token 级增量);消费方用 `BlockAssembler` 组装。 - **注册提供方适配器**——一个适配器拥有一个或多个提供方路由,其注册会捕获该路由的重试策略;重复注册同一路由会以 `DUPLICATE_ADAPTER` 失败。 - **通过配置暴露并激活提供方**——适配器声明可配置提供方路由与 settings namespace,配置界面因此可以激活休眠提供方并编辑连接信息,无需重启。`LlmConfigurableProvider.error` 报告供修复的配置诊断;未受影响的模型仍可提供服务。条目还可携带 `defaultBaseURL`,即配置未设置端点时适配器使用的端点;以及 `nativeAuth`,即配置未指定凭据引用时适配器认证读取的环境变量与 OAuth 登录;`baseURLEnv` 列出配置端点所用的环境变量。配置界面直接从目录读取这些字段,无需调用适配器。 @@ -114,7 +115,7 @@ const configure = (maxTokens: number): ConfigureCall => |---|---| | [`src/index.ts`](src/index.ts) | `LlmRuntime` 服务:适配器注册表、可配置提供方目录、模型发现、调用准备与流式边界 | | [`src/types.ts`](src/types.ts) | `StreamChunk` 协议、内容块映射、结束原因与共享词汇 | -| [`src/message.ts`](src/message.ts) | 投递、历史与请求共享的不可变消息构造函数 | +| [`src/message.ts`](src/message.ts) | 内容文本提取与投递、历史、请求共享的不可变消息构造函数 | | [`src/assembler.ts`](src/assembler.ts) | `BlockAssembler`:分片到块的增量组装 | | [`src/assistant-stream.ts`](src/assistant-stream.ts) | 带时间信息的紧凑 Assistant 流累积、严格校验、精确展开与记录级读取器 | | [`src/call-config.ts`](src/call-config.ts) | 调用配置校验、适配器默认值填入与请求冻结 | diff --git a/packages/llm/llm/src/index.ts b/packages/llm/llm/src/index.ts index 2f4299d8cd..5271c50291 100644 --- a/packages/llm/llm/src/index.ts +++ b/packages/llm/llm/src/index.ts @@ -49,7 +49,11 @@ export * from './api-key.ts' export * from './types.ts' export * from './content.ts' export * from './assistant-stream.ts' -export * from './message.ts' +export type * from './message.ts' +export { + CONTEXT_SUMMARY_MAX_CHARS, boundContextSummary, createAssistantMessage, createDeveloperMessage, createMessage, + createSystemMessage, createToolResultMessage, createUserMessage, freezeMessage, +} from './message.ts' export * from './retry-policy.ts' export { BlockAssembler } from './assembler.ts' export { callConfigEquals, isAgentLoopRequest, markAgentLoopRequest } from './call-config.ts' diff --git a/packages/llm/llm/src/message.ts b/packages/llm/llm/src/message.ts index d96a63edb6..175c1c5f7c 100644 --- a/packages/llm/llm/src/message.ts +++ b/packages/llm/llm/src/message.ts @@ -1,4 +1,4 @@ -/** Message value types, identity, and immutable construction helpers. */ +/** Message value types, content text extraction, identity, and immutable construction helpers. */ import { randomUUID } from '@deepseek-ai/dsh-util-crypto' import { brandString } from '@deepseek-ai/dsh-brand' @@ -305,3 +305,16 @@ export function createToolResultMessage(input: ToolResultMessageInput): ToolResu isError: input.isError, }) } + +/** + * Extract and join only text blocks in content order, preserving their whitespace. + * Non-text blocks contribute neither text nor separators; content is not modified. + * Import from `@deepseek-ai/dsh-llm/message` in Host and browser code. + * @param content - source blocks to read in their existing order. + * @param options - optional text extraction settings. + * @param options.separator - text inserted between text blocks; defaults to an empty string. + * @returns joined text, or an empty string when no text blocks are present. + */ +export function extractTextContent(content: readonly ContentBlock[], options?: { separator?: string }): string { + return content.filter(block => block.type === 'text').map(block => block.text).join(options?.separator ?? '') +} diff --git a/packages/llm/llm/tests/message.spec.ts b/packages/llm/llm/tests/message.spec.ts index 1f05272fba..5b43013c79 100644 --- a/packages/llm/llm/tests/message.spec.ts +++ b/packages/llm/llm/tests/message.spec.ts @@ -1,4 +1,5 @@ import { describe, expect, expectTypeOf, it } from 'vitest' +import { AttachmentId } from '@deepseek-ai/dsh-attachment' import { ToolCallId, boundContextSummary, @@ -11,6 +12,46 @@ import { freezeMessage, MessageId, } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + +describe('extractTextContent', () => { + it('preserves whitespace and empty text blocks while omitting non-text blocks', () => { + const message = createUserMessage({ + source: { kind: 'test' }, + content: [ + { type: 'text', text: ' \talpha\n' }, + { type: 'reasoning', text: 'private reasoning' }, + { type: 'image', attachment: { + attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), + mediaType: 'image/png', bytes: 1, width: 1, height: 1, + } }, + { type: 'tool-call', id: ToolCallId('call'), name: 'tool', arguments: '{}' }, + { type: 'text', text: '' }, + { type: 'tool-removal', toolName: 'removed' }, + { type: 'text', text: 'β \r\n' }, + ], + }) + expect(extractTextContent(message.content)).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, undefined)).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, {})).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, { separator: '' })).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, { separator: '\n' })).toBe(' \talpha\n\n\nβ \r\n') + expect(extractTextContent(message.content, { separator: ' ' })).toBe(' \talpha\n β \r\n') + expect(extractTextContent(message.content, { separator: '::' })).toBe(' \talpha\n::::β \r\n') + expect(Object.isFrozen(message.content)).toBe(true) + expect(message.content[0]).toEqual({ type: 'text', text: ' \talpha\n' }) + }) + + it('returns empty text when there are no text blocks and keeps separators between empty text blocks', () => { + expect(extractTextContent([])).toBe('') + expect(extractTextContent([{ type: 'reasoning', text: 'not plain text' }], { separator: '\n' })).toBe('') + expect(extractTextContent([ + { type: 'text', text: '' }, + { type: 'reasoning', text: 'ignored' }, + { type: 'text', text: '' }, + ], { separator: '\n' })).toBe('\n') + }) +}) describe('message construction', () => { it('detaches and freezes developer tool names without copying their definitions', () => { diff --git a/packages/sdk/server/src/query-activity.ts b/packages/sdk/server/src/query-activity.ts index 17a4fc9148..7bf4c8b7bf 100644 --- a/packages/sdk/server/src/query-activity.ts +++ b/packages/sdk/server/src/query-activity.ts @@ -1,5 +1,7 @@ /** Observe command-admitted activity through quiescence and preserve a goal's first terminal outcome. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import type { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import type { GoalView } from '@deepseek-ai/dsh-goal' @@ -63,7 +65,7 @@ export class QueryActivity { } if (this.input || this.goalId !== undefined) { if (event.type === 'assistant/message') { - this.response = event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') + this.response = extractTextContent(event.data.message.content) } if (event.type === 'turn/end') this.turnReason = event.data.reason.kind } diff --git a/packages/session/session-title-first-prompt-llm/src/index.ts b/packages/session/session-title-first-prompt-llm/src/index.ts index 1cd6aa26ea..046525130e 100644 --- a/packages/session/session-title-first-prompt-llm/src/index.ts +++ b/packages/session/session-title-first-prompt-llm/src/index.ts @@ -3,7 +3,8 @@ /* jscpd:ignore-start -- both shipped providers import the same shared packages. */ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import type { LlmResolvedModelInfo, ReasoningEffortId } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' +import { type LlmResolvedModelInfo, type ReasoningEffortId } from '@deepseek-ai/dsh-llm' import { assertNever } from '@deepseek-ai/dsh-util-values' import { normalizeSessionTitle, @@ -127,10 +128,7 @@ function titleFromResponse(response: SessionTitleLlmResponse): string { if (response.blocks.some(block => block.type === 'tool-call')) { throw new Error('session-title-llm: title output must contain text only') } - const text = response.blocks - .filter((block): block is Extract<(typeof response.blocks)[number], { type: 'text' }> => block.type === 'text') - .map(block => block.text) - .join(' ') + const text = extractTextContent(response.blocks, { separator: ' ' }) const title = normalizeSessionTitle(titleFromOutput(text), Number.MAX_SAFE_INTEGER) if (title.length === 0) throw new Error('session-title-llm: title model produced no text') return title diff --git a/packages/session/session-title/src/index.ts b/packages/session/session-title/src/index.ts index c80ae7e830..9917187dba 100644 --- a/packages/session/session-title/src/index.ts +++ b/packages/session/session-title/src/index.ts @@ -8,6 +8,7 @@ import z from '@deepseek-ai/schemastery' import { z as zod } from 'zod' import type { ZodType } from 'zod' import type { Branded } from '@deepseek-ai/dsh-brand' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { isAgentLoopRequest } from '@deepseek-ai/dsh-llm' import type { GenerateOptions } from '@deepseek-ai/dsh-llm' import { assertNever, deepFreeze } from '@deepseek-ai/dsh-util-values' @@ -137,10 +138,7 @@ export interface SessionTitleProvider { function sessionTitleUserMessageOf(event: SessionEvent): SessionTitleUserMessage | undefined { if (event.type !== 'user/message' || event.data.source.kind !== 'user') return undefined const content = event.data.content - const text = content - .filter((block): block is Extract<(typeof content)[number], { type: 'text' }> => block.type === 'text') - .map(block => block.text) - .join('\n') + const text = extractTextContent(content, { separator: '\n' }) if (normalizeSessionTitle(text, Number.MAX_SAFE_INTEGER).length === 0) return undefined return { seq: event.seq, text } } diff --git a/packages/web/web-deepseek-api/src/index.ts b/packages/web/web-deepseek-api/src/index.ts index 555bab178b..4da54814ea 100644 --- a/packages/web/web-deepseek-api/src/index.ts +++ b/packages/web/web-deepseek-api/src/index.ts @@ -21,7 +21,8 @@ import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-agent' import { credentialRef, type CredentialRef } from '@deepseek-ai/dsh-credentials' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' -import type {} from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import { deepSeekApiKeyConfigured, rejectDeepSeekAccountToken, resolveDeepSeekAccountToken, resolveDeepSeekApiKey, } from '@deepseek-ai/dsh-llm-deepseek' @@ -156,7 +157,7 @@ const CAPABILITY = { function latestUserQuestion(session: Session | undefined): string | undefined { const prompt = session?.deriveMessages().findLast(message => message.role === 'user' && message.source.kind === 'user') if (prompt === undefined) return undefined - return prompt.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n') + return extractTextContent(prompt.content, { separator: '\n' }) } /** diff --git a/packages/workflow/workflow-ptc/src/guest-source.ts b/packages/workflow/workflow-ptc/src/guest-source.ts index 52313de66a..e35a126855 100644 --- a/packages/workflow/workflow-ptc/src/guest-source.ts +++ b/packages/workflow/workflow-ptc/src/guest-source.ts @@ -1,4 +1,4 @@ /** Generated by scripts/gen-workflow-guest.ts. Do not edit directly. */ /** Self-contained ESM guest transported into the mounted PTC runtime. */ -export const WORKFLOW_GUEST_SOURCE = "import * as vm from \"node:vm\";\n//#region packages/workflow/workflow-ptc/src/realm.ts\n/**\n* Materializes script VM values as plain JSON and renders thrown values.\n* Getters and proxy traps may execute inside the confined Node process;\n* process isolation and cancellation belong to PTC, not the VM.\n* @module @deepseek-ai/dsh-workflow-ptc/realm\n*/\n/** Thrown by {@link materializeFromRealm}; the caller wraps it into the right `WorkflowError` code. */\nvar MaterializeError = class extends Error {\n\tpath;\n\treason;\n\tconstructor(path, reason) {\n\t\tsuper(`${path}: ${reason}`);\n\t\tthis.path = path;\n\t\tthis.reason = reason;\n\t\tthis.name = \"MaterializeError\";\n\t}\n};\n/**\n* Render a thrown value to failure text without ever throwing: prefer the\n* `stack` (host or realm — a realm error's `stack` is a plain string read),\n* fall back to `message`, then `String()`. Reading those properties MAY run\n* script code; if that code itself throws, a fixed label is returned instead.\n* @param error - any value thrown in the host or guest realm.\n* @returns human-readable text for the failure report; prefers the stack.\n*/\nfunction renderThrown(error) {\n\ttry {\n\t\tconst stack = error?.stack;\n\t\tif (typeof stack === \"string\" && stack.length > 0) return stack;\n\t\tconst message = error?.message;\n\t\tif (typeof message === \"string\" && message.length > 0) return message;\n\t\treturn String(error);\n\t} catch {\n\t\treturn \"[unrenderable thrown value]\";\n\t}\n}\n/**\n* Whether an object's prototype chain represents a plain data object: `null`, or a prototype\n* whose own prototype is `null` (the realm's `Object.prototype` — which we\n* cannot compare by identity across realms). A `Date`/`Map`/class instance\n* has a longer chain and is rejected.\n*/\nfunction hasPlainPrototype(value) {\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto === null) return true;\n\treturn Object.getPrototypeOf(proto) === null;\n}\n/**\n* Copy `value` (typically from the vm realm) into plain host JSON data. Root `undefined` is\n* returned unchanged; nested `undefined` and values JSON cannot represent losslessly fail\n* with the offending path. Property accessors run normally, and a throwing read is wrapped\n* with its rendered failure.\n*\n* @param value - the realm value to materialize.\n* @param root - the path label for the root value (error messages).\n* @returns the host-realm copy (plain objects/arrays/scalars only).\n* @throws {@link MaterializeError} for unsupported values, cycles, sparse arrays, exotic\n* prototypes, or property reads that throw.\n*/\nfunction materializeFromRealm(value, root = \"value\") {\n\tif (value === void 0) return void 0;\n\ttry {\n\t\treturn materialize(value, root, /* @__PURE__ */ new Set());\n\t} catch (error) {\n\t\tif (error instanceof MaterializeError) throw error;\n\t\tthrow new MaterializeError(root, `reading the value threw: ${renderThrown(error)}`);\n\t}\n}\nfunction materialize(value, path, seen) {\n\tswitch (typeof value) {\n\t\tcase \"boolean\":\n\t\tcase \"string\": return value;\n\t\tcase \"number\":\n\t\t\tif (!Number.isFinite(value)) throw new MaterializeError(path, \"non-finite numbers are not JSON data\");\n\t\t\treturn value;\n\t\tcase \"bigint\": throw new MaterializeError(path, \"bigints are not JSON data\");\n\t\tcase \"function\": throw new MaterializeError(path, \"functions are not plain JSON data\");\n\t\tcase \"symbol\": throw new MaterializeError(path, \"symbols are not plain JSON data\");\n\t\tcase \"undefined\": throw new MaterializeError(path, \"undefined is not JSON data\");\n\t\tcase \"object\": break;\n\t}\n\tif (value === null) return null;\n\tconst objectValue = value;\n\tif (seen.has(objectValue)) throw new MaterializeError(path, \"circular references are not JSON data\");\n\tseen.add(objectValue);\n\ttry {\n\t\tif (Array.isArray(objectValue)) return materializeArray(objectValue, path, seen);\n\t\treturn materializeObject(objectValue, path, seen);\n\t} finally {\n\t\tseen.delete(objectValue);\n\t}\n}\nfunction materializeArray(value, path, seen) {\n\tconst out = [];\n\tfor (let index = 0; index < value.length; index++) {\n\t\tif (!(index in value)) throw new MaterializeError(`${path}[${index}]`, \"sparse arrays are not JSON data\");\n\t\tout.push(materialize(value[index], `${path}[${index}]`, seen));\n\t}\n\tfor (const key of Object.keys(value)) {\n\t\tconst index = Number(key);\n\t\tif (!Number.isInteger(index) || index < 0 || index >= value.length) throw new MaterializeError(`${path}.${key}`, \"arrays with non-index properties are not JSON data\");\n\t}\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\treturn out;\n}\nfunction materializeObject(value, path, seen) {\n\tif (!hasPlainPrototype(value)) throw new MaterializeError(path, \"only plain objects and arrays are JSON data (exotic prototype)\");\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\tconst out = {};\n\tfor (const key of Object.keys(value)) Object.defineProperty(out, key, {\n\t\tvalue: materialize(value[key], `${path}.${key}`, seen),\n\t\tenumerable: true,\n\t\twritable: true,\n\t\tconfigurable: true\n\t});\n\treturn out;\n}\n//#endregion\n//#region packages/util/brand/src/index.ts\n/**\n* Apply a compile-time string brand without changing the value.\n* @param value - string admitted by the domain that owns the target brand.\n* @returns the same string with the requested compile-time brand.\n*/\nfunction brandString(value) {\n\treturn value;\n}\n//#endregion\n//#region packages/util/error/src/index.ts\n/**\n* Harness error base with a stable machine-routable code and chained cause.\n* Package errors extend it so tool results and replay can retain failure class.\n* @module @deepseek-ai/dsh-error\n*/\n/**\n* Base class for all harness errors. Carries a `code` (stable, programmatic —\n* e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the\n* human-readable `message`, and supports `cause` chaining via the standard\n* `ErrorOptions`. `name` defaults to the subclass constructor name.\n*/\nvar HarnessError = class extends Error {\n\t/** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */\n\tcode;\n\tconstructor(message, code, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = new.target.name;\n\t}\n};\n//#endregion\n//#region packages/util/values/src/index.ts\n/**\n* Mark an unreachable closed-union branch.\n* @param value - impossible value; an unhandled typed variant fails at the call site.\n* @param context - optional switch-site label included in the failure message.\n* @returns never; a runtime value that escaped its type always throws.\n*/\nfunction assertNever(value, context) {\n\tconst rendered = JSON.stringify(value) ?? String(value);\n\tthrow new Error(`unreachable variant${context ? ` in ${context}` : \"\"}: ${rendered}`);\n}\n/** Whether a realm-owned intrinsic prototype has a native constructor matching this engine's representation. */\nfunction hasIntrinsicConstructor$1(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === Function.prototype.toString.call(name === \"Array\" ? Array : Object);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype$1(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor$1(value, \"Object\");\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */\nfunction hasPlainArrayPrototype$1(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor$1(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype$1(objectPrototype);\n}\n/** Whether an object is a plain or null-prototype record from any JavaScript realm. */\nfunction hasPlainObjectPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype$1(prototype);\n}\n/** Return every JSON-visible object key, or reject own data JSON would discard. */\nfunction enumerableStringKeys(value) {\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.some((key) => typeof key !== \"string\" || !Object.prototype.propertyIsEnumerable.call(value, key))) return void 0;\n\treturn keys;\n}\n/** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */\nfunction walkJsonValue(value, detach) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tlet root;\n\tlet parent;\n\tconst assign = (item) => {\n\t\tif (parent === void 0) {\n\t\t\tif (detach) root = item;\n\t\t} else if (parent.kind === \"array\") {\n\t\t\tif (parent.target !== void 0) parent.target[parent.key] = item;\n\t\t} else if (parent.target !== void 0) Object.defineProperty(parent.target, parent.key, {\n\t\t\tvalue: item,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true\n\t\t});\n\t};\n\tconst frames = [];\n\tlet current = value;\n\tfor (;;) {\n\t\tif (current === null) assign(null);\n\t\telse if (typeof current === \"boolean\" || typeof current === \"string\") assign(current);\n\t\telse if (typeof current === \"number\") {\n\t\t\tif (!Number.isFinite(current) || Object.is(current, -0)) return void 0;\n\t\t\tassign(current);\n\t\t} else {\n\t\t\tif (typeof current !== \"object\") return void 0;\n\t\t\tif (ancestors.has(current)) return void 0;\n\t\t\tif (Array.isArray(current)) {\n\t\t\t\tif (!hasPlainArrayPrototype$1(current)) return void 0;\n\t\t\t\tconst length = current.length;\n\t\t\t\tif (Reflect.ownKeys(current).length !== length + 1) return void 0;\n\t\t\t\tconst target = detach ? [] : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tlet indices;\n\t\t\t\tif (!Number.isInteger(length)) {\n\t\t\t\t\tindices = [];\n\t\t\t\t\tfor (let index = length - 1; index >= 0; index--) indices.push(index);\n\t\t\t\t}\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"array\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tlength: indices?.length ?? length,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: 0,\n\t\t\t\t\tindices,\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (!hasPlainObjectPrototype(current)) return void 0;\n\t\t\t\tconst keys = enumerableStringKeys(current);\n\t\t\t\tif (keys === void 0) return void 0;\n\t\t\t\tconst target = detach ? {} : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"object\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tkeys,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: \"\",\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t}\n\t\t\tancestors.add(current);\n\t\t}\n\t\tfor (;;) {\n\t\t\tconst frame = frames.at(-1);\n\t\t\tif (frame === void 0) return detach ? root : true;\n\t\t\tconst length = frame.kind === \"array\" ? frame.length : frame.keys.length;\n\t\t\tif (frame.index >= length) {\n\t\t\t\tancestors.delete(frame.source);\n\t\t\t\tframes.pop();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst index = frame.index++;\n\t\t\tparent = frame;\n\t\t\tif (frame.kind === \"array\") {\n\t\t\t\tconst key = frame.indices === void 0 ? index : frame.indices[frame.indices.length - index - 1];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured index count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(frame.source, key)) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t} else {\n\t\t\t\tconst key = frame.keys[index];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n/**\n* Test the same lossless JSON rules as {@link snapshotJsonValue} without detaching the value.\n* @param value - candidate value to test.\n* @returns whether the value survives a JSON round trip without loss.\n*/\nfunction isJsonValue(value) {\n\treturn walkJsonValue(value, false) === true;\n}\n//#endregion\n//#region packages/core/tools/src/json-schema.ts\n/**\n* Enforced JSON Schema subset shared by tool outputs, generated PTC mode\n* types, subagents, and workflows. The subset accepts any JSON root, an\n* annotation-only schema for unconstrained JSON, one scalar `type`, object\n* `properties`/`required`/boolean `additionalProperties`, array `items`,\n* type-correct scalar `enum`/`const`, and exact-one `oneOf`.\n*\n* Unsupported or misplaced keywords reject rather than being accepted without\n* enforcement. Consumers that require an object root apply\n* {@link assertObjectJsonSchema} before accepting input.\n* @module dsh-tools/json-schema\n*/\n/**\n* Thrown when a raw schema falls outside the enforced subset. `violations`\n* lists every offending path instead of stopping at the first author error.\n*/\nvar JsonSchemaError = class extends HarnessError {\n\t/** Individual schema violations in walk order. */\n\tviolations;\n\tconstructor(violations) {\n\t\tsuper(`unsupported JSON schema: ${violations.join(\"; \")}`, \"UNSUPPORTED_SCHEMA\");\n\t\tthis.name = \"JsonSchemaError\";\n\t\tthis.violations = violations;\n\t}\n};\nconst CONSTRAINT_KEYWORDS = new Set([\n\t\"type\",\n\t\"oneOf\",\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n]);\nconst ANNOTATION_KEYWORDS = new Set([\n\t\"description\",\n\t\"title\",\n\t\"default\",\n\t\"examples\"\n]);\nconst SCHEMA_TYPES = [\n\t\"object\",\n\t\"array\",\n\t\"string\",\n\t\"number\",\n\t\"integer\",\n\t\"boolean\",\n\t\"null\"\n];\n/** Whether a realm-owned intrinsic prototype is backed by its native constructor. */\nfunction hasIntrinsicConstructor(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, \"Object\");\n}\n/**\n* Test for a realm-agnostic plain JSON record without accepting arrays or\n* exotic objects.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the value has a plain-object prototype chain.\n*/\nfunction isPlainJsonRecord(value) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\ttry {\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype(prototype);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`. */\nfunction hasPlainArrayPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);\n}\n/** Return whether a record contains only own enumerable string keys. */\nfunction hasOnlyEnumerableStringKeys(value) {\n\ttry {\n\t\treturn Reflect.ownKeys(value).every((key) => typeof key === \"string\" && Object.prototype.propertyIsEnumerable.call(value, key));\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Test for an ordinary schema record whose keys survive JSON projection.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the record has an intrinsic prototype and only own enumerable string keys.\n*/\nfunction isJsonSchemaRecord(value) {\n\treturn isPlainJsonRecord(value) && hasOnlyEnumerableStringKeys(value);\n}\n/**\n* Test for a dense ordinary array with no JSON-invisible decorations.\n* @param value - candidate array from any JavaScript realm.\n* @returns Whether the array is intrinsic, dense, and undecorated.\n*/\nfunction isPlainJsonArray(value) {\n\tif (!Array.isArray(value)) return false;\n\ttry {\n\t\tif (!hasPlainArrayPrototype(value) || Reflect.ownKeys(value).length !== value.length + 1) return false;\n\t\tfor (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index)) return false;\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Lossless finite JSON number, excluding negative zero. */\nfunction isJsonNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && !Object.is(value, -0);\n}\n/** Whether a scalar is valid for one declared schema type. */\nfunction scalarMatches(type, value) {\n\tswitch (type) {\n\t\tcase \"string\": return typeof value === \"string\";\n\t\tcase \"number\": return isJsonNumber(value);\n\t\tcase \"integer\": return isJsonNumber(value) && Number.isInteger(value);\n\t\tcase \"boolean\": return typeof value === \"boolean\";\n\t\tcase \"null\": return value === null;\n\t\t/* v8 ignore next -- JsonSchemaScalarType is closed; this retains compile-time exhaustiveness. */\n\t\tdefault: return assertNever(type, \"JsonSchemaType\");\n\t}\n}\n/** Keywords that are invalid beside `oneOf`. */\nconst ONE_OF_SIBLING_KEYWORDS = [\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n];\n/** Validate object-only fields after its property schemas have been visited. */\nfunction checkObjectSchemaTail(node, path, properties, violations) {\n\tconst hasRequired = Object.hasOwn(node, \"required\");\n\tconst required = hasRequired ? node.required : void 0;\n\tif (hasRequired) if (!isPlainJsonArray(required) || required.some((entry) => typeof entry !== \"string\")) violations.push(`${path}.required must be an array of strings`);\n\telse {\n\t\tconst declared = isJsonSchemaRecord(properties) ? properties : {};\n\t\tfor (const key of required) if (!Object.hasOwn(declared, key)) violations.push(`${path}.required names \"${key}\" which is not in properties`);\n\t}\n\tif (Object.hasOwn(node, \"additionalProperties\") && typeof node.additionalProperties !== \"boolean\") violations.push(`${path}.additionalProperties must be a boolean`);\n}\n/** Collect every violation for one raw schema tree without using the JavaScript call stack. */\nfunction checkSchemaNode(root, rootPath, violations, seen) {\n\tconst tasks = [{\n\t\tkind: \"enter\",\n\t\tnode: root,\n\t\tpath: rootPath\n\t}];\n\tfor (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {\n\t\tif (task.kind === \"leave\") {\n\t\t\tseen.delete(task.node);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"one-of-tail\") {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(task.node, key)) violations.push(`${task.path}.${key} is not supported beside oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"object-tail\") {\n\t\t\tcheckObjectSchemaTail(task.node, task.path, task.properties, violations);\n\t\t\tcontinue;\n\t\t}\n\t\tconst { node, path } = task;\n\t\tif (!isJsonSchemaRecord(node)) {\n\t\t\tviolations.push(`${path} must be a schema object`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (seen.has(node)) {\n\t\t\tviolations.push(`${path} is circular`);\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(node);\n\t\ttasks.push({\n\t\t\tkind: \"leave\",\n\t\t\tnode\n\t\t});\n\t\tfor (const key of Object.keys(node)) {\n\t\t\tif (CONSTRAINT_KEYWORDS.has(key)) continue;\n\t\t\tif (ANNOTATION_KEYWORDS.has(key)) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!isJsonValue(node[key])) violations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t} catch {\n\t\t\t\t\tviolations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tviolations.push(`${path}.${key} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`);\n\t\t}\n\t\tif (Object.hasOwn(node, \"description\") && typeof node.description !== \"string\") violations.push(`${path}.description must be a string`);\n\t\tif (Object.hasOwn(node, \"title\") && typeof node.title !== \"string\") violations.push(`${path}.title must be a string`);\n\t\tconst hasType = Object.hasOwn(node, \"type\");\n\t\tconst hasOneOf = Object.hasOwn(node, \"oneOf\");\n\t\tif (hasType && hasOneOf) {\n\t\t\tviolations.push(`${path} cannot declare both type and oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!hasType && !hasOneOf) {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(node, key)) violations.push(`${path}.${key} requires type or oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (hasOneOf) {\n\t\t\tconst oneOf = node.oneOf;\n\t\t\ttasks.push({\n\t\t\t\tkind: \"one-of-tail\",\n\t\t\t\tnode,\n\t\t\t\tpath\n\t\t\t});\n\t\t\tif (!isPlainJsonArray(oneOf) || oneOf.length < 2) violations.push(`${path}.oneOf must be an array of at least two schemas`);\n\t\t\telse for (let index = oneOf.length - 1; index >= 0; index--) tasks.push({\n\t\t\t\tkind: \"enter\",\n\t\t\t\tnode: oneOf[index],\n\t\t\t\tpath: `${path}.oneOf[${index}]`\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst type = node.type;\n\t\tif (typeof type !== \"string\" || !SCHEMA_TYPES.includes(type)) {\n\t\t\tviolations.push(Array.isArray(type) ? `${path}.type must be a single type string (type arrays are not supported)` : `${path}.type must be one of ${SCHEMA_TYPES.join(\"/\")}`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst schemaType = type;\n\t\tfor (const [key, types] of Object.entries({\n\t\t\tproperties: [\"object\"],\n\t\t\trequired: [\"object\"],\n\t\t\tadditionalProperties: [\"object\"],\n\t\t\titems: [\"array\"],\n\t\t\tenum: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t],\n\t\t\tconst: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t]\n\t\t})) if (Object.hasOwn(node, key) && !types.includes(schemaType)) violations.push(`${path}.${key} is not supported on type \"${schemaType}\"`);\n\t\tswitch (schemaType) {\n\t\t\tcase \"object\": {\n\t\t\t\tconst properties = Object.hasOwn(node, \"properties\") ? node.properties : void 0;\n\t\t\t\ttasks.push({\n\t\t\t\t\tkind: \"object-tail\",\n\t\t\t\t\tnode,\n\t\t\t\t\tpath,\n\t\t\t\t\tproperties\n\t\t\t\t});\n\t\t\t\tif (Object.hasOwn(node, \"properties\")) if (!isJsonSchemaRecord(properties)) violations.push(`${path}.properties must be an object of schemas`);\n\t\t\t\telse {\n\t\t\t\t\tconst entries = Object.entries(properties);\n\t\t\t\t\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\t\t\t\t\tconst entry = entries[index];\n\t\t\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured entry count. */\n\t\t\t\t\t\tif (entry === void 0) continue;\n\t\t\t\t\t\ttasks.push({\n\t\t\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\t\t\tnode: entry[1],\n\t\t\t\t\t\t\tpath: `${path}.properties.${entry[0]}`\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"array\":\n\t\t\t\tif (Object.hasOwn(node, \"items\")) tasks.push({\n\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\tnode: node.items,\n\t\t\t\t\tpath: `${path}.items`\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"string\":\n\t\t\tcase \"number\":\n\t\t\tcase \"integer\":\n\t\t\tcase \"boolean\":\n\t\t\tcase \"null\": {\n\t\t\t\tconst hasEnum = Object.hasOwn(node, \"enum\");\n\t\t\t\tconst allowed = hasEnum ? node.enum : void 0;\n\t\t\t\tconst enumValid = isPlainJsonArray(allowed) && allowed.length > 0 && allowed.every((entry) => scalarMatches(schemaType, entry));\n\t\t\t\tif (hasEnum && !enumValid) violations.push(`${path}.enum must be a non-empty array of ${schemaType} values`);\n\t\t\t\tconst hasConst = Object.hasOwn(node, \"const\");\n\t\t\t\tconst declaredConst = hasConst ? node.const : void 0;\n\t\t\t\tconst constValid = scalarMatches(schemaType, declaredConst);\n\t\t\t\tif (hasConst) {\n\t\t\t\t\tif (!constValid) violations.push(`${path}.const must be a ${schemaType} value`);\n\t\t\t\t\telse if (enumValid && !allowed.includes(declaredConst)) violations.push(`${path}.const must be one of ${path}.enum when both are declared`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* v8 ignore next -- schemaType was narrowed from the closed SCHEMA_TYPES table above. */\n\t\t\tdefault: assertNever(schemaType, \"JsonSchemaType\");\n\t\t}\n\t}\n}\n/**\n* Assert the enforced subset plus the object-root constraint retained by\n* subagent and workflow structured outputs.\n* @param schema - untrusted caller-supplied schema.\n* @returns Assertion that the schema belongs to the supported subset and has an object root.\n*/\nfunction assertObjectJsonSchema(schema) {\n\tconst violations = [];\n\tcheckSchemaNode(schema, \"schema\", violations, /* @__PURE__ */ new Set());\n\tif (violations.length === 0 && (!isJsonSchemaRecord(schema) || !Object.hasOwn(schema, \"type\") || schema.type !== \"object\")) violations.push(\"schema.type must be \\\"object\\\" (structured output is object-rooted)\");\n\tif (violations.length > 0) throw new JsonSchemaError(violations);\n}\n//#endregion\n//#region packages/workflow/workflow/src/index.ts\n/**\n* Typed error for workflow-seam failures. Extends {@link HarnessError}, so the\n* `code` is machine-routable taxonomy. `fatal` drives the combinator\n* discipline: `parallel()`/`pipeline()` re-throw a fatal error (a typo'd\n* option or a tripped cap must kill the script loudly), and reserve the\n* per-item `null` for child-run failures and ordinary in-stage script errors.\n* Every {@link WorkflowErrorCode} is fatal; the flag exists so the\n* distinction is explicit at every catch site rather than implied.\n*/\nvar WorkflowError = class extends HarnessError {\n\t/** Whether combinators must propagate this error instead of nulling the item. */\n\tfatal;\n\tconstructor(message, code, options) {\n\t\tsuper(message, code, options);\n\t\tthis.name = \"WorkflowError\";\n\t\tthis.fatal = options?.fatal ?? true;\n\t}\n};\n/**\n* Whether combinators must re-throw `error` instead of mapping the item to `null`.\n* @param error - any thrown value; fatality is host `instanceof` (unforgeable from a script realm).\n* @returns true iff `error` is a {@link WorkflowError} whose `fatal` flag is set.\n*/\nfunction isFatalWorkflowError(error) {\n\treturn error instanceof WorkflowError && error.fatal;\n}\n//#endregion\n//#region packages/workflow/workflow-ptc/src/runtime.ts\n/**\n* Workflow VM hooks, child callbacks, ordinary concurrency limits and result serialization.\n* PTC owns process confinement and cancellation. Fatal hook and provider failures propagate\n* through combinators; ordinary child failures and stage errors become per-item nulls.\n* @module @deepseek-ai/dsh-workflow-ptc/runtime\n*/\n/** The `agent()` options the script may pass; everything else rejects loud. */\nconst SUPPORTED_AGENT_OPTIONS = new Set([\n\t\"label\",\n\t\"phase\",\n\t\"schema\",\n\t\"provider\",\n\t\"model\"\n]);\n/** Deferred Claude Code options we name explicitly in the rejection message. */\nconst DEFERRED_AGENT_OPTIONS = new Set([\n\t\"effort\",\n\t\"isolation\",\n\t\"agentType\"\n]);\n/** Flatten a child's final output blocks to text (the non-schema `agent()` result). */\nfunction outputText(blocks) {\n\treturn blocks.filter((block) => block.type === \"text\").map((block) => block.text).join(\"\");\n}\n/** A short display label derived from the prompt when the script passes none. */\nfunction defaultLabel(prompt) {\n\tconst newline = prompt.indexOf(\"\\n\");\n\tconst line = newline === -1 ? prompt : prompt.slice(0, newline);\n\treturn line.length <= 48 ? line : `${line.slice(0, 47)}…`;\n}\n/**\n* One script execution inside the confined Node process. The host owns\n* cancellation and cleanup of any dropped child work.\n*/\nvar WorkflowExecution = class {\n\tlimits;\n\tobserver;\n\tchildren;\n\t/** 1-based count of `agent()` calls started (the `agentsStarted` result field). */\n\tstarted = 0;\n\tactiveSlots = 0;\n\tslotWaiters = [];\n\tcurrentPhase;\n\tcontext;\n\tcompiled;\n\tconstructor(meta, body, args, limits, observer, children) {\n\t\tthis.limits = limits;\n\t\tthis.observer = observer;\n\t\tthis.children = children;\n\t\ttry {\n\t\t\tthis.compiled = new vm.Script(`(async () => {\\n${body}\\n})()`, {\n\t\t\t\tfilename: `workflow:${meta.name}`,\n\t\t\t\tlineOffset: -1\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new WorkflowError(`workflow script does not parse: ${String(error)}`, \"SCRIPT_PARSE\", { cause: error });\n\t\t}\n\t\tthis.context = vm.createContext({}, { name: `workflow:${meta.name}` });\n\t\tconst globals = {\n\t\t\tagent: (prompt, opts) => this.contain(this.agent(prompt, opts)),\n\t\t\tparallel: (thunks) => this.contain(this.parallel(thunks)),\n\t\t\tpipeline: (items, ...stages) => this.contain(this.pipeline(items, stages)),\n\t\t\tphase: (title) => {\n\t\t\t\tthis.phase(title);\n\t\t\t},\n\t\t\tlog: (message) => {\n\t\t\t\tthis.log(message);\n\t\t\t},\n\t\t\targs\n\t\t};\n\t\tfor (const [key, value] of Object.entries(globals)) this.context[key] = typeof value === \"function\" ? Object.freeze(value) : value;\n\t}\n\t/**\n\t* Run the script and materialize its JSON return value.\n\t* @returns A completed or error result; script failures never reject.\n\t*/\n\tasync drive() {\n\t\ttry {\n\t\t\tconst scriptPromise = this.compiled.runInContext(this.context, { timeout: this.limits.syncTimeoutMs });\n\t\t\tconst raw = await this.contain(Promise.resolve(scriptPromise));\n\t\t\treturn {\n\t\t\t\tvalue: raw === void 0 ? null : this.materializeResult(raw),\n\t\t\t\tstopReason: \"completed\",\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tvalue: null,\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terror: renderThrown(error),\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t}\n\t}\n\t/**\n\t* Attach a no-op rejection consumer WITHOUT changing what the caller\n\t* receives: if the script drops the promise, a host rejection cannot become\n\t* an unhandled rejection that kills the process; if\n\t* the script does await it, it still observes the rejection.\n\t*/\n\tcontain(promise) {\n\t\tpromise.catch(() => {});\n\t\treturn promise;\n\t}\n\t/** Materialize the script's return value; violations become RESULT_UNSERIALIZABLE. */\n\tmaterializeResult(raw) {\n\t\ttry {\n\t\t\treturn materializeFromRealm(raw, \"workflow result\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`the workflow's return value is not plain JSON data — ${error.message}. Return only JSON-serializable objects/arrays/scalars.`, \"RESULT_UNSERIALIZABLE\", { cause: error });\n\t\t}\n\t}\n\t/** Acquire one concurrency slot in FIFO order. */\n\tacquireSlot() {\n\t\tif (this.activeSlots < this.limits.maxConcurrentAgents) {\n\t\t\tthis.activeSlots += 1;\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.slotWaiters.push(() => {\n\t\t\t\tthis.activeSlots += 1;\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t}\n\treleaseSlot() {\n\t\tthis.activeSlots -= 1;\n\t\tconst next = this.slotWaiters.shift();\n\t\tif (next) next();\n\t}\n\t/** The `agent(prompt, opts)` hook. */\n\tasync agent(rawPrompt, rawOpts) {\n\t\tif (typeof rawPrompt !== \"string\" || rawPrompt.length === 0) throw new WorkflowError(\"agent() requires a non-empty prompt string\", \"INVALID_ARGUMENT\");\n\t\tconst opts = this.readAgentOptions(rawOpts);\n\t\tif (this.started >= this.limits.maxTotalAgents) throw new WorkflowError(`this run reached its total agent cap (${this.limits.maxTotalAgents}) — a runaway-loop backstop; raise the applicable maxTotalAgents limit if the scale is intentional`, \"AGENT_CAP\");\n\t\tthis.started += 1;\n\t\tconst seq = this.started;\n\t\tconst label = opts.label ?? defaultLabel(rawPrompt);\n\t\tconst phase = opts.phase ?? this.currentPhase;\n\t\tawait this.acquireSlot();\n\t\ttry {\n\t\t\tlet run;\n\t\t\ttry {\n\t\t\t\trun = await this.children.startAgent({\n\t\t\t\t\tprompt: rawPrompt,\n\t\t\t\t\t...opts.schema !== void 0 ? { schema: opts.schema } : {},\n\t\t\t\t\t...opts.provider !== void 0 ? { provider: opts.provider } : {},\n\t\t\t\t\t...opts.model !== void 0 ? { model: opts.model } : {}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow new WorkflowError(`agent() could not start a child: ${renderThrown(error)}`, \"AGENT_START\", { cause: error });\n\t\t\t}\n\t\t\tconst info = {\n\t\t\t\tseq,\n\t\t\t\tlabel,\n\t\t\t\t...phase !== void 0 ? { phase } : {},\n\t\t\t\tchildId: brandString(run.id)\n\t\t\t};\n\t\t\tthis.observer.agentStart(info);\n\t\t\ttry {\n\t\t\t\tlet result;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await run.result;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t});\n\t\t\t\t\tthrow new WorkflowError(`child agent run failed: ${renderThrown(error)}`, \"AGENT_RESULT\", { cause: error });\n\t\t\t\t}\n\t\t\t\tif (result.stopReason === \"completed\") {\n\t\t\t\t\tif (opts.schema !== void 0) {\n\t\t\t\t\t\tif (result.structured === void 0) {\n\t\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn result.structured;\n\t\t\t\t\t}\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t});\n\t\t\t\t\treturn outputText(result.output);\n\t\t\t\t}\n\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t...info,\n\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t});\n\t\t\t\treturn null;\n\t\t\t} finally {\n\t\t\t\tawait run.dispose();\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.releaseSlot();\n\t\t}\n\t}\n\t/** Materialize + validate the `agent()` options bag from the realm. */\n\treadAgentOptions(rawOpts) {\n\t\tif (rawOpts === void 0) return {};\n\t\tlet opts;\n\t\ttry {\n\t\t\topts = materializeFromRealm(rawOpts, \"agent() options\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() options must be plain JSON data — ${error.message}`, \"INVALID_ARGUMENT\", { cause: error });\n\t\t}\n\t\tif (typeof opts !== \"object\" || opts === null || Array.isArray(opts)) throw new WorkflowError(\"agent() options must be an object\", \"INVALID_ARGUMENT\");\n\t\tconst record = opts;\n\t\tfor (const key of Object.keys(record)) {\n\t\t\tif (SUPPORTED_AGENT_OPTIONS.has(key)) continue;\n\t\t\tif (DEFERRED_AGENT_OPTIONS.has(key)) throw new WorkflowError(`agent() option \"${key}\" is deferred and not supported by this engine (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t\tthrow new WorkflowError(`agent() option \"${key}\" is not recognized (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t}\n\t\tfor (const key of [\n\t\t\t\"label\",\n\t\t\t\"phase\",\n\t\t\t\"provider\",\n\t\t\t\"model\"\n\t\t]) if (record[key] !== void 0 && typeof record[key] !== \"string\") throw new WorkflowError(`agent() option \"${key}\" must be a string`, \"INVALID_ARGUMENT\");\n\t\tlet schema;\n\t\tif (record.schema !== void 0) try {\n\t\t\tassertObjectJsonSchema(record.schema);\n\t\t\tschema = record.schema;\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: assertObjectJsonSchema only throws JsonSchemaError */\n\t\t\tif (!(error instanceof JsonSchemaError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() schema is outside the supported subset — ${error.message}`, \"UNSUPPORTED_SCHEMA\", { cause: error });\n\t\t}\n\t\treturn {\n\t\t\t...record.label !== void 0 ? { label: record.label } : {},\n\t\t\t...record.phase !== void 0 ? { phase: record.phase } : {},\n\t\t\t...record.provider !== void 0 ? { provider: record.provider } : {},\n\t\t\t...record.model !== void 0 ? { model: record.model } : {},\n\t\t\t...schema !== void 0 ? { schema } : {}\n\t\t};\n\t}\n\t/** The `parallel(thunks)` hook: each thunk caught → `null`; fatal errors propagate. */\n\tasync parallel(rawThunks) {\n\t\tif (!Array.isArray(rawThunks)) throw new WorkflowError(\"parallel() requires an array of zero-argument functions\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawThunks.length, \"parallel()\");\n\t\tconst thunks = rawThunks.map((thunk, index) => {\n\t\t\tif (typeof thunk !== \"function\") throw new WorkflowError(`parallel() item ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn thunk;\n\t\t});\n\t\treturn Promise.all(thunks.map(async (thunk) => {\n\t\t\ttry {\n\t\t\t\treturn await thunk();\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\t/** The `pipeline(items, ...stages)` hook: per-item stage chains, NO cross-stage barrier. */\n\tasync pipeline(rawItems, rawStages) {\n\t\tif (!Array.isArray(rawItems)) throw new WorkflowError(\"pipeline() requires an items array\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawItems.length, \"pipeline()\");\n\t\tif (rawStages.length === 0) throw new WorkflowError(\"pipeline() requires at least one stage function\", \"INVALID_ARGUMENT\");\n\t\tconst stages = rawStages.map((stage, index) => {\n\t\t\tif (typeof stage !== \"function\") throw new WorkflowError(`pipeline() stage ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn stage;\n\t\t});\n\t\treturn Promise.all(rawItems.map(async (item, index) => {\n\t\t\tlet value = item;\n\t\t\ttry {\n\t\t\t\tfor (const stage of stages) value = await stage(value, item, index);\n\t\t\t\treturn value;\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\tassertItemCap(length, hook) {\n\t\tif (length > this.limits.maxItemsPerCall) throw new WorkflowError(`${hook} received ${length} items — over the per-call cap (${this.limits.maxItemsPerCall}); split the work or raise maxItemsPerCall in the engine config`, \"ITEM_CAP\");\n\t}\n\t/** The `phase(title)` hook: sets the current label for subsequent `agent()` calls and notifies observers. */\n\tphase(title) {\n\t\tif (typeof title !== \"string\" || title.length === 0) throw new WorkflowError(\"phase() requires a non-empty title string\", \"INVALID_ARGUMENT\");\n\t\tthis.currentPhase = title;\n\t\tthis.observer.phase(title);\n\t}\n\t/** The `log(message)` hook: narration to observers. */\n\tlog(message) {\n\t\tif (typeof message !== \"string\") throw new WorkflowError(\"log() requires a message string\", \"INVALID_ARGUMENT\");\n\t\tthis.observer.log(message);\n\t}\n};\n//#endregion\n//#region packages/workflow/workflow-ptc/src/guest.ts\n/**\n* Run a workflow with one progress batch in flight. Drain progress before child\n* disposal and the terminal result; PTC and the host own cancellation and cleanup.\n* @param host - JSON callbacks owned by this workflow run.\n* @returns The script result after progress delivery; initialization failures reject.\n*/\nasync function runWorkflowGuest(host) {\n\tconst init = await host.begin({});\n\tlet queued = [];\n\tlet inFlight;\n\tlet progressError;\n\tconst flush = () => {\n\t\tif (inFlight !== void 0 || queued.length === 0) return;\n\t\tconst batch = queued;\n\t\tqueued = [];\n\t\tinFlight = host.progress(batch).then(() => {\n\t\t\tinFlight = void 0;\n\t\t\tflush();\n\t\t}, (error) => {\n\t\t\tprogressError = renderThrown(error);\n\t\t\tqueued = [];\n\t\t\tinFlight = void 0;\n\t\t});\n\t};\n\tconst send = (event) => {\n\t\tif (progressError !== void 0) return;\n\t\tqueued.push(event);\n\t\tflush();\n\t};\n\tconst drain = async () => {\n\t\twhile (inFlight !== void 0) await inFlight;\n\t};\n\tconst result = await new WorkflowExecution(init.meta, init.body, init.args, init.limits, {\n\t\tphase: (title) => {\n\t\t\tsend({\n\t\t\t\ttype: \"phase\",\n\t\t\t\ttitle\n\t\t\t});\n\t\t},\n\t\tlog: (message) => {\n\t\t\tsend({\n\t\t\t\ttype: \"log\",\n\t\t\t\tmessage\n\t\t\t});\n\t\t},\n\t\tagentStart: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-start\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t},\n\t\tagentEnd: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-end\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t}\n\t}, { async startAgent(request) {\n\t\tconst { callId, childId } = await host.startChild(request);\n\t\tconst result = host.childResult({ callId });\n\t\tresult.catch(() => {});\n\t\treturn {\n\t\t\tid: childId,\n\t\t\tresult,\n\t\t\tasync dispose() {\n\t\t\t\tawait drain();\n\t\t\t\tawait host.disposeChild({ callId });\n\t\t\t}\n\t\t};\n\t} }).drive();\n\tawait drain();\n\treturn progressError === void 0 ? result : {\n\t\tvalue: null,\n\t\tstopReason: \"error\",\n\t\terror: progressError,\n\t\tagentsStarted: result.agentsStarted\n\t};\n}\n//#endregion\nexport { runWorkflowGuest };\n//# sourceURL=dsh-workflow-guest.js\n" +export const WORKFLOW_GUEST_SOURCE = "import * as vm from \"node:vm\";\n//#region packages/workflow/workflow-ptc/src/realm.ts\n/**\n* Materializes script VM values as plain JSON and renders thrown values.\n* Getters and proxy traps may execute inside the confined Node process;\n* process isolation and cancellation belong to PTC, not the VM.\n* @module @deepseek-ai/dsh-workflow-ptc/realm\n*/\n/** Thrown by {@link materializeFromRealm}; the caller wraps it into the right `WorkflowError` code. */\nvar MaterializeError = class extends Error {\n\tpath;\n\treason;\n\tconstructor(path, reason) {\n\t\tsuper(`${path}: ${reason}`);\n\t\tthis.path = path;\n\t\tthis.reason = reason;\n\t\tthis.name = \"MaterializeError\";\n\t}\n};\n/**\n* Render a thrown value to failure text without ever throwing: prefer the\n* `stack` (host or realm — a realm error's `stack` is a plain string read),\n* fall back to `message`, then `String()`. Reading those properties MAY run\n* script code; if that code itself throws, a fixed label is returned instead.\n* @param error - any value thrown in the host or guest realm.\n* @returns human-readable text for the failure report; prefers the stack.\n*/\nfunction renderThrown(error) {\n\ttry {\n\t\tconst stack = error?.stack;\n\t\tif (typeof stack === \"string\" && stack.length > 0) return stack;\n\t\tconst message = error?.message;\n\t\tif (typeof message === \"string\" && message.length > 0) return message;\n\t\treturn String(error);\n\t} catch {\n\t\treturn \"[unrenderable thrown value]\";\n\t}\n}\n/**\n* Whether an object's prototype chain represents a plain data object: `null`, or a prototype\n* whose own prototype is `null` (the realm's `Object.prototype` — which we\n* cannot compare by identity across realms). A `Date`/`Map`/class instance\n* has a longer chain and is rejected.\n*/\nfunction hasPlainPrototype(value) {\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto === null) return true;\n\treturn Object.getPrototypeOf(proto) === null;\n}\n/**\n* Copy `value` (typically from the vm realm) into plain host JSON data. Root `undefined` is\n* returned unchanged; nested `undefined` and values JSON cannot represent losslessly fail\n* with the offending path. Property accessors run normally, and a throwing read is wrapped\n* with its rendered failure.\n*\n* @param value - the realm value to materialize.\n* @param root - the path label for the root value (error messages).\n* @returns the host-realm copy (plain objects/arrays/scalars only).\n* @throws {@link MaterializeError} for unsupported values, cycles, sparse arrays, exotic\n* prototypes, or property reads that throw.\n*/\nfunction materializeFromRealm(value, root = \"value\") {\n\tif (value === void 0) return void 0;\n\ttry {\n\t\treturn materialize(value, root, /* @__PURE__ */ new Set());\n\t} catch (error) {\n\t\tif (error instanceof MaterializeError) throw error;\n\t\tthrow new MaterializeError(root, `reading the value threw: ${renderThrown(error)}`);\n\t}\n}\nfunction materialize(value, path, seen) {\n\tswitch (typeof value) {\n\t\tcase \"boolean\":\n\t\tcase \"string\": return value;\n\t\tcase \"number\":\n\t\t\tif (!Number.isFinite(value)) throw new MaterializeError(path, \"non-finite numbers are not JSON data\");\n\t\t\treturn value;\n\t\tcase \"bigint\": throw new MaterializeError(path, \"bigints are not JSON data\");\n\t\tcase \"function\": throw new MaterializeError(path, \"functions are not plain JSON data\");\n\t\tcase \"symbol\": throw new MaterializeError(path, \"symbols are not plain JSON data\");\n\t\tcase \"undefined\": throw new MaterializeError(path, \"undefined is not JSON data\");\n\t\tcase \"object\": break;\n\t}\n\tif (value === null) return null;\n\tconst objectValue = value;\n\tif (seen.has(objectValue)) throw new MaterializeError(path, \"circular references are not JSON data\");\n\tseen.add(objectValue);\n\ttry {\n\t\tif (Array.isArray(objectValue)) return materializeArray(objectValue, path, seen);\n\t\treturn materializeObject(objectValue, path, seen);\n\t} finally {\n\t\tseen.delete(objectValue);\n\t}\n}\nfunction materializeArray(value, path, seen) {\n\tconst out = [];\n\tfor (let index = 0; index < value.length; index++) {\n\t\tif (!(index in value)) throw new MaterializeError(`${path}[${index}]`, \"sparse arrays are not JSON data\");\n\t\tout.push(materialize(value[index], `${path}[${index}]`, seen));\n\t}\n\tfor (const key of Object.keys(value)) {\n\t\tconst index = Number(key);\n\t\tif (!Number.isInteger(index) || index < 0 || index >= value.length) throw new MaterializeError(`${path}.${key}`, \"arrays with non-index properties are not JSON data\");\n\t}\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\treturn out;\n}\nfunction materializeObject(value, path, seen) {\n\tif (!hasPlainPrototype(value)) throw new MaterializeError(path, \"only plain objects and arrays are JSON data (exotic prototype)\");\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\tconst out = {};\n\tfor (const key of Object.keys(value)) Object.defineProperty(out, key, {\n\t\tvalue: materialize(value[key], `${path}.${key}`, seen),\n\t\tenumerable: true,\n\t\twritable: true,\n\t\tconfigurable: true\n\t});\n\treturn out;\n}\n//#endregion\n//#region packages/util/brand/src/index.ts\n/**\n* Apply a compile-time string brand without changing the value.\n* @param value - string admitted by the domain that owns the target brand.\n* @returns the same string with the requested compile-time brand.\n*/\nfunction brandString(value) {\n\treturn value;\n}\n//#endregion\n//#region packages/util/values/src/index.ts\n/**\n* Mark an unreachable closed-union branch.\n* @param value - impossible value; an unhandled typed variant fails at the call site.\n* @param context - optional switch-site label included in the failure message.\n* @returns never; a runtime value that escaped its type always throws.\n*/\nfunction assertNever(value, context) {\n\tconst rendered = JSON.stringify(value) ?? String(value);\n\tthrow new Error(`unreachable variant${context ? ` in ${context}` : \"\"}: ${rendered}`);\n}\n/** Whether a realm-owned intrinsic prototype has a native constructor matching this engine's representation. */\nfunction hasIntrinsicConstructor$1(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === Function.prototype.toString.call(name === \"Array\" ? Array : Object);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype$1(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor$1(value, \"Object\");\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */\nfunction hasPlainArrayPrototype$1(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor$1(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype$1(objectPrototype);\n}\n/** Whether an object is a plain or null-prototype record from any JavaScript realm. */\nfunction hasPlainObjectPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype$1(prototype);\n}\n/** Return every JSON-visible object key, or reject own data JSON would discard. */\nfunction enumerableStringKeys(value) {\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.some((key) => typeof key !== \"string\" || !Object.prototype.propertyIsEnumerable.call(value, key))) return void 0;\n\treturn keys;\n}\n/** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */\nfunction walkJsonValue(value, detach) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tlet root;\n\tlet parent;\n\tconst assign = (item) => {\n\t\tif (parent === void 0) {\n\t\t\tif (detach) root = item;\n\t\t} else if (parent.kind === \"array\") {\n\t\t\tif (parent.target !== void 0) parent.target[parent.key] = item;\n\t\t} else if (parent.target !== void 0) Object.defineProperty(parent.target, parent.key, {\n\t\t\tvalue: item,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true\n\t\t});\n\t};\n\tconst frames = [];\n\tlet current = value;\n\tfor (;;) {\n\t\tif (current === null) assign(null);\n\t\telse if (typeof current === \"boolean\" || typeof current === \"string\") assign(current);\n\t\telse if (typeof current === \"number\") {\n\t\t\tif (!Number.isFinite(current) || Object.is(current, -0)) return void 0;\n\t\t\tassign(current);\n\t\t} else {\n\t\t\tif (typeof current !== \"object\") return void 0;\n\t\t\tif (ancestors.has(current)) return void 0;\n\t\t\tif (Array.isArray(current)) {\n\t\t\t\tif (!hasPlainArrayPrototype$1(current)) return void 0;\n\t\t\t\tconst length = current.length;\n\t\t\t\tif (Reflect.ownKeys(current).length !== length + 1) return void 0;\n\t\t\t\tconst target = detach ? [] : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tlet indices;\n\t\t\t\tif (!Number.isInteger(length)) {\n\t\t\t\t\tindices = [];\n\t\t\t\t\tfor (let index = length - 1; index >= 0; index--) indices.push(index);\n\t\t\t\t}\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"array\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tlength: indices?.length ?? length,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: 0,\n\t\t\t\t\tindices,\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (!hasPlainObjectPrototype(current)) return void 0;\n\t\t\t\tconst keys = enumerableStringKeys(current);\n\t\t\t\tif (keys === void 0) return void 0;\n\t\t\t\tconst target = detach ? {} : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"object\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tkeys,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: \"\",\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t}\n\t\t\tancestors.add(current);\n\t\t}\n\t\tfor (;;) {\n\t\t\tconst frame = frames.at(-1);\n\t\t\tif (frame === void 0) return detach ? root : true;\n\t\t\tconst length = frame.kind === \"array\" ? frame.length : frame.keys.length;\n\t\t\tif (frame.index >= length) {\n\t\t\t\tancestors.delete(frame.source);\n\t\t\t\tframes.pop();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst index = frame.index++;\n\t\t\tparent = frame;\n\t\t\tif (frame.kind === \"array\") {\n\t\t\t\tconst key = frame.indices === void 0 ? index : frame.indices[frame.indices.length - index - 1];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured index count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(frame.source, key)) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t} else {\n\t\t\t\tconst key = frame.keys[index];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n/**\n* Test the same lossless JSON rules as {@link snapshotJsonValue} without detaching the value.\n* @param value - candidate value to test.\n* @returns whether the value survives a JSON round trip without loss.\n*/\nfunction isJsonValue(value) {\n\treturn walkJsonValue(value, false) === true;\n}\n//#endregion\n//#region packages/llm/llm/src/message.ts\n/**\n* Extract and join only text blocks in content order, preserving their whitespace.\n* Non-text blocks contribute neither text nor separators; content is not modified.\n* Import from `@deepseek-ai/dsh-llm/message` in Host and browser code.\n* @param content - source blocks to read in their existing order.\n* @param options - optional text extraction settings.\n* @param options.separator - text inserted between text blocks; defaults to an empty string.\n* @returns joined text, or an empty string when no text blocks are present.\n*/\nfunction extractTextContent(content, options) {\n\treturn content.filter((block) => block.type === \"text\").map((block) => block.text).join(options?.separator ?? \"\");\n}\n//#endregion\n//#region packages/util/error/src/index.ts\n/**\n* Harness error base with a stable machine-routable code and chained cause.\n* Package errors extend it so tool results and replay can retain failure class.\n* @module @deepseek-ai/dsh-error\n*/\n/**\n* Base class for all harness errors. Carries a `code` (stable, programmatic —\n* e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the\n* human-readable `message`, and supports `cause` chaining via the standard\n* `ErrorOptions`. `name` defaults to the subclass constructor name.\n*/\nvar HarnessError = class extends Error {\n\t/** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */\n\tcode;\n\tconstructor(message, code, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = new.target.name;\n\t}\n};\n//#endregion\n//#region packages/core/tools/src/json-schema.ts\n/**\n* Enforced JSON Schema subset shared by tool outputs, generated PTC mode\n* types, subagents, and workflows. The subset accepts any JSON root, an\n* annotation-only schema for unconstrained JSON, one scalar `type`, object\n* `properties`/`required`/boolean `additionalProperties`, array `items`,\n* type-correct scalar `enum`/`const`, and exact-one `oneOf`.\n*\n* Unsupported or misplaced keywords reject rather than being accepted without\n* enforcement. Consumers that require an object root apply\n* {@link assertObjectJsonSchema} before accepting input.\n* @module dsh-tools/json-schema\n*/\n/**\n* Thrown when a raw schema falls outside the enforced subset. `violations`\n* lists every offending path instead of stopping at the first author error.\n*/\nvar JsonSchemaError = class extends HarnessError {\n\t/** Individual schema violations in walk order. */\n\tviolations;\n\tconstructor(violations) {\n\t\tsuper(`unsupported JSON schema: ${violations.join(\"; \")}`, \"UNSUPPORTED_SCHEMA\");\n\t\tthis.name = \"JsonSchemaError\";\n\t\tthis.violations = violations;\n\t}\n};\nconst CONSTRAINT_KEYWORDS = new Set([\n\t\"type\",\n\t\"oneOf\",\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n]);\nconst ANNOTATION_KEYWORDS = new Set([\n\t\"description\",\n\t\"title\",\n\t\"default\",\n\t\"examples\"\n]);\nconst SCHEMA_TYPES = [\n\t\"object\",\n\t\"array\",\n\t\"string\",\n\t\"number\",\n\t\"integer\",\n\t\"boolean\",\n\t\"null\"\n];\n/** Whether a realm-owned intrinsic prototype is backed by its native constructor. */\nfunction hasIntrinsicConstructor(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, \"Object\");\n}\n/**\n* Test for a realm-agnostic plain JSON record without accepting arrays or\n* exotic objects.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the value has a plain-object prototype chain.\n*/\nfunction isPlainJsonRecord(value) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\ttry {\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype(prototype);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`. */\nfunction hasPlainArrayPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);\n}\n/** Return whether a record contains only own enumerable string keys. */\nfunction hasOnlyEnumerableStringKeys(value) {\n\ttry {\n\t\treturn Reflect.ownKeys(value).every((key) => typeof key === \"string\" && Object.prototype.propertyIsEnumerable.call(value, key));\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Test for an ordinary schema record whose keys survive JSON projection.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the record has an intrinsic prototype and only own enumerable string keys.\n*/\nfunction isJsonSchemaRecord(value) {\n\treturn isPlainJsonRecord(value) && hasOnlyEnumerableStringKeys(value);\n}\n/**\n* Test for a dense ordinary array with no JSON-invisible decorations.\n* @param value - candidate array from any JavaScript realm.\n* @returns Whether the array is intrinsic, dense, and undecorated.\n*/\nfunction isPlainJsonArray(value) {\n\tif (!Array.isArray(value)) return false;\n\ttry {\n\t\tif (!hasPlainArrayPrototype(value) || Reflect.ownKeys(value).length !== value.length + 1) return false;\n\t\tfor (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index)) return false;\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Lossless finite JSON number, excluding negative zero. */\nfunction isJsonNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && !Object.is(value, -0);\n}\n/** Whether a scalar is valid for one declared schema type. */\nfunction scalarMatches(type, value) {\n\tswitch (type) {\n\t\tcase \"string\": return typeof value === \"string\";\n\t\tcase \"number\": return isJsonNumber(value);\n\t\tcase \"integer\": return isJsonNumber(value) && Number.isInteger(value);\n\t\tcase \"boolean\": return typeof value === \"boolean\";\n\t\tcase \"null\": return value === null;\n\t\t/* v8 ignore next -- JsonSchemaScalarType is closed; this retains compile-time exhaustiveness. */\n\t\tdefault: return assertNever(type, \"JsonSchemaType\");\n\t}\n}\n/** Keywords that are invalid beside `oneOf`. */\nconst ONE_OF_SIBLING_KEYWORDS = [\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n];\n/** Validate object-only fields after its property schemas have been visited. */\nfunction checkObjectSchemaTail(node, path, properties, violations) {\n\tconst hasRequired = Object.hasOwn(node, \"required\");\n\tconst required = hasRequired ? node.required : void 0;\n\tif (hasRequired) if (!isPlainJsonArray(required) || required.some((entry) => typeof entry !== \"string\")) violations.push(`${path}.required must be an array of strings`);\n\telse {\n\t\tconst declared = isJsonSchemaRecord(properties) ? properties : {};\n\t\tfor (const key of required) if (!Object.hasOwn(declared, key)) violations.push(`${path}.required names \"${key}\" which is not in properties`);\n\t}\n\tif (Object.hasOwn(node, \"additionalProperties\") && typeof node.additionalProperties !== \"boolean\") violations.push(`${path}.additionalProperties must be a boolean`);\n}\n/** Collect every violation for one raw schema tree without using the JavaScript call stack. */\nfunction checkSchemaNode(root, rootPath, violations, seen) {\n\tconst tasks = [{\n\t\tkind: \"enter\",\n\t\tnode: root,\n\t\tpath: rootPath\n\t}];\n\tfor (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {\n\t\tif (task.kind === \"leave\") {\n\t\t\tseen.delete(task.node);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"one-of-tail\") {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(task.node, key)) violations.push(`${task.path}.${key} is not supported beside oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"object-tail\") {\n\t\t\tcheckObjectSchemaTail(task.node, task.path, task.properties, violations);\n\t\t\tcontinue;\n\t\t}\n\t\tconst { node, path } = task;\n\t\tif (!isJsonSchemaRecord(node)) {\n\t\t\tviolations.push(`${path} must be a schema object`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (seen.has(node)) {\n\t\t\tviolations.push(`${path} is circular`);\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(node);\n\t\ttasks.push({\n\t\t\tkind: \"leave\",\n\t\t\tnode\n\t\t});\n\t\tfor (const key of Object.keys(node)) {\n\t\t\tif (CONSTRAINT_KEYWORDS.has(key)) continue;\n\t\t\tif (ANNOTATION_KEYWORDS.has(key)) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!isJsonValue(node[key])) violations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t} catch {\n\t\t\t\t\tviolations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tviolations.push(`${path}.${key} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`);\n\t\t}\n\t\tif (Object.hasOwn(node, \"description\") && typeof node.description !== \"string\") violations.push(`${path}.description must be a string`);\n\t\tif (Object.hasOwn(node, \"title\") && typeof node.title !== \"string\") violations.push(`${path}.title must be a string`);\n\t\tconst hasType = Object.hasOwn(node, \"type\");\n\t\tconst hasOneOf = Object.hasOwn(node, \"oneOf\");\n\t\tif (hasType && hasOneOf) {\n\t\t\tviolations.push(`${path} cannot declare both type and oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!hasType && !hasOneOf) {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(node, key)) violations.push(`${path}.${key} requires type or oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (hasOneOf) {\n\t\t\tconst oneOf = node.oneOf;\n\t\t\ttasks.push({\n\t\t\t\tkind: \"one-of-tail\",\n\t\t\t\tnode,\n\t\t\t\tpath\n\t\t\t});\n\t\t\tif (!isPlainJsonArray(oneOf) || oneOf.length < 2) violations.push(`${path}.oneOf must be an array of at least two schemas`);\n\t\t\telse for (let index = oneOf.length - 1; index >= 0; index--) tasks.push({\n\t\t\t\tkind: \"enter\",\n\t\t\t\tnode: oneOf[index],\n\t\t\t\tpath: `${path}.oneOf[${index}]`\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst type = node.type;\n\t\tif (typeof type !== \"string\" || !SCHEMA_TYPES.includes(type)) {\n\t\t\tviolations.push(Array.isArray(type) ? `${path}.type must be a single type string (type arrays are not supported)` : `${path}.type must be one of ${SCHEMA_TYPES.join(\"/\")}`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst schemaType = type;\n\t\tfor (const [key, types] of Object.entries({\n\t\t\tproperties: [\"object\"],\n\t\t\trequired: [\"object\"],\n\t\t\tadditionalProperties: [\"object\"],\n\t\t\titems: [\"array\"],\n\t\t\tenum: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t],\n\t\t\tconst: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t]\n\t\t})) if (Object.hasOwn(node, key) && !types.includes(schemaType)) violations.push(`${path}.${key} is not supported on type \"${schemaType}\"`);\n\t\tswitch (schemaType) {\n\t\t\tcase \"object\": {\n\t\t\t\tconst properties = Object.hasOwn(node, \"properties\") ? node.properties : void 0;\n\t\t\t\ttasks.push({\n\t\t\t\t\tkind: \"object-tail\",\n\t\t\t\t\tnode,\n\t\t\t\t\tpath,\n\t\t\t\t\tproperties\n\t\t\t\t});\n\t\t\t\tif (Object.hasOwn(node, \"properties\")) if (!isJsonSchemaRecord(properties)) violations.push(`${path}.properties must be an object of schemas`);\n\t\t\t\telse {\n\t\t\t\t\tconst entries = Object.entries(properties);\n\t\t\t\t\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\t\t\t\t\tconst entry = entries[index];\n\t\t\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured entry count. */\n\t\t\t\t\t\tif (entry === void 0) continue;\n\t\t\t\t\t\ttasks.push({\n\t\t\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\t\t\tnode: entry[1],\n\t\t\t\t\t\t\tpath: `${path}.properties.${entry[0]}`\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"array\":\n\t\t\t\tif (Object.hasOwn(node, \"items\")) tasks.push({\n\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\tnode: node.items,\n\t\t\t\t\tpath: `${path}.items`\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"string\":\n\t\t\tcase \"number\":\n\t\t\tcase \"integer\":\n\t\t\tcase \"boolean\":\n\t\t\tcase \"null\": {\n\t\t\t\tconst hasEnum = Object.hasOwn(node, \"enum\");\n\t\t\t\tconst allowed = hasEnum ? node.enum : void 0;\n\t\t\t\tconst enumValid = isPlainJsonArray(allowed) && allowed.length > 0 && allowed.every((entry) => scalarMatches(schemaType, entry));\n\t\t\t\tif (hasEnum && !enumValid) violations.push(`${path}.enum must be a non-empty array of ${schemaType} values`);\n\t\t\t\tconst hasConst = Object.hasOwn(node, \"const\");\n\t\t\t\tconst declaredConst = hasConst ? node.const : void 0;\n\t\t\t\tconst constValid = scalarMatches(schemaType, declaredConst);\n\t\t\t\tif (hasConst) {\n\t\t\t\t\tif (!constValid) violations.push(`${path}.const must be a ${schemaType} value`);\n\t\t\t\t\telse if (enumValid && !allowed.includes(declaredConst)) violations.push(`${path}.const must be one of ${path}.enum when both are declared`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* v8 ignore next -- schemaType was narrowed from the closed SCHEMA_TYPES table above. */\n\t\t\tdefault: assertNever(schemaType, \"JsonSchemaType\");\n\t\t}\n\t}\n}\n/**\n* Assert the enforced subset plus the object-root constraint retained by\n* subagent and workflow structured outputs.\n* @param schema - untrusted caller-supplied schema.\n* @returns Assertion that the schema belongs to the supported subset and has an object root.\n*/\nfunction assertObjectJsonSchema(schema) {\n\tconst violations = [];\n\tcheckSchemaNode(schema, \"schema\", violations, /* @__PURE__ */ new Set());\n\tif (violations.length === 0 && (!isJsonSchemaRecord(schema) || !Object.hasOwn(schema, \"type\") || schema.type !== \"object\")) violations.push(\"schema.type must be \\\"object\\\" (structured output is object-rooted)\");\n\tif (violations.length > 0) throw new JsonSchemaError(violations);\n}\n//#endregion\n//#region packages/workflow/workflow/src/index.ts\n/**\n* Typed error for workflow-seam failures. Extends {@link HarnessError}, so the\n* `code` is machine-routable taxonomy. `fatal` drives the combinator\n* discipline: `parallel()`/`pipeline()` re-throw a fatal error (a typo'd\n* option or a tripped cap must kill the script loudly), and reserve the\n* per-item `null` for child-run failures and ordinary in-stage script errors.\n* Every {@link WorkflowErrorCode} is fatal; the flag exists so the\n* distinction is explicit at every catch site rather than implied.\n*/\nvar WorkflowError = class extends HarnessError {\n\t/** Whether combinators must propagate this error instead of nulling the item. */\n\tfatal;\n\tconstructor(message, code, options) {\n\t\tsuper(message, code, options);\n\t\tthis.name = \"WorkflowError\";\n\t\tthis.fatal = options?.fatal ?? true;\n\t}\n};\n/**\n* Whether combinators must re-throw `error` instead of mapping the item to `null`.\n* @param error - any thrown value; fatality is host `instanceof` (unforgeable from a script realm).\n* @returns true iff `error` is a {@link WorkflowError} whose `fatal` flag is set.\n*/\nfunction isFatalWorkflowError(error) {\n\treturn error instanceof WorkflowError && error.fatal;\n}\n//#endregion\n//#region packages/workflow/workflow-ptc/src/runtime.ts\n/**\n* Workflow VM hooks, child callbacks, ordinary concurrency limits and result serialization.\n* PTC owns process confinement and cancellation. Fatal hook and provider failures propagate\n* through combinators; ordinary child failures and stage errors become per-item nulls.\n* @module @deepseek-ai/dsh-workflow-ptc/runtime\n*/\n/** The `agent()` options the script may pass; everything else rejects loud. */\nconst SUPPORTED_AGENT_OPTIONS = new Set([\n\t\"label\",\n\t\"phase\",\n\t\"schema\",\n\t\"provider\",\n\t\"model\"\n]);\n/** Deferred Claude Code options we name explicitly in the rejection message. */\nconst DEFERRED_AGENT_OPTIONS = new Set([\n\t\"effort\",\n\t\"isolation\",\n\t\"agentType\"\n]);\n/** A short display label derived from the prompt when the script passes none. */\nfunction defaultLabel(prompt) {\n\tconst newline = prompt.indexOf(\"\\n\");\n\tconst line = newline === -1 ? prompt : prompt.slice(0, newline);\n\treturn line.length <= 48 ? line : `${line.slice(0, 47)}…`;\n}\n/**\n* One script execution inside the confined Node process. The host owns\n* cancellation and cleanup of any dropped child work.\n*/\nvar WorkflowExecution = class {\n\tlimits;\n\tobserver;\n\tchildren;\n\t/** 1-based count of `agent()` calls started (the `agentsStarted` result field). */\n\tstarted = 0;\n\tactiveSlots = 0;\n\tslotWaiters = [];\n\tcurrentPhase;\n\tcontext;\n\tcompiled;\n\tconstructor(meta, body, args, limits, observer, children) {\n\t\tthis.limits = limits;\n\t\tthis.observer = observer;\n\t\tthis.children = children;\n\t\ttry {\n\t\t\tthis.compiled = new vm.Script(`(async () => {\\n${body}\\n})()`, {\n\t\t\t\tfilename: `workflow:${meta.name}`,\n\t\t\t\tlineOffset: -1\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new WorkflowError(`workflow script does not parse: ${String(error)}`, \"SCRIPT_PARSE\", { cause: error });\n\t\t}\n\t\tthis.context = vm.createContext({}, { name: `workflow:${meta.name}` });\n\t\tconst globals = {\n\t\t\tagent: (prompt, opts) => this.contain(this.agent(prompt, opts)),\n\t\t\tparallel: (thunks) => this.contain(this.parallel(thunks)),\n\t\t\tpipeline: (items, ...stages) => this.contain(this.pipeline(items, stages)),\n\t\t\tphase: (title) => {\n\t\t\t\tthis.phase(title);\n\t\t\t},\n\t\t\tlog: (message) => {\n\t\t\t\tthis.log(message);\n\t\t\t},\n\t\t\targs\n\t\t};\n\t\tfor (const [key, value] of Object.entries(globals)) this.context[key] = typeof value === \"function\" ? Object.freeze(value) : value;\n\t}\n\t/**\n\t* Run the script and materialize its JSON return value.\n\t* @returns A completed or error result; script failures never reject.\n\t*/\n\tasync drive() {\n\t\ttry {\n\t\t\tconst scriptPromise = this.compiled.runInContext(this.context, { timeout: this.limits.syncTimeoutMs });\n\t\t\tconst raw = await this.contain(Promise.resolve(scriptPromise));\n\t\t\treturn {\n\t\t\t\tvalue: raw === void 0 ? null : this.materializeResult(raw),\n\t\t\t\tstopReason: \"completed\",\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tvalue: null,\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terror: renderThrown(error),\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t}\n\t}\n\t/**\n\t* Attach a no-op rejection consumer WITHOUT changing what the caller\n\t* receives: if the script drops the promise, a host rejection cannot become\n\t* an unhandled rejection that kills the process; if\n\t* the script does await it, it still observes the rejection.\n\t*/\n\tcontain(promise) {\n\t\tpromise.catch(() => {});\n\t\treturn promise;\n\t}\n\t/** Materialize the script's return value; violations become RESULT_UNSERIALIZABLE. */\n\tmaterializeResult(raw) {\n\t\ttry {\n\t\t\treturn materializeFromRealm(raw, \"workflow result\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`the workflow's return value is not plain JSON data — ${error.message}. Return only JSON-serializable objects/arrays/scalars.`, \"RESULT_UNSERIALIZABLE\", { cause: error });\n\t\t}\n\t}\n\t/** Acquire one concurrency slot in FIFO order. */\n\tacquireSlot() {\n\t\tif (this.activeSlots < this.limits.maxConcurrentAgents) {\n\t\t\tthis.activeSlots += 1;\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.slotWaiters.push(() => {\n\t\t\t\tthis.activeSlots += 1;\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t}\n\treleaseSlot() {\n\t\tthis.activeSlots -= 1;\n\t\tconst next = this.slotWaiters.shift();\n\t\tif (next) next();\n\t}\n\t/** The `agent(prompt, opts)` hook. */\n\tasync agent(rawPrompt, rawOpts) {\n\t\tif (typeof rawPrompt !== \"string\" || rawPrompt.length === 0) throw new WorkflowError(\"agent() requires a non-empty prompt string\", \"INVALID_ARGUMENT\");\n\t\tconst opts = this.readAgentOptions(rawOpts);\n\t\tif (this.started >= this.limits.maxTotalAgents) throw new WorkflowError(`this run reached its total agent cap (${this.limits.maxTotalAgents}) — a runaway-loop backstop; raise the applicable maxTotalAgents limit if the scale is intentional`, \"AGENT_CAP\");\n\t\tthis.started += 1;\n\t\tconst seq = this.started;\n\t\tconst label = opts.label ?? defaultLabel(rawPrompt);\n\t\tconst phase = opts.phase ?? this.currentPhase;\n\t\tawait this.acquireSlot();\n\t\ttry {\n\t\t\tlet run;\n\t\t\ttry {\n\t\t\t\trun = await this.children.startAgent({\n\t\t\t\t\tprompt: rawPrompt,\n\t\t\t\t\t...opts.schema !== void 0 ? { schema: opts.schema } : {},\n\t\t\t\t\t...opts.provider !== void 0 ? { provider: opts.provider } : {},\n\t\t\t\t\t...opts.model !== void 0 ? { model: opts.model } : {}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow new WorkflowError(`agent() could not start a child: ${renderThrown(error)}`, \"AGENT_START\", { cause: error });\n\t\t\t}\n\t\t\tconst info = {\n\t\t\t\tseq,\n\t\t\t\tlabel,\n\t\t\t\t...phase !== void 0 ? { phase } : {},\n\t\t\t\tchildId: brandString(run.id)\n\t\t\t};\n\t\t\tthis.observer.agentStart(info);\n\t\t\ttry {\n\t\t\t\tlet result;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await run.result;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t});\n\t\t\t\t\tthrow new WorkflowError(`child agent run failed: ${renderThrown(error)}`, \"AGENT_RESULT\", { cause: error });\n\t\t\t\t}\n\t\t\t\tif (result.stopReason === \"completed\") {\n\t\t\t\t\tif (opts.schema !== void 0) {\n\t\t\t\t\t\tif (result.structured === void 0) {\n\t\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn result.structured;\n\t\t\t\t\t}\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t});\n\t\t\t\t\treturn extractTextContent(result.output);\n\t\t\t\t}\n\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t...info,\n\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t});\n\t\t\t\treturn null;\n\t\t\t} finally {\n\t\t\t\tawait run.dispose();\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.releaseSlot();\n\t\t}\n\t}\n\t/** Materialize + validate the `agent()` options bag from the realm. */\n\treadAgentOptions(rawOpts) {\n\t\tif (rawOpts === void 0) return {};\n\t\tlet opts;\n\t\ttry {\n\t\t\topts = materializeFromRealm(rawOpts, \"agent() options\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() options must be plain JSON data — ${error.message}`, \"INVALID_ARGUMENT\", { cause: error });\n\t\t}\n\t\tif (typeof opts !== \"object\" || opts === null || Array.isArray(opts)) throw new WorkflowError(\"agent() options must be an object\", \"INVALID_ARGUMENT\");\n\t\tconst record = opts;\n\t\tfor (const key of Object.keys(record)) {\n\t\t\tif (SUPPORTED_AGENT_OPTIONS.has(key)) continue;\n\t\t\tif (DEFERRED_AGENT_OPTIONS.has(key)) throw new WorkflowError(`agent() option \"${key}\" is deferred and not supported by this engine (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t\tthrow new WorkflowError(`agent() option \"${key}\" is not recognized (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t}\n\t\tfor (const key of [\n\t\t\t\"label\",\n\t\t\t\"phase\",\n\t\t\t\"provider\",\n\t\t\t\"model\"\n\t\t]) if (record[key] !== void 0 && typeof record[key] !== \"string\") throw new WorkflowError(`agent() option \"${key}\" must be a string`, \"INVALID_ARGUMENT\");\n\t\tlet schema;\n\t\tif (record.schema !== void 0) try {\n\t\t\tassertObjectJsonSchema(record.schema);\n\t\t\tschema = record.schema;\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: assertObjectJsonSchema only throws JsonSchemaError */\n\t\t\tif (!(error instanceof JsonSchemaError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() schema is outside the supported subset — ${error.message}`, \"UNSUPPORTED_SCHEMA\", { cause: error });\n\t\t}\n\t\treturn {\n\t\t\t...record.label !== void 0 ? { label: record.label } : {},\n\t\t\t...record.phase !== void 0 ? { phase: record.phase } : {},\n\t\t\t...record.provider !== void 0 ? { provider: record.provider } : {},\n\t\t\t...record.model !== void 0 ? { model: record.model } : {},\n\t\t\t...schema !== void 0 ? { schema } : {}\n\t\t};\n\t}\n\t/** The `parallel(thunks)` hook: each thunk caught → `null`; fatal errors propagate. */\n\tasync parallel(rawThunks) {\n\t\tif (!Array.isArray(rawThunks)) throw new WorkflowError(\"parallel() requires an array of zero-argument functions\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawThunks.length, \"parallel()\");\n\t\tconst thunks = rawThunks.map((thunk, index) => {\n\t\t\tif (typeof thunk !== \"function\") throw new WorkflowError(`parallel() item ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn thunk;\n\t\t});\n\t\treturn Promise.all(thunks.map(async (thunk) => {\n\t\t\ttry {\n\t\t\t\treturn await thunk();\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\t/** The `pipeline(items, ...stages)` hook: per-item stage chains, NO cross-stage barrier. */\n\tasync pipeline(rawItems, rawStages) {\n\t\tif (!Array.isArray(rawItems)) throw new WorkflowError(\"pipeline() requires an items array\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawItems.length, \"pipeline()\");\n\t\tif (rawStages.length === 0) throw new WorkflowError(\"pipeline() requires at least one stage function\", \"INVALID_ARGUMENT\");\n\t\tconst stages = rawStages.map((stage, index) => {\n\t\t\tif (typeof stage !== \"function\") throw new WorkflowError(`pipeline() stage ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn stage;\n\t\t});\n\t\treturn Promise.all(rawItems.map(async (item, index) => {\n\t\t\tlet value = item;\n\t\t\ttry {\n\t\t\t\tfor (const stage of stages) value = await stage(value, item, index);\n\t\t\t\treturn value;\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\tassertItemCap(length, hook) {\n\t\tif (length > this.limits.maxItemsPerCall) throw new WorkflowError(`${hook} received ${length} items — over the per-call cap (${this.limits.maxItemsPerCall}); split the work or raise maxItemsPerCall in the engine config`, \"ITEM_CAP\");\n\t}\n\t/** The `phase(title)` hook: sets the current label for subsequent `agent()` calls and notifies observers. */\n\tphase(title) {\n\t\tif (typeof title !== \"string\" || title.length === 0) throw new WorkflowError(\"phase() requires a non-empty title string\", \"INVALID_ARGUMENT\");\n\t\tthis.currentPhase = title;\n\t\tthis.observer.phase(title);\n\t}\n\t/** The `log(message)` hook: narration to observers. */\n\tlog(message) {\n\t\tif (typeof message !== \"string\") throw new WorkflowError(\"log() requires a message string\", \"INVALID_ARGUMENT\");\n\t\tthis.observer.log(message);\n\t}\n};\n//#endregion\n//#region packages/workflow/workflow-ptc/src/guest.ts\n/**\n* Run a workflow with one progress batch in flight. Drain progress before child\n* disposal and the terminal result; PTC and the host own cancellation and cleanup.\n* @param host - JSON callbacks owned by this workflow run.\n* @returns The script result after progress delivery; initialization failures reject.\n*/\nasync function runWorkflowGuest(host) {\n\tconst init = await host.begin({});\n\tlet queued = [];\n\tlet inFlight;\n\tlet progressError;\n\tconst flush = () => {\n\t\tif (inFlight !== void 0 || queued.length === 0) return;\n\t\tconst batch = queued;\n\t\tqueued = [];\n\t\tinFlight = host.progress(batch).then(() => {\n\t\t\tinFlight = void 0;\n\t\t\tflush();\n\t\t}, (error) => {\n\t\t\tprogressError = renderThrown(error);\n\t\t\tqueued = [];\n\t\t\tinFlight = void 0;\n\t\t});\n\t};\n\tconst send = (event) => {\n\t\tif (progressError !== void 0) return;\n\t\tqueued.push(event);\n\t\tflush();\n\t};\n\tconst drain = async () => {\n\t\twhile (inFlight !== void 0) await inFlight;\n\t};\n\tconst result = await new WorkflowExecution(init.meta, init.body, init.args, init.limits, {\n\t\tphase: (title) => {\n\t\t\tsend({\n\t\t\t\ttype: \"phase\",\n\t\t\t\ttitle\n\t\t\t});\n\t\t},\n\t\tlog: (message) => {\n\t\t\tsend({\n\t\t\t\ttype: \"log\",\n\t\t\t\tmessage\n\t\t\t});\n\t\t},\n\t\tagentStart: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-start\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t},\n\t\tagentEnd: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-end\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t}\n\t}, { async startAgent(request) {\n\t\tconst { callId, childId } = await host.startChild(request);\n\t\tconst result = host.childResult({ callId });\n\t\tresult.catch(() => {});\n\t\treturn {\n\t\t\tid: childId,\n\t\t\tresult,\n\t\t\tasync dispose() {\n\t\t\t\tawait drain();\n\t\t\t\tawait host.disposeChild({ callId });\n\t\t\t}\n\t\t};\n\t} }).drive();\n\tawait drain();\n\treturn progressError === void 0 ? result : {\n\t\tvalue: null,\n\t\tstopReason: \"error\",\n\t\terror: progressError,\n\t\tagentsStarted: result.agentsStarted\n\t};\n}\n//#endregion\nexport { runWorkflowGuest };\n//# sourceURL=dsh-workflow-guest.js\n" diff --git a/packages/workflow/workflow-ptc/src/runtime.ts b/packages/workflow/workflow-ptc/src/runtime.ts index 71c153e586..373bd1bf87 100644 --- a/packages/workflow/workflow-ptc/src/runtime.ts +++ b/packages/workflow/workflow-ptc/src/runtime.ts @@ -7,7 +7,7 @@ import * as vm from 'node:vm' import { brandString } from '@deepseek-ai/dsh-brand' -import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { SessionId } from '@deepseek-ai/dsh-session' import { assertObjectJsonSchema, JsonSchemaError } from '@deepseek-ai/dsh-tools' import type { ObjectJsonSchema } from '@deepseek-ai/dsh-tools' @@ -34,14 +34,6 @@ const SUPPORTED_AGENT_OPTIONS = new Set(['label', 'phase', 'schema', 'provider', /** Deferred Claude Code options we name explicitly in the rejection message. */ const DEFERRED_AGENT_OPTIONS = new Set(['effort', 'isolation', 'agentType']) -/** Flatten a child's final output blocks to text (the non-schema `agent()` result). */ -function outputText(blocks: ContentBlock[]): string { - return blocks - .filter((block): block is Extract => block.type === 'text') - .map(block => block.text) - .join('') -} - /** A short display label derived from the prompt when the script passes none. */ function defaultLabel(prompt: string): string { const newline = prompt.indexOf('\n') @@ -216,7 +208,7 @@ export class WorkflowExecution { return result.structured } this.observer.agentEnd({ ...info, outcome: 'completed' }) - return outputText(result.output) + return extractTextContent(result.output) } this.observer.agentEnd({ ...info, outcome: 'failed' }) return null From 3268ba0ccd11717fefed03978ea0e74dbf3ad434 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Wed, 11 Nov 2026 14:17:28 +0800 Subject: [PATCH 12/48] refactor(llm): share extractTextContent across text consumers --- docs/config-catalog.md | 10 ++--- docs/config-catalog.zh.md | 10 ++--- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- docs/module-graph.md | 3 +- docs/module-graph.zh.md | 3 +- docs/persistence-catalog.i18n.yaml | 4 +- docs/persistence-catalog.md | 2 +- docs/persistence-catalog.zh.md | 2 +- packages/bundle/headless/src/index.ts | 6 +-- .../src/client/conversation-nodes/command.ts | 5 +-- .../src/client/contract/system-prompt.ts | 3 +- .../src/client/queue/QueueDock.tsx | 5 ++- .../src/client/tool/toolviews/office-row.tsx | 3 +- .../session-reference/src/projection.ts | 10 ++--- packages/core/tool-executor-ptc/src/ptc.ts | 3 +- .../claude-code-mods/src/host-ops.ts | 9 ++-- .../claude-code-mods/src/index.ts | 9 ++-- .../client-ui-stats/src/client/stats-fold.ts | 12 ++---- .../experimental/forge-session/package.json | 1 + .../forge-session/src/projection.ts | 4 +- .../forge-session/src/reference-lookup.ts | 4 +- .../hooks-claude-code/src/index.ts | 10 ++--- .../experimental/hooks-codex/src/index.ts | 12 ++---- .../src/index.ts | 8 ++-- packages/llm/llm-deepseek/src/serialize.ts | 6 +-- packages/llm/llm-pi-ai/src/context.ts | 20 +++------ packages/llm/llm/README.i18n.yaml | 8 ++-- packages/llm/llm/README.md | 3 +- packages/llm/llm/README.zh.md | 3 +- packages/llm/llm/src/index.ts | 6 ++- packages/llm/llm/src/message.ts | 15 ++++++- packages/llm/llm/tests/message.spec.ts | 41 +++++++++++++++++++ packages/sdk/server/src/query-activity.ts | 4 +- .../src/index.ts | 8 ++-- packages/session/session-title/src/index.ts | 6 +-- packages/web/web-deepseek-api/src/index.ts | 5 ++- .../workflow/workflow-ptc/src/guest-source.ts | 2 +- packages/workflow/workflow-ptc/src/runtime.ts | 12 +----- 39 files changed, 154 insertions(+), 127 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 825cea47b9..605f3537d8 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1645,7 +1645,7 @@ export interface Config { - `inject`: `agentDefaultModel` · `agents` · `sessions` - `refs`: [`ApprovalPolicy`](subsystems/approval.md) -- `source`: [`packages/bundle/headless/src/index.ts:48`](../packages/bundle/headless/src/index.ts) +- `source`: [`packages/bundle/headless/src/index.ts:49`](../packages/bundle/headless/src/index.ts) ```ts config-catalog /** Plugin config: the task and run options resolved from this app's injected provider service. */ @@ -1693,7 +1693,7 @@ export interface HmrConfig extends ChokidarOptions { ## `@deepseek-ai/dsh-hooks-claude-code` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:50`](../packages/experimental/hooks-claude-code/src/index.ts) +- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:51`](../packages/experimental/hooks-claude-code/src/index.ts) ```ts config-catalog /** Plugin config: where the CC hook config lives + substitution roots. */ @@ -1732,7 +1732,7 @@ export interface Config { ## `@deepseek-ai/dsh-hooks-codex` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-codex/src/index.ts:49`](../packages/experimental/hooks-codex/src/index.ts) +- `source`: [`packages/experimental/hooks-codex/src/index.ts:50`](../packages/experimental/hooks-codex/src/index.ts) ```ts config-catalog /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */ @@ -3330,7 +3330,7 @@ export enum SessionTelemetryMode { ## `@deepseek-ai/dsh-session-title` - `inject`: `sessions` · `sessionProjections` · `agents` -- `source`: [`packages/session/session-title/src/index.ts:56`](../packages/session/session-title/src/index.ts) +- `source`: [`packages/session/session-title/src/index.ts:57`](../packages/session/session-title/src/index.ts) ```ts config-catalog /** Required deterministic fallback and accepted-title limits. */ @@ -4815,7 +4815,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-deepseek-api/src/index.ts:64`](../packages/web/web-deepseek-api/src/index.ts) +- `source`: [`packages/web/web-deepseek-api/src/index.ts:65`](../packages/web/web-deepseek-api/src/index.ts) ```ts config-catalog /** diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 09c61e5660..e36e5652ba 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1647,7 +1647,7 @@ export interface Config { - `inject`: `agentDefaultModel` · `agents` · `sessions` - `refs`: [`ApprovalPolicy`](subsystems/approval.zh.md) -- `source`: [`packages/bundle/headless/src/index.ts:48`](../packages/bundle/headless/src/index.ts) +- `source`: [`packages/bundle/headless/src/index.ts:49`](../packages/bundle/headless/src/index.ts) ```ts config-catalog /** Plugin config: the task and run options resolved from this app's injected provider service. */ @@ -1695,7 +1695,7 @@ export interface HmrConfig extends ChokidarOptions { ## `@deepseek-ai/dsh-hooks-claude-code` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:50`](../packages/experimental/hooks-claude-code/src/index.ts) +- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:51`](../packages/experimental/hooks-claude-code/src/index.ts) ```ts config-catalog /** Plugin config: where the CC hook config lives + substitution roots. */ @@ -1734,7 +1734,7 @@ export interface Config { ## `@deepseek-ai/dsh-hooks-codex` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-codex/src/index.ts:49`](../packages/experimental/hooks-codex/src/index.ts) +- `source`: [`packages/experimental/hooks-codex/src/index.ts:50`](../packages/experimental/hooks-codex/src/index.ts) ```ts config-catalog /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */ @@ -3332,7 +3332,7 @@ export enum SessionTelemetryMode { ## `@deepseek-ai/dsh-session-title` - `inject`: `sessions` · `sessionProjections` · `agents` -- `source`: [`packages/session/session-title/src/index.ts:56`](../packages/session/session-title/src/index.ts) +- `source`: [`packages/session/session-title/src/index.ts:57`](../packages/session/session-title/src/index.ts) ```ts config-catalog /** Required deterministic fallback and accepted-title limits. */ @@ -4817,7 +4817,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-deepseek-api/src/index.ts:64`](../packages/web/web-deepseek-api/src/index.ts) +- `source`: [`packages/web/web-deepseek-api/src/index.ts:65`](../packages/web/web-deepseek-api/src/index.ts) ```ts config-catalog /** diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 3a8967f3a0..7bf87ba05c 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -60,7 +60,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 605c83f4f3..4e69269e5c 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -62,7 +62,7 @@ | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | diff --git a/docs/module-graph.md b/docs/module-graph.md index 717151dcef..33d3de5dd9 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -1124,6 +1124,7 @@ flowchart TD pkg_experimental_auto_review --> pkg_tools pkg_experimental_auto_review --> pkg_working_directory pkg_experimental_forge_session --> pkg_experimental_forge + pkg_experimental_forge_session --> pkg_llm pkg_experimental_forge_session --> pkg_sandbox_policy pkg_experimental_forge_session --> pkg_session pkg_experimental_forge_session --> pkg_session_projection @@ -1853,7 +1854,7 @@ flowchart TD | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | | [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | +| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | | [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | | [`tool-cordis`](../packages/extensions/tool-cordis) | `extensions` | [`agent`](../packages/core/agent), [`app-boot`](../packages/boot/app-boot), [`cordis-host-runner`](../packages/extensions/cordis-host-runner), [`tools`](../packages/core/tools) | | [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`brand`](../packages/util/brand), [`typert-protocol`](../packages/typert/protocol) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 42507cab06..e0e4a65102 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -1126,6 +1126,7 @@ flowchart TD pkg_experimental_auto_review --> pkg_tools pkg_experimental_auto_review --> pkg_working_directory pkg_experimental_forge_session --> pkg_experimental_forge + pkg_experimental_forge_session --> pkg_llm pkg_experimental_forge_session --> pkg_sandbox_policy pkg_experimental_forge_session --> pkg_session pkg_experimental_forge_session --> pkg_session_projection @@ -1855,7 +1856,7 @@ flowchart TD | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | | [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | +| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | | [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | | [`tool-cordis`](../packages/extensions/tool-cordis) | `extensions` | [`agent`](../packages/core/agent), [`app-boot`](../packages/boot/app-boot), [`cordis-host-runner`](../packages/extensions/cordis-host-runner), [`tools`](../packages/core/tools) | | [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`brand`](../packages/util/brand), [`typert-protocol`](../packages/typert/protocol) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index 4e1e235fcb..20fbd2e33b 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -183,8 +183,8 @@ en: 20645a60e921f012 zh: 7141cafe3a0e71d7 /session-persistence-event-catalog/events/session/session-title-log-only: - en: 6c6a27578dff5828 - zh: 9a5add2bc0df2d0a + en: 5775e52a72c0ce94 + zh: fa211a35b4660c10 /session-persistence-event-catalog/events/session/session-title-llm-request-log-only: en: 59b02baa2be32ca0 zh: 3637c99652ca89cf diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 8392c8b354..fd81a9a562 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -865,7 +865,7 @@ Source: [`packages/core/session/src/types.ts:435`](../packages/core/session/src/ Types: [SessionTitleEventData](subsystems/session-title.md) -Source: [`packages/session/session-title/src/index.ts:77`](../packages/session/session-title/src/index.ts) +Source: [`packages/session/session-title/src/index.ts:78`](../packages/session/session-title/src/index.ts) diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index acbfefaf7d..c7fa4a6edb 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -867,7 +867,7 @@ export type SessionEvent = { 类型:[SessionTitleEventData](subsystems/session-title.zh.md) -来源:[`packages/session/session-title/src/index.ts:77`](../packages/session/session-title/src/index.ts) +来源:[`packages/session/session-title/src/index.ts:78`](../packages/session/session-title/src/index.ts) diff --git a/packages/bundle/headless/src/index.ts b/packages/bundle/headless/src/index.ts index bc98d7ae6b..69b40ac06a 100644 --- a/packages/bundle/headless/src/index.ts +++ b/packages/bundle/headless/src/index.ts @@ -18,6 +18,7 @@ import type { Agent, AgentOptions } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-agent-default-model' import { installModelSelection } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-fs' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { APPROVAL_POLICIES, setApprovalPolicy, type ApprovalPolicy } from '@deepseek-ai/dsh-user-approval' import { assertNever } from '@deepseek-ai/dsh-util-values' @@ -99,10 +100,7 @@ function summarize(session: Session, firstSeq: SessionLogOffset): RunOutcome { } if (!started) continue if (event.type === 'assistant/message') { - const joined = event.data.message.content - .filter(block => block.type === 'text') - .map(block => block.text) - .join('') + const joined = extractTextContent(event.data.message.content) if (joined !== '') text = joined } if (event.type === 'turn/end') reason = event.data.reason diff --git a/packages/client/ui-chat/src/client/conversation-nodes/command.ts b/packages/client/ui-chat/src/client/conversation-nodes/command.ts index a52b877552..de407aa354 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/command.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/command.ts @@ -1,3 +1,4 @@ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { Context } from '@deepseek-ai/cordis' import type { CommandNode, CompactionSummaryNode, ConversationMatch, ConversationNodeContext, ConversationNodeDefinition, @@ -105,9 +106,7 @@ function compactSummary(match: ConversationMatch | undefined, checkpoint: Conver if (match?.event.type === 'compaction/summary') { const data = match.event.data if (Array.isArray(data.summary)) { - const text = data.summary - .map(block => block.type === 'text' ? block.text : '') - .join('') + const text = extractTextContent(data.summary) summary = text.trim() === '' ? null : text } shadowedItemCount = Array.isArray(data.shadowedSeqs) diff --git a/packages/client/ui-conversation/src/client/contract/system-prompt.ts b/packages/client/ui-conversation/src/client/contract/system-prompt.ts index e61b35d81b..3ac1fadcc7 100644 --- a/packages/client/ui-conversation/src/client/contract/system-prompt.ts +++ b/packages/client/ui-conversation/src/client/contract/system-prompt.ts @@ -1,4 +1,5 @@ /** Immutable system-only interpretation of the loaded Session surface. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { SessionEvent } from '@deepseek-ai/dsh-session/types' import { isSurfaceEvent } from '@deepseek-ai/dsh-session/surface' import type { SystemPromptNode } from './request-inspection.ts' @@ -61,7 +62,7 @@ export function inspectSystemPrompt(previous: SystemPromptState | undefined, eve time: event.time, turn: event.data.turn, step: event.data.step, - text: event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join(''), + text: extractTextContent(event.data.message.content), update: op === 'append' && previous?.nodes.some(item => item.node.text !== '') === true, } : undefined diff --git a/packages/client/ui-conversation/src/client/queue/QueueDock.tsx b/packages/client/ui-conversation/src/client/queue/QueueDock.tsx index b0907447c6..efbf311ef6 100644 --- a/packages/client/ui-conversation/src/client/queue/QueueDock.tsx +++ b/packages/client/ui-conversation/src/client/queue/QueueDock.tsx @@ -1,3 +1,4 @@ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { Context } from '@deepseek-ai/cordis' import { useEffect, useId, useMemo, useState } from 'react' import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' @@ -23,7 +24,7 @@ const QUEUE_TEXT_FACTS: Readonly> = { function textOf(content: InboxState['next-turn'][number]['content']): string | null { if (!content.every(block => block.type === 'text')) return null - return content.map(block => block.text).join('') + return extractTextContent(content) } /** Queue operations injected by the session-scoped registration. */ @@ -228,7 +229,7 @@ export function QueueDock({ useSession, useProjection, updateQueue, notify, load )} {renderFactorySlot('conversation.user.text', { - text: row.content.filter(block => block.type === 'text').map(block => block.text).join(''), + text: extractTextContent(row.content), facts: QUEUE_TEXT_FACTS, interactive: false, ellipsis: true, })} diff --git a/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx b/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx index e52ff7d10f..c3e14750fe 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx +++ b/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx @@ -1,6 +1,7 @@ // Office toolview links target the input, not the temporary output. Rows show the // result's text blocks; rendered page images reach the model but are not displayed. +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { IconBrowseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { Context } from '@deepseek-ai/cordis' import { toolFileInject } from '../file-menu.ts' @@ -26,7 +27,7 @@ export function OfficeRow({ const row = toolRowModel(toolName, block, cwd, home) // Image blocks flatten to JSON attachment references, so a settled result with only images shows no body. const output = 'kind' in block - ? block.content.flatMap(part => part.type === 'text' ? [part.text] : []).join('\n') || null + ? extractTextContent(block.content, { separator: '\n' }) || null : row.output const path = office.filePath return ( diff --git a/packages/context/session-reference/src/projection.ts b/packages/context/session-reference/src/projection.ts index 196c75b4e1..f747f242c3 100644 --- a/packages/context/session-reference/src/projection.ts +++ b/packages/context/session-reference/src/projection.ts @@ -1,5 +1,7 @@ /** Current-surface projection and byte-bounded rendering. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import { isCompactCheckpointSource } from '@deepseek-ai/dsh-compaction' import type { SessionSurfaceSnapshot } from '@deepseek-ai/dsh-session-query' import { TextRetainer } from '@deepseek-ai/dsh-output-retention' @@ -42,12 +44,12 @@ function projectSessionConversation(snapshot: SessionSurfaceSnapshot): Projected case 'user/message': { const checkpoint = isCompactCheckpointSource(event.data.source) if (!checkpoint && event.data.source.kind !== 'user') break - const text = textContent(event.data.content) + const text = extractTextContent(event.data.content, { separator: '\n' }) if (text !== '') conversation.push({ role: 'user', text, checkpoint, originalText: text, omittedBytes: 0 }) break } case 'assistant/message': { - const text = textContent(event.data.message.content) + const text = extractTextContent(event.data.message.content, { separator: '\n' }) if (text !== '') conversation.push({ role: 'assistant', text, checkpoint: false, originalText: text, omittedBytes: 0 }) break } @@ -145,10 +147,6 @@ export function retainReferencedSession( } } -function textContent(content: readonly { type: string; text?: string }[]): string { - return content.flatMap(block => block.type === 'text' && typeof block.text === 'string' ? [block.text] : []).join('\n') -} - function truncateWithNotice(text: string, maxOutputBytes: number): { text: string; omittedBytes: number } { /* v8 ignore next -- callers invoke this only with a target smaller than the selected original text. */ if (Buffer.byteLength(text, 'utf8') <= maxOutputBytes) return { text, omittedBytes: 0 } diff --git a/packages/core/tool-executor-ptc/src/ptc.ts b/packages/core/tool-executor-ptc/src/ptc.ts index 7fa2b79c78..ce3202e2b9 100644 --- a/packages/core/tool-executor-ptc/src/ptc.ts +++ b/packages/core/tool-executor-ptc/src/ptc.ts @@ -10,6 +10,7 @@ import { isDeepStrictEqual } from 'node:util' import type { PtcDispatchLog } from './runtime-types.ts' import { symbols, type Context } from '@deepseek-ai/cordis' import { brandString } from '@deepseek-ai/dsh-brand' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage, HarnessError, resolveImageAttachmentAccess } from '@deepseek-ai/dsh-llm' import type { ContentBlock, ToolCallId, ToolSchema } from '@deepseek-ai/dsh-llm' @@ -704,7 +705,7 @@ export function createRunCodeTransport( if (first !== undefined && images.length === 1) return programImage(first.attachment) if (outcome.imageRemoved) { throw new Error('Image output was removed by a tool output policy.\n' - + outcome.content.filter(block => block.type === 'text').map(block => block.text).join('\n')) + + extractTextContent(outcome.content, { separator: '\n' })) } if (name === 'read_image' || images.length > 1) throw new Error('Image-producing tools must return exactly one image') } diff --git a/packages/experimental/claude-code-mods/src/host-ops.ts b/packages/experimental/claude-code-mods/src/host-ops.ts index 1ad62ef0c7..9908a22ff1 100644 --- a/packages/experimental/claude-code-mods/src/host-ops.ts +++ b/packages/experimental/claude-code-mods/src/host-ops.ts @@ -16,6 +16,7 @@ import type { CommandDefinition } from '@deepseek-ai/dsh-commands' import type { FileSystem, FsTarget } from '@deepseek-ai/dsh-fs' import { brandString } from '@deepseek-ai/dsh-brand' import { createUserMessage, type ToolCallId } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { ContentBlock, Message } from '@deepseek-ai/dsh-llm' import { scopeOf } from '@deepseek-ai/dsh-scope' import type { WorkingDirectoryService } from '@deepseek-ai/dsh-working-directory' @@ -107,17 +108,13 @@ function requireAgent(context: OpContext, op: string): Agent { return agent } -function textOf(content: readonly ContentBlock[]): string { - return content.filter((block): block is Extract => block.type === 'text').map(block => block.text).join('') -} - /** * Project one tool outcome onto Claude Code's `tool.call` result. * @param result - the harness tool outcome. * @returns its text as `result`, with `isError` on a failure. */ export function toolCallResultOf(result: ToolExecutionResult): ToolCallResult { - return result.isError ? { result: textOf(result.content), isError: true } : { result: textOf(result.content) } + return result.isError ? { result: extractTextContent(result.content), isError: true } : { result: extractTextContent(result.content) } } /** The model's raw JSON arguments as an object; an unparsable string is an empty input. */ @@ -137,7 +134,7 @@ function sessionMessages(messages: readonly Message[], aliases: ToolNameAliases) const toolUses = message.content .filter((block): block is Extract => block.type === 'tool-call') .map(block => ({ tool_use_id: block.id, tool: aliases.toMod(block.name), input: argumentsOf(block.arguments) })) - out.push({ role: message.role, text: textOf(message.content), toolUses }) + out.push({ role: message.role, text: extractTextContent(message.content), toolUses }) } return out } diff --git a/packages/experimental/claude-code-mods/src/index.ts b/packages/experimental/claude-code-mods/src/index.ts index 5a725ae533..bed288d211 100644 --- a/packages/experimental/claude-code-mods/src/index.ts +++ b/packages/experimental/claude-code-mods/src/index.ts @@ -18,6 +18,7 @@ import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' import type { AssistantMessage, ContentBlock, TokenUsage } from '@deepseek-ai/dsh-llm' import { brandString } from '@deepseek-ai/dsh-brand' import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { UserMessage } from '@deepseek-ai/dsh-session' import { scopeOf } from '@deepseek-ai/dsh-scope' import { validateJsonSchemaValue } from '@deepseek-ai/dsh-tools' @@ -78,10 +79,6 @@ function assertPositive(field: string, value: number): void { if (!Number.isFinite(value) || value <= 0) throw new Error(`claude-code-mods: ${field} must be a positive number of milliseconds`) } -function textOf(blocks: readonly ContentBlock[]): string { - return blocks.filter((block): block is Extract => block.type === 'text').map(block => block.text).join('') -} - /** The human's own messages among a claim: the prompt a `prompt.submit` hook sees and may rewrite. */ function promptMessages(claimed: readonly UserMessage[]): UserMessage[] { return claimed.filter(message => message.source.kind === 'user') @@ -141,7 +138,7 @@ interface TurnRecord { /** Fold one committed assistant message into the turn's answer and usage. */ function foldAssistantMessage(turnRecord: TurnRecord, data: { message: AssistantMessage; usage?: TokenUsage }): void { - turnRecord.answer = textOf(data.message.content) + turnRecord.answer = extractTextContent(data.message.content) if (data.usage === undefined) return const { model } = data.message.source const usage = turnRecord.usage ?? { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, model } @@ -349,7 +346,7 @@ export class ClaudeCodeMods extends TypertRemoteService { const first = !started.has(turn) started.add(turn) const prompt = promptMessages(messages) - const text = textOf(prompt.flatMap(message => message.content)) + const text = extractTextContent(prompt.flatMap(message => message.content)) let submitted: PromptSubmitResult = { text } // A batch of injected context alone is not a prompt: Claude Code raises prompt.submit for typed prompts. if (prompt.length > 0) { diff --git a/packages/experimental/client-ui-stats/src/client/stats-fold.ts b/packages/experimental/client-ui-stats/src/client/stats-fold.ts index 365a7873f1..fd7c6d78e8 100644 --- a/packages/experimental/client-ui-stats/src/client/stats-fold.ts +++ b/packages/experimental/client-ui-stats/src/client/stats-fold.ts @@ -1,5 +1,6 @@ /** Event folding and per-step metric derivation for the Statistics table. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { SessionEventLike } from '@deepseek-ai/dsh-api-session-controller/client' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { AssistantMessage, ContentBlock, StreamChunk, UserMessage } from '@deepseek-ai/dsh-llm' @@ -267,10 +268,7 @@ const OPAQUE_SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9 export function triggerSenderOf(message: UserMessage): string | null { const kind: string = message.source.kind if (kind !== 'agent-message' && kind !== 'team-message') return null - let text = '' - for (const block of message.content) { - if (block.type === 'text') text += block.text - } + const text = extractTextContent(message.content) const team = TEAM_MESSAGE_PREFIX.exec(text) /* v8 ignore next -- a matched capture group is always present. */ if (team !== null) return team[1]?.trim() ?? null @@ -291,11 +289,7 @@ function answerOf(message: AssistantMessage): { body: string truncated: boolean } | null { - const parts: string[] = [] - for (const block of message.content) { - if (block.type === 'text') parts.push(block.text) - } - const text = parts.join('\n').trim() + const text = extractTextContent(message.content, { separator: '\n' }).trim() if (text === '') return null return { preview: text.length > ANSWER_LIMIT ? text.slice(0, ANSWER_LIMIT) : text, diff --git a/packages/experimental/forge-session/package.json b/packages/experimental/forge-session/package.json index 90c20a4398..227cf26989 100644 --- a/packages/experimental/forge-session/package.json +++ b/packages/experimental/forge-session/package.json @@ -43,6 +43,7 @@ }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-experimental-forge": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", diff --git a/packages/experimental/forge-session/src/projection.ts b/packages/experimental/forge-session/src/projection.ts index 1f1ab54a43..0a285de34d 100644 --- a/packages/experimental/forge-session/src/projection.ts +++ b/packages/experimental/forge-session/src/projection.ts @@ -1,5 +1,7 @@ /** Projection that folds shell results and binding records into one Session's change request bindings, and shows clients the bindings. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import { z } from 'zod' import { pluginRecordOf, SessionSeq } from '@deepseek-ai/dsh-session' import type { SessionEvent, SessionEventMap } from '@deepseek-ai/dsh-session' @@ -105,7 +107,7 @@ function applyResult(state: ForgeChangeRequestsState, result: SessionEventMap['t if (pending === undefined) return state const rest = state.pending.filter(entry => entry !== pending) if (result.message.isError === true) return { ...state, pending: rest } - const text = result.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n') + const text = extractTextContent(result.message.content, { separator: '\n' }) const printed = pending.urls === 'created' ? changeRequestUrls(text) : ownChangeRequestUrls(text) return { pending: rest, diff --git a/packages/experimental/forge-session/src/reference-lookup.ts b/packages/experimental/forge-session/src/reference-lookup.ts index 7cce3eb6dc..b648911c58 100644 --- a/packages/experimental/forge-session/src/reference-lookup.ts +++ b/packages/experimental/forge-session/src/reference-lookup.ts @@ -1,5 +1,7 @@ /** Resolve unqualified CLI references in the shell execution world and persist only confirmed URLs. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import type { Context } from '@deepseek-ai/cordis' import type { Session } from '@deepseek-ai/dsh-session' import type { ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools' @@ -53,7 +55,7 @@ export function observeReferences(ctx: Context, timeoutMs: number, record: (sess const argumentsResult = shellArguments.safeParse(exec.arguments) const shell = completedShell.safeParse(result.value) if (!argumentsResult.success || !shell.success) return - const printed = result.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n') + const printed = extractTextContent(result.content, { separator: '\n' }) if (ownChangeRequestUrls(printed).length > 0) return const lookups = ghReferences(argumentsResult.data.command).flatMap(reference => reference.lookup === null ? [] : [reference.lookup]) const agent = exec.agent diff --git a/packages/experimental/hooks-claude-code/src/index.ts b/packages/experimental/hooks-claude-code/src/index.ts index 5e2b59d3d8..2541297e3d 100644 --- a/packages/experimental/hooks-claude-code/src/index.ts +++ b/packages/experimental/hooks-claude-code/src/index.ts @@ -13,6 +13,7 @@ import { readFileSync } from 'node:fs' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' declare module '@deepseek-ai/dsh-llm' { @@ -319,11 +320,6 @@ function lastTurn(ctx: Context, agent: Agent | undefined): number { return ctx.agents.turnBoundaryOf(agent.session).lastTurn } -/** Flatten content blocks to the text a hook payload carries (the common case). */ -function blocksToText(content: ContentBlock[]): string { - return content.filter((b): b is Extract => b.type === 'text').map(b => b.text).join('') -} - function base(agent: Agent | undefined, event: string): Record { return { session_id: agent?.session.header.id ?? '', @@ -338,13 +334,13 @@ function sessionStartPayload(agent: Agent, source: string): Record { - return { ...base(agent, 'UserPromptSubmit'), prompt: blocksToText(content) } + return { ...base(agent, 'UserPromptSubmit'), prompt: extractTextContent(content) } } function preToolPayload(exec: ToolExecution): Record { return { ...base(exec.agent, 'PreToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId } } function postToolPayload(exec: ToolExecution, result: ToolExecutionResult): Record { - return { ...base(exec.agent, 'PostToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId, tool_response: blocksToText(result.content) } + return { ...base(exec.agent, 'PostToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId, tool_response: extractTextContent(result.content) } } function stopPayload(agent: Agent): Record { return { ...base(agent, 'Stop'), stop_hook_active: false } diff --git a/packages/experimental/hooks-codex/src/index.ts b/packages/experimental/hooks-codex/src/index.ts index 2d9b3c3daf..6d86ae79f3 100644 --- a/packages/experimental/hooks-codex/src/index.ts +++ b/packages/experimental/hooks-codex/src/index.ts @@ -16,6 +16,7 @@ import { readFileSync } from 'node:fs' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' declare module '@deepseek-ai/dsh-llm' { @@ -203,7 +204,7 @@ export function apply(ctx: Context, config: Config): void { const payload = { ...base(agent, 'UserPromptSubmit', model), turn_id: String(turn), - prompt: blocksToText(messages.flatMap(message => message.content)), + prompt: extractTextContent(messages.flatMap(message => message.content)), } const merged = await runPoint('UserPromptSubmit', '', payload, { agent, turn, plainStdoutAsContext: true, signal, @@ -275,17 +276,12 @@ export function apply(ctx: Context, config: Config): void { // --- Codex DIALECT payloads: snake_case, model on every event, turn_id on // turn-scoped events. --- -// These small payload helpers intentionally remain next to the dialect shape; -// sharing them would pull bridge-only agent/LLM dependencies into hook-protocol. +// Shared hook-protocol code has no Agent dependency, so turn lookup stays in the bridge. /* jscpd:ignore-start */ function lastTurn(ctx: Context, agent: Agent | undefined): number { if (!agent) return 0 return ctx.agents.turnBoundaryOf(agent.session).lastTurn } - -function blocksToText(content: ContentBlock[]): string { - return content.filter((b): b is Extract => b.type === 'text').map(b => b.text).join('') -} /* jscpd:ignore-end */ /** Base fields on every Codex payload (no turn_id). */ @@ -324,5 +320,5 @@ function preToolPayload(ctx: Context, exec: ToolExecution, model: string): Recor } function postToolPayload(ctx: Context, exec: ToolExecution, result: ToolExecutionResult, model: string): Record { - return { ...turnBase(ctx, exec.agent, 'PostToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId, tool_response: blocksToText(result.content) } + return { ...turnBase(ctx, exec.agent, 'PostToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId, tool_response: extractTextContent(result.content) } } diff --git a/packages/experimental/session-title-all-prompts-llm/src/index.ts b/packages/experimental/session-title-all-prompts-llm/src/index.ts index 042267bc49..f2623be0c4 100644 --- a/packages/experimental/session-title-all-prompts-llm/src/index.ts +++ b/packages/experimental/session-title-all-prompts-llm/src/index.ts @@ -3,7 +3,8 @@ /* jscpd:ignore-start -- both shipped providers import the same shared packages. */ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import type { LlmResolvedModelInfo, ReasoningEffortId } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' +import { type LlmResolvedModelInfo, type ReasoningEffortId } from '@deepseek-ai/dsh-llm' import { assertNever } from '@deepseek-ai/dsh-util-values' import { brandString } from '@deepseek-ai/dsh-brand' import type { SessionTitleProviderId } from '@deepseek-ai/dsh-session-title/types' @@ -137,10 +138,7 @@ function titleFromResponse(response: SessionTitleLlmResponse): string { if (response.blocks.some(block => block.type === 'tool-call')) { throw new Error('session-title-llm: title output must contain text only') } - const text = response.blocks - .filter((block): block is Extract<(typeof response.blocks)[number], { type: 'text' }> => block.type === 'text') - .map(block => block.text) - .join(' ') + const text = extractTextContent(response.blocks, { separator: ' ' }) const title = normalizeSessionTitle(titleFromOutput(text), Number.MAX_SAFE_INTEGER) if (title.length === 0) throw new Error('session-title-llm: title model produced no text') return title diff --git a/packages/llm/llm-deepseek/src/serialize.ts b/packages/llm/llm-deepseek/src/serialize.ts index f08412c0e9..ab5e0f75d7 100644 --- a/packages/llm/llm-deepseek/src/serialize.ts +++ b/packages/llm/llm-deepseek/src/serialize.ts @@ -1,5 +1,6 @@ /** Map system snapshots, tool changes, and conversation turns to Messages using the configured route capability. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { LlmError, requestImageHandleText } from '@deepseek-ai/dsh-llm' import type { ContentBlock, GenerateOptions, ImageAttachmentAccessResolver, Message, RequestMessage } from '@deepseek-ai/dsh-llm' import type { ImageAttachmentRef, RequestImageAttachment } from '@deepseek-ai/dsh-attachment' @@ -104,9 +105,8 @@ export function serialize( return unsupported('tool-change blocks outside developer messages') } if (message.role === 'system') { - const texts = message.content.filter(block => block.type === 'text') - if (texts.length !== message.content.length) return unsupported('non-text system message') - const text = texts.map(block => block.text).join('') + if (message.content.some(block => block.type !== 'text')) return unsupported('non-text system message') + const text = extractTextContent(message.content) if (inHistory && messages.length > 0) { if (text.length === 0) return unsupported('empty in-history system update') systemUpdates.push({ role: 'system', content: [{ type: 'text', text }] }) diff --git a/packages/llm/llm-pi-ai/src/context.ts b/packages/llm/llm-pi-ai/src/context.ts index d8a657d4e6..fa8b833d43 100644 --- a/packages/llm/llm-pi-ai/src/context.ts +++ b/packages/llm/llm-pi-ai/src/context.ts @@ -5,6 +5,7 @@ */ import { brandString } from '@deepseek-ai/dsh-brand' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { contentHasImage, IMAGE_OFFLOAD_REQUIRED_CODE, LlmError, offloadedImageText, projectOffloadedImages, requestImageHandleText, requiredImageOffload } from '@deepseek-ai/dsh-llm' import type { ContentBlock, GenerateOptions, ImageAttachmentAccessResolver, Message, RequestMessage, ToolCallId } from '@deepseek-ai/dsh-llm' import type { AttachmentId } from '@deepseek-ai/dsh-attachment/types' @@ -20,15 +21,6 @@ import type { PrefixDigests } from './prefix-binding.ts' import { requestImageDimensions } from '@deepseek-ai/dsh-attachment' import { DEFAULT_REQUEST_IMAGE_MAX_BYTES, DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET } from './config.ts' -/** Join the text blocks of a harness message. */ -function flattenText(message: RequestMessage): string { - return message.content - .filter(block => block.type === 'text') - .map(block => block.text) - .join('') -} - - /** Recover the pi-ai toolResult message for one harness tool-role message. */ function toolResultOf( message: Extract, @@ -94,7 +86,7 @@ function userContent( break } } - if (content.every(block => block.type === 'text')) return content.map(block => block.text).join('') + if (content.every(block => block.type === 'text')) return extractTextContent(content) return content } @@ -151,7 +143,7 @@ function splitSystemPrompt(options: GenerateOptions): SystemPromptSplit { let end = 0 for (const message of options.messages) { if (message.role !== 'system') break - text.push(flattenText(message)) + text.push(extractTextContent(message.content)) end++ } const systemPrompt = text.filter(Boolean).join('\n\n') @@ -230,7 +222,7 @@ function appendSharedHistory( return true } if (message.role === 'system') { - const content = flattenText(message) + const content = extractTextContent(message.content) if (content.length > 0) { if (supportsMidConvoSystemMessages) { messages.push({ role: 'system', content, timestamp: 0 }) @@ -264,10 +256,10 @@ function textOnlyContext( } if (appendSharedHistory(message, options, messages, toolNames, supportsMidConvoSystemMessages, onReplayDegrade, prefixDigests)) continue if (message.role === 'tool') { - messages.push(toolResultOf(message, toolNames, flattenText(message))) + messages.push(toolResultOf(message, toolNames, extractTextContent(message.content))) continue } - messages.push({ role: 'user', content: flattenText(message), timestamp: 0 }) + messages.push({ role: 'user', content: extractTextContent(message.content), timestamp: 0 }) } return piContext(split.systemPrompt, options, messages) } diff --git a/packages/llm/llm/README.i18n.yaml b/packages/llm/llm/README.i18n.yaml index 1bc7dd7016..ee9b1d0bd5 100644 --- a/packages/llm/llm/README.i18n.yaml +++ b/packages/llm/llm/README.i18n.yaml @@ -24,8 +24,8 @@ en: cf221d60fb42a278 zh: 0ea17503495d386b /deepseek-ai-dsh-llm/use-this-package/what-you-can-do: - en: dc61eb86585f6e0d - zh: 9c0d6b240dfd2cda + en: cb9f0c6ee3203ab3 + zh: 8513340a40192513 /deepseek-ai-dsh-llm/use-this-package/failures-and-recovery: en: 47f4dab3c377a4cd zh: 49ac1c366de19136 @@ -36,8 +36,8 @@ en: 12d0444c18a397c7 zh: 9d4a5468b4bb7fcd /deepseek-ai-dsh-llm/understand-the-implementation/source-map: - en: ae1618577f4e8364 - zh: a6e8ab1563c08dfb + en: 8ec1ca8903e09bc0 + zh: 77c7bc3413cbab1c /deepseek-ai-dsh-llm/understand-the-implementation/main-flow: en: c95d4947745e39bb zh: ec37b969f27629e2 diff --git a/packages/llm/llm/README.md b/packages/llm/llm/README.md index e5d2838586..1419acbe3b 100644 --- a/packages/llm/llm/README.md +++ b/packages/llm/llm/README.md @@ -85,6 +85,7 @@ const configure = (maxTokens: number): ConfigureCall => ### What you can do +- **Extract content text** — `extractTextContent(content, options?)` from `@deepseek-ai/dsh-llm/message` joins only `text` blocks in order, preserving whitespace and empty text blocks while omitting all other block types without placeholders. The optional `options.separator` defaults to `''`. It accepts read-only content and returns `''` when no text blocks exist. - **Stream one model call** — `ctx.llm.stream(options)` yields raw chunks (token-level deltas) for any registered provider and model; consumers assemble them with `BlockAssembler`. - **Register provider adapters** — an adapter owns one or more provider routes, and its registration captures that route's retry policy; registering the same route twice fails with `DUPLICATE_ADAPTER`. - **Expose and activate providers through configuration** — adapters declare configurable-provider routes plus a settings namespace, so configuration surfaces can activate dormant providers and edit connection facts without a restart. `LlmConfigurableProvider.error` reports a configuration diagnostic for repair; unaffected models can remain serviceable. An entry can also carry `defaultBaseURL`, the endpoint the adapter uses when the profile sets none, and `nativeAuth`, the environment variables and OAuth sign-in that the adapter's authentication reads when the profile names no credential reference; `baseURLEnv` lists environment variables used to configure the endpoint. Configuration UIs read these fields from the directory without calling the adapter. @@ -116,7 +117,7 @@ The service is built on one separation: **the logical contract is provider-neutr |---|---| | [`src/index.ts`](src/index.ts) | The `LlmRuntime` service: adapter registry, configurable-provider directory, model discovery, call preparation, and the streaming boundary | | [`src/types.ts`](src/types.ts) | The `StreamChunk` protocol, content-block map, finish reasons, and shared vocabulary | -| [`src/message.ts`](src/message.ts) | Immutable message constructors shared by delivery, history, and requests | +| [`src/message.ts`](src/message.ts) | Content text extraction and immutable message constructors shared by delivery, history, and requests | | [`src/assembler.ts`](src/assembler.ts) | `BlockAssembler`: incremental chunk-to-block assembly | | [`src/assistant-stream.ts`](src/assistant-stream.ts) | Compact timed Assistant stream accumulation, strict validation, exact expansion, and record-level readers | | [`src/call-config.ts`](src/call-config.ts) | Call-config validation, adapter-default materialization, and request freezing | diff --git a/packages/llm/llm/README.zh.md b/packages/llm/llm/README.zh.md index 21e2b778ba..777d877ff0 100644 --- a/packages/llm/llm/README.zh.md +++ b/packages/llm/llm/README.zh.md @@ -85,6 +85,7 @@ const configure = (maxTokens: number): ConfigureCall => ### 你可以做什么 +- **提取内容文本**——从 `@deepseek-ai/dsh-llm/message` 导入的 `extractTextContent(content, options?)` 按顺序仅拼接 `text` 块,保留空白与空文本块,忽略所有其他块类型且不生成占位符。可选的 `options.separator` 默认为 `''`。它接受只读内容,没有文本块时返回 `''`。 - **流式发起一次模型调用**——`ctx.llm.stream(options)` 为任何已注册提供方与模型产出原始分片(token 级增量);消费方用 `BlockAssembler` 组装。 - **注册提供方适配器**——一个适配器拥有一个或多个提供方路由,其注册会捕获该路由的重试策略;重复注册同一路由会以 `DUPLICATE_ADAPTER` 失败。 - **通过配置暴露并激活提供方**——适配器声明可配置提供方路由与 settings namespace,配置界面因此可以激活休眠提供方并编辑连接信息,无需重启。`LlmConfigurableProvider.error` 报告供修复的配置诊断;未受影响的模型仍可提供服务。条目还可携带 `defaultBaseURL`,即配置未设置端点时适配器使用的端点;以及 `nativeAuth`,即配置未指定凭据引用时适配器认证读取的环境变量与 OAuth 登录;`baseURLEnv` 列出配置端点所用的环境变量。配置界面直接从目录读取这些字段,无需调用适配器。 @@ -116,7 +117,7 @@ const configure = (maxTokens: number): ConfigureCall => |---|---| | [`src/index.ts`](src/index.ts) | `LlmRuntime` 服务:适配器注册表、可配置提供方目录、模型发现、调用准备与流式边界 | | [`src/types.ts`](src/types.ts) | `StreamChunk` 协议、内容块映射、结束原因与共享词汇 | -| [`src/message.ts`](src/message.ts) | 投递、历史与请求共享的不可变消息构造函数 | +| [`src/message.ts`](src/message.ts) | 内容文本提取与投递、历史、请求共享的不可变消息构造函数 | | [`src/assembler.ts`](src/assembler.ts) | `BlockAssembler`:分片到块的增量组装 | | [`src/assistant-stream.ts`](src/assistant-stream.ts) | 带时间信息的紧凑 Assistant 流累积、严格校验、精确展开与记录级读取器 | | [`src/call-config.ts`](src/call-config.ts) | 调用配置校验、适配器默认值填入与请求冻结 | diff --git a/packages/llm/llm/src/index.ts b/packages/llm/llm/src/index.ts index cd1aa71ca8..7475ad9a18 100644 --- a/packages/llm/llm/src/index.ts +++ b/packages/llm/llm/src/index.ts @@ -49,7 +49,11 @@ export * from './api-key.ts' export type * from './types.ts' export * from './content.ts' export * from './assistant-stream.ts' -export * from './message.ts' +export type * from './message.ts' +export { + CONTEXT_SUMMARY_MAX_CHARS, boundContextSummary, createAssistantMessage, createDeveloperMessage, createMessage, + createSystemMessage, createToolResultMessage, createUserMessage, freezeMessage, +} from './message.ts' export * from './retry-policy.ts' export { BlockAssembler } from './assembler.ts' export { callConfigEquals, isAgentLoopRequest, markAgentLoopRequest } from './call-config.ts' diff --git a/packages/llm/llm/src/message.ts b/packages/llm/llm/src/message.ts index 0138452426..fc43cbadbc 100644 --- a/packages/llm/llm/src/message.ts +++ b/packages/llm/llm/src/message.ts @@ -1,4 +1,4 @@ -/** Message value types, identity, and immutable construction helpers. */ +/** Message value types, content text extraction, identity, and immutable construction helpers. */ import { randomUUID } from '@deepseek-ai/dsh-util-crypto' import { brandString } from '@deepseek-ai/dsh-brand' @@ -304,3 +304,16 @@ export function createToolResultMessage(input: ToolResultMessageInput): ToolResu isError: input.isError, }) } + +/** + * Extract and join only text blocks in content order, preserving their whitespace. + * Non-text blocks contribute neither text nor separators; content is not modified. + * Import from `@deepseek-ai/dsh-llm/message` in Host and browser code. + * @param content - source blocks to read in their existing order. + * @param options - optional text extraction settings. + * @param options.separator - text inserted between text blocks; defaults to an empty string. + * @returns joined text, or an empty string when no text blocks are present. + */ +export function extractTextContent(content: readonly ContentBlock[], options?: { separator?: string }): string { + return content.filter(block => block.type === 'text').map(block => block.text).join(options?.separator ?? '') +} diff --git a/packages/llm/llm/tests/message.spec.ts b/packages/llm/llm/tests/message.spec.ts index d3e3ba995e..f70710672e 100644 --- a/packages/llm/llm/tests/message.spec.ts +++ b/packages/llm/llm/tests/message.spec.ts @@ -1,5 +1,6 @@ import { describe, expect, expectTypeOf, it } from 'vitest' import { brandString } from '@deepseek-ai/dsh-brand' +import type { AttachmentId } from '@deepseek-ai/dsh-attachment' import { type ToolCallId, boundContextSummary, @@ -12,6 +13,46 @@ import { freezeMessage, type MessageId, } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + +describe('extractTextContent', () => { + it('preserves whitespace and empty text blocks while omitting non-text blocks', () => { + const message = createUserMessage({ + source: { kind: 'test' }, + content: [ + { type: 'text', text: ' \talpha\n' }, + { type: 'reasoning', text: 'private reasoning' }, + { type: 'image', attachment: { + attachmentId: brandString(`sha256:${'a'.repeat(64)}`), + mediaType: 'image/png', bytes: 1, width: 1, height: 1, + } }, + { type: 'tool-call', id: brandString('call'), name: 'tool', arguments: '{}' }, + { type: 'text', text: '' }, + { type: 'tool-removal', toolName: 'removed' }, + { type: 'text', text: 'β \r\n' }, + ], + }) + expect(extractTextContent(message.content)).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, undefined)).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, {})).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, { separator: '' })).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, { separator: '\n' })).toBe(' \talpha\n\n\nβ \r\n') + expect(extractTextContent(message.content, { separator: ' ' })).toBe(' \talpha\n β \r\n') + expect(extractTextContent(message.content, { separator: '::' })).toBe(' \talpha\n::::β \r\n') + expect(Object.isFrozen(message.content)).toBe(true) + expect(message.content[0]).toEqual({ type: 'text', text: ' \talpha\n' }) + }) + + it('returns empty text when there are no text blocks and keeps separators between empty text blocks', () => { + expect(extractTextContent([])).toBe('') + expect(extractTextContent([{ type: 'reasoning', text: 'not plain text' }], { separator: '\n' })).toBe('') + expect(extractTextContent([ + { type: 'text', text: '' }, + { type: 'reasoning', text: 'ignored' }, + { type: 'text', text: '' }, + ], { separator: '\n' })).toBe('\n') + }) +}) describe('message construction', () => { it('detaches and freezes developer tool names without copying their definitions', () => { diff --git a/packages/sdk/server/src/query-activity.ts b/packages/sdk/server/src/query-activity.ts index 17a4fc9148..7bf4c8b7bf 100644 --- a/packages/sdk/server/src/query-activity.ts +++ b/packages/sdk/server/src/query-activity.ts @@ -1,5 +1,7 @@ /** Observe command-admitted activity through quiescence and preserve a goal's first terminal outcome. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import type { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import type { GoalView } from '@deepseek-ai/dsh-goal' @@ -63,7 +65,7 @@ export class QueryActivity { } if (this.input || this.goalId !== undefined) { if (event.type === 'assistant/message') { - this.response = event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') + this.response = extractTextContent(event.data.message.content) } if (event.type === 'turn/end') this.turnReason = event.data.reason.kind } diff --git a/packages/session/session-title-first-prompt-llm/src/index.ts b/packages/session/session-title-first-prompt-llm/src/index.ts index 7515630a88..099cf3c830 100644 --- a/packages/session/session-title-first-prompt-llm/src/index.ts +++ b/packages/session/session-title-first-prompt-llm/src/index.ts @@ -3,7 +3,8 @@ /* jscpd:ignore-start -- both shipped providers import the same shared packages. */ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import type { LlmResolvedModelInfo, ReasoningEffortId } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' +import { type LlmResolvedModelInfo, type ReasoningEffortId } from '@deepseek-ai/dsh-llm' import { assertNever } from '@deepseek-ai/dsh-util-values' import { brandString } from '@deepseek-ai/dsh-brand' import type { SessionTitleProviderId } from '@deepseek-ai/dsh-session-title/types' @@ -128,10 +129,7 @@ function titleFromResponse(response: SessionTitleLlmResponse): string { if (response.blocks.some(block => block.type === 'tool-call')) { throw new Error('session-title-llm: title output must contain text only') } - const text = response.blocks - .filter((block): block is Extract<(typeof response.blocks)[number], { type: 'text' }> => block.type === 'text') - .map(block => block.text) - .join(' ') + const text = extractTextContent(response.blocks, { separator: ' ' }) const title = normalizeSessionTitle(titleFromOutput(text), Number.MAX_SAFE_INTEGER) if (title.length === 0) throw new Error('session-title-llm: title model produced no text') return title diff --git a/packages/session/session-title/src/index.ts b/packages/session/session-title/src/index.ts index c80ae7e830..9917187dba 100644 --- a/packages/session/session-title/src/index.ts +++ b/packages/session/session-title/src/index.ts @@ -8,6 +8,7 @@ import z from '@deepseek-ai/schemastery' import { z as zod } from 'zod' import type { ZodType } from 'zod' import type { Branded } from '@deepseek-ai/dsh-brand' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { isAgentLoopRequest } from '@deepseek-ai/dsh-llm' import type { GenerateOptions } from '@deepseek-ai/dsh-llm' import { assertNever, deepFreeze } from '@deepseek-ai/dsh-util-values' @@ -137,10 +138,7 @@ export interface SessionTitleProvider { function sessionTitleUserMessageOf(event: SessionEvent): SessionTitleUserMessage | undefined { if (event.type !== 'user/message' || event.data.source.kind !== 'user') return undefined const content = event.data.content - const text = content - .filter((block): block is Extract<(typeof content)[number], { type: 'text' }> => block.type === 'text') - .map(block => block.text) - .join('\n') + const text = extractTextContent(content, { separator: '\n' }) if (normalizeSessionTitle(text, Number.MAX_SAFE_INTEGER).length === 0) return undefined return { seq: event.seq, text } } diff --git a/packages/web/web-deepseek-api/src/index.ts b/packages/web/web-deepseek-api/src/index.ts index 555bab178b..4da54814ea 100644 --- a/packages/web/web-deepseek-api/src/index.ts +++ b/packages/web/web-deepseek-api/src/index.ts @@ -21,7 +21,8 @@ import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-agent' import { credentialRef, type CredentialRef } from '@deepseek-ai/dsh-credentials' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' -import type {} from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import { deepSeekApiKeyConfigured, rejectDeepSeekAccountToken, resolveDeepSeekAccountToken, resolveDeepSeekApiKey, } from '@deepseek-ai/dsh-llm-deepseek' @@ -156,7 +157,7 @@ const CAPABILITY = { function latestUserQuestion(session: Session | undefined): string | undefined { const prompt = session?.deriveMessages().findLast(message => message.role === 'user' && message.source.kind === 'user') if (prompt === undefined) return undefined - return prompt.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n') + return extractTextContent(prompt.content, { separator: '\n' }) } /** diff --git a/packages/workflow/workflow-ptc/src/guest-source.ts b/packages/workflow/workflow-ptc/src/guest-source.ts index ff57ab8e8f..86ae9078ed 100644 --- a/packages/workflow/workflow-ptc/src/guest-source.ts +++ b/packages/workflow/workflow-ptc/src/guest-source.ts @@ -1,4 +1,4 @@ /** Generated by scripts/gen-workflow-guest.ts. Do not edit directly. */ /** Self-contained ESM guest transported into the mounted PTC runtime. */ -export const WORKFLOW_GUEST_SOURCE = "import * as vm from \"node:vm\";\n//#region packages/workflow/workflow-ptc/src/realm.ts\n/**\n* Materializes script VM values as plain JSON and renders thrown values.\n* Getters and proxy traps may execute inside the confined Node process;\n* process isolation and cancellation belong to PTC, not the VM.\n* @module @deepseek-ai/dsh-workflow-ptc/realm\n*/\n/** Thrown by {@link materializeFromRealm}; the caller wraps it into the right `WorkflowError` code. */\nvar MaterializeError = class extends Error {\n\tpath;\n\treason;\n\tconstructor(path, reason) {\n\t\tsuper(`${path}: ${reason}`);\n\t\tthis.path = path;\n\t\tthis.reason = reason;\n\t\tthis.name = \"MaterializeError\";\n\t}\n};\n/**\n* Render a thrown value to failure text without ever throwing: prefer the\n* `stack` (host or realm — a realm error's `stack` is a plain string read),\n* fall back to `message`, then `String()`. Reading those properties MAY run\n* script code; if that code itself throws, a fixed label is returned instead.\n* @param error - any value thrown in the host or guest realm.\n* @returns human-readable text for the failure report; prefers the stack.\n*/\nfunction renderThrown(error) {\n\ttry {\n\t\tconst stack = error?.stack;\n\t\tif (typeof stack === \"string\" && stack.length > 0) return stack;\n\t\tconst message = error?.message;\n\t\tif (typeof message === \"string\" && message.length > 0) return message;\n\t\treturn String(error);\n\t} catch {\n\t\treturn \"[unrenderable thrown value]\";\n\t}\n}\n/**\n* Whether an object's prototype chain represents a plain data object: `null`, or a prototype\n* whose own prototype is `null` (the realm's `Object.prototype` — which we\n* cannot compare by identity across realms). A `Date`/`Map`/class instance\n* has a longer chain and is rejected.\n*/\nfunction hasPlainPrototype(value) {\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto === null) return true;\n\treturn Object.getPrototypeOf(proto) === null;\n}\n/**\n* Copy `value` (typically from the vm realm) into plain host JSON data. Root `undefined` is\n* returned unchanged; nested `undefined` and values JSON cannot represent losslessly fail\n* with the offending path. Property accessors run normally, and a throwing read is wrapped\n* with its rendered failure.\n*\n* @param value - the realm value to materialize.\n* @param root - the path label for the root value (error messages).\n* @returns the host-realm copy (plain objects/arrays/scalars only).\n* @throws {@link MaterializeError} for unsupported values, cycles, sparse arrays, exotic\n* prototypes, or property reads that throw.\n*/\nfunction materializeFromRealm(value, root = \"value\") {\n\tif (value === void 0) return void 0;\n\ttry {\n\t\treturn materialize(value, root, /* @__PURE__ */ new Set());\n\t} catch (error) {\n\t\tif (error instanceof MaterializeError) throw error;\n\t\tthrow new MaterializeError(root, `reading the value threw: ${renderThrown(error)}`);\n\t}\n}\nfunction materialize(value, path, seen) {\n\tswitch (typeof value) {\n\t\tcase \"boolean\":\n\t\tcase \"string\": return value;\n\t\tcase \"number\":\n\t\t\tif (!Number.isFinite(value)) throw new MaterializeError(path, \"non-finite numbers are not JSON data\");\n\t\t\treturn value;\n\t\tcase \"bigint\": throw new MaterializeError(path, \"bigints are not JSON data\");\n\t\tcase \"function\": throw new MaterializeError(path, \"functions are not plain JSON data\");\n\t\tcase \"symbol\": throw new MaterializeError(path, \"symbols are not plain JSON data\");\n\t\tcase \"undefined\": throw new MaterializeError(path, \"undefined is not JSON data\");\n\t\tcase \"object\": break;\n\t}\n\tif (value === null) return null;\n\tconst objectValue = value;\n\tif (seen.has(objectValue)) throw new MaterializeError(path, \"circular references are not JSON data\");\n\tseen.add(objectValue);\n\ttry {\n\t\tif (Array.isArray(objectValue)) return materializeArray(objectValue, path, seen);\n\t\treturn materializeObject(objectValue, path, seen);\n\t} finally {\n\t\tseen.delete(objectValue);\n\t}\n}\nfunction materializeArray(value, path, seen) {\n\tconst out = [];\n\tfor (let index = 0; index < value.length; index++) {\n\t\tif (!(index in value)) throw new MaterializeError(`${path}[${index}]`, \"sparse arrays are not JSON data\");\n\t\tout.push(materialize(value[index], `${path}[${index}]`, seen));\n\t}\n\tfor (const key of Object.keys(value)) {\n\t\tconst index = Number(key);\n\t\tif (!Number.isInteger(index) || index < 0 || index >= value.length) throw new MaterializeError(`${path}.${key}`, \"arrays with non-index properties are not JSON data\");\n\t}\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\treturn out;\n}\nfunction materializeObject(value, path, seen) {\n\tif (!hasPlainPrototype(value)) throw new MaterializeError(path, \"only plain objects and arrays are JSON data (exotic prototype)\");\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\tconst out = {};\n\tfor (const key of Object.keys(value)) Object.defineProperty(out, key, {\n\t\tvalue: materialize(value[key], `${path}.${key}`, seen),\n\t\tenumerable: true,\n\t\twritable: true,\n\t\tconfigurable: true\n\t});\n\treturn out;\n}\n//#endregion\n//#region packages/util/brand/src/index.ts\n/**\n* Apply a compile-time string brand without changing the value.\n* @param value - string admitted by the domain that owns the target brand.\n* @returns the same string with the requested compile-time brand.\n*/\nfunction brandString(value) {\n\treturn value;\n}\n//#endregion\n//#region packages/util/error/src/index.ts\n/**\n* Harness error base with a stable machine-routable code and chained cause.\n* Package errors extend it so tool results and replay can retain failure class.\n* @module @deepseek-ai/dsh-error\n*/\n/**\n* Base class for all harness errors. Carries a `code` (stable, programmatic —\n* e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the\n* human-readable `message`, and supports `cause` chaining via the standard\n* `ErrorOptions`. `name` defaults to the subclass constructor name.\n*/\nvar HarnessError = class extends Error {\n\t/** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */\n\tcode;\n\tconstructor(message, code, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = new.target.name;\n\t}\n};\n//#endregion\n//#region packages/util/values/src/index.ts\n/**\n* Mark an unreachable closed-union branch.\n* @param value - impossible value; an unhandled typed variant fails at the call site.\n* @param context - optional switch-site label included in the failure message.\n* @returns never; a runtime value that escaped its type always throws.\n*/\nfunction assertNever(value, context) {\n\tconst rendered = JSON.stringify(value) ?? String(value);\n\tthrow new Error(`unreachable variant${context ? ` in ${context}` : \"\"}: ${rendered}`);\n}\n/** Whether a realm-owned intrinsic prototype has a native constructor matching this engine's representation. */\nfunction hasIntrinsicConstructor$1(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === Function.prototype.toString.call(name === \"Array\" ? Array : Object);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype$1(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor$1(value, \"Object\");\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */\nfunction hasPlainArrayPrototype$1(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor$1(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype$1(objectPrototype);\n}\n/** Whether an object is a plain or null-prototype record from any JavaScript realm. */\nfunction hasPlainObjectPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype$1(prototype);\n}\n/** Return every JSON-visible object key, or reject own data JSON would discard. */\nfunction enumerableStringKeys(value) {\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.some((key) => typeof key !== \"string\" || !Object.prototype.propertyIsEnumerable.call(value, key))) return void 0;\n\treturn keys;\n}\n/** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */\nfunction walkJsonValue(value, detach) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tlet root;\n\tlet parent;\n\tconst assign = (item) => {\n\t\tif (parent === void 0) {\n\t\t\tif (detach) root = item;\n\t\t} else if (parent.kind === \"array\") {\n\t\t\tif (parent.target !== void 0) parent.target[parent.key] = item;\n\t\t} else if (parent.target !== void 0) Object.defineProperty(parent.target, parent.key, {\n\t\t\tvalue: item,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true\n\t\t});\n\t};\n\tconst frames = [];\n\tlet current = value;\n\tfor (;;) {\n\t\tif (current === null) assign(null);\n\t\telse if (typeof current === \"boolean\" || typeof current === \"string\") assign(current);\n\t\telse if (typeof current === \"number\") {\n\t\t\tif (!Number.isFinite(current) || Object.is(current, -0)) return void 0;\n\t\t\tassign(current);\n\t\t} else {\n\t\t\tif (typeof current !== \"object\") return void 0;\n\t\t\tif (ancestors.has(current)) return void 0;\n\t\t\tif (Array.isArray(current)) {\n\t\t\t\tif (!hasPlainArrayPrototype$1(current)) return void 0;\n\t\t\t\tconst length = current.length;\n\t\t\t\tif (Reflect.ownKeys(current).length !== length + 1) return void 0;\n\t\t\t\tconst target = detach ? [] : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tlet indices;\n\t\t\t\tif (!Number.isInteger(length)) {\n\t\t\t\t\tindices = [];\n\t\t\t\t\tfor (let index = length - 1; index >= 0; index--) indices.push(index);\n\t\t\t\t}\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"array\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tlength: indices?.length ?? length,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: 0,\n\t\t\t\t\tindices,\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (!hasPlainObjectPrototype(current)) return void 0;\n\t\t\t\tconst keys = enumerableStringKeys(current);\n\t\t\t\tif (keys === void 0) return void 0;\n\t\t\t\tconst target = detach ? {} : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"object\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tkeys,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: \"\",\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t}\n\t\t\tancestors.add(current);\n\t\t}\n\t\tfor (;;) {\n\t\t\tconst frame = frames.at(-1);\n\t\t\tif (frame === void 0) return detach ? root : true;\n\t\t\tconst length = frame.kind === \"array\" ? frame.length : frame.keys.length;\n\t\t\tif (frame.index >= length) {\n\t\t\t\tancestors.delete(frame.source);\n\t\t\t\tframes.pop();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst index = frame.index++;\n\t\t\tparent = frame;\n\t\t\tif (frame.kind === \"array\") {\n\t\t\t\tconst key = frame.indices === void 0 ? index : frame.indices[frame.indices.length - index - 1];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured index count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(frame.source, key)) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t} else {\n\t\t\t\tconst key = frame.keys[index];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n/**\n* Test the same lossless JSON rules as {@link snapshotJsonValue} without detaching the value.\n* @param value - candidate value to test.\n* @returns whether the value survives a JSON round trip without loss.\n*/\nfunction isJsonValue(value) {\n\treturn walkJsonValue(value, false) === true;\n}\n//#endregion\n//#region packages/core/tools/src/json-schema.ts\n/**\n* Enforced JSON Schema subset shared by tool outputs, generated PTC mode\n* types, subagents, and workflows. The subset accepts any JSON root, an\n* annotation-only schema for unconstrained JSON, one scalar `type`, object\n* `properties`/`required`/boolean `additionalProperties`, array `items`,\n* type-correct scalar `enum`/`const`, and exact-one `oneOf`.\n*\n* Unsupported or misplaced keywords reject rather than being accepted without\n* enforcement. Consumers that require an object root apply\n* {@link assertObjectJsonSchema} before accepting input.\n* @module dsh-tools/json-schema\n*/\n/**\n* Thrown when a raw schema falls outside the enforced subset. `violations`\n* lists every offending path instead of stopping at the first author error.\n*/\nvar JsonSchemaError = class extends HarnessError {\n\t/** Individual schema violations in walk order. */\n\tviolations;\n\tconstructor(violations) {\n\t\tsuper(`unsupported JSON schema: ${violations.join(\"; \")}`, \"UNSUPPORTED_SCHEMA\");\n\t\tthis.name = \"JsonSchemaError\";\n\t\tthis.violations = violations;\n\t}\n};\nconst CONSTRAINT_KEYWORDS = new Set([\n\t\"type\",\n\t\"oneOf\",\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n]);\nconst ANNOTATION_KEYWORDS = new Set([\n\t\"description\",\n\t\"title\",\n\t\"default\",\n\t\"examples\"\n]);\nconst SCHEMA_TYPES = [\n\t\"object\",\n\t\"array\",\n\t\"string\",\n\t\"number\",\n\t\"integer\",\n\t\"boolean\",\n\t\"null\"\n];\n/** Whether a realm-owned intrinsic prototype is backed by its native constructor. */\nfunction hasIntrinsicConstructor(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, \"Object\");\n}\n/**\n* Test for a realm-agnostic plain JSON record without accepting arrays or\n* exotic objects.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the value has a plain-object prototype chain.\n*/\nfunction isPlainJsonRecord(value) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\ttry {\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype(prototype);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`. */\nfunction hasPlainArrayPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);\n}\n/** Return whether a record contains only own enumerable string keys. */\nfunction hasOnlyEnumerableStringKeys(value) {\n\ttry {\n\t\treturn Reflect.ownKeys(value).every((key) => typeof key === \"string\" && Object.prototype.propertyIsEnumerable.call(value, key));\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Test for an ordinary schema record whose keys survive JSON projection.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the record has an intrinsic prototype and only own enumerable string keys.\n*/\nfunction isJsonSchemaRecord(value) {\n\treturn isPlainJsonRecord(value) && hasOnlyEnumerableStringKeys(value);\n}\n/**\n* Test for a dense ordinary array with no JSON-invisible decorations.\n* @param value - candidate array from any JavaScript realm.\n* @returns Whether the array is intrinsic, dense, and undecorated.\n*/\nfunction isPlainJsonArray(value) {\n\tif (!Array.isArray(value)) return false;\n\ttry {\n\t\tif (!hasPlainArrayPrototype(value) || Reflect.ownKeys(value).length !== value.length + 1) return false;\n\t\tfor (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index)) return false;\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Lossless finite JSON number, excluding negative zero. */\nfunction isJsonNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && !Object.is(value, -0);\n}\n/** Whether a scalar is valid for one declared schema type. */\nfunction scalarMatches(type, value) {\n\tswitch (type) {\n\t\tcase \"string\": return typeof value === \"string\";\n\t\tcase \"number\": return isJsonNumber(value);\n\t\tcase \"integer\": return isJsonNumber(value) && Number.isInteger(value);\n\t\tcase \"boolean\": return typeof value === \"boolean\";\n\t\tcase \"null\": return value === null;\n\t\t/* v8 ignore next -- JsonSchemaScalarType is closed; this retains compile-time exhaustiveness. */\n\t\tdefault: return assertNever(type, \"JsonSchemaType\");\n\t}\n}\n/** Keywords that are invalid beside `oneOf`. */\nconst ONE_OF_SIBLING_KEYWORDS = [\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n];\n/** Validate object-only fields after its property schemas have been visited. */\nfunction checkObjectSchemaTail(node, path, properties, violations) {\n\tconst hasRequired = Object.hasOwn(node, \"required\");\n\tconst required = hasRequired ? node.required : void 0;\n\tif (hasRequired) if (!isPlainJsonArray(required) || required.some((entry) => typeof entry !== \"string\")) violations.push(`${path}.required must be an array of strings`);\n\telse {\n\t\tconst declared = isJsonSchemaRecord(properties) ? properties : {};\n\t\tfor (const key of required) if (!Object.hasOwn(declared, key)) violations.push(`${path}.required names \"${key}\" which is not in properties`);\n\t}\n\tif (Object.hasOwn(node, \"additionalProperties\") && typeof node.additionalProperties !== \"boolean\") violations.push(`${path}.additionalProperties must be a boolean`);\n}\n/** Collect every violation for one raw schema tree without using the JavaScript call stack. */\nfunction checkSchemaNode(root, rootPath, violations, seen) {\n\tconst tasks = [{\n\t\tkind: \"enter\",\n\t\tnode: root,\n\t\tpath: rootPath\n\t}];\n\tfor (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {\n\t\tif (task.kind === \"leave\") {\n\t\t\tseen.delete(task.node);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"one-of-tail\") {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(task.node, key)) violations.push(`${task.path}.${key} is not supported beside oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"object-tail\") {\n\t\t\tcheckObjectSchemaTail(task.node, task.path, task.properties, violations);\n\t\t\tcontinue;\n\t\t}\n\t\tconst { node, path } = task;\n\t\tif (!isJsonSchemaRecord(node)) {\n\t\t\tviolations.push(`${path} must be a schema object`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (seen.has(node)) {\n\t\t\tviolations.push(`${path} is circular`);\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(node);\n\t\ttasks.push({\n\t\t\tkind: \"leave\",\n\t\t\tnode\n\t\t});\n\t\tfor (const key of Object.keys(node)) {\n\t\t\tif (CONSTRAINT_KEYWORDS.has(key)) continue;\n\t\t\tif (ANNOTATION_KEYWORDS.has(key)) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!isJsonValue(node[key])) violations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t} catch {\n\t\t\t\t\tviolations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tviolations.push(`${path}.${key} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`);\n\t\t}\n\t\tif (Object.hasOwn(node, \"description\") && typeof node.description !== \"string\") violations.push(`${path}.description must be a string`);\n\t\tif (Object.hasOwn(node, \"title\") && typeof node.title !== \"string\") violations.push(`${path}.title must be a string`);\n\t\tconst hasType = Object.hasOwn(node, \"type\");\n\t\tconst hasOneOf = Object.hasOwn(node, \"oneOf\");\n\t\tif (hasType && hasOneOf) {\n\t\t\tviolations.push(`${path} cannot declare both type and oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!hasType && !hasOneOf) {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(node, key)) violations.push(`${path}.${key} requires type or oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (hasOneOf) {\n\t\t\tconst oneOf = node.oneOf;\n\t\t\ttasks.push({\n\t\t\t\tkind: \"one-of-tail\",\n\t\t\t\tnode,\n\t\t\t\tpath\n\t\t\t});\n\t\t\tif (!isPlainJsonArray(oneOf) || oneOf.length < 2) violations.push(`${path}.oneOf must be an array of at least two schemas`);\n\t\t\telse for (let index = oneOf.length - 1; index >= 0; index--) tasks.push({\n\t\t\t\tkind: \"enter\",\n\t\t\t\tnode: oneOf[index],\n\t\t\t\tpath: `${path}.oneOf[${index}]`\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst type = node.type;\n\t\tif (typeof type !== \"string\" || !SCHEMA_TYPES.includes(type)) {\n\t\t\tviolations.push(Array.isArray(type) ? `${path}.type must be a single type string (type arrays are not supported)` : `${path}.type must be one of ${SCHEMA_TYPES.join(\"/\")}`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst schemaType = type;\n\t\tfor (const [key, types] of Object.entries({\n\t\t\tproperties: [\"object\"],\n\t\t\trequired: [\"object\"],\n\t\t\tadditionalProperties: [\"object\"],\n\t\t\titems: [\"array\"],\n\t\t\tenum: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t],\n\t\t\tconst: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t]\n\t\t})) if (Object.hasOwn(node, key) && !types.includes(schemaType)) violations.push(`${path}.${key} is not supported on type \"${schemaType}\"`);\n\t\tswitch (schemaType) {\n\t\t\tcase \"object\": {\n\t\t\t\tconst properties = Object.hasOwn(node, \"properties\") ? node.properties : void 0;\n\t\t\t\ttasks.push({\n\t\t\t\t\tkind: \"object-tail\",\n\t\t\t\t\tnode,\n\t\t\t\t\tpath,\n\t\t\t\t\tproperties\n\t\t\t\t});\n\t\t\t\tif (Object.hasOwn(node, \"properties\")) if (!isJsonSchemaRecord(properties)) violations.push(`${path}.properties must be an object of schemas`);\n\t\t\t\telse {\n\t\t\t\t\tconst entries = Object.entries(properties);\n\t\t\t\t\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\t\t\t\t\tconst entry = entries[index];\n\t\t\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured entry count. */\n\t\t\t\t\t\tif (entry === void 0) continue;\n\t\t\t\t\t\ttasks.push({\n\t\t\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\t\t\tnode: entry[1],\n\t\t\t\t\t\t\tpath: `${path}.properties.${entry[0]}`\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"array\":\n\t\t\t\tif (Object.hasOwn(node, \"items\")) tasks.push({\n\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\tnode: node.items,\n\t\t\t\t\tpath: `${path}.items`\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"string\":\n\t\t\tcase \"number\":\n\t\t\tcase \"integer\":\n\t\t\tcase \"boolean\":\n\t\t\tcase \"null\": {\n\t\t\t\tconst hasEnum = Object.hasOwn(node, \"enum\");\n\t\t\t\tconst allowed = hasEnum ? node.enum : void 0;\n\t\t\t\tconst enumValid = isPlainJsonArray(allowed) && allowed.length > 0 && allowed.every((entry) => scalarMatches(schemaType, entry));\n\t\t\t\tif (hasEnum && !enumValid) violations.push(`${path}.enum must be a non-empty array of ${schemaType} values`);\n\t\t\t\tconst hasConst = Object.hasOwn(node, \"const\");\n\t\t\t\tconst declaredConst = hasConst ? node.const : void 0;\n\t\t\t\tconst constValid = scalarMatches(schemaType, declaredConst);\n\t\t\t\tif (hasConst) {\n\t\t\t\t\tif (!constValid) violations.push(`${path}.const must be a ${schemaType} value`);\n\t\t\t\t\telse if (enumValid && !allowed.includes(declaredConst)) violations.push(`${path}.const must be one of ${path}.enum when both are declared`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* v8 ignore next -- schemaType was narrowed from the closed SCHEMA_TYPES table above. */\n\t\t\tdefault: assertNever(schemaType, \"JsonSchemaType\");\n\t\t}\n\t}\n}\n/**\n* Assert the enforced subset plus the object-root constraint retained by\n* subagent and workflow structured outputs.\n* @param schema - untrusted caller-supplied schema.\n* @returns Assertion that the schema belongs to the supported subset and has an object root.\n*/\nfunction assertObjectJsonSchema(schema) {\n\tconst violations = [];\n\tcheckSchemaNode(schema, \"schema\", violations, /* @__PURE__ */ new Set());\n\tif (violations.length === 0 && (!isJsonSchemaRecord(schema) || !Object.hasOwn(schema, \"type\") || schema.type !== \"object\")) violations.push(\"schema.type must be \\\"object\\\" (structured output is object-rooted)\");\n\tif (violations.length > 0) throw new JsonSchemaError(violations);\n}\n//#endregion\n//#region packages/workflow/workflow/src/index.ts\n/**\n* Typed error for workflow-seam failures. Extends {@link HarnessError}, so the\n* `code` is machine-routable taxonomy. `fatal` drives the combinator\n* discipline: `parallel()`/`pipeline()` re-throw a fatal error (a typo'd\n* option or a tripped cap must kill the script loudly), and reserve the\n* per-item `null` for child-run failures and ordinary in-stage script errors.\n* Every {@link WorkflowErrorCode} is fatal; the flag exists so the\n* distinction is explicit at every catch site rather than implied.\n*/\nvar WorkflowError = class extends HarnessError {\n\tcode;\n\t/** Whether combinators must propagate this error instead of nulling the item. */\n\tfatal;\n\tconstructor(message, code, options) {\n\t\tsuper(message, code, options);\n\t\tthis.name = \"WorkflowError\";\n\t\tthis.code = code;\n\t\tthis.fatal = options?.fatal ?? true;\n\t}\n};\n/**\n* Whether combinators must re-throw `error` instead of mapping the item to `null`.\n* @param error - any thrown value; fatality is host `instanceof` (unforgeable from a script realm).\n* @returns true iff `error` is a {@link WorkflowError} whose `fatal` flag is set.\n*/\nfunction isFatalWorkflowError(error) {\n\treturn error instanceof WorkflowError && error.fatal;\n}\n//#endregion\n//#region packages/workflow/workflow-ptc/src/runtime.ts\n/**\n* Workflow VM hooks, child callbacks, ordinary concurrency limits and result serialization.\n* PTC owns process confinement and cancellation. Fatal hook and provider failures propagate\n* through combinators; ordinary child failures and stage errors become per-item nulls.\n* @module @deepseek-ai/dsh-workflow-ptc/runtime\n*/\n/** The `agent()` options the script may pass; everything else rejects loud. */\nconst SUPPORTED_AGENT_OPTIONS = new Set([\n\t\"label\",\n\t\"phase\",\n\t\"schema\",\n\t\"provider\",\n\t\"model\"\n]);\n/** Deferred Claude Code options we name explicitly in the rejection message. */\nconst DEFERRED_AGENT_OPTIONS = new Set([\n\t\"effort\",\n\t\"isolation\",\n\t\"agentType\"\n]);\n/** Flatten a child's final output blocks to text (the non-schema `agent()` result). */\nfunction outputText(blocks) {\n\treturn blocks.filter((block) => block.type === \"text\").map((block) => block.text).join(\"\");\n}\n/** A short display label derived from the prompt when the script passes none. */\nfunction defaultLabel(prompt) {\n\tconst newline = prompt.indexOf(\"\\n\");\n\tconst line = newline === -1 ? prompt : prompt.slice(0, newline);\n\treturn line.length <= 48 ? line : `${line.slice(0, 47)}…`;\n}\n/**\n* One script execution inside the confined Node process. The host owns\n* cancellation and cleanup of any dropped child work.\n*/\nvar WorkflowExecution = class {\n\tlimits;\n\tobserver;\n\tchildren;\n\t/** 1-based count of `agent()` calls started (the `agentsStarted` result field). */\n\tstarted = 0;\n\tactiveSlots = 0;\n\tslotWaiters = [];\n\tcurrentPhase;\n\tcontext;\n\tcompiled;\n\tconstructor(meta, body, args, limits, observer, children) {\n\t\tthis.limits = limits;\n\t\tthis.observer = observer;\n\t\tthis.children = children;\n\t\ttry {\n\t\t\tthis.compiled = new vm.Script(`(async () => {\\n${body}\\n})()`, {\n\t\t\t\tfilename: `workflow:${meta.name}`,\n\t\t\t\tlineOffset: -1\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new WorkflowError(`workflow script does not parse: ${String(error)}`, \"SCRIPT_PARSE\", { cause: error });\n\t\t}\n\t\tthis.context = vm.createContext({}, { name: `workflow:${meta.name}` });\n\t\tconst globals = {\n\t\t\tagent: (prompt, opts) => this.contain(this.agent(prompt, opts)),\n\t\t\tparallel: (thunks) => this.contain(this.parallel(thunks)),\n\t\t\tpipeline: (items, ...stages) => this.contain(this.pipeline(items, stages)),\n\t\t\tphase: (title) => {\n\t\t\t\tthis.phase(title);\n\t\t\t},\n\t\t\tlog: (message) => {\n\t\t\t\tthis.log(message);\n\t\t\t},\n\t\t\targs\n\t\t};\n\t\tfor (const [key, value] of Object.entries(globals)) this.context[key] = typeof value === \"function\" ? Object.freeze(value) : value;\n\t}\n\t/**\n\t* Run the script and materialize its JSON return value.\n\t* @returns A completed or error result; script failures never reject.\n\t*/\n\tasync drive() {\n\t\ttry {\n\t\t\tconst scriptPromise = this.compiled.runInContext(this.context, { timeout: this.limits.syncTimeoutMs });\n\t\t\tconst raw = await this.contain(Promise.resolve(scriptPromise));\n\t\t\treturn {\n\t\t\t\tvalue: raw === void 0 ? null : this.materializeResult(raw),\n\t\t\t\tstopReason: \"completed\",\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tvalue: null,\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terror: renderThrown(error),\n\t\t\t\t...error instanceof WorkflowError ? { errorCode: error.code } : {},\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t}\n\t}\n\t/**\n\t* Attach a no-op rejection consumer WITHOUT changing what the caller\n\t* receives: if the script drops the promise, a host rejection cannot become\n\t* an unhandled rejection that kills the process; if\n\t* the script does await it, it still observes the rejection.\n\t*/\n\tcontain(promise) {\n\t\tpromise.catch(() => {});\n\t\treturn promise;\n\t}\n\t/** Materialize the script's return value; violations become RESULT_UNSERIALIZABLE. */\n\tmaterializeResult(raw) {\n\t\ttry {\n\t\t\treturn materializeFromRealm(raw, \"workflow result\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`the workflow's return value is not plain JSON data — ${error.message}. Return only JSON-serializable objects/arrays/scalars.`, \"RESULT_UNSERIALIZABLE\", { cause: error });\n\t\t}\n\t}\n\t/** Acquire one concurrency slot in FIFO order. */\n\tacquireSlot() {\n\t\tif (this.activeSlots < this.limits.maxConcurrentAgents) {\n\t\t\tthis.activeSlots += 1;\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.slotWaiters.push(() => {\n\t\t\t\tthis.activeSlots += 1;\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t}\n\treleaseSlot() {\n\t\tthis.activeSlots -= 1;\n\t\tconst next = this.slotWaiters.shift();\n\t\tif (next) next();\n\t}\n\t/** The `agent(prompt, opts)` hook. */\n\tasync agent(rawPrompt, rawOpts) {\n\t\tif (typeof rawPrompt !== \"string\" || rawPrompt.length === 0) throw new WorkflowError(\"agent() requires a non-empty prompt string\", \"INVALID_ARGUMENT\");\n\t\tconst opts = this.readAgentOptions(rawOpts);\n\t\tif (this.started >= this.limits.maxTotalAgents) throw new WorkflowError(`this run reached its total agent cap (${this.limits.maxTotalAgents}) — a runaway-loop backstop; raise the applicable maxTotalAgents limit if the scale is intentional`, \"AGENT_CAP\");\n\t\tthis.started += 1;\n\t\tconst seq = this.started;\n\t\tconst label = opts.label ?? defaultLabel(rawPrompt);\n\t\tconst phase = opts.phase ?? this.currentPhase;\n\t\tawait this.acquireSlot();\n\t\ttry {\n\t\t\tlet run;\n\t\t\ttry {\n\t\t\t\trun = await this.children.startAgent({\n\t\t\t\t\tprompt: rawPrompt,\n\t\t\t\t\t...opts.schema !== void 0 ? { schema: opts.schema } : {},\n\t\t\t\t\t...opts.provider !== void 0 ? { provider: opts.provider } : {},\n\t\t\t\t\t...opts.model !== void 0 ? { model: opts.model } : {}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow new WorkflowError(`agent() could not start a child: ${renderThrown(error)}`, \"AGENT_START\", { cause: error });\n\t\t\t}\n\t\t\tconst info = {\n\t\t\t\tseq,\n\t\t\t\tlabel,\n\t\t\t\t...phase !== void 0 ? { phase } : {},\n\t\t\t\tchildId: brandString(run.id)\n\t\t\t};\n\t\t\tthis.observer.agentStart(info);\n\t\t\ttry {\n\t\t\t\tlet result;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await run.result;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t});\n\t\t\t\t\tthrow new WorkflowError(`child agent run failed: ${renderThrown(error)}`, \"AGENT_RESULT\", { cause: error });\n\t\t\t\t}\n\t\t\t\tif (result.stopReason === \"completed\") {\n\t\t\t\t\tif (opts.schema !== void 0) {\n\t\t\t\t\t\tif (result.structured === void 0) {\n\t\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn result.structured;\n\t\t\t\t\t}\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t});\n\t\t\t\t\treturn outputText(result.output);\n\t\t\t\t}\n\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t...info,\n\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t});\n\t\t\t\treturn null;\n\t\t\t} finally {\n\t\t\t\tawait run.dispose();\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.releaseSlot();\n\t\t}\n\t}\n\t/** Materialize + validate the `agent()` options bag from the realm. */\n\treadAgentOptions(rawOpts) {\n\t\tif (rawOpts === void 0) return {};\n\t\tlet opts;\n\t\ttry {\n\t\t\topts = materializeFromRealm(rawOpts, \"agent() options\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() options must be plain JSON data — ${error.message}`, \"INVALID_ARGUMENT\", { cause: error });\n\t\t}\n\t\tif (typeof opts !== \"object\" || opts === null || Array.isArray(opts)) throw new WorkflowError(\"agent() options must be an object\", \"INVALID_ARGUMENT\");\n\t\tconst record = opts;\n\t\tfor (const key of Object.keys(record)) {\n\t\t\tif (SUPPORTED_AGENT_OPTIONS.has(key)) continue;\n\t\t\tif (DEFERRED_AGENT_OPTIONS.has(key)) throw new WorkflowError(`agent() option \"${key}\" is deferred and not supported by this engine (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t\tthrow new WorkflowError(`agent() option \"${key}\" is not recognized (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t}\n\t\tfor (const key of [\n\t\t\t\"label\",\n\t\t\t\"phase\",\n\t\t\t\"provider\",\n\t\t\t\"model\"\n\t\t]) if (record[key] !== void 0 && typeof record[key] !== \"string\") throw new WorkflowError(`agent() option \"${key}\" must be a string`, \"INVALID_ARGUMENT\");\n\t\tlet schema;\n\t\tif (record.schema !== void 0) try {\n\t\t\tassertObjectJsonSchema(record.schema);\n\t\t\tschema = record.schema;\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: assertObjectJsonSchema only throws JsonSchemaError */\n\t\t\tif (!(error instanceof JsonSchemaError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() schema is outside the supported subset — ${error.message}`, \"UNSUPPORTED_SCHEMA\", { cause: error });\n\t\t}\n\t\treturn {\n\t\t\t...record.label !== void 0 ? { label: record.label } : {},\n\t\t\t...record.phase !== void 0 ? { phase: record.phase } : {},\n\t\t\t...record.provider !== void 0 ? { provider: record.provider } : {},\n\t\t\t...record.model !== void 0 ? { model: record.model } : {},\n\t\t\t...schema !== void 0 ? { schema } : {}\n\t\t};\n\t}\n\t/** The `parallel(thunks)` hook: each thunk caught → `null`; fatal errors propagate. */\n\tasync parallel(rawThunks) {\n\t\tif (!Array.isArray(rawThunks)) throw new WorkflowError(\"parallel() requires an array of zero-argument functions\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawThunks.length, \"parallel()\");\n\t\tconst thunks = rawThunks.map((thunk, index) => {\n\t\t\tif (typeof thunk !== \"function\") throw new WorkflowError(`parallel() item ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn thunk;\n\t\t});\n\t\treturn Promise.all(thunks.map(async (thunk) => {\n\t\t\ttry {\n\t\t\t\treturn await thunk();\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\t/** The `pipeline(items, ...stages)` hook: per-item stage chains, NO cross-stage barrier. */\n\tasync pipeline(rawItems, rawStages) {\n\t\tif (!Array.isArray(rawItems)) throw new WorkflowError(\"pipeline() requires an items array\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawItems.length, \"pipeline()\");\n\t\tif (rawStages.length === 0) throw new WorkflowError(\"pipeline() requires at least one stage function\", \"INVALID_ARGUMENT\");\n\t\tconst stages = rawStages.map((stage, index) => {\n\t\t\tif (typeof stage !== \"function\") throw new WorkflowError(`pipeline() stage ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn stage;\n\t\t});\n\t\treturn Promise.all(rawItems.map(async (item, index) => {\n\t\t\tlet value = item;\n\t\t\ttry {\n\t\t\t\tfor (const stage of stages) value = await stage(value, item, index);\n\t\t\t\treturn value;\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\tassertItemCap(length, hook) {\n\t\tif (length > this.limits.maxItemsPerCall) throw new WorkflowError(`${hook} received ${length} items — over the per-call cap (${this.limits.maxItemsPerCall}); split the work or raise maxItemsPerCall in the engine config`, \"ITEM_CAP\");\n\t}\n\t/** The `phase(title)` hook: sets the current label for subsequent `agent()` calls and notifies observers. */\n\tphase(title) {\n\t\tif (typeof title !== \"string\" || title.length === 0) throw new WorkflowError(\"phase() requires a non-empty title string\", \"INVALID_ARGUMENT\");\n\t\tthis.currentPhase = title;\n\t\tthis.observer.phase(title);\n\t}\n\t/** The `log(message)` hook: narration to observers. */\n\tlog(message) {\n\t\tif (typeof message !== \"string\") throw new WorkflowError(\"log() requires a message string\", \"INVALID_ARGUMENT\");\n\t\tthis.observer.log(message);\n\t}\n};\n//#endregion\n//#region packages/workflow/workflow-ptc/src/guest.ts\n/**\n* Run a workflow with one progress batch in flight. Drain progress before child\n* disposal and the terminal result; PTC and the host own cancellation and cleanup.\n* @param host - JSON callbacks owned by this workflow run.\n* @returns The script result after progress delivery; initialization failures reject.\n*/\nasync function runWorkflowGuest(host) {\n\tconst init = await host.begin({});\n\tlet queued = [];\n\tlet inFlight;\n\tlet progressError;\n\tconst flush = () => {\n\t\tif (inFlight !== void 0 || queued.length === 0) return;\n\t\tconst batch = queued;\n\t\tqueued = [];\n\t\tinFlight = host.progress(batch).then(() => {\n\t\t\tinFlight = void 0;\n\t\t\tflush();\n\t\t}, (error) => {\n\t\t\tprogressError = renderThrown(error);\n\t\t\tqueued = [];\n\t\t\tinFlight = void 0;\n\t\t});\n\t};\n\tconst send = (event) => {\n\t\tif (progressError !== void 0) return;\n\t\tqueued.push(event);\n\t\tflush();\n\t};\n\tconst drain = async () => {\n\t\twhile (inFlight !== void 0) await inFlight;\n\t};\n\tconst result = await new WorkflowExecution(init.meta, init.body, init.args, init.limits, {\n\t\tphase: (title) => {\n\t\t\tsend({\n\t\t\t\ttype: \"phase\",\n\t\t\t\ttitle\n\t\t\t});\n\t\t},\n\t\tlog: (message) => {\n\t\t\tsend({\n\t\t\t\ttype: \"log\",\n\t\t\t\tmessage\n\t\t\t});\n\t\t},\n\t\tagentStart: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-start\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t},\n\t\tagentEnd: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-end\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t}\n\t}, { async startAgent(request) {\n\t\tconst { callId, childId } = await host.startChild(request);\n\t\tconst result = host.childResult({ callId });\n\t\tresult.catch(() => {});\n\t\treturn {\n\t\t\tid: childId,\n\t\t\tresult,\n\t\t\tasync dispose() {\n\t\t\t\tawait drain();\n\t\t\t\tawait host.disposeChild({ callId });\n\t\t\t}\n\t\t};\n\t} }).drive();\n\tawait drain();\n\treturn progressError === void 0 ? result : {\n\t\tvalue: null,\n\t\tstopReason: \"error\",\n\t\terror: progressError,\n\t\tagentsStarted: result.agentsStarted\n\t};\n}\n//#endregion\nexport { runWorkflowGuest };\n//# sourceURL=dsh-workflow-guest.js\n" +export const WORKFLOW_GUEST_SOURCE = "import * as vm from \"node:vm\";\n//#region packages/workflow/workflow-ptc/src/realm.ts\n/**\n* Materializes script VM values as plain JSON and renders thrown values.\n* Getters and proxy traps may execute inside the confined Node process;\n* process isolation and cancellation belong to PTC, not the VM.\n* @module @deepseek-ai/dsh-workflow-ptc/realm\n*/\n/** Thrown by {@link materializeFromRealm}; the caller wraps it into the right `WorkflowError` code. */\nvar MaterializeError = class extends Error {\n\tpath;\n\treason;\n\tconstructor(path, reason) {\n\t\tsuper(`${path}: ${reason}`);\n\t\tthis.path = path;\n\t\tthis.reason = reason;\n\t\tthis.name = \"MaterializeError\";\n\t}\n};\n/**\n* Render a thrown value to failure text without ever throwing: prefer the\n* `stack` (host or realm — a realm error's `stack` is a plain string read),\n* fall back to `message`, then `String()`. Reading those properties MAY run\n* script code; if that code itself throws, a fixed label is returned instead.\n* @param error - any value thrown in the host or guest realm.\n* @returns human-readable text for the failure report; prefers the stack.\n*/\nfunction renderThrown(error) {\n\ttry {\n\t\tconst stack = error?.stack;\n\t\tif (typeof stack === \"string\" && stack.length > 0) return stack;\n\t\tconst message = error?.message;\n\t\tif (typeof message === \"string\" && message.length > 0) return message;\n\t\treturn String(error);\n\t} catch {\n\t\treturn \"[unrenderable thrown value]\";\n\t}\n}\n/**\n* Whether an object's prototype chain represents a plain data object: `null`, or a prototype\n* whose own prototype is `null` (the realm's `Object.prototype` — which we\n* cannot compare by identity across realms). A `Date`/`Map`/class instance\n* has a longer chain and is rejected.\n*/\nfunction hasPlainPrototype(value) {\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto === null) return true;\n\treturn Object.getPrototypeOf(proto) === null;\n}\n/**\n* Copy `value` (typically from the vm realm) into plain host JSON data. Root `undefined` is\n* returned unchanged; nested `undefined` and values JSON cannot represent losslessly fail\n* with the offending path. Property accessors run normally, and a throwing read is wrapped\n* with its rendered failure.\n*\n* @param value - the realm value to materialize.\n* @param root - the path label for the root value (error messages).\n* @returns the host-realm copy (plain objects/arrays/scalars only).\n* @throws {@link MaterializeError} for unsupported values, cycles, sparse arrays, exotic\n* prototypes, or property reads that throw.\n*/\nfunction materializeFromRealm(value, root = \"value\") {\n\tif (value === void 0) return void 0;\n\ttry {\n\t\treturn materialize(value, root, /* @__PURE__ */ new Set());\n\t} catch (error) {\n\t\tif (error instanceof MaterializeError) throw error;\n\t\tthrow new MaterializeError(root, `reading the value threw: ${renderThrown(error)}`);\n\t}\n}\nfunction materialize(value, path, seen) {\n\tswitch (typeof value) {\n\t\tcase \"boolean\":\n\t\tcase \"string\": return value;\n\t\tcase \"number\":\n\t\t\tif (!Number.isFinite(value)) throw new MaterializeError(path, \"non-finite numbers are not JSON data\");\n\t\t\treturn value;\n\t\tcase \"bigint\": throw new MaterializeError(path, \"bigints are not JSON data\");\n\t\tcase \"function\": throw new MaterializeError(path, \"functions are not plain JSON data\");\n\t\tcase \"symbol\": throw new MaterializeError(path, \"symbols are not plain JSON data\");\n\t\tcase \"undefined\": throw new MaterializeError(path, \"undefined is not JSON data\");\n\t\tcase \"object\": break;\n\t}\n\tif (value === null) return null;\n\tconst objectValue = value;\n\tif (seen.has(objectValue)) throw new MaterializeError(path, \"circular references are not JSON data\");\n\tseen.add(objectValue);\n\ttry {\n\t\tif (Array.isArray(objectValue)) return materializeArray(objectValue, path, seen);\n\t\treturn materializeObject(objectValue, path, seen);\n\t} finally {\n\t\tseen.delete(objectValue);\n\t}\n}\nfunction materializeArray(value, path, seen) {\n\tconst out = [];\n\tfor (let index = 0; index < value.length; index++) {\n\t\tif (!(index in value)) throw new MaterializeError(`${path}[${index}]`, \"sparse arrays are not JSON data\");\n\t\tout.push(materialize(value[index], `${path}[${index}]`, seen));\n\t}\n\tfor (const key of Object.keys(value)) {\n\t\tconst index = Number(key);\n\t\tif (!Number.isInteger(index) || index < 0 || index >= value.length) throw new MaterializeError(`${path}.${key}`, \"arrays with non-index properties are not JSON data\");\n\t}\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\treturn out;\n}\nfunction materializeObject(value, path, seen) {\n\tif (!hasPlainPrototype(value)) throw new MaterializeError(path, \"only plain objects and arrays are JSON data (exotic prototype)\");\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\tconst out = {};\n\tfor (const key of Object.keys(value)) Object.defineProperty(out, key, {\n\t\tvalue: materialize(value[key], `${path}.${key}`, seen),\n\t\tenumerable: true,\n\t\twritable: true,\n\t\tconfigurable: true\n\t});\n\treturn out;\n}\n//#endregion\n//#region packages/util/brand/src/index.ts\n/**\n* Apply a compile-time string brand without changing the value.\n* @param value - string admitted by the domain that owns the target brand.\n* @returns the same string with the requested compile-time brand.\n*/\nfunction brandString(value) {\n\treturn value;\n}\n//#endregion\n//#region packages/util/values/src/index.ts\n/**\n* Mark an unreachable closed-union branch.\n* @param value - impossible value; an unhandled typed variant fails at the call site.\n* @param context - optional switch-site label included in the failure message.\n* @returns never; a runtime value that escaped its type always throws.\n*/\nfunction assertNever(value, context) {\n\tconst rendered = JSON.stringify(value) ?? String(value);\n\tthrow new Error(`unreachable variant${context ? ` in ${context}` : \"\"}: ${rendered}`);\n}\n/** Whether a realm-owned intrinsic prototype has a native constructor matching this engine's representation. */\nfunction hasIntrinsicConstructor$1(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === Function.prototype.toString.call(name === \"Array\" ? Array : Object);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype$1(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor$1(value, \"Object\");\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */\nfunction hasPlainArrayPrototype$1(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor$1(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype$1(objectPrototype);\n}\n/** Whether an object is a plain or null-prototype record from any JavaScript realm. */\nfunction hasPlainObjectPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype$1(prototype);\n}\n/** Return every JSON-visible object key, or reject own data JSON would discard. */\nfunction enumerableStringKeys(value) {\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.some((key) => typeof key !== \"string\" || !Object.prototype.propertyIsEnumerable.call(value, key))) return void 0;\n\treturn keys;\n}\n/** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */\nfunction walkJsonValue(value, detach) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tlet root;\n\tlet parent;\n\tconst assign = (item) => {\n\t\tif (parent === void 0) {\n\t\t\tif (detach) root = item;\n\t\t} else if (parent.kind === \"array\") {\n\t\t\tif (parent.target !== void 0) parent.target[parent.key] = item;\n\t\t} else if (parent.target !== void 0) Object.defineProperty(parent.target, parent.key, {\n\t\t\tvalue: item,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true\n\t\t});\n\t};\n\tconst frames = [];\n\tlet current = value;\n\tfor (;;) {\n\t\tif (current === null) assign(null);\n\t\telse if (typeof current === \"boolean\" || typeof current === \"string\") assign(current);\n\t\telse if (typeof current === \"number\") {\n\t\t\tif (!Number.isFinite(current) || Object.is(current, -0)) return void 0;\n\t\t\tassign(current);\n\t\t} else {\n\t\t\tif (typeof current !== \"object\") return void 0;\n\t\t\tif (ancestors.has(current)) return void 0;\n\t\t\tif (Array.isArray(current)) {\n\t\t\t\tif (!hasPlainArrayPrototype$1(current)) return void 0;\n\t\t\t\tconst length = current.length;\n\t\t\t\tif (Reflect.ownKeys(current).length !== length + 1) return void 0;\n\t\t\t\tconst target = detach ? [] : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tlet indices;\n\t\t\t\tif (!Number.isInteger(length)) {\n\t\t\t\t\tindices = [];\n\t\t\t\t\tfor (let index = length - 1; index >= 0; index--) indices.push(index);\n\t\t\t\t}\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"array\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tlength: indices?.length ?? length,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: 0,\n\t\t\t\t\tindices,\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (!hasPlainObjectPrototype(current)) return void 0;\n\t\t\t\tconst keys = enumerableStringKeys(current);\n\t\t\t\tif (keys === void 0) return void 0;\n\t\t\t\tconst target = detach ? {} : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"object\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tkeys,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: \"\",\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t}\n\t\t\tancestors.add(current);\n\t\t}\n\t\tfor (;;) {\n\t\t\tconst frame = frames.at(-1);\n\t\t\tif (frame === void 0) return detach ? root : true;\n\t\t\tconst length = frame.kind === \"array\" ? frame.length : frame.keys.length;\n\t\t\tif (frame.index >= length) {\n\t\t\t\tancestors.delete(frame.source);\n\t\t\t\tframes.pop();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst index = frame.index++;\n\t\t\tparent = frame;\n\t\t\tif (frame.kind === \"array\") {\n\t\t\t\tconst key = frame.indices === void 0 ? index : frame.indices[frame.indices.length - index - 1];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured index count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(frame.source, key)) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t} else {\n\t\t\t\tconst key = frame.keys[index];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n/**\n* Test the same lossless JSON rules as {@link snapshotJsonValue} without detaching the value.\n* @param value - candidate value to test.\n* @returns whether the value survives a JSON round trip without loss.\n*/\nfunction isJsonValue(value) {\n\treturn walkJsonValue(value, false) === true;\n}\n//#endregion\n//#region packages/llm/llm/src/message.ts\n/**\n* Extract and join only text blocks in content order, preserving their whitespace.\n* Non-text blocks contribute neither text nor separators; content is not modified.\n* Import from `@deepseek-ai/dsh-llm/message` in Host and browser code.\n* @param content - source blocks to read in their existing order.\n* @param options - optional text extraction settings.\n* @param options.separator - text inserted between text blocks; defaults to an empty string.\n* @returns joined text, or an empty string when no text blocks are present.\n*/\nfunction extractTextContent(content, options) {\n\treturn content.filter((block) => block.type === \"text\").map((block) => block.text).join(options?.separator ?? \"\");\n}\n//#endregion\n//#region packages/util/error/src/index.ts\n/**\n* Harness error base with a stable machine-routable code and chained cause.\n* Package errors extend it so tool results and replay can retain failure class.\n* @module @deepseek-ai/dsh-error\n*/\n/**\n* Base class for all harness errors. Carries a `code` (stable, programmatic —\n* e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the\n* human-readable `message`, and supports `cause` chaining via the standard\n* `ErrorOptions`. `name` defaults to the subclass constructor name.\n*/\nvar HarnessError = class extends Error {\n\t/** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */\n\tcode;\n\tconstructor(message, code, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = new.target.name;\n\t}\n};\n//#endregion\n//#region packages/core/tools/src/json-schema.ts\n/**\n* Enforced JSON Schema subset shared by tool outputs, generated PTC mode\n* types, subagents, and workflows. The subset accepts any JSON root, an\n* annotation-only schema for unconstrained JSON, one scalar `type`, object\n* `properties`/`required`/boolean `additionalProperties`, array `items`,\n* type-correct scalar `enum`/`const`, and exact-one `oneOf`.\n*\n* Unsupported or misplaced keywords reject rather than being accepted without\n* enforcement. Consumers that require an object root apply\n* {@link assertObjectJsonSchema} before accepting input.\n* @module dsh-tools/json-schema\n*/\n/**\n* Thrown when a raw schema falls outside the enforced subset. `violations`\n* lists every offending path instead of stopping at the first author error.\n*/\nvar JsonSchemaError = class extends HarnessError {\n\t/** Individual schema violations in walk order. */\n\tviolations;\n\tconstructor(violations) {\n\t\tsuper(`unsupported JSON schema: ${violations.join(\"; \")}`, \"UNSUPPORTED_SCHEMA\");\n\t\tthis.name = \"JsonSchemaError\";\n\t\tthis.violations = violations;\n\t}\n};\nconst CONSTRAINT_KEYWORDS = new Set([\n\t\"type\",\n\t\"oneOf\",\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n]);\nconst ANNOTATION_KEYWORDS = new Set([\n\t\"description\",\n\t\"title\",\n\t\"default\",\n\t\"examples\"\n]);\nconst SCHEMA_TYPES = [\n\t\"object\",\n\t\"array\",\n\t\"string\",\n\t\"number\",\n\t\"integer\",\n\t\"boolean\",\n\t\"null\"\n];\n/** Whether a realm-owned intrinsic prototype is backed by its native constructor. */\nfunction hasIntrinsicConstructor(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, \"Object\");\n}\n/**\n* Test for a realm-agnostic plain JSON record without accepting arrays or\n* exotic objects.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the value has a plain-object prototype chain.\n*/\nfunction isPlainJsonRecord(value) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\ttry {\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype(prototype);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`. */\nfunction hasPlainArrayPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);\n}\n/** Return whether a record contains only own enumerable string keys. */\nfunction hasOnlyEnumerableStringKeys(value) {\n\ttry {\n\t\treturn Reflect.ownKeys(value).every((key) => typeof key === \"string\" && Object.prototype.propertyIsEnumerable.call(value, key));\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Test for an ordinary schema record whose keys survive JSON projection.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the record has an intrinsic prototype and only own enumerable string keys.\n*/\nfunction isJsonSchemaRecord(value) {\n\treturn isPlainJsonRecord(value) && hasOnlyEnumerableStringKeys(value);\n}\n/**\n* Test for a dense ordinary array with no JSON-invisible decorations.\n* @param value - candidate array from any JavaScript realm.\n* @returns Whether the array is intrinsic, dense, and undecorated.\n*/\nfunction isPlainJsonArray(value) {\n\tif (!Array.isArray(value)) return false;\n\ttry {\n\t\tif (!hasPlainArrayPrototype(value) || Reflect.ownKeys(value).length !== value.length + 1) return false;\n\t\tfor (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index)) return false;\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Lossless finite JSON number, excluding negative zero. */\nfunction isJsonNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && !Object.is(value, -0);\n}\n/** Whether a scalar is valid for one declared schema type. */\nfunction scalarMatches(type, value) {\n\tswitch (type) {\n\t\tcase \"string\": return typeof value === \"string\";\n\t\tcase \"number\": return isJsonNumber(value);\n\t\tcase \"integer\": return isJsonNumber(value) && Number.isInteger(value);\n\t\tcase \"boolean\": return typeof value === \"boolean\";\n\t\tcase \"null\": return value === null;\n\t\t/* v8 ignore next -- JsonSchemaScalarType is closed; this retains compile-time exhaustiveness. */\n\t\tdefault: return assertNever(type, \"JsonSchemaType\");\n\t}\n}\n/** Keywords that are invalid beside `oneOf`. */\nconst ONE_OF_SIBLING_KEYWORDS = [\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n];\n/** Validate object-only fields after its property schemas have been visited. */\nfunction checkObjectSchemaTail(node, path, properties, violations) {\n\tconst hasRequired = Object.hasOwn(node, \"required\");\n\tconst required = hasRequired ? node.required : void 0;\n\tif (hasRequired) if (!isPlainJsonArray(required) || required.some((entry) => typeof entry !== \"string\")) violations.push(`${path}.required must be an array of strings`);\n\telse {\n\t\tconst declared = isJsonSchemaRecord(properties) ? properties : {};\n\t\tfor (const key of required) if (!Object.hasOwn(declared, key)) violations.push(`${path}.required names \"${key}\" which is not in properties`);\n\t}\n\tif (Object.hasOwn(node, \"additionalProperties\") && typeof node.additionalProperties !== \"boolean\") violations.push(`${path}.additionalProperties must be a boolean`);\n}\n/** Collect every violation for one raw schema tree without using the JavaScript call stack. */\nfunction checkSchemaNode(root, rootPath, violations, seen) {\n\tconst tasks = [{\n\t\tkind: \"enter\",\n\t\tnode: root,\n\t\tpath: rootPath\n\t}];\n\tfor (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {\n\t\tif (task.kind === \"leave\") {\n\t\t\tseen.delete(task.node);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"one-of-tail\") {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(task.node, key)) violations.push(`${task.path}.${key} is not supported beside oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"object-tail\") {\n\t\t\tcheckObjectSchemaTail(task.node, task.path, task.properties, violations);\n\t\t\tcontinue;\n\t\t}\n\t\tconst { node, path } = task;\n\t\tif (!isJsonSchemaRecord(node)) {\n\t\t\tviolations.push(`${path} must be a schema object`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (seen.has(node)) {\n\t\t\tviolations.push(`${path} is circular`);\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(node);\n\t\ttasks.push({\n\t\t\tkind: \"leave\",\n\t\t\tnode\n\t\t});\n\t\tfor (const key of Object.keys(node)) {\n\t\t\tif (CONSTRAINT_KEYWORDS.has(key)) continue;\n\t\t\tif (ANNOTATION_KEYWORDS.has(key)) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!isJsonValue(node[key])) violations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t} catch {\n\t\t\t\t\tviolations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tviolations.push(`${path}.${key} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`);\n\t\t}\n\t\tif (Object.hasOwn(node, \"description\") && typeof node.description !== \"string\") violations.push(`${path}.description must be a string`);\n\t\tif (Object.hasOwn(node, \"title\") && typeof node.title !== \"string\") violations.push(`${path}.title must be a string`);\n\t\tconst hasType = Object.hasOwn(node, \"type\");\n\t\tconst hasOneOf = Object.hasOwn(node, \"oneOf\");\n\t\tif (hasType && hasOneOf) {\n\t\t\tviolations.push(`${path} cannot declare both type and oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!hasType && !hasOneOf) {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(node, key)) violations.push(`${path}.${key} requires type or oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (hasOneOf) {\n\t\t\tconst oneOf = node.oneOf;\n\t\t\ttasks.push({\n\t\t\t\tkind: \"one-of-tail\",\n\t\t\t\tnode,\n\t\t\t\tpath\n\t\t\t});\n\t\t\tif (!isPlainJsonArray(oneOf) || oneOf.length < 2) violations.push(`${path}.oneOf must be an array of at least two schemas`);\n\t\t\telse for (let index = oneOf.length - 1; index >= 0; index--) tasks.push({\n\t\t\t\tkind: \"enter\",\n\t\t\t\tnode: oneOf[index],\n\t\t\t\tpath: `${path}.oneOf[${index}]`\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst type = node.type;\n\t\tif (typeof type !== \"string\" || !SCHEMA_TYPES.includes(type)) {\n\t\t\tviolations.push(Array.isArray(type) ? `${path}.type must be a single type string (type arrays are not supported)` : `${path}.type must be one of ${SCHEMA_TYPES.join(\"/\")}`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst schemaType = type;\n\t\tfor (const [key, types] of Object.entries({\n\t\t\tproperties: [\"object\"],\n\t\t\trequired: [\"object\"],\n\t\t\tadditionalProperties: [\"object\"],\n\t\t\titems: [\"array\"],\n\t\t\tenum: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t],\n\t\t\tconst: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t]\n\t\t})) if (Object.hasOwn(node, key) && !types.includes(schemaType)) violations.push(`${path}.${key} is not supported on type \"${schemaType}\"`);\n\t\tswitch (schemaType) {\n\t\t\tcase \"object\": {\n\t\t\t\tconst properties = Object.hasOwn(node, \"properties\") ? node.properties : void 0;\n\t\t\t\ttasks.push({\n\t\t\t\t\tkind: \"object-tail\",\n\t\t\t\t\tnode,\n\t\t\t\t\tpath,\n\t\t\t\t\tproperties\n\t\t\t\t});\n\t\t\t\tif (Object.hasOwn(node, \"properties\")) if (!isJsonSchemaRecord(properties)) violations.push(`${path}.properties must be an object of schemas`);\n\t\t\t\telse {\n\t\t\t\t\tconst entries = Object.entries(properties);\n\t\t\t\t\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\t\t\t\t\tconst entry = entries[index];\n\t\t\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured entry count. */\n\t\t\t\t\t\tif (entry === void 0) continue;\n\t\t\t\t\t\ttasks.push({\n\t\t\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\t\t\tnode: entry[1],\n\t\t\t\t\t\t\tpath: `${path}.properties.${entry[0]}`\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"array\":\n\t\t\t\tif (Object.hasOwn(node, \"items\")) tasks.push({\n\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\tnode: node.items,\n\t\t\t\t\tpath: `${path}.items`\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"string\":\n\t\t\tcase \"number\":\n\t\t\tcase \"integer\":\n\t\t\tcase \"boolean\":\n\t\t\tcase \"null\": {\n\t\t\t\tconst hasEnum = Object.hasOwn(node, \"enum\");\n\t\t\t\tconst allowed = hasEnum ? node.enum : void 0;\n\t\t\t\tconst enumValid = isPlainJsonArray(allowed) && allowed.length > 0 && allowed.every((entry) => scalarMatches(schemaType, entry));\n\t\t\t\tif (hasEnum && !enumValid) violations.push(`${path}.enum must be a non-empty array of ${schemaType} values`);\n\t\t\t\tconst hasConst = Object.hasOwn(node, \"const\");\n\t\t\t\tconst declaredConst = hasConst ? node.const : void 0;\n\t\t\t\tconst constValid = scalarMatches(schemaType, declaredConst);\n\t\t\t\tif (hasConst) {\n\t\t\t\t\tif (!constValid) violations.push(`${path}.const must be a ${schemaType} value`);\n\t\t\t\t\telse if (enumValid && !allowed.includes(declaredConst)) violations.push(`${path}.const must be one of ${path}.enum when both are declared`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* v8 ignore next -- schemaType was narrowed from the closed SCHEMA_TYPES table above. */\n\t\t\tdefault: assertNever(schemaType, \"JsonSchemaType\");\n\t\t}\n\t}\n}\n/**\n* Assert the enforced subset plus the object-root constraint retained by\n* subagent and workflow structured outputs.\n* @param schema - untrusted caller-supplied schema.\n* @returns Assertion that the schema belongs to the supported subset and has an object root.\n*/\nfunction assertObjectJsonSchema(schema) {\n\tconst violations = [];\n\tcheckSchemaNode(schema, \"schema\", violations, /* @__PURE__ */ new Set());\n\tif (violations.length === 0 && (!isJsonSchemaRecord(schema) || !Object.hasOwn(schema, \"type\") || schema.type !== \"object\")) violations.push(\"schema.type must be \\\"object\\\" (structured output is object-rooted)\");\n\tif (violations.length > 0) throw new JsonSchemaError(violations);\n}\n//#endregion\n//#region packages/workflow/workflow/src/index.ts\n/**\n* Typed error for workflow-seam failures. Extends {@link HarnessError}, so the\n* `code` is machine-routable taxonomy. `fatal` drives the combinator\n* discipline: `parallel()`/`pipeline()` re-throw a fatal error (a typo'd\n* option or a tripped cap must kill the script loudly), and reserve the\n* per-item `null` for child-run failures and ordinary in-stage script errors.\n* Every {@link WorkflowErrorCode} is fatal; the flag exists so the\n* distinction is explicit at every catch site rather than implied.\n*/\nvar WorkflowError = class extends HarnessError {\n\tcode;\n\t/** Whether combinators must propagate this error instead of nulling the item. */\n\tfatal;\n\tconstructor(message, code, options) {\n\t\tsuper(message, code, options);\n\t\tthis.name = \"WorkflowError\";\n\t\tthis.code = code;\n\t\tthis.fatal = options?.fatal ?? true;\n\t}\n};\n/**\n* Whether combinators must re-throw `error` instead of mapping the item to `null`.\n* @param error - any thrown value; fatality is host `instanceof` (unforgeable from a script realm).\n* @returns true iff `error` is a {@link WorkflowError} whose `fatal` flag is set.\n*/\nfunction isFatalWorkflowError(error) {\n\treturn error instanceof WorkflowError && error.fatal;\n}\n//#endregion\n//#region packages/workflow/workflow-ptc/src/runtime.ts\n/**\n* Workflow VM hooks, child callbacks, ordinary concurrency limits and result serialization.\n* PTC owns process confinement and cancellation. Fatal hook and provider failures propagate\n* through combinators; ordinary child failures and stage errors become per-item nulls.\n* @module @deepseek-ai/dsh-workflow-ptc/runtime\n*/\n/** The `agent()` options the script may pass; everything else rejects loud. */\nconst SUPPORTED_AGENT_OPTIONS = new Set([\n\t\"label\",\n\t\"phase\",\n\t\"schema\",\n\t\"provider\",\n\t\"model\"\n]);\n/** Deferred Claude Code options we name explicitly in the rejection message. */\nconst DEFERRED_AGENT_OPTIONS = new Set([\n\t\"effort\",\n\t\"isolation\",\n\t\"agentType\"\n]);\n/** A short display label derived from the prompt when the script passes none. */\nfunction defaultLabel(prompt) {\n\tconst newline = prompt.indexOf(\"\\n\");\n\tconst line = newline === -1 ? prompt : prompt.slice(0, newline);\n\treturn line.length <= 48 ? line : `${line.slice(0, 47)}…`;\n}\n/**\n* One script execution inside the confined Node process. The host owns\n* cancellation and cleanup of any dropped child work.\n*/\nvar WorkflowExecution = class {\n\tlimits;\n\tobserver;\n\tchildren;\n\t/** 1-based count of `agent()` calls started (the `agentsStarted` result field). */\n\tstarted = 0;\n\tactiveSlots = 0;\n\tslotWaiters = [];\n\tcurrentPhase;\n\tcontext;\n\tcompiled;\n\tconstructor(meta, body, args, limits, observer, children) {\n\t\tthis.limits = limits;\n\t\tthis.observer = observer;\n\t\tthis.children = children;\n\t\ttry {\n\t\t\tthis.compiled = new vm.Script(`(async () => {\\n${body}\\n})()`, {\n\t\t\t\tfilename: `workflow:${meta.name}`,\n\t\t\t\tlineOffset: -1\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new WorkflowError(`workflow script does not parse: ${String(error)}`, \"SCRIPT_PARSE\", { cause: error });\n\t\t}\n\t\tthis.context = vm.createContext({}, { name: `workflow:${meta.name}` });\n\t\tconst globals = {\n\t\t\tagent: (prompt, opts) => this.contain(this.agent(prompt, opts)),\n\t\t\tparallel: (thunks) => this.contain(this.parallel(thunks)),\n\t\t\tpipeline: (items, ...stages) => this.contain(this.pipeline(items, stages)),\n\t\t\tphase: (title) => {\n\t\t\t\tthis.phase(title);\n\t\t\t},\n\t\t\tlog: (message) => {\n\t\t\t\tthis.log(message);\n\t\t\t},\n\t\t\targs\n\t\t};\n\t\tfor (const [key, value] of Object.entries(globals)) this.context[key] = typeof value === \"function\" ? Object.freeze(value) : value;\n\t}\n\t/**\n\t* Run the script and materialize its JSON return value.\n\t* @returns A completed or error result; script failures never reject.\n\t*/\n\tasync drive() {\n\t\ttry {\n\t\t\tconst scriptPromise = this.compiled.runInContext(this.context, { timeout: this.limits.syncTimeoutMs });\n\t\t\tconst raw = await this.contain(Promise.resolve(scriptPromise));\n\t\t\treturn {\n\t\t\t\tvalue: raw === void 0 ? null : this.materializeResult(raw),\n\t\t\t\tstopReason: \"completed\",\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tvalue: null,\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terror: renderThrown(error),\n\t\t\t\t...error instanceof WorkflowError ? { errorCode: error.code } : {},\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t}\n\t}\n\t/**\n\t* Attach a no-op rejection consumer WITHOUT changing what the caller\n\t* receives: if the script drops the promise, a host rejection cannot become\n\t* an unhandled rejection that kills the process; if\n\t* the script does await it, it still observes the rejection.\n\t*/\n\tcontain(promise) {\n\t\tpromise.catch(() => {});\n\t\treturn promise;\n\t}\n\t/** Materialize the script's return value; violations become RESULT_UNSERIALIZABLE. */\n\tmaterializeResult(raw) {\n\t\ttry {\n\t\t\treturn materializeFromRealm(raw, \"workflow result\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`the workflow's return value is not plain JSON data — ${error.message}. Return only JSON-serializable objects/arrays/scalars.`, \"RESULT_UNSERIALIZABLE\", { cause: error });\n\t\t}\n\t}\n\t/** Acquire one concurrency slot in FIFO order. */\n\tacquireSlot() {\n\t\tif (this.activeSlots < this.limits.maxConcurrentAgents) {\n\t\t\tthis.activeSlots += 1;\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.slotWaiters.push(() => {\n\t\t\t\tthis.activeSlots += 1;\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t}\n\treleaseSlot() {\n\t\tthis.activeSlots -= 1;\n\t\tconst next = this.slotWaiters.shift();\n\t\tif (next) next();\n\t}\n\t/** The `agent(prompt, opts)` hook. */\n\tasync agent(rawPrompt, rawOpts) {\n\t\tif (typeof rawPrompt !== \"string\" || rawPrompt.length === 0) throw new WorkflowError(\"agent() requires a non-empty prompt string\", \"INVALID_ARGUMENT\");\n\t\tconst opts = this.readAgentOptions(rawOpts);\n\t\tif (this.started >= this.limits.maxTotalAgents) throw new WorkflowError(`this run reached its total agent cap (${this.limits.maxTotalAgents}) — a runaway-loop backstop; raise the applicable maxTotalAgents limit if the scale is intentional`, \"AGENT_CAP\");\n\t\tthis.started += 1;\n\t\tconst seq = this.started;\n\t\tconst label = opts.label ?? defaultLabel(rawPrompt);\n\t\tconst phase = opts.phase ?? this.currentPhase;\n\t\tawait this.acquireSlot();\n\t\ttry {\n\t\t\tlet run;\n\t\t\ttry {\n\t\t\t\trun = await this.children.startAgent({\n\t\t\t\t\tprompt: rawPrompt,\n\t\t\t\t\t...opts.schema !== void 0 ? { schema: opts.schema } : {},\n\t\t\t\t\t...opts.provider !== void 0 ? { provider: opts.provider } : {},\n\t\t\t\t\t...opts.model !== void 0 ? { model: opts.model } : {}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow new WorkflowError(`agent() could not start a child: ${renderThrown(error)}`, \"AGENT_START\", { cause: error });\n\t\t\t}\n\t\t\tconst info = {\n\t\t\t\tseq,\n\t\t\t\tlabel,\n\t\t\t\t...phase !== void 0 ? { phase } : {},\n\t\t\t\tchildId: brandString(run.id)\n\t\t\t};\n\t\t\tthis.observer.agentStart(info);\n\t\t\ttry {\n\t\t\t\tlet result;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await run.result;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t});\n\t\t\t\t\tthrow new WorkflowError(`child agent run failed: ${renderThrown(error)}`, \"AGENT_RESULT\", { cause: error });\n\t\t\t\t}\n\t\t\t\tif (result.stopReason === \"completed\") {\n\t\t\t\t\tif (opts.schema !== void 0) {\n\t\t\t\t\t\tif (result.structured === void 0) {\n\t\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn result.structured;\n\t\t\t\t\t}\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t});\n\t\t\t\t\treturn extractTextContent(result.output);\n\t\t\t\t}\n\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t...info,\n\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t});\n\t\t\t\treturn null;\n\t\t\t} finally {\n\t\t\t\tawait run.dispose();\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.releaseSlot();\n\t\t}\n\t}\n\t/** Materialize + validate the `agent()` options bag from the realm. */\n\treadAgentOptions(rawOpts) {\n\t\tif (rawOpts === void 0) return {};\n\t\tlet opts;\n\t\ttry {\n\t\t\topts = materializeFromRealm(rawOpts, \"agent() options\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() options must be plain JSON data — ${error.message}`, \"INVALID_ARGUMENT\", { cause: error });\n\t\t}\n\t\tif (typeof opts !== \"object\" || opts === null || Array.isArray(opts)) throw new WorkflowError(\"agent() options must be an object\", \"INVALID_ARGUMENT\");\n\t\tconst record = opts;\n\t\tfor (const key of Object.keys(record)) {\n\t\t\tif (SUPPORTED_AGENT_OPTIONS.has(key)) continue;\n\t\t\tif (DEFERRED_AGENT_OPTIONS.has(key)) throw new WorkflowError(`agent() option \"${key}\" is deferred and not supported by this engine (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t\tthrow new WorkflowError(`agent() option \"${key}\" is not recognized (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t}\n\t\tfor (const key of [\n\t\t\t\"label\",\n\t\t\t\"phase\",\n\t\t\t\"provider\",\n\t\t\t\"model\"\n\t\t]) if (record[key] !== void 0 && typeof record[key] !== \"string\") throw new WorkflowError(`agent() option \"${key}\" must be a string`, \"INVALID_ARGUMENT\");\n\t\tlet schema;\n\t\tif (record.schema !== void 0) try {\n\t\t\tassertObjectJsonSchema(record.schema);\n\t\t\tschema = record.schema;\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: assertObjectJsonSchema only throws JsonSchemaError */\n\t\t\tif (!(error instanceof JsonSchemaError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() schema is outside the supported subset — ${error.message}`, \"UNSUPPORTED_SCHEMA\", { cause: error });\n\t\t}\n\t\treturn {\n\t\t\t...record.label !== void 0 ? { label: record.label } : {},\n\t\t\t...record.phase !== void 0 ? { phase: record.phase } : {},\n\t\t\t...record.provider !== void 0 ? { provider: record.provider } : {},\n\t\t\t...record.model !== void 0 ? { model: record.model } : {},\n\t\t\t...schema !== void 0 ? { schema } : {}\n\t\t};\n\t}\n\t/** The `parallel(thunks)` hook: each thunk caught → `null`; fatal errors propagate. */\n\tasync parallel(rawThunks) {\n\t\tif (!Array.isArray(rawThunks)) throw new WorkflowError(\"parallel() requires an array of zero-argument functions\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawThunks.length, \"parallel()\");\n\t\tconst thunks = rawThunks.map((thunk, index) => {\n\t\t\tif (typeof thunk !== \"function\") throw new WorkflowError(`parallel() item ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn thunk;\n\t\t});\n\t\treturn Promise.all(thunks.map(async (thunk) => {\n\t\t\ttry {\n\t\t\t\treturn await thunk();\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\t/** The `pipeline(items, ...stages)` hook: per-item stage chains, NO cross-stage barrier. */\n\tasync pipeline(rawItems, rawStages) {\n\t\tif (!Array.isArray(rawItems)) throw new WorkflowError(\"pipeline() requires an items array\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawItems.length, \"pipeline()\");\n\t\tif (rawStages.length === 0) throw new WorkflowError(\"pipeline() requires at least one stage function\", \"INVALID_ARGUMENT\");\n\t\tconst stages = rawStages.map((stage, index) => {\n\t\t\tif (typeof stage !== \"function\") throw new WorkflowError(`pipeline() stage ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn stage;\n\t\t});\n\t\treturn Promise.all(rawItems.map(async (item, index) => {\n\t\t\tlet value = item;\n\t\t\ttry {\n\t\t\t\tfor (const stage of stages) value = await stage(value, item, index);\n\t\t\t\treturn value;\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\tassertItemCap(length, hook) {\n\t\tif (length > this.limits.maxItemsPerCall) throw new WorkflowError(`${hook} received ${length} items — over the per-call cap (${this.limits.maxItemsPerCall}); split the work or raise maxItemsPerCall in the engine config`, \"ITEM_CAP\");\n\t}\n\t/** The `phase(title)` hook: sets the current label for subsequent `agent()` calls and notifies observers. */\n\tphase(title) {\n\t\tif (typeof title !== \"string\" || title.length === 0) throw new WorkflowError(\"phase() requires a non-empty title string\", \"INVALID_ARGUMENT\");\n\t\tthis.currentPhase = title;\n\t\tthis.observer.phase(title);\n\t}\n\t/** The `log(message)` hook: narration to observers. */\n\tlog(message) {\n\t\tif (typeof message !== \"string\") throw new WorkflowError(\"log() requires a message string\", \"INVALID_ARGUMENT\");\n\t\tthis.observer.log(message);\n\t}\n};\n//#endregion\n//#region packages/workflow/workflow-ptc/src/guest.ts\n/**\n* Run a workflow with one progress batch in flight. Drain progress before child\n* disposal and the terminal result; PTC and the host own cancellation and cleanup.\n* @param host - JSON callbacks owned by this workflow run.\n* @returns The script result after progress delivery; initialization failures reject.\n*/\nasync function runWorkflowGuest(host) {\n\tconst init = await host.begin({});\n\tlet queued = [];\n\tlet inFlight;\n\tlet progressError;\n\tconst flush = () => {\n\t\tif (inFlight !== void 0 || queued.length === 0) return;\n\t\tconst batch = queued;\n\t\tqueued = [];\n\t\tinFlight = host.progress(batch).then(() => {\n\t\t\tinFlight = void 0;\n\t\t\tflush();\n\t\t}, (error) => {\n\t\t\tprogressError = renderThrown(error);\n\t\t\tqueued = [];\n\t\t\tinFlight = void 0;\n\t\t});\n\t};\n\tconst send = (event) => {\n\t\tif (progressError !== void 0) return;\n\t\tqueued.push(event);\n\t\tflush();\n\t};\n\tconst drain = async () => {\n\t\twhile (inFlight !== void 0) await inFlight;\n\t};\n\tconst result = await new WorkflowExecution(init.meta, init.body, init.args, init.limits, {\n\t\tphase: (title) => {\n\t\t\tsend({\n\t\t\t\ttype: \"phase\",\n\t\t\t\ttitle\n\t\t\t});\n\t\t},\n\t\tlog: (message) => {\n\t\t\tsend({\n\t\t\t\ttype: \"log\",\n\t\t\t\tmessage\n\t\t\t});\n\t\t},\n\t\tagentStart: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-start\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t},\n\t\tagentEnd: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-end\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t}\n\t}, { async startAgent(request) {\n\t\tconst { callId, childId } = await host.startChild(request);\n\t\tconst result = host.childResult({ callId });\n\t\tresult.catch(() => {});\n\t\treturn {\n\t\t\tid: childId,\n\t\t\tresult,\n\t\t\tasync dispose() {\n\t\t\t\tawait drain();\n\t\t\t\tawait host.disposeChild({ callId });\n\t\t\t}\n\t\t};\n\t} }).drive();\n\tawait drain();\n\treturn progressError === void 0 ? result : {\n\t\tvalue: null,\n\t\tstopReason: \"error\",\n\t\terror: progressError,\n\t\tagentsStarted: result.agentsStarted\n\t};\n}\n//#endregion\nexport { runWorkflowGuest };\n//# sourceURL=dsh-workflow-guest.js\n" diff --git a/packages/workflow/workflow-ptc/src/runtime.ts b/packages/workflow/workflow-ptc/src/runtime.ts index b99424420b..ca79b2f3fb 100644 --- a/packages/workflow/workflow-ptc/src/runtime.ts +++ b/packages/workflow/workflow-ptc/src/runtime.ts @@ -7,7 +7,7 @@ import * as vm from 'node:vm' import { brandString } from '@deepseek-ai/dsh-brand' -import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { SessionId } from '@deepseek-ai/dsh-session' import { assertObjectJsonSchema, JsonSchemaError } from '@deepseek-ai/dsh-tools' import type { ObjectJsonSchema } from '@deepseek-ai/dsh-tools' @@ -34,14 +34,6 @@ const SUPPORTED_AGENT_OPTIONS = new Set(['label', 'phase', 'schema', 'provider', /** Deferred Claude Code options we name explicitly in the rejection message. */ const DEFERRED_AGENT_OPTIONS = new Set(['effort', 'isolation', 'agentType']) -/** Flatten a child's final output blocks to text (the non-schema `agent()` result). */ -function outputText(blocks: ContentBlock[]): string { - return blocks - .filter((block): block is Extract => block.type === 'text') - .map(block => block.text) - .join('') -} - /** A short display label derived from the prompt when the script passes none. */ function defaultLabel(prompt: string): string { const newline = prompt.indexOf('\n') @@ -222,7 +214,7 @@ export class WorkflowExecution { return result.structured } this.observer.agentEnd({ ...info, outcome: 'completed' }) - return outputText(result.output) + return extractTextContent(result.output) } this.observer.agentEnd({ ...info, outcome: 'failed' }) return null From 7d83af645cd64a0d850f524dc0e099e7b07cca28 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Wed, 11 Nov 2026 19:33:52 +0800 Subject: [PATCH 13/48] docs(llm): fix route credential contracts and the package index budget - RouteCredential.configured: the owner may read its store to answer; the contract no longer claims "without reading the credential's value". Same text in the source JSDoc, both llm-streaming type-equiv blocks, and the seam Agent Note. - llm-deepseek README: replace the stale resolveAuth(connection) summary with the resolveAuth(connection, endpoint) contract. - llm-deepseek-account README: the listing cache is keyed by a SHA-256 of the credential headers, not of the token. - web-deepseek-api tests/routes.ts: note that composition.spec.ts covers the real route plugins. - packages/README: restore the document/, credentials/, and util/ rows and raise the verify-doc-budgets ceiling to 1,060 for the account/ row. --- .../2026-11-10-llm-route-credential-seam.i18n.yaml | 4 ++-- .../architecture/2026-11-10-llm-route-credential-seam.md | 2 +- .../architecture/2026-11-10-llm-route-credential-seam.zh.md | 2 +- docs/AGENTS.md | 2 +- docs/subsystems/llm-streaming.md | 4 ++-- docs/subsystems/llm-streaming.zh.md | 4 ++-- packages/README.i18n.yaml | 4 ++-- packages/README.md | 6 +++--- packages/README.zh.md | 6 +++--- packages/llm/llm-deepseek-account/README.i18n.yaml | 4 ++-- packages/llm/llm-deepseek-account/README.md | 2 +- packages/llm/llm-deepseek-account/README.zh.md | 2 +- packages/llm/llm-deepseek/README.i18n.yaml | 4 ++-- packages/llm/llm-deepseek/README.md | 2 +- packages/llm/llm-deepseek/README.zh.md | 2 +- packages/llm/llm/src/types.ts | 4 ++-- packages/web/web-deepseek-api/tests/routes.ts | 6 +++++- scripts/doc-budgets.manifest.json | 2 +- 18 files changed, 33 insertions(+), 29 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index 957eb36d50..6926949697 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -9,8 +9,8 @@ en: 9665e1879893fe76 zh: 9da30ad0be6fc38d /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision: - en: d7f7ef9ed3038ef7 - zh: c003e6b3338d1f3e + en: 5819b658fc81482d + zh: 948e9cb0a668e623 /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered: en: 8177946a6bfa1a6d zh: f523f9057b4b47c5 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md index f3af0daf41..ba7c05d753 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -10,7 +10,7 @@ Several packages shared one DeepSeek credential without an owner. `@deepseek-ai/ ## Decision -`@deepseek-ai/dsh-llm` owns the Service Definition. `LlmAdapter.routeCredential(provider)` publishes a `RouteCredential`: the route's `kind` (merge-extensible, with `api-key` and `account` declared), its resolved `baseURL`, an optional credential `reference` for diagnostics, `configured(endpoint)` for presence checks that read no value, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with the protocol `headers`, the bare `value` for destinations that render it differently, and an optional `reject()` for HTTP 401. `LlmRuntime.routeCredential(provider)` forwards to the owning adapter; an unregistered route answers `undefined`, and a route whose configuration does not resolve propagates the adapter's failure. The adapter reads one configuration generation per call, as it does per model request. +`@deepseek-ai/dsh-llm` owns the Service Definition. `LlmAdapter.routeCredential(provider)` publishes a `RouteCredential`: the route's `kind` (merge-extensible, with `api-key` and `account` declared), its resolved `baseURL`, an optional credential `reference` for diagnostics, `configured(endpoint)` for presence checks that neither validate the credential nor contact the destination, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with the protocol `headers`, the bare `value` for destinations that render it differently, and an optional `reject()` for HTTP 401. `LlmRuntime.routeCredential(provider)` forwards to the owning adapter; an unregistered route answers `undefined`, and a route whose configuration does not resolve propagates the adapter's failure. The adapter reads one configuration generation per call, as it does per model request. `@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the grant or `undefined`; `missingCredential(connection, provider)` names the failure of a request without one, `MISSING_CREDENTIAL` by default; `credential` declares the published kind, reference, and presence check. The listing cache scopes by endpoint and a hash of the credential headers. diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index 497aec414d..9651ca13d6 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.routeCredential(provider)` 发布一个 `RouteCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不读取值的存在性检查 `configured(endpoint)`,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`,以及可选的 HTTP 401 `reject()`。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 +`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.routeCredential(provider)` 发布一个 `RouteCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不校验凭据、不联系目的地的存在性检查 `configured(endpoint)`,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`,以及可选的 HTTP 401 `reject()`。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 `@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回授权或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`;`credential` 声明发布的种类、引用和存在性检查。列表缓存以端点和凭据请求头的哈希划分作用域。 diff --git a/docs/AGENTS.md b/docs/AGENTS.md index 818f40b452..d27a99ce49 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -56,7 +56,7 @@ When the gate goes red: 2. **Condense** content that belongs here but can be shorter. 3. **Raise** the ceiling only when the words need the space; justify the manifest diff in the PR. A too-low ceiling is a budget bug. -Ceilings are guardrails, not reduction targets. At or below target, retain at least 5% headroom; above target, freeze the ceiling until relocation or condensation brings the document under target. Lower a ceiling only when the document still has room. Targets: root `AGENTS.md` ≤ 2,080; `architecture.md` ≤ 2,400; subtree `AGENTS.md` ≤ 600, except `packages/AGENTS.md` ≤ 810 and this file ≤ 1,430; `packages/README.md` ≤ 994; plus `cordis-primer.md` 600, `testing.md` 1,300, `examples/AGENTS.md` 310. Review governs unbudgeted tiers. +Ceilings are guardrails, not reduction targets. At or below target, retain at least 5% headroom; above target, freeze the ceiling until relocation or condensation brings the document under target. Lower a ceiling only when the document still has room. Targets: root `AGENTS.md` ≤ 2,080; `architecture.md` ≤ 2,400; subtree `AGENTS.md` ≤ 600, except `packages/AGENTS.md` ≤ 810 and this file ≤ 1,430; `packages/README.md` ≤ 1,060; plus `cordis-primer.md` 600, `testing.md` 1,300, `examples/AGENTS.md` 310. Review governs unbudgeted tiers. ## The slop checklist diff --git a/docs/subsystems/llm-streaming.md b/docs/subsystems/llm-streaming.md index 5b90d98955..4ab60ea418 100644 --- a/docs/subsystems/llm-streaming.md +++ b/docs/subsystems/llm-streaming.md @@ -582,8 +582,8 @@ interface RouteCredential { readonly reference?: string /** * Whether {@link resolve} would release a credential for `endpoint`, checked - * without reading the credential's value, validating it, or contacting the - * destination. Store failures reject. + * without validating the credential or contacting the destination; the owner + * may read its store to answer. Store failures reject. * @param endpoint - absolute URL the credential would be sent to. * @returns whether a credential is configured for that destination. */ diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index f6683eb136..19a694ea5e 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -588,8 +588,8 @@ interface RouteCredential { readonly reference?: string /** * Whether {@link resolve} would release a credential for `endpoint`, checked - * without reading the credential's value, validating it, or contacting the - * destination. Store failures reject. + * without validating the credential or contacting the destination; the owner + * may read its store to answer. Store failures reject. * @param endpoint - absolute URL the credential would be sent to. * @returns whether a credential is configured for that destination. */ diff --git a/packages/README.i18n.yaml b/packages/README.i18n.yaml index 81357d69c5..aad4b43c53 100644 --- a/packages/README.i18n.yaml +++ b/packages/README.i18n.yaml @@ -15,8 +15,8 @@ en: ffc55792d6e922e1 zh: 83bd759638857e2d /packages/package-groups: - en: 2f76ab75d2b0b872 - zh: 7e6ce5f883d805c9 + en: d9e9a1a89c88f2e1 + zh: b48ff513befdad5b /packages/release-expectations: en: 236081c1659b25ab zh: 809110adf003802e diff --git a/packages/README.md b/packages/README.md index a8c0dbc993..426b6c25ab 100644 --- a/packages/README.md +++ b/packages/README.md @@ -57,7 +57,7 @@ Every package lives in exactly one group; new packages join existing groups, and | [`experimental/`](experimental/README.md) | Capabilities under evaluation; [status and support policy](experimental/README.md#status) | | [`workflow/`](workflow/README.md) | Workflow seam, PTC process engine, and the model-facing `workflow` tool | | [`web/`](web/README.md) | Web capability family: seam, search/fetch providers, model-facing web tools | -| [`document/`](document/README.md) | Host Office rendering, conversion, and recalculation, the Office tools, and Kit engine resolution | +| [`document/`](document/README.md) | Shared Host Office rendering, conversion, and recalculation, the Office tools, and Kit engine resolution | | [`attachment/`](attachment/README.md) | Durable attachment identity, validation, local content-addressed storage | | [`spill/`](spill/README.md) | Spill capability family: storage seam, local impl, tool-result spill policy | | [`todo/`](todo/README.md) | The model-facing `todo_write` tool | @@ -70,7 +70,7 @@ Every package lives in exactly one group; new packages join existing groups, and | [`session/`](session/README.md) | Durable session data plane: persistence seam + backends, projection seam, log-backed titles, session reporting | | [`session-query/`](session-query/README.md) | Session retrieval family: logical corpus, bounded reads, lineage, semantic filtering, SQLite full-text search | | [`settings/`](settings/README.md) | User-settings seam + file-backed provider | -| [`credentials/`](credentials/README.md) | Credential reference and record seam, env-over-`.env` provider, and authorization flows that ask a human | +| [`credentials/`](credentials/README.md) | Credential-reference and credential-record seam + env-over-`.env` provider + authorization flows that ask a human | | [`account/`](account/README.md) | DeepSeek account sign-in and Host-only request credentials | | [`storage/`](storage/README.md) | Non-session storage hub + backends + domain form | | [`workspace/`](workspace/README.md) | Workspace entity | @@ -81,7 +81,7 @@ Every package lives in exactly one group; new packages join existing groups, and | [`host/`](host/README.md) | Web GUI host services, directory picking, application launch, plugin inventory, and product telemetry | | [`client/`](client/README.md) | Web-GUI browser half: shell, wire, object services, slots, `ui-*` plugins | | [`test-support/`](test-support/README.md) | Test infrastructure (testkits, replay, Loader smokes) | -| [`util/`](util/README.md) | Low-level utilities and data-only package lists shared across groups | +| [`util/`](util/README.md) | Low-level utilities and data-only package lists shared across groups (`Branded`, home/path helpers, timeout, retention, official bundle lists) | ----- diff --git a/packages/README.zh.md b/packages/README.zh.md index fda5527ba1..14332e87fd 100644 --- a/packages/README.zh.md +++ b/packages/README.zh.md @@ -57,7 +57,7 @@ harness 由 `packages/` 下的 npm 包组装而成,按能力系列分组:会 | [`experimental/`](experimental/README.zh.md) | 仍在评估中的能力;[状态与支持策略](experimental/README.zh.md#status) | | [`workflow/`](workflow/README.zh.md) | 工作流 seam、PTC 进程引擎、面向模型的 `workflow` 工具 | | [`web/`](web/README.zh.md) | Web 能力系列:seam、搜索/获取提供方、面向模型的 Web 工具 | -| [`document/`](document/README.zh.md) | 宿主 Office 渲染、转换与重算、Office 工具与 Kit 引擎解析 | +| [`document/`](document/README.zh.md) | 共享宿主 Office 渲染、转换与重算、Office 工具与 Kit 引擎解析 | | [`attachment/`](attachment/README.zh.md) | 持久附件标识、校验、本地内容寻址存储 | | [`spill/`](spill/README.zh.md) | spill 能力系列:存储 seam、本地实现、工具结果 spill 策略 | | [`todo/`](todo/README.zh.md) | 面向模型的 `todo_write` 工具 | @@ -70,7 +70,7 @@ harness 由 `packages/` 下的 npm 包组装而成,按能力系列分组:会 | [`session/`](session/README.zh.md) | 持久会话数据平面:持久化 seam + 后端、投影 seam、基于日志的标题、会话上报 | | [`session-query/`](session-query/README.zh.md) | 会话检索系列:逻辑语料库、有界读取、血缘、语义过滤、SQLite 全文搜索 | | [`settings/`](settings/README.zh.md) | 用户设置 seam + 基于文件的提供方 | -| [`credentials/`](credentials/README.zh.md) | 凭据引用与记录 seam、环境变量优先于 `.env` 的提供方,以及需要向人询问的授权流程 | +| [`credentials/`](credentials/README.zh.md) | 凭据引用与凭据记录 seam + 环境变量优先于 `.env` 的提供方 + 需要向人询问的授权流程 | | [`account/`](account/README.zh.md) | DeepSeek 账号登录与仅限 Host 的请求凭据 | | [`storage/`](storage/README.zh.md) | 非会话存储中枢 + 后端 + 领域形式 | | [`workspace/`](workspace/README.zh.md) | Workspace 实体 | @@ -81,7 +81,7 @@ harness 由 `packages/` 下的 npm 包组装而成,按能力系列分组:会 | [`host/`](host/README.zh.md) | Web GUI 宿主服务、目录选择、应用启动、插件清单和产品遥测 | | [`client/`](client/README.zh.md) | web GUI 浏览器半侧:shell、协议层、对象服务、slot、`ui-*` 插件 | | [`test-support/`](test-support/README.zh.md) | 测试基础设施(testkit、回放、Loader 冒烟测试) | -| [`util/`](util/README.zh.md) | 组间共享的低层工具与纯数据包列表 | +| [`util/`](util/README.zh.md) | 组间共享的低层工具与纯数据包列表(`Branded`、home/路径辅助函数、超时、留存、官方组合包列表) | ----- diff --git a/packages/llm/llm-deepseek-account/README.i18n.yaml b/packages/llm/llm-deepseek-account/README.i18n.yaml index b2cab10d84..580d4e4d87 100644 --- a/packages/llm/llm-deepseek-account/README.i18n.yaml +++ b/packages/llm/llm-deepseek-account/README.i18n.yaml @@ -18,8 +18,8 @@ en: 3d952599a9b0bf85 zh: 231c0331a7d217e3 /deepseek-ai-dsh-llm-deepseek-account/understand-the-implementation: - en: ee65c14a90dfa0dd - zh: 91778b3e940da7f7 + en: 37319d3b3317b0cf + zh: 90362d4dff489e35 /deepseek-ai-dsh-llm-deepseek-account/further-exploration: en: 30a69b9c66d89580 zh: fcc026a6373c1bee diff --git a/packages/llm/llm-deepseek-account/README.md b/packages/llm/llm-deepseek-account/README.md index 9b5ee9f706..17322210bb 100644 --- a/packages/llm/llm-deepseek-account/README.md +++ b/packages/llm/llm-deepseek-account/README.md @@ -63,7 +63,7 @@ The settings namespace is the Cordis entry id, or the plugin name without an ent ## Understand the implementation -Account credential lookup and invalidation go through the account service's `resolveRequestCredential`; this plugin retains HTTP error classification and owns the sign-out policy over running Agents in [`account-tasks.ts`](src/account-tasks.ts). Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport, which the API-key route also uses; the cache lives in memory and is keyed by endpoint and a SHA-256 of the token. +Account credential lookup and invalidation go through the account service's `resolveRequestCredential`; this plugin retains HTTP error classification and owns the sign-out policy over running Agents in [`account-tasks.ts`](src/account-tasks.ts). Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport, which the API-key route also uses; the cache lives in memory and is keyed by endpoint and a SHA-256 of the credential headers. A failed request the shared transport classifies as `QUOTA` is rewritten to `ACCOUNT_QUOTA` before it leaves this provider, covering an HTTP 402 response and an in-band SSE error alike. The shared transport and the `deepseek-official` route keep `QUOTA`, so the account route's top-up action never appears for an API-key or third-party failure. diff --git a/packages/llm/llm-deepseek-account/README.zh.md b/packages/llm/llm-deepseek-account/README.zh.md index 2f6958d366..26d6694096 100644 --- a/packages/llm/llm-deepseek-account/README.zh.md +++ b/packages/llm/llm-deepseek-account/README.zh.md @@ -63,7 +63,7 @@ kind: "package-reference" ## 理解实现 -账号凭据的读取与作废经由账号服务的 `resolveRequestCredential`;本插件保留 HTTP 错误分类,并在 [`account-tasks.ts`](src/account-tasks.ts) 中拥有针对运行中 Agent 的退登策略。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入目录和门控。列表请求、缓存和目录解析来自共享传输包,API key 路由也使用它们;缓存只在内存中,以端点和 token 的 SHA-256 为键。 +账号凭据的读取与作废经由账号服务的 `resolveRequestCredential`;本插件保留 HTTP 错误分类,并在 [`account-tasks.ts`](src/account-tasks.ts) 中拥有针对运行中 Agent 的退登策略。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入目录和门控。列表请求、缓存和目录解析来自共享传输包,API key 路由也使用它们;缓存只在内存中,以端点和凭据请求头的 SHA-256 为键。 共享传输判定为 `QUOTA` 的失败请求离开本提供方前会被改写为 `ACCOUNT_QUOTA`,HTTP 402 响应与流内 SSE 错误都适用。共享传输与 `deepseek-official` 路由保留 `QUOTA`,因此账号路由的充值操作不会出现在 API Key 或第三方失败上。 diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index 68db96e254..47f19261a6 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -9,8 +9,8 @@ en: e66a018af9e2de3c zh: d7188003d01964bb /deepseek-ai-dsh-llm-deepseek/summary: - en: a8871f9ce192ac6a - zh: 7d642e993f4ca71c + en: dc3675dcd430459e + zh: 4abf101572e2e595 /deepseek-ai-dsh-llm-deepseek/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 5333f68e3c..04404624b7 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -11,7 +11,7 @@ English | [中文](README.zh.md) Provide the shared DeepSeek Messages transport, request configuration, and model capabilities. Compose [API-key](../llm-deepseek-api-key/README.md) or [account](../llm-deepseek-account/README.md) plugins for authentication, model discovery, and provider registration. Valid settings changes affect subsequent calls while in-flight calls retain their configuration. This package can run beside the [pi-ai adapter](../llm-pi-ai/README.md). -`resolveAuth(connection)` returns the provider-owned authentication headers and an optional failure callback bound to that request’s credential. Messages and Files send those headers without selecting a credential mode. Upload reuse is isolated by endpoint and a hash of the authentication headers; raw credentials are not persisted. +`resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: its headers, its bare value, and an optional failure callback, or `undefined` when none is configured. Messages and Files send those headers without selecting a credential mode. Upload reuse is isolated by endpoint and a hash of the authentication headers; raw credentials are not persisted. ## Table of Contents diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index 8a83625697..142674331c 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" 提供共享的 DeepSeek Messages 传输、请求配置和模型能力。组合 [API key](../llm-deepseek-api-key/README.zh.md) 或[账号](../llm-deepseek-account/README.zh.md)插件以提供鉴权、模型发现与 provider 注册。有效的设置更改在后续请求生效,进行中的请求保留原配置。本包可与 [pi-ai 适配器](../llm-pi-ai/README.zh.md)并用。 -`resolveAuth(connection)` 返回提供方持有的鉴权请求头,以及绑定本次请求凭据的可选失败回调。Messages 和 Files 直接使用这些请求头,不判断凭据类型。上传复用按端点和鉴权请求头的哈希隔离,不持久化原始凭据。 +`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:请求头、裸凭据值以及可选的失败回调;未配置时返回 `undefined`。Messages 和 Files 直接使用这些请求头,不判断凭据类型。上传复用按端点和鉴权请求头的哈希隔离,不持久化原始凭据。 ## 目录 diff --git a/packages/llm/llm/src/types.ts b/packages/llm/llm/src/types.ts index 53b0acb3e4..a17f8d6de0 100644 --- a/packages/llm/llm/src/types.ts +++ b/packages/llm/llm/src/types.ts @@ -356,8 +356,8 @@ export interface RouteCredential { readonly reference?: string /** * Whether {@link resolve} would release a credential for `endpoint`, checked - * without reading the credential's value, validating it, or contacting the - * destination. Store failures reject. + * without validating the credential or contacting the destination; the owner + * may read its store to answer. Store failures reject. * @param endpoint - absolute URL the credential would be sent to. * @returns whether a credential is configured for that destination. */ diff --git a/packages/web/web-deepseek-api/tests/routes.ts b/packages/web/web-deepseek-api/tests/routes.ts index 620a3b87f5..4180bb486d 100644 --- a/packages/web/web-deepseek-api/tests/routes.ts +++ b/packages/web/web-deepseek-api/tests/routes.ts @@ -1,4 +1,8 @@ -/** A stand-in model service publishing DeepSeek route credentials the way the route plugins do. */ +/** + * A stand-in model service publishing DeepSeek route credentials the way the route plugins do. It reimplements their + * publication over the plugins' config resolvers, so `composition.spec.ts`, which boots the real route plugins through + * the Loader, is what covers the production path. + */ import type { Context } from '@deepseek-ai/cordis' import { credentialRefConfigured, resolveCredentialRef } from '@deepseek-ai/dsh-credentials' import type {} from '@deepseek-ai/dsh-deepseek-account' diff --git a/scripts/doc-budgets.manifest.json b/scripts/doc-budgets.manifest.json index f301060236..4e37f05fcc 100644 --- a/scripts/doc-budgets.manifest.json +++ b/scripts/doc-budgets.manifest.json @@ -5,5 +5,5 @@ "docs/cordis-primer.md": 600, "docs/testing.md": 1350, "packages/AGENTS.md": 810, - "packages/README.md": 994 + "packages/README.md": 1060 } From 3ca18d169ff795f48ec652994359aede596ffc05 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Wed, 11 Nov 2026 20:29:37 +0800 Subject: [PATCH 14/48] fix(account): invalidate a rejected token on the account service mounted at rejection - deepseek-account: the request credential's reject() re-resolves the account service through the resolving context, so a reload between a request and the destination's HTTP 401 still removes the stored grant; without a mounted service the grant stays for the next one to reject. resolveToken and rejectToken become private; the e2e sign-in stand-in and the generated API catalog follow. - llm-deepseek: routeCredential().resolve() publishes the grant's headers, value, and rejection only, keeping the adapter's onRequestError behind the seam. - web-deepseek-api: a route publishing an unparsable base URL becomes a misconfigured source instead of throwing from readiness or dispatch. --- apps/web/tests/cot-translation-paid.e2e.ts | 6 +- docs/subsystems/account.i18n.yaml | 8 +- docs/subsystems/account.md | 21 +---- docs/subsystems/account.zh.md | 21 +---- .../llm-route-credential/guide.i18n.yaml | 4 +- .../v0.2.2-rc.2/llm-route-credential/guide.md | 4 +- .../llm-route-credential/guide.zh.md | 4 +- .../account/deepseek-account/README.i18n.yaml | 8 +- packages/account/deepseek-account/README.md | 6 +- .../account/deepseek-account/README.zh.md | 6 +- .../account/deepseek-account/src/index.ts | 12 ++- .../account/deepseek-account/src/types.ts | 5 +- .../deepseek-account/tests/account.spec.ts | 91 +++++++++++++++---- .../extensions/tool-cordis/src/api-catalog.ts | 14 +-- packages/llm/llm-deepseek/src/adapter.ts | 6 +- packages/llm/llm-deepseek/src/types.ts | 5 +- .../tests/route-credential.spec.ts | 18 +++- packages/web/web-deepseek-api/src/index.ts | 14 +-- .../tests/credential-resolution.spec.ts | 11 +++ packages/web/web-deepseek-api/tests/routes.ts | 6 +- 20 files changed, 162 insertions(+), 108 deletions(-) diff --git a/apps/web/tests/cot-translation-paid.e2e.ts b/apps/web/tests/cot-translation-paid.e2e.ts index 37c2199298..7648cbe3ff 100644 --- a/apps/web/tests/cot-translation-paid.e2e.ts +++ b/apps/web/tests/cot-translation-paid.e2e.ts @@ -142,8 +142,10 @@ it.skipIf(MODE === 'record')('reuses saved native Account Flash translations acr const account = scaffold.ctx.get('deepseekAccount') if (account === undefined) throw new Error('Shipped native Account service is absent') // Only credential acquisition is nondeterministic; the Loader-owned native route and wire remain real. - const auth = vi.spyOn(account, 'resolveToken').mockImplementation(async (url: string) => - new URL(url).origin === origin ? 'paid-browser-fixture-token' : undefined) + const auth = vi.spyOn(account, 'resolveRequestCredential').mockImplementation(async (url: string) => + new URL(url).origin === origin + ? { headers: { 'x-dsh-auth-token': 'paid-browser-fixture-token' }, value: 'paid-browser-fixture-token', reject: () => Promise.resolve() } + : undefined) resources.restoreAuth = () => { auth.mockRestore() } scaffold.ctx.emit('llm/adapters-updated') const owner = [...scaffold.ctx.loader.entries()].find(entry => entry.options.id === 'llm-deepseek-account') diff --git a/docs/subsystems/account.i18n.yaml b/docs/subsystems/account.i18n.yaml index 90e4efdb1c..b202a8713e 100644 --- a/docs/subsystems/account.i18n.yaml +++ b/docs/subsystems/account.i18n.yaml @@ -6,11 +6,11 @@ en: 2302e2999588bac3 zh: 5e0ac058b50036dc /deepseek-account/request-credentials: - en: 76f2eb1df1948c8a - zh: 70f698243f8e3ae8 + en: 808ace524e0dbc0b + zh: c4268221fa4c1c09 /deepseek-account/embedded-platform-credentials: en: 9a651d70acbe83a6 zh: 4624b0299f5fdd8e /deepseek-account/cordis-api/deepseek-account-events/deepseek-account-signed-out-emit: - en: b2c8c533124a121c - zh: c2a5c227b5a01146 + en: 3065c17cb319f756 + zh: e69c2692a109c38b diff --git a/docs/subsystems/account.md b/docs/subsystems/account.md index 0706d14f80..b3a20e14ff 100644 --- a/docs/subsystems/account.md +++ b/docs/subsystems/account.md @@ -8,7 +8,7 @@ Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/accoun ## Request credentials -`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. The `deepseek-account` model route publishes this credential through `ctx.llm.routeCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `resolveToken(url)` returns the bare token under the same policy for consumers that compose their own request, and `rejectToken(token)` is the invalidation `reject()` performs. +`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. The `deepseek-account` model route publishes this credential through `ctx.llm.routeCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `reject()` runs on the account service mounted when it is called, so a reload between a request and the destination's answer still removes the grant; without a mounted service it leaves the grant for the next one to reject. Model routes that bill the account register a running-task report with `registerRunningTaskReport(report)` inside `ctx.effect()`; `hasRunningAccountTasks()` answers true while any report does, so the sign-out confirmation can warn about work the sign-out interrupts. The route plugin owns cancellation of that work after `deepseek-account/signed-out`. @@ -81,13 +81,6 @@ Account login, credentials, and client-safe Remote operations. */ @Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise -/** - * Remove an inference-rejected token only while it still matches the stored login. - * @param token - token captured by the rejected inference request. - * @returns after matching credentials are removed and the expiry notification is emitted. - */ -async rejectToken(token: string): Promise - /** * Read existing login identity without creating a device or returning credentials. * @returns optional device/account identifiers and the provider's OS version string. @@ -101,16 +94,10 @@ async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; */ async getPlatformSession(): Promise -/** - * Resolve a credential only for the inference origin allowed by the provider. - * @param url - actual request destination or API base URL. - * @returns stored token, or undefined for other origins or a signed-out account. - */ -async resolveToken(url: string): Promise - /** * Release the account credential for one request to `url` as the request - * carries it, together with its invalidation. Host-only. + * carries it, together with its invalidation, which runs on the account + * service mounted when it is called. Host-only. * @param url - actual request destination or API base URL. * @returns the request credential, or undefined for other origins or a signed-out account. */ @@ -229,6 +216,6 @@ Local grant removal has completed. Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts) -The account Service Definition exposes getState, getProfile, getBalance, getNotifications, getNotificationContent, reportNotificationEvent, startSignIn, cancelSignIn, signOut, watch, and Host-only resolveToken, resolveRequestCredential, registerRunningTaskReport, and getPlatformSession. The platform provider implements it with an AuthorizationFlow and a private GrantRecord. AccountView distinguishes stored presence from server validation; attempt IDs bind cancellation to one local flow. AccountUpdate carries a complete AccountView in state and a type of snapshot for initial or progress updates, or credentials-changed for credential writes and removal. Pending credential changes take priority over progress updates. See [the account package](../../packages/account/deepseek-account/README.md). +The account Service Definition exposes getState, getProfile, getBalance, getNotifications, getNotificationContent, reportNotificationEvent, startSignIn, cancelSignIn, signOut, watch, and Host-only resolveRequestCredential, registerRunningTaskReport, and getPlatformSession. The platform provider implements it with an AuthorizationFlow and a private GrantRecord. AccountView distinguishes stored presence from server validation; attempt IDs bind cancellation to one local flow. AccountUpdate carries a complete AccountView in state and a type of snapshot for initial or progress updates, or credentials-changed for credential writes and removal. Pending credential changes take priority over progress updates. See [the account package](../../packages/account/deepseek-account/README.md). `AccountClientMetadata` carries `version` from the caller’s `DSH_CLIENT_VERSION`, its active UI `locale`, and `timezoneOffsetSeconds` sampled when the operation begins. The offset is local time minus UTC in seconds: UTC+8 is `28800`. It contains no credentials. Login attempts retain their initiating metadata through exchange and cancellation; sign-out retains its metadata for revocation retries. diff --git a/docs/subsystems/account.zh.md b/docs/subsystems/account.zh.md index 45d5d03973..341b2923ac 100644 --- a/docs/subsystems/account.zh.md +++ b/docs/subsystems/account.zh.md @@ -8,7 +8,7 @@ ## 请求凭据 -`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`resolveToken(url)` 在同一策略下为自行组装请求的消费方返回裸 token,`rejectToken(token)` 则是 `reject()` 执行的失效操作。 +`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。 按账号计费的模型路由在 `ctx.effect()` 内用 `registerRunningTaskReport(report)` 注册运行中任务报告;只要有报告回答 true,`hasRunningAccountTasks()` 就回答 true,使退登确认能够提醒退登将打断的工作。`deepseek-account/signed-out` 之后取消这些工作由路由插件负责。 @@ -81,13 +81,6 @@ Account login, credentials, and client-safe Remote operations. */ @Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise -/** - * Remove an inference-rejected token only while it still matches the stored login. - * @param token - token captured by the rejected inference request. - * @returns after matching credentials are removed and the expiry notification is emitted. - */ -async rejectToken(token: string): Promise - /** * Read existing login identity without creating a device or returning credentials. * @returns optional device/account identifiers and the provider's OS version string. @@ -101,16 +94,10 @@ async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; */ async getPlatformSession(): Promise -/** - * Resolve a credential only for the inference origin allowed by the provider. - * @param url - actual request destination or API base URL. - * @returns stored token, or undefined for other origins or a signed-out account. - */ -async resolveToken(url: string): Promise - /** * Release the account credential for one request to `url` as the request - * carries it, together with its invalidation. Host-only. + * carries it, together with its invalidation, which runs on the account + * service mounted when it is called. Host-only. * @param url - actual request destination or API base URL. * @returns the request credential, or undefined for other origins or a signed-out account. */ @@ -229,6 +216,6 @@ Local grant removal has completed. Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts) -账号服务定义提供 getState、getProfile、getBalance、getNotifications、getNotificationContent、reportNotificationEvent、startSignIn、cancelSignIn、signOut、watch 及仅限 Host 的 resolveToken、resolveRequestCredential、registerRunningTaskReport 和 getPlatformSession。平台提供者使用 AuthorizationFlow 和私有 GrantRecord 实现这些操作。AccountView 区分本地存在与服务器验证;尝试 ID 将取消绑定到单次本地流程。AccountUpdate 的 state 携带完整 AccountView,type 为 snapshot 时表示首次或进度更新,为 credentials-changed 时表示凭据写入或删除。待发送的凭据变化优先于进度更新。参见[账号包](../../packages/account/deepseek-account/README.zh.md)。 +账号服务定义提供 getState、getProfile、getBalance、getNotifications、getNotificationContent、reportNotificationEvent、startSignIn、cancelSignIn、signOut、watch 及仅限 Host 的 resolveRequestCredential、registerRunningTaskReport 和 getPlatformSession。平台提供者使用 AuthorizationFlow 和私有 GrantRecord 实现这些操作。AccountView 区分本地存在与服务器验证;尝试 ID 将取消绑定到单次本地流程。AccountUpdate 的 state 携带完整 AccountView,type 为 snapshot 时表示首次或进度更新,为 credentials-changed 时表示凭据写入或删除。待发送的凭据变化优先于进度更新。参见[账号包](../../packages/account/deepseek-account/README.zh.md)。 `AccountClientMetadata` 携带调用方 `DSH_CLIENT_VERSION` 提供的 `version`、当前界面 `locale`,以及操作发起时采样的 `timezoneOffsetSeconds`。偏移为本地时间减 UTC 的秒数:UTC+8 对应 `28800`。其中不含凭证。登录申请在兑换及取消期间保留发起时的元数据;退出操作为撤销重试保留其元数据。 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml index feb25c5ab8..224eac372f 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml @@ -9,8 +9,8 @@ en: f0139803159ee9c9 zh: 73bd5dfd53ed8d36 /deepseek-routes-publish-the-credential-web-consumers-reuse/change: - en: 7a63f24e07fb3d33 - zh: 99c64684a589088e + en: 09ab43933a9e5950 + zh: a18da5d560cf0c9f /deepseek-routes-publish-the-credential-web-consumers-reuse/migration: en: 64ac045c8d9a1336 zh: 4712f6eacd85a151 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md index 2ec50f9a98..996805e3ee 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md @@ -9,13 +9,13 @@ English | [中文](guide.zh.md) ## Change -`LlmAdapter.routeCredential(provider)` and `LlmRuntime.routeCredential(provider)` publish a route's current credential as a `RouteCredential`: kind, resolved base URL, optional reference, a value-free `configured(endpoint)` check, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with protocol headers, the bare value, and an optional `reject()`. +`LlmAdapter.routeCredential(provider)` and `LlmRuntime.routeCredential(provider)` publish a route's current credential as a `RouteCredential`: kind, resolved base URL, optional reference, a `configured(endpoint)` presence check, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with protocol headers, the bare value, and an optional `reject()`. `@deepseek-ai/dsh-llm-deepseek` no longer exports `resolveDeepSeekApiKey`, `deepSeekApiKeyConfigured`, `resolveDeepSeekAccountToken`, or `rejectDeepSeekAccountToken`. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns `DeepSeekRequestAuth | undefined`, and `DeepSeekRequestAuth` requires `value` beside `headers`; the new `missingCredential` and `credential` options name the missing-credential failure and the published credential. `createModelListingCache` takes `credential(url)` returning request headers, and its `load` is optional. `@deepseek-ai/dsh-llm-deepseek-api-key` no longer exports `plainOptions` and `resolveAdapterOptions`; `@deepseek-ai/dsh-llm-deepseek-account` no longer exports `plainAccountOptions` and `resolveAccountOptions`. The account route plugin cancels its running Agents after sign-out and registers a running-task report. -`@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)`; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name. `@deepseek-ai/dsh-credentials` adds `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`. +`@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)` and makes `resolveToken(url)` and `rejectToken(token)` private; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name. `@deepseek-ai/dsh-credentials` adds `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`. `@deepseek-ai/dsh-web-deepseek-api` drops its peer dependencies on `dsh-llm-deepseek`, both route plugins, and `cordis-plugin-loader`; `@deepseek-ai/dsh-web-search-deepseek` drops `dsh-llm-deepseek` and `dsh-deepseek-account` and adds `dsh-llm`. Both read route credentials through `ctx.llm.routeCredential()`, so an adapter registered under a DeepSeek route id without a published credential counts as no route. Without the account route, the Search and Fetch APIs send the account credential to the origin `DEEPSEEK_BASE_URL` names and reject a value that is not an HTTP(S) URL without embedded credentials. `DeepSeekSearchProviderOptions` replaces `resolveAccountToken` and `rejectAccountToken` with `resolveAccountCredential(endpoint)`. diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md index 187434d603..18fdd11b89 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md @@ -9,13 +9,13 @@ description: "DeepSeek 模型路由通过 ctx.llm.routeCredential() 发布自己 ## 变更 -`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、不读取值的 `configured(endpoint)` 检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值和可选的 `reject()`。 +`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、`configured(endpoint)` 存在性检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值和可选的 `reject()`。 `@deepseek-ai/dsh-llm-deepseek` 不再导出 `resolveDeepSeekApiKey`、`deepSeekApiKeyConfigured`、`resolveDeepSeekAccountToken` 和 `rejectDeepSeekAccountToken`。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回 `DeepSeekRequestAuth | undefined`,且 `DeepSeekRequestAuth` 在 `headers` 之外要求 `value`;新增的 `missingCredential` 与 `credential` 选项分别命名凭据缺失的失败和发布的凭据。`createModelListingCache` 的 `credential(url)` 返回请求头,其 `load` 变为可选。 `@deepseek-ai/dsh-llm-deepseek-api-key` 不再导出 `plainOptions` 和 `resolveAdapterOptions`;`@deepseek-ai/dsh-llm-deepseek-account` 不再导出 `plainAccountOptions` 和 `resolveAccountOptions`。账号路由插件在退登后取消其运行中的 Agent,并注册运行中任务报告。 -`@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。该包移除 `dsh-agent` 与 `dsh-llm` peer 依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。`@deepseek-ai/dsh-credentials` 新增 `resolveCredentialRef(ctx, ref)` 与 `credentialRefConfigured(ctx, ref)`。 +`@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`,并将 `resolveToken(url)` 与 `rejectToken(token)` 改为私有;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。该包移除 `dsh-agent` 与 `dsh-llm` peer 依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。`@deepseek-ai/dsh-credentials` 新增 `resolveCredentialRef(ctx, ref)` 与 `credentialRefConfigured(ctx, ref)`。 `@deepseek-ai/dsh-web-deepseek-api` 移除对 `dsh-llm-deepseek`、两个路由插件和 `cordis-plugin-loader` 的 peer 依赖;`@deepseek-ai/dsh-web-search-deepseek` 移除 `dsh-llm-deepseek` 与 `dsh-deepseek-account`,新增 `dsh-llm`。两者都通过 `ctx.llm.routeCredential()` 读取路由凭据,因此以 DeepSeek 路由 id 注册但不发布凭据的适配器视为没有路由。没有账号路由时,Search 与 Fetch API 把账号凭据发往 `DEEPSEEK_BASE_URL` 所指的 origin,并拒绝不是不含内嵌凭据的 HTTP(S) URL 的值。`DeepSeekSearchProviderOptions` 用 `resolveAccountCredential(endpoint)` 替换 `resolveAccountToken` 与 `rejectAccountToken`。 diff --git a/packages/account/deepseek-account/README.i18n.yaml b/packages/account/deepseek-account/README.i18n.yaml index 95ce3a191b..e9ec42ad16 100644 --- a/packages/account/deepseek-account/README.i18n.yaml +++ b/packages/account/deepseek-account/README.i18n.yaml @@ -6,8 +6,8 @@ en: 9dbb9bc3960a11fe zh: ed58987926489d3e /deepseek-ai-dsh-deepseek-account: - en: 06fe55f319bd1b2c - zh: 9559b712e50bbc73 + en: d5aad878bc7d3059 + zh: 3573506e849ad4d4 /deepseek-ai-dsh-deepseek-account/summary: en: 28bcca957bf6abf4 zh: 4a3fc8a59f2925bc @@ -15,8 +15,8 @@ en: af856ba79fe31b8e zh: 15b7d1a5d1856de2 /deepseek-ai-dsh-deepseek-account/use-this-package: - en: 02b899ac5ad80227 - zh: 0cb4d6984ae6ed62 + en: 210ba1bd070bb8c4 + zh: 4e1286bff076a3b6 /deepseek-ai-dsh-deepseek-account/understand-the-implementation: en: 76d2da2dab100ac3 zh: 2c9404f27915daab diff --git a/packages/account/deepseek-account/README.md b/packages/account/deepseek-account/README.md index 34d87bf729..b26272b1d0 100644 --- a/packages/account/deepseek-account/README.md +++ b/packages/account/deepseek-account/README.md @@ -9,11 +9,11 @@ English | [中文](README.zh.md) Every operation that reaches Platform takes the caller's `AccountClientMetadata`: the client version, the active UI language, and the UTC offset in seconds. The service derives the five Platform client headers from that metadata and the composition's platform, so each request reports the UI that made it instead of the last caller the Host saw. A new sign-in attempt captures the metadata for its initialization, exchange, and cancellation, and a joining caller never replaces it; sign-out captures the metadata for the revocation retries that outlive the request. -getPlatformSession exports the stored grant only when its issuer matches platformOrigin. This Host-only operation supports native Platform embedding without widening the model/file origin configured for resolveToken. Its userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID; the snapshot issues no profile request of its own, so a slow or failed profile request never delays it, and an unknown ID leaves userId null, which consumers treat as temporary-storage mode. A credential change during the grant read discards the snapshot. +getPlatformSession exports the stored grant only when its issuer matches platformOrigin. This Host-only operation supports native Platform embedding without widening the inference origin that `resolveRequestCredential` enforces. Its userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID; the snapshot issues no profile request of its own, so a slow or failed profile request never delays it, and an unknown ID leaves userId null, which consumers treat as temporary-storage mode. A credential change during the grant read discards the snapshot. `desktopPlatform` defaults to `null`, which sends `x-client-platform: web`; the Desktop profile supplies `darwin` or `win32`, becoming `desktop-mac` or `desktop-win`. The service owns all five headers, so deployment configuration cannot override them; `x-client-bundle-id` is intentionally empty, and `x-client-locale` reduces the caller's language to `zh_CN` or `en_US`. PlatformSession carries deployment headers only, and the embedding client composes the same five headers for the Platform documents and API requests it opens, only at the configured origin. -Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. Host inference consumers can report a rejected request token through `rejectToken`; removal requires that it still matches the stored login. `resolveRequestCredential(url)` releases the credential for one allowed destination as the request headers, the bare token, and a `reject()` that performs that removal after an HTTP 401 while containing storage failures; the account model route and the DeepSeek web providers use it instead of composing headers themselves. +Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. `resolveRequestCredential(url)` releases the credential for one allowed destination as the request headers, the bare token, and a `reject()` that removes the stored grant after an HTTP 401 while it still matches that token, containing storage failures; the removal runs on the account service mounted when `reject()` is called, so a reload between the request and the destination's answer still removes the grant. The account model route and the DeepSeek web providers use it instead of composing headers themselves. ## Summary @@ -32,7 +32,7 @@ Device identity reads validate the existing login device record and expose only ## Use this package -The service exposes its client-safe operations through the `account` Remote namespace. The application loads its generated `./remote` contribution; no separate controller is needed. Login, profile, balance, notification, sign-out-impact, and expiry operations remain available through `ctx.remote.account`. Remote `watch` omits the Host-only identity subscription option. `resolveToken`, `rejectToken`, `getPlatformSession`, and `getDeviceIdentity` remain Host-only. +The service exposes its client-safe operations through the `account` Remote namespace. The application loads its generated `./remote` contribution; no separate controller is needed. Login, profile, balance, notification, sign-out-impact, and expiry operations remain available through `ctx.remote.account`. Remote `watch` omits the Host-only identity subscription option. `resolveRequestCredential`, `getPlatformSession`, and `getDeviceIdentity` remain Host-only. `DeepSeekAccount` is the concrete service owning login, credentials, and Remote operations. The `/types` entry exposes types without loading the service implementation. `watch` returns complete state tagged as `snapshot` or `credentials-changed`; Host-only `watch(signal, true)` also receives profile-identity changes, while Remote subscriptions omit that option. diff --git a/packages/account/deepseek-account/README.zh.md b/packages/account/deepseek-account/README.zh.md index 88b4801909..d219131533 100644 --- a/packages/account/deepseek-account/README.zh.md +++ b/packages/account/deepseek-account/README.zh.md @@ -9,11 +9,11 @@ kind: "package-reference" 每个到达 Platform 的操作都接收调用方的 `AccountClientMetadata`:客户端版本、当前界面语言和以秒为单位的 UTC 偏移。服务据此与组合出的平台推导五个 Platform 客户端请求头,因此每个请求报告的是发起它的界面,而不是 Host 上一次见到的调用方。新的登录申请会为该申请的初始化、兑换和取消捕获这份元数据,中途加入的调用方不会替换它;退登则为在请求之后继续进行的撤销重试捕获这份元数据。 -getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导出该授权。这个仅限 Host 的操作支持原生 Platform 内嵌,不扩大 resolveToken 配置的模型及文件请求来源。其 userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照不自行发起资料请求,因此资料请求缓慢或失败都不会延迟它;ID 未知时 userId 为 null,使用方将其视为临时存储模式。读取授权期间凭证变化时丢弃快照。 +getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导出该授权。这个仅限 Host 的操作支持原生 Platform 内嵌,不扩大 `resolveRequestCredential` 限定的推理来源。其 userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照不自行发起资料请求,因此资料请求缓慢或失败都不会延迟它;ID 未知时 userId 为 null,使用方将其视为临时存储模式。读取授权期间凭证变化时丢弃快照。 `desktopPlatform` 默认为 `null`,此时携带 `x-client-platform: web`;Desktop profile 提供 `darwin` 或 `win32`,改为 `desktop-mac` 或 `desktop-win`。五个请求头均由 provider 拥有,部署配置无法覆盖;`x-client-bundle-id` 有意保持为空,`x-client-locale` 将调用方语言归约为 `zh_CN` 或 `en_US`。PlatformSession 只携带部署请求头,内嵌客户端为自行打开的 Platform 文档和 API 请求组装同样的五个请求头,且仅在配置来源发送。 -资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。Host 推理调用方可以通过 `rejectToken` 报告被拒绝的请求 token;仅当它仍匹配当前登录凭据时才执行清除。`resolveRequestCredential(url)` 把一个允许目标的凭据以请求头、裸 token 和 `reject()` 的形式释放;`reject()` 在 HTTP 401 后执行上述清除并隔离存储失败。账号模型路由和 DeepSeek Web 提供方使用它,而不自行组装请求头。 +资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。`resolveRequestCredential(url)` 把一个允许目标的凭据以请求头、裸 token 和 `reject()` 的形式释放;`reject()` 在 HTTP 401 后、且存储的授权仍匹配该 token 时清除它并隔离存储失败;清除在 `reject()` 被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会清除授权。账号模型路由和 DeepSeek Web 提供方使用它,而不自行组装请求头。 ## 概述 @@ -32,7 +32,7 @@ getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导 ## 使用此包 -服务通过 `account` Remote 命名空间暴露可供客户端使用的操作。应用加载其生成的 `./remote` 贡献,无需单独的 controller。登录、资料、余额、通知、退出影响检查和凭据过期操作均通过 `ctx.remote.account` 调用。Remote `watch` 不接受仅供 Host 使用的身份订阅选项。`resolveToken`、`rejectToken`、`getPlatformSession` 和 `getDeviceIdentity` 仍仅供 Host 使用。 +服务通过 `account` Remote 命名空间暴露可供客户端使用的操作。应用加载其生成的 `./remote` 贡献,无需单独的 controller。登录、资料、余额、通知、退出影响检查和凭据过期操作均通过 `ctx.remote.account` 调用。Remote `watch` 不接受仅供 Host 使用的身份订阅选项。`resolveRequestCredential`、`getPlatformSession` 和 `getDeviceIdentity` 仍仅供 Host 使用。 `DeepSeekAccount` 是具体服务,拥有登录、凭证和 Remote 操作。`/types` 提供不加载服务实现的类型出口。`watch` 返回完整状态与 `snapshot` 或 `credentials-changed` 类型;仅 Host 的 `watch(signal, true)` 还接收资料身份变化,Remote 订阅不启用该选项。 diff --git a/packages/account/deepseek-account/src/index.ts b/packages/account/deepseek-account/src/index.ts index 739907057e..cee5f107e4 100644 --- a/packages/account/deepseek-account/src/index.ts +++ b/packages/account/deepseek-account/src/index.ts @@ -373,7 +373,7 @@ export class DeepSeekAccount extends TypertRemoteService { * @param token - token captured by the rejected inference request. * @returns after matching credentials are removed and the expiry notification is emitted. */ - async rejectToken(token: string): Promise { + private async rejectToken(token: string): Promise { const lifetime = this.detailsLifetime const stored = await this.readCurrentGrant(lifetime) if (stored?.token !== token || this.detailsLifetime !== lifetime) return @@ -450,7 +450,7 @@ export class DeepSeekAccount extends TypertRemoteService { * @param url - actual request destination or API base URL. * @returns stored token, or undefined for other origins or a signed-out account. */ - async resolveToken(url: string): Promise { + private async resolveToken(url: string): Promise { if (this.closed || this.removing !== undefined) return undefined const destination = new URL(url) if (destination.origin !== this.inferenceOrigin || destination.username || destination.password) return undefined @@ -470,18 +470,22 @@ export class DeepSeekAccount extends TypertRemoteService { /** * Release the account credential for one request to `url` as the request - * carries it, together with its invalidation. Host-only. + * carries it, together with its invalidation, which runs on the account + * service mounted when it is called. Host-only. * @param url - actual request destination or API base URL. * @returns the request credential, or undefined for other origins or a signed-out account. */ async resolveRequestCredential(url: string): Promise { const token = await this.resolveToken(url) if (token === undefined) return undefined + // The destination answers after a reload may have replaced this instance, so the rejection runs on the account + // service mounted at that time; without one, the grant stays for the next mounted service to reject. + const { ctx } = this return { headers: { [ACCOUNT_TOKEN_HEADER]: token }, value: token, reject: async () => { - try { await this.rejectToken(token) } + try { await ctx.get('deepseekAccount')?.rejectToken(token) } catch (_credentialRemovalFailed) { /* The destination's rejection is the failure to report; the next rejection retries. */ } }, } diff --git a/packages/account/deepseek-account/src/types.ts b/packages/account/deepseek-account/src/types.ts index 9a0f23c772..e49c4455ce 100644 --- a/packages/account/deepseek-account/src/types.ts +++ b/packages/account/deepseek-account/src/types.ts @@ -122,7 +122,10 @@ export interface AccountRequestCredential { readonly value: string /** * Remove the stored token after the destination rejected it, unless a newer - * sign-in replaced it. Storage failures are contained: the caller reports + * sign-in replaced it. The removal runs on the account service mounted when + * this is called, so a reload between the request and the rejection does + * not keep the token; without a mounted service the token stays for the + * next one to reject. Storage failures are contained: the caller reports * the destination's rejection, and the next rejection retries the removal. * @returns settlement after the removal attempt. */ diff --git a/packages/account/deepseek-account/tests/account.spec.ts b/packages/account/deepseek-account/tests/account.spec.ts index a5a1662868..33d4bfd029 100644 --- a/packages/account/deepseek-account/tests/account.spec.ts +++ b/packages/account/deepseek-account/tests/account.spec.ts @@ -157,11 +157,12 @@ async function fixture( const authorization = ctx.plugin(AuthorizationService) await authorization await beforeAccount?.(ctx, origin) - const provider = ctx.plugin(DeepSeekAccount, { + const accountConfig = { platformOrigin: origin, inferenceOrigin, embeddedPageDist, desktopPlatform, allowLoopbackHttp: true, requestHeaders, accountRequestHeaders, rewriteBrowserOrigin, logoutRetryDelayMs: 1, balanceTimeoutMs, - }) + } + let provider = ctx.plugin(DeepSeekAccount, accountConfig) await provider cleanups.push(async () => { await provider.dispose(); await authorization.dispose(); await credentials.dispose(); await web.dispose() }) const account = ctx.deepseekAccount @@ -184,6 +185,13 @@ async function fixture( invalidateSummary: () => { normalWallets = [{ currency: 'CNY', balance: 'not-a-decimal' }] }, normalWallets: (value: unknown) => { normalWallets = value }, dispose: () => provider.dispose(), exchanged, release, + /** Replace the account service as a settings reload does; the stored grant and the other services stay. */ + remount: async () => { + await provider.dispose() + provider = ctx.plugin(DeepSeekAccount, accountConfig) + await provider + return ctx.deepseekAccount + }, redirect: () => { redirect = true }, hold: () => { hold = true }, initResponse: (value: Record) => { initOverride = value }, @@ -267,7 +275,7 @@ it('stores a grant before redirecting, restores account presence, and signs out await f.account.getProfile(clientMetadata()) expect(await f.account.getPlatformSession()).toEqual({ origin: f.origin, userId: 'test-user', token: 'dsh_mock_test', requestHeaders: {} }) - expect(await f.account.resolveToken('https://api.deepseek.com')).toBeUndefined() + expect(await f.account.resolveRequestCredential('https://api.deepseek.com')).toBeUndefined() await f.account.signOut(clientMetadata()) expect((await f.account.getState()).status).toBe('signed-out') expect(await f.account.getPlatformSession()).toBeNull() @@ -300,9 +308,9 @@ it('allows real account credentials only on the exact official HTTPS origin', as await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ kind: 'grant', payload: { version: 1, issuer: 'https://platform.deepseek.com', token: 'test-account-token' }, })) - expect(await f.account.resolveToken('https://api.deepseek.com/v1')).toBe('test-account-token') + expect((await f.account.resolveRequestCredential('https://api.deepseek.com/v1'))?.value).toBe('test-account-token') for (const url of ['http://api.deepseek.com', 'https://api.deepseek.com.evil.test', 'https://api.deepseek.com:8443', 'https://user@api.deepseek.com']) { - expect(await f.account.resolveToken(url)).toBeUndefined() + expect(await f.account.resolveRequestCredential(url)).toBeUndefined() } }) @@ -332,7 +340,32 @@ it('contains a storage failure while removing a rejected token', async () => { const credential = await f.account.resolveRequestCredential('http://inference.example.test:8094/v1/tools/search') await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ kind: 'api-key', key: 'wrong-kind' })) await expect(credential!.reject()).resolves.toBeUndefined() - await expect(f.account.rejectToken('test-account-token')).rejects.toThrow('account: storage') + // The contained failure is the store's: it still holds the unreadable record. + await expect(f.account.getState()).rejects.toThrow('account: storage') +}) + +it('invalidates a rejected token through the account service mounted when the rejection runs', async () => { + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) + await storeAccount(f) + const credential = await storedCredential(f) + // A settings reload replaces the service between the request's dispatch and the destination's answer. + const replacement = await f.remount() + const published: string[] = [] + f.ctx.on('deepseek-account/signed-out', () => { published.push('signed-out') }) + await credential.reject() + expect(published).toEqual(['signed-out']) + expect((await replacement.getState()).status).toBe('signed-out') + expect(await f.ctx.credentials.readRecord(credentialKey('deepseek-account-platform', 'default'))).toBeUndefined() +}) + +it('keeps a rejected token for the next mounted account service while none is mounted', async () => { + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) + await storeAccount(f) + const credential = await storedCredential(f) + await f.dispose() + await expect(credential.reject()).resolves.toBeUndefined() + expect(await f.ctx.credentials.readRecord(credentialKey('deepseek-account-platform', 'default'))) + .toMatchObject({ kind: 'grant', payload: { token: 'test-platform-grant' } }) }) it('restricts platform destinations to the configured origin and route', () => { @@ -424,6 +457,16 @@ async function storeAccount(f: Awaited>) { })) } +/** Inference origin a fixture allows a grant `storeAccount` wrote, which official inference refuses as development-issued. */ +const PRIVATE_INFERENCE = 'http://inference.example.test:8094' + +/** The request credential of the stored grant, released for the private inference origin. */ +async function storedCredential(f: Awaited>) { + const credential = await f.account.resolveRequestCredential(`${PRIVATE_INFERENCE}/v1/messages`) + if (credential === undefined) throw new Error('missing stored credential') + return credential +} + it('queries Platform Web endpoints with the stored grant and projects only masked profile and separate recharge and bonus balances', async () => { const f = await fixture() expect(await readDetails(f.account)).toBeNull() @@ -454,7 +497,7 @@ it('publishes sign-out only after local grant removal and refuses token resoluti const observed: string[] = [] f.ctx.on('deepseek-account/signed-out', () => { observed.push('signed-out') }) const pending = f.account.signOut(clientMetadata()) - expect(await f.account.resolveToken('https://api.deepseek.com')).toBeUndefined() + expect(await f.account.resolveRequestCredential('https://api.deepseek.com')).toBeUndefined() await pending expect(observed).toEqual(['signed-out']) expect((await f.account.getState()).status).toBe('signed-out') @@ -855,10 +898,10 @@ it('sends a development grant only to its configured inference origin', async () await f.wait('waiting-browser') await fetch(f.callback(), { redirect: 'manual' }) await f.wait('succeeded') - expect(await f.account.resolveToken('http://inference.example.test:8094/api')).toBe('test-account-token') + expect((await f.account.resolveRequestCredential('http://inference.example.test:8094/api'))?.value).toBe('test-account-token') for (const url of ['https://api.deepseek.com', 'http://inference.example.test:8095/api', 'https://inference.example.test:8094/api', 'http://user@inference.example.test:8094/api']) { - expect(await f.account.resolveToken(url)).toBeUndefined() + expect(await f.account.resolveRequestCredential(url)).toBeUndefined() } }) @@ -1117,14 +1160,14 @@ it.each([{ kind: 'api-key' as const, key: 'wrong-kind' }, { kind: 'grant' as con await expect(f.account.getState()).rejects.toThrow('account: storage') await expect(f.account.getProfile(clientMetadata())).rejects.toThrow('account: storage') await expect(f.account.getPlatformSession()).rejects.toThrow('account: storage') - await expect(f.account.resolveToken('https://api.deepseek.com')).rejects.toThrow('account: storage') + await expect(f.account.resolveRequestCredential('https://api.deepseek.com')).rejects.toThrow('account: storage') await expect(f.account.signOut(clientMetadata())).rejects.toThrow('account: storage') }, ) it('returns no credentials when signed out or disposed', async () => { const f = await fixture() - expect(await f.account.resolveToken('https://api.deepseek.com')).toBeUndefined() + expect(await f.account.resolveRequestCredential('https://api.deepseek.com')).toBeUndefined() expect(await f.account.getPlatformSession()).toBeNull() await f.account.cancelSignIn('missing' as import('@deepseek-ai/dsh-deepseek-account').SignInAttemptId) await f.dispose() @@ -1139,7 +1182,7 @@ it('rejects sign-out and inference grants issued by another environment', async await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ kind: 'grant', payload: { version: 1, token: 'real-token', issuer: 'https://other.example' }, })) - expect(await f.account.resolveToken('https://private.example')).toBeUndefined() + expect(await f.account.resolveRequestCredential('https://private.example')).toBeUndefined() await expect(f.account.signOut(clientMetadata())).rejects.toThrow('account: protocol') }) @@ -1148,7 +1191,7 @@ it('never sends a development issuer grant to official inference', async () => { await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ kind: 'grant', payload: { version: 1, token: 'real-token', issuer: f.origin }, })) - expect(await f.account.resolveToken('https://api.deepseek.com')).toBeUndefined() + expect(await f.account.resolveRequestCredential('https://api.deepseek.com')).toBeUndefined() }) it('merges account cookies when there are no base cookies', async () => { @@ -1632,13 +1675,14 @@ it('ignores a 401 whose response cleanup overlaps a credential replacement', asy }) it('expires an inference-rejected token without another Platform request', async () => { - const f = await fixture() + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) await storeAccount(f) + const credential = await storedCredential(f) const published: string[] = [] f.ctx.on('deepseek-account/signed-out', () => { published.push('signed-out') }) f.ctx.on('deepseek-account/session-expired', () => { published.push('session-expired') }) - await f.account.rejectToken('test-platform-grant') - await f.account.rejectToken('test-platform-grant') + await credential.reject() + await credential.reject() const state = await f.account.getState() expect({ status: state.status, published, detailRequests: f.detailRequests }) .toMatchInlineSnapshot(` @@ -1654,17 +1698,24 @@ it('expires an inference-rejected token without another Platform request', async }) it('retains a replacement login when inference rejects the previous token', async () => { - const f = await fixture() + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) + await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ + kind: 'grant', payload: { version: 1, issuer: f.origin, token: 'previous-platform-grant' }, + })) + const previous = await storedCredential(f) await storeAccount(f) - await f.account.rejectToken('previous-platform-grant') + await previous.reject() expect(await f.account.getState()).toMatchObject({ status: 'credential-stored' }) expect(await f.ctx.credentials.readRecord(credentialKey('deepseek-account-platform', 'default'))) .toMatchObject({ kind: 'grant', payload: { token: 'test-platform-grant' } }) }) it('ignores an inference rejection while already signed out', async () => { - const f = await fixture() - await f.account.rejectToken('previous-platform-grant') + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) + await storeAccount(f) + const credential = await storedCredential(f) + await f.ctx.credentials.deleteRecord(credentialKey('deepseek-account-platform', 'default')) + await credential.reject() expect(await f.account.getState()).toMatchObject({ status: 'signed-out' }) expect(await f.account.getState()).not.toHaveProperty('signOutReason') }) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 48b0edd085..0e7238eef5 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1017,12 +1017,6 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'id', description: 'notification the user interacted with.' }, { name: 'event', description: 'displayed frame, non-dismiss action click, or explicit dismissal.' }, { name: 'client', description: 'identity of the requesting UI for this call.' }], returns: 'true once the server accepts the event; false if signed out or credentials changed during the call.', }, - { - signature: 'async rejectToken(token: string): Promise', - description: 'Remove an inference-rejected token only while it still matches the stored login.', - parameters: [{ name: 'token', description: 'token captured by the rejected inference request.' }], - returns: 'after matching credentials are removed and the expiry notification is emitted.', - }, { signature: 'async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }>', description: 'Read existing login identity without creating a device or returning credentials.', @@ -1035,15 +1029,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [], returns: 'a Host-only snapshot, or null while signed out or when the credential changed during the read.', }, - { - signature: 'async resolveToken(url: string): Promise', - description: 'Resolve a credential only for the inference origin allowed by the provider.', - parameters: [{ name: 'url', description: 'actual request destination or API base URL.' }], - returns: 'stored token, or undefined for other origins or a signed-out account.', - }, { signature: 'async resolveRequestCredential(url: string): Promise', - description: 'Release the account credential for one request to `url` as the request carries it, together with its invalidation. Host-only.', + description: 'Release the account credential for one request to `url` as the request carries it, together with its invalidation, which runs on the account service mounted when it is called. Host-only.', parameters: [{ name: 'url', description: 'actual request destination or API base URL.' }], returns: 'the request credential, or undefined for other origins or a signed-out account.', }, diff --git a/packages/llm/llm-deepseek/src/adapter.ts b/packages/llm/llm-deepseek/src/adapter.ts index 0020cf5cde..8529f69988 100644 --- a/packages/llm/llm-deepseek/src/adapter.ts +++ b/packages/llm/llm-deepseek/src/adapter.ts @@ -60,7 +60,11 @@ export class DeepSeekAdapter extends LlmAdapt configured: endpoint => publication.configured(connection, endpoint), resolve: async (endpoint, signal) => { signal?.throwIfAborted() - return await this.dependencies.resolveAuth(connection, endpoint) + const auth = await this.dependencies.resolveAuth(connection, endpoint) + if (auth === undefined) return undefined + // The adapter's failure classification stays behind the seam. + const reject = auth.reject?.bind(auth) + return { headers: auth.headers, value: auth.value, ...reject === undefined ? {} : { reject } } }, } } diff --git a/packages/llm/llm-deepseek/src/types.ts b/packages/llm/llm-deepseek/src/types.ts index a9f50b20a6..60444fc85e 100644 --- a/packages/llm/llm-deepseek/src/types.ts +++ b/packages/llm/llm-deepseek/src/types.ts @@ -142,7 +142,10 @@ export interface DeepSeekAdapterOptions LlmError - /** Publish the route's credential through `routeCredential()`; omission publishes none. */ + /** + * Publish the route's credential through `routeCredential()`, whose `resolve` forwards the headers, value, and + * rejection of {@link resolveAuth} without its failure classification; omission publishes none. + */ credential?: DeepSeekRouteCredentialOptions /** Resolve the harness-home anonymous id shared with telemetry and feedback. */ resolveUserId: () => AnonymousUserId diff --git a/packages/llm/llm-deepseek/tests/route-credential.spec.ts b/packages/llm/llm-deepseek/tests/route-credential.spec.ts index 8176bc65aa..404927a098 100644 --- a/packages/llm/llm-deepseek/tests/route-credential.spec.ts +++ b/packages/llm/llm-deepseek/tests/route-credential.spec.ts @@ -52,26 +52,36 @@ it('publishes no credential for a provider that declares none', async () => { }) it('publishes the declared credential from one configuration generation and resolves it per endpoint', async () => { + const reject = vi.fn(() => Promise.resolve()) const resolveAuth = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string): Promise => - endpoint === ALLOWED ? { headers: { 'x-fixture': 'k' }, value: 'k' } : undefined) + endpoint === ALLOWED ? { headers: { 'x-fixture': 'k' }, value: 'k', reject, onRequestError: error => Promise.resolve(error) } : undefined) const configured = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string) => endpoint === ALLOWED) const ctx = await route({ resolveAuth, credential: { kind: 'api-key', reference: () => 'FIXTURE_KEY', configured } }) const credential = ctx.llm.routeCredential('fixture-route') expect(credential).toMatchObject({ kind: 'api-key', baseURL: BASE_URL, reference: 'FIXTURE_KEY' }) await expect(credential!.configured(ALLOWED)).resolves.toBe(true) await expect(credential!.configured(OTHER)).resolves.toBe(false) - await expect(credential!.resolve(ALLOWED)).resolves.toEqual({ headers: { 'x-fixture': 'k' }, value: 'k' }) + // The grant carries the seam's fields only; the adapter's failure classification stays behind it. + const grant = await credential!.resolve(ALLOWED) + expect(Object.keys(grant!)).toEqual(['headers', 'value', 'reject']) + expect(grant).toMatchObject({ headers: { 'x-fixture': 'k' }, value: 'k' }) + await grant!.reject!() + expect(reject).toHaveBeenCalledTimes(1) await expect(credential!.resolve(OTHER)).resolves.toBeUndefined() await expect(credential!.resolve(ALLOWED, AbortSignal.abort(new Error('caller left')))).rejects.toThrow('caller left') expect(resolveAuth).toHaveBeenCalledTimes(2) expect(configured.mock.calls.map(([{ baseURL }]) => baseURL)).toEqual([BASE_URL, BASE_URL]) }) -it('omits the reference of a credential kind without one', async () => { - const ctx = await route({ credential: { kind: 'account', configured: () => Promise.resolve(false) } }) +it('omits the reference of a credential kind without one and the rejection of a grant without one', async () => { + const ctx = await route({ + resolveAuth: () => Promise.resolve({ headers: { 'x-fixture': 'k' }, value: 'k' }), + credential: { kind: 'account', configured: () => Promise.resolve(false) }, + }) const credential = ctx.llm.routeCredential('fixture-route') expect(credential).toMatchObject({ kind: 'account', baseURL: BASE_URL }) expect(credential).not.toHaveProperty('reference') + await expect(credential!.resolve(ALLOWED)).resolves.toEqual({ headers: { 'x-fixture': 'k' }, value: 'k' }) }) it('fails a request without a credential before any network I/O, with the default diagnostic', async () => { diff --git a/packages/web/web-deepseek-api/src/index.ts b/packages/web/web-deepseek-api/src/index.ts index 0b610ce7ab..476dd51256 100644 --- a/packages/web/web-deepseek-api/src/index.ts +++ b/packages/web/web-deepseek-api/src/index.ts @@ -22,7 +22,7 @@ import type {} from '@deepseek-ai/dsh-agent' import { credentialRef, credentialRefConfigured, resolveCredentialRef, type CredentialRef } from '@deepseek-ai/dsh-credentials' import type {} from '@deepseek-ai/dsh-deepseek-account' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' -import { assertUsableApiKey, type RouteCredential } from '@deepseek-ai/dsh-llm' +import { assertUsableApiKey } from '@deepseek-ai/dsh-llm' import type { Session } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-web' import { DeepSeekFetchApiProvider } from './fetch.ts' @@ -258,13 +258,15 @@ function ruleSources(ctx: Context, capability: Capability, rule: Rule): DeepSeek * @param capability - the capability whose diagnostics a misconfigured source names. * @param provider - the route. * @returns the source; undefined when no mounted route publishes a credential as `provider`; a misconfigured source - * when the route's settings do not resolve. + * when the route's settings do not resolve or its published base URL does not parse. */ function routeSource(ctx: Context, capability: Capability, provider: RouteName): DeepSeekWebAuthSource | undefined { - let credential: RouteCredential | undefined - try { credential = ctx.get('llm')?.routeCredential(provider) } - catch (error: unknown) { return misconfigured(capability, provider, error) } - return credential === undefined ? undefined : { kind: 'route', baseURL: toolsBase(credential.baseURL), credential } + try { + const credential = ctx.get('llm')?.routeCredential(provider) + return credential === undefined ? undefined : { kind: 'route', baseURL: toolsBase(credential.baseURL), credential } + } catch (error: unknown) { + return misconfigured(capability, provider, error) + } } /** diff --git a/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts b/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts index abd6896b76..dfeda94d4c 100644 --- a/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts +++ b/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts @@ -687,6 +687,17 @@ describe('route credential failures', () => { await expect(failure).rejects.toThrow('that provider\'s settings do not resolve: route resolver unavailable. Search did not send') expect(sent()).toEqual([]) }) + + it('reports a route publishing an unparsable base URL as misconfigured, before readiness and without sending', async () => { + const { ctx, sent } = await mount({ + routes: [{ provider: 'deepseek-official', publishedBaseURL: 'not a url' }], environment: { DEEPSEEK_API_KEY: 'chat-key' }, + }) + expect(await ready(ctx, 'search', 'deepseek-official')).toBe(false) + const failure = operate(ctx, 'search', 'deepseek-official') + await expect(failure).rejects.toMatchObject({ code: 'WEB_PROVIDER_MISCONFIGURED' }) + await expect(failure).rejects.toThrow('that provider\'s settings do not resolve: Invalid URL. Search did not send') + expect(sent()).toEqual([]) + }) }) describe('billing settings', () => { diff --git a/packages/web/web-deepseek-api/tests/routes.ts b/packages/web/web-deepseek-api/tests/routes.ts index 4180bb486d..fff97df6c3 100644 --- a/packages/web/web-deepseek-api/tests/routes.ts +++ b/packages/web/web-deepseek-api/tests/routes.ts @@ -23,6 +23,8 @@ export interface RouteRow { withoutCredential?: boolean /** Value `routeCredential()` throws instead of publishing. */ throws?: unknown + /** Base URL published in place of the resolved one, as a route publishing an unparsable base would. */ + publishedBaseURL?: string } /** The credential `route` publishes, resolved from its config as the route plugin resolves it on each call. */ @@ -32,7 +34,7 @@ function credentialOf(ctx: Context, route: RouteRow): RouteCredential { const resolved = resolveAdapterOptions(plainOptions(OfficialConfig(route.config ?? {})), environment) const ref = resolved.apiKeyEnv return { - kind: 'api-key', baseURL: resolved.baseURL, reference: ref, + kind: 'api-key', baseURL: route.publishedBaseURL ?? resolved.baseURL, reference: ref, configured: () => credentialRefConfigured(ctx, ref), resolve: async () => { const key = await resolveCredentialRef(ctx, ref) @@ -42,7 +44,7 @@ function credentialOf(ctx: Context, route: RouteRow): RouteCredential { } const resolved = resolveAccountOptions(plainAccountOptions(AccountConfig(route.config ?? {})), environment) return { - kind: 'account', baseURL: resolved.protocol.baseURL, + kind: 'account', baseURL: route.publishedBaseURL ?? resolved.protocol.baseURL, configured: async endpoint => (await ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint)) !== undefined, resolve: endpoint => ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint) ?? Promise.resolve(undefined), } From ed6721f6dc0b573b7b38b85e245ef9ee9bbd5576 Mon Sep 17 00:00:00 2001 From: dsh-ci-bot Date: Thu, 12 Nov 2026 05:44:38 +0800 Subject: [PATCH 15/48] test(web): let the sampled fold transition settle before the next posture change assertFoldResize finishes the sampled grid-template-columns transition from the page side; CSS delivers the matching transitionend in a later rendering update. The sidebar-drawer e2e then changes the posture again. When that end event arrives after the new window is armed, AppFrame's settle handler drops data-animating and cancels the new transition, so the next assertFoldResize poll never sees a running transition (master CI runs 43002182954 and 43076752328 failed at apps/web/tests/sidebar-drawer.e2e.ts:500). Give the frame a rendering update and wait for data-animating to clear at the end of the helper, so the next step starts from a settled frame. --- apps/web/tests/sidebar-drawer.e2e.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/apps/web/tests/sidebar-drawer.e2e.ts b/apps/web/tests/sidebar-drawer.e2e.ts index 99b5c3fd43..b8768155bb 100644 --- a/apps/web/tests/sidebar-drawer.e2e.ts +++ b/apps/web/tests/sidebar-drawer.e2e.ts @@ -216,6 +216,28 @@ async function assertFoldResize(toggle: Locator, from: number, to: number): Prom expect(sample.middle.width).toBeGreaterThan(Math.min(from, to)) expect(sample.middle.width).toBeLessThan(Math.max(from, to)) expect(sample.middle.gap).toBeCloseTo(sample.start.gap, 1) + // The sample above finishes this track transition from the page side, and CSS + // delivers the matching transitionend in a later rendering update. Give it that + // update and wait for the frame to settle before the caller changes the layout + // again: an end event from this sample delivered after the next toggle would + // settle the new window, drop data-animating and cancel the transition the next + // assertFoldResize looks for. + await toggle.evaluate(() => new Promise((resolve) => { + let frames = 0 + const tick = () => { + frames += 1 + if (frames >= 2) resolve() + else requestAnimationFrame(tick) + } + requestAnimationFrame(tick) + // A hidden or throttled page may withhold animation frames; the settle poll below + // still covers that case through AppFrame's own 600ms fallback. + setTimeout(resolve, 2_000) + })) + await expect.poll( + () => toggle.evaluate(button => button.closest('[data-animating]') === null), + { timeout: 5_000 }, + ).toBe(true) } it('overlays the conversation and closes after navigation without losing its sidebar content', async () => { From 0f8d6ab12bb6cc80b8646f15d3dc727d21659c33 Mon Sep 17 00:00:00 2001 From: dsh-ci-bot Date: Thu, 12 Nov 2026 06:15:51 +0800 Subject: [PATCH 16/48] test(web): cancel the sampled fold transitions before the next posture change finish() only moves a transition to its end state; the matching transitionend is dispatched in a later rendering update. That end event arrived after the caller armed the next fold window, so AppFrame settled the new window, dropped data-animating and cancelled the transition the next assertFoldResize waits for. Awaiting two animation frames narrowed that window without closing it: AppFrame's own 600 ms fallback can settle and cancel the transition before the end event is dispatched, so the end event can still be pending when the helper returns. Cancel the sampled transitions instead. A cancelled transition dispatches transitioncancel, which AppFrame does not observe, so the helper leaves no end event pending. The frame then settles through AppFrame's 600 ms fallback, and the helper waits for data-animating to clear before it returns. The sampled start/middle/end values and the final grid are unchanged: cancelling drops the transition effect and the computed grid lands on the same target. --- apps/web/tests/sidebar-drawer.e2e.ts | 36 +++++++++++++--------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/apps/web/tests/sidebar-drawer.e2e.ts b/apps/web/tests/sidebar-drawer.e2e.ts index b8768155bb..4a5caf7249 100644 --- a/apps/web/tests/sidebar-drawer.e2e.ts +++ b/apps/web/tests/sidebar-drawer.e2e.ts @@ -184,7 +184,11 @@ async function assertMaskFade(frame: Locator, from: number, to: number): Promise }) } -/** Sample both width transitions on the same clock to detect detached sidebar controls. */ +/** + * Sample both width transitions on the same clock to detect detached sidebar controls. + * Returns only after this sample's transitions can no longer dispatch an end event, so + * the caller's next posture change starts from a window that no pending event settles. + */ async function assertFoldResize(toggle: Locator, from: number, to: number): Promise { await expect.poll(() => toggle.evaluate((button, target) => { const frame = button.closest('[data-animating]') @@ -208,7 +212,14 @@ async function assertFoldResize(toggle: Locator, from: number, to: number): Prom const start = at(0) const middle = at(0.5) const end = at(1) - for (const transition of transitions) transition.finish() + // Cancel instead of finish: a finished transition queues its transitionend for a + // later rendering update, and an end event arriving after the caller's next posture + // change settles the new window, drops data-animating and cancels the transition the + // next assertFoldResize looks for. A cancelled transition dispatches transitioncancel, + // which AppFrame does not observe, so this sample leaves no end event pending. Both + // values stay at the end state: cancelling drops the transition effect, and the + // computed grid lands on the same target the finished transition would show. + for (const transition of transitions) transition.cancel() frame.style.removeProperty('--ds-transition-duration-slow') return { endpoints: [start.width, end.width], start, middle } }) @@ -216,24 +227,9 @@ async function assertFoldResize(toggle: Locator, from: number, to: number): Prom expect(sample.middle.width).toBeGreaterThan(Math.min(from, to)) expect(sample.middle.width).toBeLessThan(Math.max(from, to)) expect(sample.middle.gap).toBeCloseTo(sample.start.gap, 1) - // The sample above finishes this track transition from the page side, and CSS - // delivers the matching transitionend in a later rendering update. Give it that - // update and wait for the frame to settle before the caller changes the layout - // again: an end event from this sample delivered after the next toggle would - // settle the new window, drop data-animating and cancel the transition the next - // assertFoldResize looks for. - await toggle.evaluate(() => new Promise((resolve) => { - let frames = 0 - const tick = () => { - frames += 1 - if (frames >= 2) resolve() - else requestAnimationFrame(tick) - } - requestAnimationFrame(tick) - // A hidden or throttled page may withhold animation frames; the settle poll below - // still covers that case through AppFrame's own 600ms fallback. - setTimeout(resolve, 2_000) - })) + // AppFrame removes data-animating either from a transitionend or from its own 600 ms + // fallback, which is the only remaining settle path once the transitions are cancelled. + // Wait for that settle so the caller's next posture change starts from a clear window. await expect.poll( () => toggle.evaluate(button => button.closest('[data-animating]') === null), { timeout: 5_000 }, From a6672fb5c35b7deb120eef82f075453ec6700fea Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 12 Nov 2026 12:55:16 +0800 Subject: [PATCH 17/48] fix(llm-deepseek-api-key): prefix key diagnostics with the settings namespace An unusable API key's INVALID_CREDENTIAL diagnostic was prefixed with the literal `llm-deepseek`, left from when the lookup lived in the transport package. It now names the mount's settings namespace, the same value the provider directory lists: the Loader entry id, or the plugin name without an entry. Product profiles mount the route as `llm-deepseek`, so their diagnostic text is unchanged. --- .../llm/llm-deepseek-api-key/README.i18n.yaml | 4 +-- packages/llm/llm-deepseek-api-key/README.md | 2 +- .../llm/llm-deepseek-api-key/README.zh.md | 2 +- .../llm/llm-deepseek-api-key/src/index.ts | 6 ++-- .../tests/discovery.spec.ts | 31 +++++++++++++++++-- packages/llm/llm/src/index.ts | 2 +- 6 files changed, 38 insertions(+), 9 deletions(-) diff --git a/packages/llm/llm-deepseek-api-key/README.i18n.yaml b/packages/llm/llm-deepseek-api-key/README.i18n.yaml index 68ac287b92..01dc753b77 100644 --- a/packages/llm/llm-deepseek-api-key/README.i18n.yaml +++ b/packages/llm/llm-deepseek-api-key/README.i18n.yaml @@ -15,8 +15,8 @@ en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 /deepseek-ai-dsh-llm-deepseek-api-key/use-this-package: - en: 77aeaaf77e17245f - zh: 5b621a9a4aeea7d9 + en: 78c395041b12b9cc + zh: 289f789926a0fe43 /deepseek-ai-dsh-llm-deepseek-api-key/understand-the-implementation: en: 2fe0f32c15603cd9 zh: 984ce05b82e8e679 diff --git a/packages/llm/llm-deepseek-api-key/README.md b/packages/llm/llm-deepseek-api-key/README.md index e646cb1ef2..c5eb1ebb19 100644 --- a/packages/llm/llm-deepseek-api-key/README.md +++ b/packages/llm/llm-deepseek-api-key/README.md @@ -25,7 +25,7 @@ Authentication resolution returns the validated API key in `x-api-key` for Messa ## Use this package -`apiKeyEnv` defaults to `DEEPSEEK_API_KEY` and resolves per request and model discovery. It reads the key through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md): when the credentials service exists, its precedence applies, and only compositions without that service read the launch environment directly. Requests with missing credentials fail with `MISSING_CREDENTIAL`; malformed credentials fail with `INVALID_CREDENTIAL`. Model discovery returns an empty catalog when the credential is missing, hiding the route from model selectors while retaining its settings entry. Malformed credentials and other lookup failures propagate. Adding or removing a key affects the next discovery call. +`apiKeyEnv` defaults to `DEEPSEEK_API_KEY` and resolves per request and model discovery. It reads the key through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md): when the credentials service exists, its precedence applies, and only compositions without that service read the launch environment directly. Requests with missing credentials fail with `MISSING_CREDENTIAL`; malformed credentials fail with `INVALID_CREDENTIAL`, whose diagnostic names this plugin's settings namespace and the credential reference. Model discovery returns an empty catalog when the credential is missing, hiding the route from model selectors while retaining its settings entry. Malformed credentials and other lookup failures propagate. Adding or removing a key affects the next discovery call. ```yaml - id: llm-deepseek diff --git a/packages/llm/llm-deepseek-api-key/README.zh.md b/packages/llm/llm-deepseek-api-key/README.zh.md index b26da9ab8b..317c75655b 100644 --- a/packages/llm/llm-deepseek-api-key/README.zh.md +++ b/packages/llm/llm-deepseek-api-key/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用此包 -`apiKeyEnv` 默认为 `DEEPSEEK_API_KEY`,在每次请求和模型发现时解析凭据。密钥通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数读取:已组合 credentials 服务时,按其优先级解析;只有未组合该服务时才直接读取启动环境。请求时凭据缺失以 `MISSING_CREDENTIAL` 失败;格式错误以 `INVALID_CREDENTIAL` 失败。模型发现在凭据缺失时返回空目录,在模型选择器中隐藏该路由,但保留其设置入口。凭据格式错误和其他读取失败继续上报。添加或删除密钥会影响下一次模型发现。 +`apiKeyEnv` 默认为 `DEEPSEEK_API_KEY`,在每次请求和模型发现时解析凭据。密钥通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数读取:已组合 credentials 服务时,按其优先级解析;只有未组合该服务时才直接读取启动环境。请求时凭据缺失以 `MISSING_CREDENTIAL` 失败;格式错误以 `INVALID_CREDENTIAL` 失败,其诊断点名本插件的设置命名空间与凭据引用。模型发现在凭据缺失时返回空目录,在模型选择器中隐藏该路由,但保留其设置入口。凭据格式错误和其他读取失败继续上报。添加或删除密钥会影响下一次模型发现。 ```yaml - id: llm-deepseek diff --git a/packages/llm/llm-deepseek-api-key/src/index.ts b/packages/llm/llm-deepseek-api-key/src/index.ts index 9fa4f2a996..e1e2f3cf35 100644 --- a/packages/llm/llm-deepseek-api-key/src/index.ts +++ b/packages/llm/llm-deepseek-api-key/src/index.ts @@ -32,12 +32,14 @@ interface OfficialConnection extends ResolvedDeepSeekOptions { } export function apply(ctx: Context, config: Config): void { + /** Settings namespace of this mount, which the provider directory lists and credential diagnostics name. */ + const settingsNs = ctx.fiber.entry?.options.id ?? name const options = () => resolveAdapterOptions(plainOptions(config), launchEnvironmentOf(ctx)) options() /** The validated API key, or `undefined` when none is configured; store and format failures propagate. */ const resolveApiKey = async (connection: ResolvedDeepSeekOptions): Promise => { const value = await resolveCredentialRef(ctx, connection.apiKeyEnv) - return value === undefined ? undefined : assertUsableApiKey(value, 'llm-deepseek', connection.apiKeyEnv) + return value === undefined ? undefined : assertUsableApiKey(value, settingsNs, connection.apiKeyEnv) } const resolveAuth = async (connection: ResolvedDeepSeekOptions): Promise => { const key = await resolveApiKey(connection) @@ -70,7 +72,7 @@ export function apply(ctx: Context, config: Config): void { return { ...connection, models: catalog.resolution, offered: catalog.offered, refusals: catalog.refusals, badges: catalog.badges } } ctx.llm.registerConfigurableProviders([ - { provider: PROVIDER, displayName: 'DeepSeek', settingsNs: ctx.fiber.entry?.options.id ?? name, settingsPath: [] }, + { provider: PROVIDER, displayName: 'DeepSeek', settingsNs, settingsPath: [] }, ]) registerDeepSeekProvider(ctx, PROVIDER, { providerName: 'DeepSeek', diff --git a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts index 528d332e2d..bde4d26873 100644 --- a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts +++ b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts @@ -32,13 +32,40 @@ it('advertises configured models with an API key', async () => { } }) -it('reports malformed credentials during discovery', async () => { +it('reports malformed credentials during discovery under the settings namespace the provider directory lists', async () => { vi.stubEnv('DEEPSEEK_API_KEY', 'invalid\nheader') const ctx = new Context() try { await ctx.plugin(LlmRuntime) await ctx.plugin(ApiKey, {}) - await expect(ctx.llm.listModels('deepseek-official')).rejects.toMatchObject({ code: 'INVALID_CREDENTIAL' }) + const [directory] = ctx.llm.listConfigurableProviders() + expect(directory?.settingsNs).toBe('llm-deepseek-api-key') + const failure = ctx.llm.listModels('deepseek-official') + await expect(failure).rejects.toMatchObject({ code: 'INVALID_CREDENTIAL' }) + await expect(failure).rejects.toThrow('llm-deepseek-api-key: the API key resolved from DEEPSEEK_API_KEY contains characters') + } finally { + await ctx.fiber.dispose() + vi.unstubAllEnvs() + } +}) + +it('names the Loader entry id in credential diagnostics, as product profiles mount the route', async () => { + vi.stubEnv('DEEPSEEK_API_KEY', 'invalid\nheader') + const ctx = new Context() + try { + await ctx.plugin(LlmRuntime) + await ctx.plugin({ + name: ApiKey.name, inject: ApiKey.inject, Config: ApiKey.Config, + apply: (inner: Context, config: ApiKey.Config) => { + // The Loader attaches the entry before a plugin applies; product profiles use the id `llm-deepseek`. + Object.defineProperty(inner.fiber, 'entry', { value: { options: { id: 'llm-deepseek' } } }) + ApiKey.apply(inner, config) + }, + }, {}) + expect(ctx.llm.listConfigurableProviders().map(entry => entry.settingsNs)).toEqual(['llm-deepseek']) + await expect(ctx.llm.listModels('deepseek-official')).rejects.toThrow( + 'llm-deepseek: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry', + ) } finally { await ctx.fiber.dispose() vi.unstubAllEnvs() diff --git a/packages/llm/llm/src/index.ts b/packages/llm/llm/src/index.ts index 113c698e0d..429db6b507 100644 --- a/packages/llm/llm/src/index.ts +++ b/packages/llm/llm/src/index.ts @@ -160,7 +160,7 @@ export class LlmError extends HarnessError { * module stays dependency-free; both adapters share this one diagnosis instead * of keeping near-identical local copies. * @param raw - the credential exactly as supplied. - * @param pkg - the refusing package name, prefixed to the diagnostic. + * @param pkg - the refusing plugin's settings namespace or package name, prefixed to the diagnostic. * @param ref - the credential reference the value resolved through. * @returns the trimmed, usable key. */ From 8607cf5b0e6bacaf62fe6c21ca37fc3795341be6 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 12 Nov 2026 13:20:13 +0800 Subject: [PATCH 18/48] fix(web): bind route account credentials to their origin and contain failed rejection - web-search-deepseek: the initiating route's account credential is used only when the search endpoint has the origin of that route's base URL. For another origin the provider does not ask the route and sends the API key, and readiness answers the same way. A route publishing an unparsable base URL is treated like settings that do not resolve. - web-deepseek-api, web-search-deepseek: after HTTP 401 a failure of the grant's reject() is contained, so the reported error stays the HTTP rejection whichever owner published the credential. --- ...-11-10-llm-route-credential-seam.i18n.yaml | 4 +- .../2026-11-10-llm-route-credential-seam.md | 2 +- ...2026-11-10-llm-route-credential-seam.zh.md | 2 +- .../web/web-deepseek-api/src/transport.ts | 5 +- .../web-deepseek-api/tests/transport.spec.ts | 8 ++- .../web/web-search-deepseek/README.i18n.yaml | 12 ++--- packages/web/web-search-deepseek/README.md | 10 ++-- packages/web/web-search-deepseek/README.zh.md | 10 ++-- packages/web/web-search-deepseek/src/index.ts | 30 +++++++---- .../web/web-search-deepseek/src/provider.ts | 6 ++- .../tests/deepseek.spec.ts | 54 ++++++++++++++----- 11 files changed, 91 insertions(+), 52 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index 6926949697..c528ae84df 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -9,8 +9,8 @@ en: 9665e1879893fe76 zh: 9da30ad0be6fc38d /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision: - en: 5819b658fc81482d - zh: 948e9cb0a668e623 + en: 8d28911b4a7aaca0 + zh: db511eb9dfdc5f5e /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered: en: 8177946a6bfa1a6d zh: f523f9057b4b47c5 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md index ba7c05d753..7ed0451345 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -18,7 +18,7 @@ The route plugins own credentials. `llm-deepseek-api-key` reads its key through `@deepseek-ai/dsh-deepseek-account` releases request credentials. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, the bare token, and a `reject()` that removes the grant while it still matches and contains storage failures; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The service inspects no Agents and depends on neither `dsh-agent` nor `dsh-llm`. The package lives in the `packages/account/` group under its unchanged name. -The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.routeCredential('deepseek-official')` and `routeCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account`, and the reference helpers otherwise. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. +The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.routeCredential('deepseek-official')` and `routeCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account` and the search endpoint has the origin of the route's base URL, and the reference helpers otherwise; it does not request an account credential published for another origin. Both web consumers contain a failed `reject()`, so the HTTP rejection stays the reported error for every credential kind. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index 9651ca13d6..e02353e078 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -18,7 +18,7 @@ Status: implemented `@deepseek-ai/dsh-deepseek-account` 释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、裸 token 和 `reject()`;`reject()` 仅在授权仍一致时删除它并隔离存储失败。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。该服务不检查任何 Agent,也不依赖 `dsh-agent` 或 `dsh-llm`。包以不变的名字位于 `packages/account/` 组。 -Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.routeCredential('deepseek-official')` 和 `routeCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类时使用其账号凭据,否则使用引用函数。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 +Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.routeCredential('deepseek-official')` 和 `routeCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类且搜索端点与该路由的基础地址同源时使用其账号凭据,否则使用引用函数;为其他 origin 发布的账号凭据不会被索取。两个 Web 消费方都会隔离失败的 `reject()`,因此对任何凭据种类,报告的都是 HTTP 拒绝。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 ## 考虑过的替代方案 diff --git a/packages/web/web-deepseek-api/src/transport.ts b/packages/web/web-deepseek-api/src/transport.ts index f8c841bb60..2508e2c714 100644 --- a/packages/web/web-deepseek-api/src/transport.ts +++ b/packages/web/web-deepseek-api/src/transport.ts @@ -161,7 +161,7 @@ interface SearchAuth { readonly endpoint: string /** Headers carrying the credential. */ readonly headers: Readonly> - /** Request-bound invalidation of the sent credential, present when its grant offers one. */ + /** Request-bound invalidation of the sent credential, present when its grant offers one; the dispatch contains its failure. */ readonly reject?: () => Promise } @@ -230,7 +230,8 @@ export async function dispatchDeepSeekWeb( if (status === 401) { // Invalidation can cancel this Session; finish reading the HTTP failure before it does. A cancelled read still // invalidates the credential the status rejected. - await auth.reject?.() + try { await auth.reject?.() } + catch (_invalidationFailed) { /* The HTTP rejection stays the reported failure when the invalidation itself fails. */ } // The account service released its credential only for its inference origin, so the endpoint is not what the // user must change. if (auth.kind === 'account') throw aborted ?? accountRejectedError(message) diff --git a/packages/web/web-deepseek-api/tests/transport.spec.ts b/packages/web/web-deepseek-api/tests/transport.spec.ts index c6620a9d13..3a082c938f 100644 --- a/packages/web/web-deepseek-api/tests/transport.spec.ts +++ b/packages/web/web-deepseek-api/tests/transport.spec.ts @@ -18,8 +18,8 @@ function keyRef(resolve: () => Promise, configured: () => Pr } /** * A route source on {@link ACCOUNT_BASE} whose account credential releases `resolveToken(endpoint)` as the token header; - * an empty token releases nothing. `rejectToken` observes each invalidated token, and its failures are contained as the - * account service contains them. + * an empty token releases nothing. `rejectToken` observes each invalidated token, and its failure rejects the grant's + * invalidation, as an owner that does not contain its storage failures does. */ function accountSource( resolveToken: (endpoint: string) => Promise, rejectToken: (token: string) => Promise = async () => {}, @@ -27,9 +27,7 @@ function accountSource( const grant = async (endpoint: string) => { const token = await resolveToken(endpoint) if (token === undefined || token.length === 0) return undefined - return { headers: { 'x-dsh-auth-token': token }, value: token, reject: async () => { - try { await rejectToken(token) } catch (_storageFailure) { /* Contained as the account service contains it. */ } - } } + return { headers: { 'x-dsh-auth-token': token }, value: token, reject: () => rejectToken(token) } } return { kind: 'route', baseURL: ACCOUNT_BASE, credential: { kind: 'account', configured: async endpoint => (await grant(endpoint)) !== undefined, resolve: grant, diff --git a/packages/web/web-search-deepseek/README.i18n.yaml b/packages/web/web-search-deepseek/README.i18n.yaml index d83724b59e..d25d04cf27 100644 --- a/packages/web/web-search-deepseek/README.i18n.yaml +++ b/packages/web/web-search-deepseek/README.i18n.yaml @@ -24,8 +24,8 @@ en: 3ed88edabdf63c8d zh: c66176c8a7c9a434 /deepseek-ai-dsh-web-search-deepseek/use-this-package/authentication: - en: 7e625c9a31ecad31 - zh: 19088d0014d51b24 + en: b9d2e372face46f1 + zh: cc8e5820d6aada38 /deepseek-ai-dsh-web-search-deepseek/use-this-package/what-a-search-returns: en: e30442c90365357b zh: 9c9e2f1182963a8a @@ -39,14 +39,14 @@ en: 9842c69ad3636bb3 zh: 3cdc3f816cbdd0cb /deepseek-ai-dsh-web-search-deepseek/understand-the-implementation/design-philosophy: - en: 76d5fb7c1e00079c - zh: 6f0e835157a3c982 + en: 9ebf133e28acbd3a + zh: 440399ab6a4f5540 /deepseek-ai-dsh-web-search-deepseek/understand-the-implementation/source-map: en: 6488e1c85646339f zh: 2b5ca1c6b5939a8c /deepseek-ai-dsh-web-search-deepseek/understand-the-implementation/request-flow: - en: a45785f95dbde10a - zh: 399bd28592d34721 + en: ec407206b9f6371d + zh: a94d1e864102342b /deepseek-ai-dsh-web-search-deepseek/further-exploration: en: 3a650478cf33d792 zh: ab4247c4c31f4a90 diff --git a/packages/web/web-search-deepseek/README.md b/packages/web/web-search-deepseek/README.md index 230f4cc63e..91411478f7 100644 --- a/packages/web/web-search-deepseek/README.md +++ b/packages/web/web-search-deepseek/README.md @@ -58,9 +58,9 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a ### Authentication -A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names a model route that publishes an account credential through `ctx.llm.routeCredential`, the `deepseek-account` route, and that credential resolves for the search endpoint. The account service releases one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only the credential's headers, `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the credential that search sent through the credential's own invalidation: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. +A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names a model route that publishes an account credential through `ctx.llm.routeCredential`, the `deepseek-account` route, the search endpoint has the origin of that route's base URL, and that credential resolves for the search endpoint. The provider asks a route for its credential only at that origin, so an account credential published for another deployment is never sent to the search endpoint. The account service releases one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only the credential's headers, `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the credential that search sent through the credential's own invalidation: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. -The provider's `ready()` answers whether the search a model request would make has a credential, on any model route: the request's route publishes an account credential that reports itself configured for the configured search endpoint, or a literal `apiKey` is set or `ctx.credentials.describe` reports the `apiKeyEnv` reference configured (without that service, the process environment must carry it). It checks them in the order a search resolves them, and a route whose settings do not resolve or a failed account-credential or credential-store read answers false, because the search fails there instead of trying the next credential. While this provider is the selected search provider, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and its prompt guidance from each request for which it answers false. Only presence is checked: a wrong key, or an endpoint that does not serve the native `web_search_20250305` server tool, counts as ready and fails each call. A call that still arrives resolves credentials when it runs. +The provider's `ready()` answers whether the search a model request would make has a credential, on any model route: the request's route publishes an account credential for the origin of the configured search endpoint that reports itself configured for that endpoint, or a literal `apiKey` is set or `ctx.credentials.describe` reports the `apiKeyEnv` reference configured (without that service, the process environment must carry it). It checks them in the order a search resolves them, and a route whose settings do not resolve or whose published base URL does not parse, or a failed account-credential or credential-store read, answers false, because the search fails there instead of trying the next credential. While this provider is the selected search provider, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and its prompt guidance from each request for which it answers false. Only presence is checked: a wrong key, or an endpoint that does not serve the native `web_search_20250305` server tool, counts as ready and fails each call. A call that still arrives resolves credentials when it runs. Referenced keys go through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md) and receive the same whitespace normalization and format validation as model requests. A malformed referenced key fails before dispatch; readiness remains a presence-only check. @@ -91,7 +91,7 @@ This section explains the design decisions behind the provider; the observable b The provider is built on two commitments: - **Structured blocks only.** DeepSeek runs the search server-side and returns structured `web_search_tool_result` blocks; the provider parses those blocks and never scrapes URLs out of model prose. In strict mode, a response with no such block throws `WEB_PROVIDER_ERROR` instead of degrading. -- **Conversation credentials, resolved per search.** The provider adds no secret: a search from a Session on a route that publishes an account credential uses that credential, and every other search reuses the `DEEPSEEK_API_KEY` reference. The auxiliary request endpoint stays independent through `$DEEPSEEK_SEARCH_BASE_URL`. A mounted credentials service is authoritative; without one the provider falls back to the launching process environment. Resolving per call means a key stored or rotated in the Web Models page, or an account sign-in, reaches the next search without a restart. +- **Conversation credentials, resolved per search.** The provider adds no secret: a search from a Session on a route that publishes an account credential for the search endpoint's origin uses that credential, and every other search reuses the `DEEPSEEK_API_KEY` reference. The auxiliary request endpoint stays independent through `$DEEPSEEK_SEARCH_BASE_URL`. A mounted credentials service is authoritative; without one the provider falls back to the launching process environment. Resolving per call means a key stored or rotated in the Web Models page, or an account sign-in, reaches the next search without a restart. ### Source map @@ -103,9 +103,9 @@ The provider is built on two commitments: ### Request flow -Each search captures the current Config values into provider options — endpoint, model, key reference, limits — then asks the initiating Session's model route for its account credential through `ctx.llm.routeCredential` when it publishes one, otherwise resolves the credential reference through `ctx.credentials` (or the environment), appends the log-only session event, and dispatches the Messages request with the native `web_search` server tool. The response's `web_search_tool_result` blocks become `sources[]`; `cited_text` entries from text blocks are joined to their URLs as snippets; results are deduplicated by URL; and the service enforces the requested source bound on the way back. +Each search captures the current Config values into provider options — endpoint, model, key reference, limits — then asks the initiating Session's model route for its account credential through `ctx.llm.routeCredential` when it publishes one for the search endpoint's origin, otherwise resolves the credential reference through `ctx.credentials` (or the environment), appends the log-only session event, and dispatches the Messages request with the native `web_search` server tool. The response's `web_search_tool_result` blocks become `sources[]`; `cited_text` entries from text blocks are joined to their URLs as snippets; results are deduplicated by URL; and the service enforces the requested source bound on the way back. -Readiness captures the same options but reads no API key value: on a route publishing an account credential it first asks that credential whether it is configured for the search endpoint, then checks the literal key or asks `ctx.credentials.describe()` (or the environment) whether the key reference is configured. +Readiness captures the same options but reads no API key value: on a route publishing an account credential for the search endpoint's origin it first asks that credential whether it is configured for the search endpoint, then checks the literal key or asks `ctx.credentials.describe()` (or the environment) whether the key reference is configured.
diff --git a/packages/web/web-search-deepseek/README.zh.md b/packages/web/web-search-deepseek/README.zh.md index a55dc76495..c4908267e8 100644 --- a/packages/web/web-search-deepseek/README.zh.md +++ b/packages/web/web-search-deepseek/README.zh.md @@ -58,9 +58,9 @@ kind: "package-reference" ### 鉴权 -当发起会话最近的 `request/context` 事件指明的模型路由通过 `ctx.llm.routeCredential` 发布账号凭据(即 `deepseek-account` 路由),且该凭据为搜索端点解析成功时,搜索使用 DeepSeek 账号鉴权。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)释放凭据。这类搜索只发送该凭据的请求头 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并通过凭据自身的失效操作只作废该搜索实际发送的凭据:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。 +当发起会话最近的 `request/context` 事件指明的模型路由通过 `ctx.llm.routeCredential` 发布账号凭据(即 `deepseek-account` 路由),搜索端点与该路由的基础地址同源,且该凭据为搜索端点解析成功时,搜索使用 DeepSeek 账号鉴权。提供方只在同源时向路由索取凭据,因此为其他部署发布的账号凭据不会发往搜索端点。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)释放凭据。这类搜索只发送该凭据的请求头 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并通过凭据自身的失效操作只作废该搜索实际发送的凭据:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。 -提供方的 `ready()` 回答模型请求将发起的搜索是否有凭据,不论模型路由:该请求的路由发布的账号凭据报告自身已为配置的搜索端点配置,或者设置了字面 `apiKey`,或 `ctx.credentials.describe` 报告 `apiKeyEnv` 引用已配置(没有该服务时,进程环境中必须存在该变量)。它按搜索解析凭据的顺序检查;路由设置无法解析,或读取账号凭据或凭据存储失败时回答 false,因为搜索会在那里失败,而不会尝试下一种凭据。本提供方是选中的搜索提供方时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它回答 false 的每个请求中撤下 `web_search` 及其提示词说明。这里只检查凭据是否存在:错误的密钥,或不提供原生 `web_search_20250305` 服务器工具的端点,都视为就绪并使每次调用失败。仍然到达的调用会在运行时解析凭据。 +提供方的 `ready()` 回答模型请求将发起的搜索是否有凭据,不论模型路由:该请求的路由为配置的搜索端点所在 origin 发布了账号凭据且该凭据报告自身已为该端点配置,或者设置了字面 `apiKey`,或 `ctx.credentials.describe` 报告 `apiKeyEnv` 引用已配置(没有该服务时,进程环境中必须存在该变量)。它按搜索解析凭据的顺序检查;路由设置无法解析或其发布的基础地址无法解析,或读取账号凭据或凭据存储失败时回答 false,因为搜索会在那里失败,而不会尝试下一种凭据。本提供方是选中的搜索提供方时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它回答 false 的每个请求中撤下 `web_search` 及其提示词说明。这里只检查凭据是否存在:错误的密钥,或不提供原生 `web_search_20250305` 服务器工具的端点,都视为就绪并使每次调用失败。仍然到达的调用会在运行时解析凭据。 引用密钥通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数读取,接受与模型请求相同的首尾空白规范化和格式校验。引用密钥格式错误会在发送请求前失败;就绪判断仍只检查是否存在。 @@ -91,7 +91,7 @@ kind: "package-reference" 本提供方建立在两项承诺之上: - **只取结构化块。** DeepSeek 在服务端执行搜索并返回结构化的 `web_search_tool_result` 块;提供方解析这些块,绝不从模型文本中抓取 URL。严格模式下,没有此类块的响应会抛出 `WEB_PROVIDER_ERROR`,而非降级。 -- **会话凭据,逐次解析。** 提供方不新增密钥:来自发布账号凭据的路由会话的搜索使用该凭据,其余搜索复用 `DEEPSEEK_API_KEY` 引用。辅助请求端点通过 `$DEEPSEEK_SEARCH_BASE_URL` 保持独立。已挂载的凭据服务具有权威性;没有该服务时回退到启动进程的环境。按次解析意味着在 Web 的 Models 页中存储或轮换的密钥,或一次账号登录,无需重启即可用于下一次搜索。 +- **会话凭据,逐次解析。** 提供方不新增密钥:发起会话的路由为搜索端点所在 origin 发布账号凭据时,搜索使用该凭据,其余搜索复用 `DEEPSEEK_API_KEY` 引用。辅助请求端点通过 `$DEEPSEEK_SEARCH_BASE_URL` 保持独立。已挂载的凭据服务具有权威性;没有该服务时回退到启动进程的环境。按次解析意味着在 Web 的 Models 页中存储或轮换的密钥,或一次账号登录,无需重启即可用于下一次搜索。 ### 源码地图 @@ -103,9 +103,9 @@ kind: "package-reference" ### 请求流程 -每次搜索先把当前 Config 段投影为提供方选项——端点、模型、密钥引用、上限——然后在发起会话的模型路由通过 `ctx.llm.routeCredential` 发布账号凭据时向其索取该凭据,否则通过 `ctx.credentials`(或环境)解析凭据引用,追加仅用于日志的会话事件,并以原生 `web_search` 服务器工具分发 Messages 请求。响应中的 `web_search_tool_result` 块变为 `sources[]`;文本块中的 `cited_text` 条目按其 URL 拼接为 snippet;结果按 URL 去重;服务在返回路径上强制执行请求的来源上限。 +每次搜索先把当前 Config 段投影为提供方选项——端点、模型、密钥引用、上限——然后在发起会话的模型路由通过 `ctx.llm.routeCredential` 为搜索端点所在 origin 发布账号凭据时向其索取该凭据,否则通过 `ctx.credentials`(或环境)解析凭据引用,追加仅用于日志的会话事件,并以原生 `web_search` 服务器工具分发 Messages 请求。响应中的 `web_search_tool_result` 块变为 `sources[]`;文本块中的 `cited_text` 条目按其 URL 拼接为 snippet;结果按 URL 去重;服务在返回路径上强制执行请求的来源上限。 -就绪判断捕获相同的选项,但不读取 API 密钥的值:发布账号凭据的路由先询问该凭据是否已为搜索端点配置,再检查字面密钥,或询问 `ctx.credentials.describe()`(或环境)密钥引用是否已配置。 +就绪判断捕获相同的选项,但不读取 API 密钥的值:路由为搜索端点所在 origin 发布账号凭据时,先询问该凭据是否已为搜索端点配置,再检查字面密钥,或询问 `ctx.credentials.describe()`(或环境)密钥引用是否已配置。
diff --git a/packages/web/web-search-deepseek/src/index.ts b/packages/web/web-search-deepseek/src/index.ts index da16c7c2a6..40934c78bc 100644 --- a/packages/web/web-search-deepseek/src/index.ts +++ b/packages/web/web-search-deepseek/src/index.ts @@ -2,7 +2,8 @@ * Register a DeepSeek-backed provider in `ctx.web`. It calls the Anthropic-compatible Messages API * with native `web_search_20250305`. A search initiated by a Session whose latest model request used * a route that publishes an account credential through `ctx.llm.routeCredential()` authenticates with - * that credential when its owner allows the search endpoint; every other search reuses + * that credential when the search endpoint has the origin of that route's base URL and the + * credential's owner allows the endpoint; every other search reuses * `DEEPSEEK_API_KEY`. The provider does not reuse `DEEPSEEK_BASE_URL`; auxiliary search has its own * endpoint configuration. The provider reports itself not ready for a model request whose search * would have no credential. @@ -93,15 +94,19 @@ export const WEB_SEARCH_DEEPSEEK_SETTINGS_NAMESPACE = 'web-search-deepseek' type SearchOptions = DeepSeekSearchProviderOptions & { readonly apiKeyEnv: CredentialRef } /** - * The account credential the model route `route` publishes, when it publishes one of that kind. + * The account credential the model route `route` publishes for the deployment that serves `endpoint`. A route's + * account credential is sent only to the origin of that route's base URL, whatever destinations its owner would + * release it for. * @param ctx - plugin context supplying the optional model service. * @param route - provider route of a model request; undefined names none. - * @returns the route's account credential, or undefined for another kind, no credential, or no route. - * @throws when the route's settings do not resolve. + * @param endpoint - absolute URL the search dispatches to. + * @returns the route's account credential, or undefined for another kind, another origin, no credential, or no route. + * @throws when the route's settings do not resolve, or its published base URL or `endpoint` does not parse. */ -function accountCredentialOf(ctx: Context, route: string | undefined): RouteCredential | undefined { +function accountCredentialOf(ctx: Context, route: string | undefined, endpoint: string): RouteCredential | undefined { const credential = route === undefined ? undefined : ctx.get('llm')?.routeCredential(route) - return credential?.kind === 'account' ? credential : undefined + if (credential?.kind !== 'account') return undefined + return new URL(credential.baseURL).origin === new URL(endpoint).origin ? credential : undefined } /** @@ -124,7 +129,8 @@ function resolveOptions( resolveAccountCredential: async (endpoint) => { // The latest request context names the route that served the model // request which called this search, as account sign-out reads it. - const credential = accountCredentialOf(ctx, ctx.get('agents')?.currentInitiator()?.session.requestContext()?.provider) + const route = ctx.get('agents')?.currentInitiator()?.session.requestContext()?.provider + const credential = accountCredentialOf(ctx, route, endpoint) return credential === undefined ? undefined : await credential.resolve(endpoint) }, resolveApiKey: async () => { @@ -150,8 +156,9 @@ function resolveOptions( /** * Whether the search a model request on `route` would make has a credential, checked in the order - * the search resolves them: the account credential the route publishes first, then the API key. A - * route whose settings do not resolve or a failed read answers false, because the search fails there + * the search resolves them: the account credential the route publishes for the origin of the search + * endpoint first, then the API key. A route whose settings do not resolve or whose published base URL + * does not parse, or a failed read, answers false, because the search fails there * instead of trying the next credential. Only presence is checked: the API key's value is not read * and the endpoint is not contacted, so a wrong key or an endpoint without native search still * counts as configured. @@ -163,11 +170,12 @@ function resolveOptions( async function searchConfigured( ctx: Context, options: SearchOptions, route: string | undefined, ): Promise { + const endpoint = `${options.baseURL}/messages` let account: RouteCredential | undefined - try { account = accountCredentialOf(ctx, route) } + try { account = accountCredentialOf(ctx, route, endpoint) } catch (_unresolvedRoute) { return false /* The search fails on this route before it reads any credential. */ } if (account !== undefined) { - try { if (await account.configured(`${options.baseURL}/messages`)) return true } + try { if (await account.configured(endpoint)) return true } catch (_unreadableGrant) { return false /* The search fails on this read before it tries the API key. */ } } if (options.apiKey !== undefined) return true diff --git a/packages/web/web-search-deepseek/src/provider.ts b/packages/web/web-search-deepseek/src/provider.ts index ccc14b9f3d..5472a8f2b9 100644 --- a/packages/web/web-search-deepseek/src/provider.ts +++ b/packages/web/web-search-deepseek/src/provider.ts @@ -96,7 +96,8 @@ export interface DeepSeekSearchProviderOptions { /** * Resolve the DeepSeek account credential for one search endpoint. A credential takes * precedence over every API key and is sent only through the headers of its grant, which - * also invalidates it after HTTP 401; `undefined` selects API-key authentication. + * also invalidates it after HTTP 401; a failure of that invalidation is contained, and the + * search reports the HTTP rejection. `undefined` selects API-key authentication. */ resolveAccountCredential?: (endpoint: string) => Promise /** Literal DeepSeek API key; when present it wins over {@link resolveApiKey}. */ @@ -301,7 +302,8 @@ export class DeepSeekSearchProvider implements WebSearchProvider { if (status === 401 && auth.kind === 'account') { // Invalidation can cancel this Session; finish reading the HTTP failure before it does. A cancelled read // still invalidates the credential the status rejected. - await auth.reject?.() + try { await auth.reject?.() } + catch (_invalidationFailed) { /* The HTTP rejection stays the reported failure when the invalidation itself fails. */ } throw aborted ?? accountRejectedError(message) } if (aborted !== undefined) throw aborted diff --git a/packages/web/web-search-deepseek/tests/deepseek.spec.ts b/packages/web/web-search-deepseek/tests/deepseek.spec.ts index a1feb29aba..9ecd5ee4b9 100644 --- a/packages/web/web-search-deepseek/tests/deepseek.spec.ts +++ b/packages/web/web-search-deepseek/tests/deepseek.spec.ts @@ -12,7 +12,7 @@ import LocalCredentialProvider from '@deepseek-ai/dsh-credentials-local' import { createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY } from '@deepseek-ai/dsh-launch-environment' import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' import LlmRuntime from '@deepseek-ai/dsh-llm' -import type { RouteCredentialGrant } from '@deepseek-ai/dsh-llm' +import type { RouteCredential, RouteCredentialGrant } from '@deepseek-ai/dsh-llm' import * as AccountRoute from '@deepseek-ai/dsh-llm-deepseek-account' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import WebRuntime, { WebError, type WebSearchResult } from '@deepseek-ai/dsh-web' @@ -33,7 +33,7 @@ const searchProvider = (options: DeepSeekSearchProviderOptions): DeepSeekSearchP /** * The account credential resolver a route publishes over `token`, with `reject` observing each invalidated token; - * a throwing observer is contained as the account service contains storage failures. + * a throwing observer rejects the grant's invalidation, as an owner that does not contain its storage failures does. */ function accountCredential( token: (endpoint: string) => Promise, reject?: (token: string) => Promise, @@ -41,9 +41,7 @@ function accountCredential( return async (endpoint) => { const value = await token(endpoint) if (value === undefined || value.length === 0) return undefined - return { headers: { 'x-dsh-auth-token': value }, value, ...reject === undefined ? {} : { reject: async () => { - try { await reject(value) } catch (_storageFailure) { /* Contained as the account service contains it. */ } - } } } + return { headers: { 'x-dsh-auth-token': value }, value, ...reject === undefined ? {} : { reject: () => reject(value) } } } } @@ -58,6 +56,12 @@ async function rejectedWebError(operation: Promise): Promise throw new Error('expected search operation to reject') } +/** + * Base URL of the account route the composed suites mount, set in the route's config so that a `DEEPSEEK_BASE_URL` in + * the environment running them cannot move the route off the origin of the default search endpoint. + */ +const ACCOUNT_ROUTE_BASE = 'https://api.deepseek.com/anthropic' + const options = { apiKey: 'ds-key', baseURL: 'https://api.deepseek.test/anthropic/v1', @@ -772,9 +776,12 @@ describe('web-search-deepseek account route selection', () => { * initiator whose latest request context names `provider`. * @param provider - route recorded by the initiating Session's request context; undefined runs the * search without an initiator while a Session on the account route exists. + * @param routeBaseURL - base URL of the mounted account route, whose origin its credential is published for. * @returns the headers the search sent and the URLs the account was asked about. */ - async function searchAs(provider: string | undefined): Promise<{ headers: Record; asked: string[] }> { + async function searchAs( + provider: string | undefined, routeBaseURL = ACCOUNT_ROUTE_BASE, + ): Promise<{ headers: Record; asked: string[] }> { const fetchMock = vi.fn(async (_input: string, _init?: RequestInit) => jsonResponse(searchResponse())) vi.stubGlobal('fetch', fetchMock) const asked: string[] = [] @@ -785,7 +792,7 @@ describe('web-search-deepseek account route selection', () => { await ctx.plugin(AgentRegistry) await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) await ctx.plugin(LlmRuntime) - await ctx.plugin(AccountRoute, {}) + await ctx.plugin(AccountRoute, { baseURL: routeBaseURL }) ctx.provide('deepseekAccount', accountStub({ token: (url) => { asked.push(url); return 'account-token' } })) await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' }) const session = ctx.sessions.create(SessionId(`web-search-account-${provider ?? 'none'}`)) @@ -808,6 +815,14 @@ describe('web-search-deepseek account route selection', () => { expect(headers).not.toHaveProperty('x-api-key') }) + it('sends the API key when the account route publishes its credential for another origin, without asking the account', async () => { + // The stand-in account releases its token for every destination, so only the origin comparison withholds it. + const { headers, asked } = await searchAs('deepseek-account', 'https://other-deployment.test/anthropic') + expect(asked).toEqual([]) + expect(headers['x-api-key']).toBe('ds-key') + expect(headers).not.toHaveProperty('x-dsh-auth-token') + }) + it('keeps a sign-in that replaced the sent token before its late 401', async () => { let current = 'old-token' const rejectToken = vi.fn(async (token: string) => { if (token === current) current = '' }) @@ -822,7 +837,7 @@ describe('web-search-deepseek account route selection', () => { await ctx.plugin(AgentRegistry) await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) await ctx.plugin(LlmRuntime) - await ctx.plugin(AccountRoute, {}) + await ctx.plugin(AccountRoute, { baseURL: ACCOUNT_ROUTE_BASE }) ctx.provide('deepseekAccount', accountStub({ token: () => current, reject: rejectToken })) await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' }) const session = ctx.sessions.create(SessionId('web-search-account-late-401')) @@ -890,7 +905,7 @@ describe('web-search-deepseek search readiness', () => { mounted.push(ctx) await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) await ctx.plugin(LlmRuntime) - await ctx.plugin(AccountRoute, {}) + await ctx.plugin(AccountRoute, { baseURL: ACCOUNT_ROUTE_BASE }) if (setup.credentialsDir !== undefined) { await ctx.plugin(LocalCredentialProvider, { path: join(setup.credentialsDir, '.credentials.yaml'), watch: false }) } @@ -942,6 +957,15 @@ describe('web-search-deepseek search readiness', () => { expect(asked).toEqual([]) }) + it('does not ask the account about a search endpoint at another origin than the account route\'s base URL', async () => { + const asked: string[] = [] + // The stand-in account releases its token for every destination, so only the origin comparison withholds it. + const account = accountStub({ token: (url) => { asked.push(url); return 'account-token' } }) + const ctx = await compose({ config: { baseURL: 'https://gateway.test/anthropic/v1' }, account }) + expect(await ctx.web.searchReady('deepseek-account')).toBe(false) + expect(asked).toEqual([]) + }) + it.each<[string, Setup]>([ ['a search endpoint outside the account origin', { config: { baseURL: 'https://gateway.test/anthropic/v1' }, account: officialOriginAccount() }], ['a signed-out account', { account: accountStub({ token: () => undefined }) }], @@ -988,13 +1012,19 @@ describe('web-search-deepseek search readiness', () => { } }) - it('is not ready and fails the search when the initiating route\'s settings do not resolve, despite a literal key', async () => { + it.each<[string, () => RouteCredential, string]>([ + ['settings do not resolve', () => { throw new Error('route settings do not resolve') }, 'route settings do not resolve'], + ['published base URL does not parse', () => ({ + kind: 'account', baseURL: 'not a url', configured: () => Promise.resolve(true), + resolve: () => Promise.resolve({ headers: { 'x-dsh-auth-token': 'account-token' }, value: 'account-token' }), + }), 'Invalid URL'], + ])('is not ready and fails the search when the initiating route\'s %s, despite a literal key', async (_fault, routeCredential, diagnostic) => { const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init: RequestInit = {}) => jsonResponse(searchResponse())) vi.stubGlobal('fetch', fetchMock) const ctx = new Context() mounted.push(ctx) await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) - ctx.provide('llm', { routeCredential: () => { throw new Error('route settings do not resolve') } } as never) + ctx.provide('llm', { routeCredential } as never) await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' }) expect(await ctx.web.searchReady('deepseek-account')).toBe(false) expect(await ctx.web.searchReady(undefined)).toBe(true) @@ -1006,7 +1036,7 @@ describe('web-search-deepseek search readiness', () => { session.append('request/context', { provider: 'deepseek-account', model: 'deepseek-v4-flash' }) const failure = await rejectedWebError(ctx.agents.withInitiator({ session } as Agent, () => ctx.web.search({ query: 'q' }))) expect(failure.code).toBe('WEB_PROVIDER_ERROR') - expect(failure.message).toContain('route settings do not resolve') + expect(failure.message).toContain(diagnostic) expect(fetchMock).not.toHaveBeenCalled() }) From eb30025883580d33bc1e1dc3a6452ea8ec6d1fd8 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 12 Nov 2026 13:24:25 +0800 Subject: [PATCH 19/48] docs(web-search-deepseek): keep the module comment at its line count The config catalog records the source line of the plugin's Config. The previous commit grew the module comment by one line, which moved that line and left the generated catalog stale; reflowing the comment keeps the catalog as committed. --- packages/web/web-search-deepseek/src/index.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/web/web-search-deepseek/src/index.ts b/packages/web/web-search-deepseek/src/index.ts index 40934c78bc..006749c9d9 100644 --- a/packages/web/web-search-deepseek/src/index.ts +++ b/packages/web/web-search-deepseek/src/index.ts @@ -3,10 +3,9 @@ * with native `web_search_20250305`. A search initiated by a Session whose latest model request used * a route that publishes an account credential through `ctx.llm.routeCredential()` authenticates with * that credential when the search endpoint has the origin of that route's base URL and the - * credential's owner allows the endpoint; every other search reuses - * `DEEPSEEK_API_KEY`. The provider does not reuse `DEEPSEEK_BASE_URL`; auxiliary search has its own - * endpoint configuration. The provider reports itself not ready for a model request whose search - * would have no credential. + * credential's owner allows the endpoint; every other search reuses `DEEPSEEK_API_KEY`. The provider + * does not reuse `DEEPSEEK_BASE_URL`; auxiliary search has its own endpoint configuration. The + * provider reports itself not ready for a model request whose search would have no credential. * @module @deepseek-ai/dsh-web-search-deepseek */ import type { Volatile } from '@deepseek-ai/cordis' From 98003bd816581f0b3a4cef077f17ecfe0164bec8 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 12 Nov 2026 14:18:17 +0800 Subject: [PATCH 20/48] test(headless): expect the keyless mount's namespace in key diagnostics The invalid-credential scenario mounts the API-key route as entry `llm-deepseek-keyless`. Since fb007f605d4 the INVALID_CREDENTIAL diagnostic of an unusable key names the settings namespace of the mount instead of the fixed `llm-deepseek`, so the expected stream names `llm-deepseek-keyless` in its two failure records. The file is refreshed through the test's own DSH_SNAPSHOT=refresh mode; nothing else in it changes. --- .../expected/invalid-credential/stream-json.expected.jsonl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl index 9f15c8c621..235e8e695e 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl @@ -9,7 +9,7 @@ {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/context","seq":11,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":1000000}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title","seq":12,"time":0,"data":{"title":"say pong","messageSeqs":[8],"source":{"kind":"fallback"}}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title-llm-request","seq":13,"time":0,"data":{"titleProvider":"session-title-first-prompt-llm","messageSeqs":[8],"route":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"Create a concise title for an AI coding-assistant session from the supplied human messages.\nReturn only the title on one line, **in plain text of natural language**, with no quotes, prefix, explanation, Markdown, XML, or terminal control codes. No code is allowed.\nUse the language of the messages.\nAim for about 5 words in non-CJK languages or 10 CJK characters.\nIf the messages give little to name, still return a short best-effort title, such as Greeting, instead of explaining.","messages":[{"content":[{"type":"text","text":"Generate the session title from this JSON array of human messages:\n[{\"seq\":8,\"text\":\"say pong\"}]"}],"source":{"kind":"dsh-session-title-llm"},"role":"user","id":"{{sessionId}}"}],"maxTokens":4096,"reasoningEffort":"off"}}} -{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/attempt","seq":14,"time":0,"data":{"turn":1,"step":1,"stream":[{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"error","failure":{"message":"llm-deepseek: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry; set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)","code":"INVALID_CREDENTIAL"}}}}]}}} +{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/attempt","seq":14,"time":0,"data":{"turn":1,"step":1,"stream":[{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"error","failure":{"message":"llm-deepseek-keyless: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry; set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)","code":"INVALID_CREDENTIAL"}}}}]}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/end","seq":15,"time":0,"data":{"turn":1,"step":1}}} -{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/end","seq":16,"time":0,"data":{"turn":1,"reason":{"kind":"error","error":{"message":"llm-deepseek: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry; set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)","code":"INVALID_CREDENTIAL"}}}}} +{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/end","seq":16,"time":0,"data":{"turn":1,"reason":{"kind":"error","error":{"message":"llm-deepseek-keyless: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry; set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)","code":"INVALID_CREDENTIAL"}}}}} {"type":"result","sessionId":"{{sessionId}}","output":""} From bca49d2ee0e5c2dd61713eb60135d0fe42d5453b Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 13 Nov 2026 11:36:30 +0800 Subject: [PATCH 21/48] fix(llm-deepseek-api-key): release the route key only for the route's origin The credential published through ctx.llm.routeCredential() ignored the destination: resolve() and configured() answered for any URL, unlike the account route, whose owner checks the destination. Both now answer only for destinations under the origin of the route's base URL without embedded credentials, and read the credential store for no other destination. Messages, Files, and listing requests derive their URLs from that base URL and are unchanged. --- ...-11-10-llm-route-credential-seam.i18n.yaml | 4 +-- .../2026-11-10-llm-route-credential-seam.md | 2 +- ...2026-11-10-llm-route-credential-seam.zh.md | 2 +- .../llm/llm-deepseek-api-key/README.i18n.yaml | 4 +-- packages/llm/llm-deepseek-api-key/README.md | 2 +- .../llm/llm-deepseek-api-key/README.zh.md | 2 +- .../llm/llm-deepseek-api-key/src/index.ts | 17 +++++++++-- .../tests/discovery.spec.ts | 28 +++++++++++++++++++ 8 files changed, 50 insertions(+), 11 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index c528ae84df..50a9766fee 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -9,8 +9,8 @@ en: 9665e1879893fe76 zh: 9da30ad0be6fc38d /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision: - en: 8d28911b4a7aaca0 - zh: db511eb9dfdc5f5e + en: 5c11dfca48a6343b + zh: e637091ff8593f5d /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered: en: 8177946a6bfa1a6d zh: f523f9057b4b47c5 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md index 7ed0451345..2724189196 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -14,7 +14,7 @@ Several packages shared one DeepSeek credential without an owner. `@deepseek-ai/ `@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the grant or `undefined`; `missingCredential(connection, provider)` names the failure of a request without one, `MISSING_CREDENTIAL` by default; `credential` declares the published kind, reference, and presence check. The listing cache scopes by endpoint and a hash of the credential headers. -The route plugins own credentials. `llm-deepseek-api-key` reads its key through `resolveCredentialRef` and `credentialRefConfigured`, new in `@deepseek-ai/dsh-credentials`, which treat a mounted credentials service as authoritative and read the launch environment only without one; it publishes kind `api-key` with the `apiKeyEnv` reference. `llm-deepseek-account` reads `ctx.deepseekAccount.resolveRequestCredential(endpoint)`, maps HTTP 401 to `ACCOUNT_TOKEN_INVALID` and quota failures to `ACCOUNT_QUOTA`, fails without a credential as `ACCOUNT_SIGN_IN_REQUIRED`, publishes kind `account`, and owns the sign-out policy: it cancels its running Agents on `deepseek-account/signed-out` and registers a running-task report with the account service. +The route plugins own credentials. `llm-deepseek-api-key` reads its key through `resolveCredentialRef` and `credentialRefConfigured`, new in `@deepseek-ai/dsh-credentials`, which treat a mounted credentials service as authoritative and read the launch environment only without one; it publishes kind `api-key` with the `apiKeyEnv` reference and releases the key only for destinations under the origin of its base URL. `llm-deepseek-account` reads `ctx.deepseekAccount.resolveRequestCredential(endpoint)`, maps HTTP 401 to `ACCOUNT_TOKEN_INVALID` and quota failures to `ACCOUNT_QUOTA`, fails without a credential as `ACCOUNT_SIGN_IN_REQUIRED`, publishes kind `account`, and owns the sign-out policy: it cancels its running Agents on `deepseek-account/signed-out` and registers a running-task report with the account service. `@deepseek-ai/dsh-deepseek-account` releases request credentials. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, the bare token, and a `reject()` that removes the grant while it still matches and contains storage failures; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The service inspects no Agents and depends on neither `dsh-agent` nor `dsh-llm`. The package lives in the `packages/account/` group under its unchanged name. diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index e02353e078..72ac5291ed 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -14,7 +14,7 @@ Status: implemented `@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回授权或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`;`credential` 声明发布的种类、引用和存在性检查。列表缓存以端点和凭据请求头的哈希划分作用域。 -路由插件拥有凭据。`llm-deepseek-api-key` 通过 `@deepseek-ai/dsh-credentials` 新增的 `resolveCredentialRef` 和 `credentialRefConfigured` 读取密钥,二者把已挂载的凭据服务视为权威,仅在没有该服务时读取启动环境;它发布种类 `api-key` 并附带 `apiKeyEnv` 引用。`llm-deepseek-account` 读取 `ctx.deepseekAccount.resolveRequestCredential(endpoint)`,把 HTTP 401 映射为 `ACCOUNT_TOKEN_INVALID`、配额失败映射为 `ACCOUNT_QUOTA`,没有凭据时以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,发布种类 `account`,并拥有退登策略:在 `deepseek-account/signed-out` 时取消其运行中的 Agent,并向账号服务注册运行中任务报告。 +路由插件拥有凭据。`llm-deepseek-api-key` 通过 `@deepseek-ai/dsh-credentials` 新增的 `resolveCredentialRef` 和 `credentialRefConfigured` 读取密钥,二者把已挂载的凭据服务视为权威,仅在没有该服务时读取启动环境;它发布种类 `api-key` 并附带 `apiKeyEnv` 引用,且只对其基础地址所在 origin 下的目的地释放密钥。`llm-deepseek-account` 读取 `ctx.deepseekAccount.resolveRequestCredential(endpoint)`,把 HTTP 401 映射为 `ACCOUNT_TOKEN_INVALID`、配额失败映射为 `ACCOUNT_QUOTA`,没有凭据时以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,发布种类 `account`,并拥有退登策略:在 `deepseek-account/signed-out` 时取消其运行中的 Agent,并向账号服务注册运行中任务报告。 `@deepseek-ai/dsh-deepseek-account` 释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、裸 token 和 `reject()`;`reject()` 仅在授权仍一致时删除它并隔离存储失败。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。该服务不检查任何 Agent,也不依赖 `dsh-agent` 或 `dsh-llm`。包以不变的名字位于 `packages/account/` 组。 diff --git a/packages/llm/llm-deepseek-api-key/README.i18n.yaml b/packages/llm/llm-deepseek-api-key/README.i18n.yaml index 01dc753b77..f1bae2778c 100644 --- a/packages/llm/llm-deepseek-api-key/README.i18n.yaml +++ b/packages/llm/llm-deepseek-api-key/README.i18n.yaml @@ -9,8 +9,8 @@ en: b6871195e386cc64 zh: 742b05a3ca80883c /deepseek-ai-dsh-llm-deepseek-api-key/summary: - en: 69c60bbfb6aafb7a - zh: 1afe49ea9cdc3cd5 + en: ea0a35b73d3b8f2c + zh: 7e404ed4617c2789 /deepseek-ai-dsh-llm-deepseek-api-key/table-of-contents: en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 diff --git a/packages/llm/llm-deepseek-api-key/README.md b/packages/llm/llm-deepseek-api-key/README.md index c5eb1ebb19..d387b0b36b 100644 --- a/packages/llm/llm-deepseek-api-key/README.md +++ b/packages/llm/llm-deepseek-api-key/README.md @@ -11,7 +11,7 @@ English | [中文](README.zh.md) Register authentication, model discovery, and the official model listing for `deepseek-official`. This plugin shares the [Messages transport](../llm-deepseek/README.md) and owns credential resolution, catalog availability, and model admission. -Authentication resolution returns the validated API key in `x-api-key` for Messages, Files, and listing requests, and publishes the same key through `ctx.llm.routeCredential('deepseek-official')` with the route's base URL and `apiKeyEnv` reference, so the DeepSeek web providers send it as a bearer token to the same deployment. +Authentication resolution returns the validated API key in `x-api-key` for Messages, Files, and listing requests, and publishes the same key through `ctx.llm.routeCredential('deepseek-official')` with the route's base URL and `apiKeyEnv` reference, so the DeepSeek web providers send it as a bearer token to the same deployment. The published credential releases the key only for destinations under the origin of that base URL: for another origin, or a URL that embeds credentials, `configured()` answers false and `resolve()` releases nothing, and neither reads the credential store. ## Table of Contents diff --git a/packages/llm/llm-deepseek-api-key/README.zh.md b/packages/llm/llm-deepseek-api-key/README.zh.md index 317c75655b..b0f724fe8a 100644 --- a/packages/llm/llm-deepseek-api-key/README.zh.md +++ b/packages/llm/llm-deepseek-api-key/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" 为 `deepseek-official` 注册鉴权、模型发现和官方模型列表。通过 [llm-deepseek](../llm-deepseek/README.zh.md) 共用 Messages 请求实现;本包拥有凭据解析、目录可用性判断和模型准入。 -鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages、Files 和列表请求使用,并通过 `ctx.llm.routeCredential('deepseek-official')` 连同路由的基础地址和 `apiKeyEnv` 引用发布同一密钥,使 DeepSeek Web 提供方以 Bearer 令牌把它发往同一部署。 +鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages、Files 和列表请求使用,并通过 `ctx.llm.routeCredential('deepseek-official')` 连同路由的基础地址和 `apiKeyEnv` 引用发布同一密钥,使 DeepSeek Web 提供方以 Bearer 令牌把它发往同一部署。发布的凭据只对该基础地址所在 origin 下的目的地释放密钥:对其他 origin 或内嵌凭据的 URL,`configured()` 回答 false,`resolve()` 不释放任何内容,二者都不读取凭据存储。 ## 目录 diff --git a/packages/llm/llm-deepseek-api-key/src/index.ts b/packages/llm/llm-deepseek-api-key/src/index.ts index e1e2f3cf35..a35e6aebaa 100644 --- a/packages/llm/llm-deepseek-api-key/src/index.ts +++ b/packages/llm/llm-deepseek-api-key/src/index.ts @@ -41,7 +41,17 @@ export function apply(ctx: Context, config: Config): void { const value = await resolveCredentialRef(ctx, connection.apiKeyEnv) return value === undefined ? undefined : assertUsableApiKey(value, settingsNs, connection.apiKeyEnv) } - const resolveAuth = async (connection: ResolvedDeepSeekOptions): Promise => { + /** + * Whether `endpoint` belongs to the deployment this route sends its key to: the origin of the route's base URL, + * without credentials embedded in the URL. + */ + const servedByRoute = (connection: ResolvedDeepSeekOptions, endpoint: string): boolean => { + const destination = new URL(endpoint) + return destination.origin === new URL(connection.baseURL).origin && destination.username === '' && destination.password === '' + } + const resolveAuth = async (connection: ResolvedDeepSeekOptions, endpoint: string): Promise => { + // The store is read only for a destination this route serves, as the presence check below. + if (!servedByRoute(connection, endpoint)) return undefined const key = await resolveApiKey(connection) return key === undefined ? undefined : { headers: { 'x-api-key': key }, value: key } } @@ -52,7 +62,7 @@ export function apply(ctx: Context, config: Config): void { ) const listings = createModelListingCache(ctx, name, PROVIDER, { settings: () => options().listing, - credential: async () => (await resolveAuth(options()))?.headers, + credential: async url => (await resolveAuth(options(), url))?.headers, }) let reportedListing: ModelListing | undefined /** Resolve the catalog, reporting each listing's hidden entries and dropped badges once. */ @@ -98,7 +108,8 @@ export function apply(ctx: Context, config: Config): void { credential: { kind: 'api-key', reference: connection => connection.apiKeyEnv, - configured: connection => credentialRefConfigured(ctx, connection.apiKeyEnv), + configured: async (connection, endpoint) => + servedByRoute(connection, endpoint) && await credentialRefConfigured(ctx, connection.apiKeyEnv), }, admit: (connection, model) => { refuseListedModel(model, connection.refusals.get(model)) }, discoverModels: async (provider) => { diff --git a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts index bde4d26873..976ce160ae 100644 --- a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts +++ b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts @@ -94,3 +94,31 @@ it('publishes the route API key for its consumers from the credential planes it vi.unstubAllEnvs() } }) + +it.each([ + 'https://other-origin.example/v1/tools/search', + 'http://route.deepseek.test/v1/tools/search', + 'https://route.deepseek.test:8443/v1/tools/search', + 'https://user@route.deepseek.test/v1/tools/search', + 'https://:secret@route.deepseek.test/v1/tools/search', +])('releases no key for %s, a destination outside the origin of its base URL, without reading the credential store', async (endpoint) => { + const resolve = vi.fn(async () => ({ value: 'stored-key' })) + const describe = vi.fn(async () => ({ configured: true })) + const ctx = new Context() + try { + ctx.provide('credentials', { resolve, describe } as never) + await ctx.plugin(LlmRuntime) + await ctx.plugin(ApiKey, { baseURL: 'https://route.deepseek.test/anthropic' }) + const credential = ctx.llm.routeCredential('deepseek-official') + await expect(credential!.configured(endpoint)).resolves.toBe(false) + await expect(credential!.resolve(endpoint)).resolves.toBeUndefined() + expect(resolve).not.toHaveBeenCalled() + expect(describe).not.toHaveBeenCalled() + // The same store answers for a destination under the route's origin. + const served = 'https://route.deepseek.test/v1/tools/search' + await expect(credential!.configured(served)).resolves.toBe(true) + await expect(credential!.resolve(served)).resolves.toEqual({ headers: { 'x-api-key': 'stored-key' }, value: 'stored-key' }) + } finally { + await ctx.fiber.dispose() + } +}) From 6a82fdba513e80256112a4f350979447c23badf9 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 13 Nov 2026 11:47:46 +0800 Subject: [PATCH 22/48] fix(web-deepseek-api): accept only a route's own credential kind Search and Fetch picked a route credential by route id without comparing its kind, so an adapter registered as deepseek-official that publishes an account credential had that credential sent under API-key billing, and the reverse held for deepseek-account. A credential whose kind differs from the route's counts as no route, as an adapter publishing no credential already does: API-key billing falls back to DEEPSEEK_API_KEY at the official base, and account billing asks the account service. Readiness and dispatch share the source, so both follow the same rule. --- ...-11-10-llm-route-credential-seam.i18n.yaml | 4 +- .../2026-11-10-llm-route-credential-seam.md | 2 +- ...2026-11-10-llm-route-credential-seam.zh.md | 2 +- .../llm-route-credential/guide.i18n.yaml | 4 +- .../v0.2.2-rc.2/llm-route-credential/guide.md | 2 +- .../llm-route-credential/guide.zh.md | 2 +- .../web/web-deepseek-api/README.i18n.yaml | 4 +- packages/web/web-deepseek-api/README.md | 2 +- packages/web/web-deepseek-api/README.zh.md | 2 +- packages/web/web-deepseek-api/src/index.ts | 18 ++++++-- .../tests/credential-resolution.spec.ts | 44 +++++++++++++++++++ packages/web/web-deepseek-api/tests/routes.ts | 4 +- 12 files changed, 73 insertions(+), 17 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index 50a9766fee..ab73ce9fc2 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -9,8 +9,8 @@ en: 9665e1879893fe76 zh: 9da30ad0be6fc38d /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision: - en: 5c11dfca48a6343b - zh: e637091ff8593f5d + en: 964d66432578805a + zh: 90b93fb955b60afb /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered: en: 8177946a6bfa1a6d zh: f523f9057b4b47c5 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md index 2724189196..08eaef0f5a 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -18,7 +18,7 @@ The route plugins own credentials. `llm-deepseek-api-key` reads its key through `@deepseek-ai/dsh-deepseek-account` releases request credentials. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, the bare token, and a `reject()` that removes the grant while it still matches and contains storage failures; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The service inspects no Agents and depends on neither `dsh-agent` nor `dsh-llm`. The package lives in the `packages/account/` group under its unchanged name. -The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.routeCredential('deepseek-official')` and `routeCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account` and the search endpoint has the origin of the route's base URL, and the reference helpers otherwise; it does not request an account credential published for another origin. Both web consumers contain a failed `reject()`, so the HTTP rejection stays the reported error for every credential kind. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. +The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.routeCredential('deepseek-official')` and `routeCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Under each route id it accepts only the kind that route publishes, `api-key` as `deepseek-official` and `account` as `deepseek-account`, so billing by route id never sends the other kind. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account` and the search endpoint has the origin of the route's base URL, and the reference helpers otherwise; it does not request an account credential published for another origin. Both web consumers contain a failed `reject()`, so the HTTP rejection stays the reported error for every credential kind. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index 72ac5291ed..573eafd0e4 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -18,7 +18,7 @@ Status: implemented `@deepseek-ai/dsh-deepseek-account` 释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、裸 token 和 `reject()`;`reject()` 仅在授权仍一致时删除它并隔离存储失败。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。该服务不检查任何 Agent,也不依赖 `dsh-agent` 或 `dsh-llm`。包以不变的名字位于 `packages/account/` 组。 -Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.routeCredential('deepseek-official')` 和 `routeCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类且搜索端点与该路由的基础地址同源时使用其账号凭据,否则使用引用函数;为其他 origin 发布的账号凭据不会被索取。两个 Web 消费方都会隔离失败的 `reject()`,因此对任何凭据种类,报告的都是 HTTP 拒绝。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 +Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.routeCredential('deepseek-official')` 和 `routeCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。每个路由 id 下只接受该路由发布的种类(`deepseek-official` 下为 `api-key`,`deepseek-account` 下为 `account`),因此按路由 id 计费不会发出另一种凭据。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类且搜索端点与该路由的基础地址同源时使用其账号凭据,否则使用引用函数;为其他 origin 发布的账号凭据不会被索取。两个 Web 消费方都会隔离失败的 `reject()`,因此对任何凭据种类,报告的都是 HTTP 拒绝。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 ## 考虑过的替代方案 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml index 224eac372f..18492ce96a 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml @@ -9,8 +9,8 @@ en: f0139803159ee9c9 zh: 73bd5dfd53ed8d36 /deepseek-routes-publish-the-credential-web-consumers-reuse/change: - en: 09ab43933a9e5950 - zh: a18da5d560cf0c9f + en: 47b4fa692d98e1cf + zh: 42869beb3efbe290 /deepseek-routes-publish-the-credential-web-consumers-reuse/migration: en: 64ac045c8d9a1336 zh: 4712f6eacd85a151 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md index 996805e3ee..852212e5c3 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md @@ -17,7 +17,7 @@ English | [中文](guide.zh.md) `@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)` and makes `resolveToken(url)` and `rejectToken(token)` private; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name. `@deepseek-ai/dsh-credentials` adds `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`. -`@deepseek-ai/dsh-web-deepseek-api` drops its peer dependencies on `dsh-llm-deepseek`, both route plugins, and `cordis-plugin-loader`; `@deepseek-ai/dsh-web-search-deepseek` drops `dsh-llm-deepseek` and `dsh-deepseek-account` and adds `dsh-llm`. Both read route credentials through `ctx.llm.routeCredential()`, so an adapter registered under a DeepSeek route id without a published credential counts as no route. Without the account route, the Search and Fetch APIs send the account credential to the origin `DEEPSEEK_BASE_URL` names and reject a value that is not an HTTP(S) URL without embedded credentials. `DeepSeekSearchProviderOptions` replaces `resolveAccountToken` and `rejectAccountToken` with `resolveAccountCredential(endpoint)`. +`@deepseek-ai/dsh-web-deepseek-api` drops its peer dependencies on `dsh-llm-deepseek`, both route plugins, and `cordis-plugin-loader`; `@deepseek-ai/dsh-web-search-deepseek` drops `dsh-llm-deepseek` and `dsh-deepseek-account` and adds `dsh-llm`. Both read route credentials through `ctx.llm.routeCredential()`, so an adapter registered under a DeepSeek route id that publishes no credential, or a credential of the other kind, counts as no route. Without the account route, the Search and Fetch APIs send the account credential to the origin `DEEPSEEK_BASE_URL` names and reject a value that is not an HTTP(S) URL without embedded credentials. `DeepSeekSearchProviderOptions` replaces `resolveAccountToken` and `rejectAccountToken` with `resolveAccountCredential(endpoint)`. ## Migration diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md index 18fdd11b89..f4edae7d39 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md @@ -17,7 +17,7 @@ description: "DeepSeek 模型路由通过 ctx.llm.routeCredential() 发布自己 `@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`,并将 `resolveToken(url)` 与 `rejectToken(token)` 改为私有;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。该包移除 `dsh-agent` 与 `dsh-llm` peer 依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。`@deepseek-ai/dsh-credentials` 新增 `resolveCredentialRef(ctx, ref)` 与 `credentialRefConfigured(ctx, ref)`。 -`@deepseek-ai/dsh-web-deepseek-api` 移除对 `dsh-llm-deepseek`、两个路由插件和 `cordis-plugin-loader` 的 peer 依赖;`@deepseek-ai/dsh-web-search-deepseek` 移除 `dsh-llm-deepseek` 与 `dsh-deepseek-account`,新增 `dsh-llm`。两者都通过 `ctx.llm.routeCredential()` 读取路由凭据,因此以 DeepSeek 路由 id 注册但不发布凭据的适配器视为没有路由。没有账号路由时,Search 与 Fetch API 把账号凭据发往 `DEEPSEEK_BASE_URL` 所指的 origin,并拒绝不是不含内嵌凭据的 HTTP(S) URL 的值。`DeepSeekSearchProviderOptions` 用 `resolveAccountCredential(endpoint)` 替换 `resolveAccountToken` 与 `rejectAccountToken`。 +`@deepseek-ai/dsh-web-deepseek-api` 移除对 `dsh-llm-deepseek`、两个路由插件和 `cordis-plugin-loader` 的 peer 依赖;`@deepseek-ai/dsh-web-search-deepseek` 移除 `dsh-llm-deepseek` 与 `dsh-deepseek-account`,新增 `dsh-llm`。两者都通过 `ctx.llm.routeCredential()` 读取路由凭据,因此以 DeepSeek 路由 id 注册但不发布凭据、或发布另一种凭据的适配器视为没有路由。没有账号路由时,Search 与 Fetch API 把账号凭据发往 `DEEPSEEK_BASE_URL` 所指的 origin,并拒绝不是不含内嵌凭据的 HTTP(S) URL 的值。`DeepSeekSearchProviderOptions` 用 `resolveAccountCredential(endpoint)` 替换 `resolveAccountToken` 与 `rejectAccountToken`。 ## 迁移 diff --git a/packages/web/web-deepseek-api/README.i18n.yaml b/packages/web/web-deepseek-api/README.i18n.yaml index 42582881ec..67b48ecaed 100644 --- a/packages/web/web-deepseek-api/README.i18n.yaml +++ b/packages/web/web-deepseek-api/README.i18n.yaml @@ -54,8 +54,8 @@ en: 14f9af39f3be4fac zh: 3c7139fba0f17862 /deepseek-ai-dsh-web-deepseek-api/known-limitations-and-deferred-work: - en: 3880e7c032129fb7 - zh: ad1450509e3473ab + en: c71abd58d3afbcfe + zh: d463321359b84e94 /deepseek-ai-dsh-web-deepseek-api/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 zh: 9f56528562c7c914 diff --git a/packages/web/web-deepseek-api/README.md b/packages/web/web-deepseek-api/README.md index a653aadad9..737cf87336 100644 --- a/packages/web/web-deepseek-api/README.md +++ b/packages/web/web-deepseek-api/README.md @@ -132,7 +132,7 @@ A returning or removed web tool changes the declared tools as [`dsh-tool-web`](. - API query and URL constraints are enforced by the remote service. An unresolvable Fetch target returned HTTP 500 rather than the documented 404 on 2026-10-16, and its failure carries the same endpoint guidance as an endpoint failure. Fetch exposes neither the target status nor the final redirect URL, so results report HTTP 200 and the requested URL; the provider discards the API's page title. - `available()` cannot query asynchronous credential stores; `ready()` does, so model steps withhold the tools when the store lacks the key. A direct `ctx.web.search()` or `ctx.web.fetch()` call can still fail with a missing-credential error. - Search pacing limits send times within one plugin instance. Other processes and clients on the same account share the account-wide 5 QPS limit without coordination, and network jitter can still bunch arrivals; an HTTP 429 fails that search, and `dsh-tool-web` then fails the whole multi-query call. Fetch is not paced, so parallel `web_fetch` calls can exceed the Fetch limit. -- Route endpoints and credentials follow what the adapter registered as `deepseek-official` or `deepseek-account` publishes through `ctx.llm.routeCredential`; an adapter that publishes no credential, such as a test replay adapter, counts as no route, so its conversations use `DEEPSEEK_API_KEY` and the official base. +- Route endpoints and credentials follow what the adapter registered as `deepseek-official` or `deepseek-account` publishes through `ctx.llm.routeCredential`. An adapter that publishes no credential, such as a test replay adapter, or a credential of the other kind (an account credential as `deepseek-official`, an API key as `deepseek-account`) counts as no route: its conversations use `DEEPSEEK_API_KEY` and the official base, and `account` billing asks the account service as it does without the account route. ### Dev Note diff --git a/packages/web/web-deepseek-api/README.zh.md b/packages/web/web-deepseek-api/README.zh.md index c59eeb474a..9075dfe2c5 100644 --- a/packages/web/web-deepseek-api/README.zh.md +++ b/packages/web/web-deepseek-api/README.zh.md @@ -132,7 +132,7 @@ Search API 接收 `query`、`count`(配置的结果数,或请求中更小的 - 查询和 URL 约束由远端服务执行。2026-10-16 抓取无法解析的目标域名时返回 HTTP 500,而非文档所述的 404,其失败信息与端点失败附带相同的端点指引。Fetch 既不暴露目标状态,也不暴露最终重定向 URL,因此结果报告 HTTP 200 和请求 URL;提供者丢弃 API 返回的页面标题。 - `available()` 无法查询异步凭据存储;`ready()` 可以,因此凭据存储缺少密钥时,模型步骤会撤下这两个工具。直接调用 `ctx.web.search()` 或 `ctx.web.fetch()` 仍可能因凭据缺失失败。 - Search 限速只约束单个插件实例内的发送时间。同一账号下的其他进程和客户端共享账号级 5 QPS 限制,彼此不协调,网络抖动也可能使请求集中到达;HTTP 429 会使该次搜索失败,随后 `dsh-tool-web` 会使整个多查询调用失败。Fetch 不限速,因此并行的 `web_fetch` 调用可能超过 Fetch 限制。 -- 路由端点与凭据只认以 `deepseek-official` 或 `deepseek-account` 注册的适配器通过 `ctx.llm.routeCredential` 发布的内容;不发布凭据的适配器(例如测试回放适配器)视为没有路由,其会话使用 `DEEPSEEK_API_KEY` 与官方基础地址。 +- 路由端点与凭据只认以 `deepseek-official` 或 `deepseek-account` 注册的适配器通过 `ctx.llm.routeCredential` 发布的内容。不发布凭据的适配器(例如测试回放适配器),或发布另一种凭据的适配器(以 `deepseek-official` 发布账号凭据,或以 `deepseek-account` 发布 API 密钥),都视为没有路由:其会话使用 `DEEPSEEK_API_KEY` 与官方基础地址,`account` 计费则像没有账号路由时一样询问账号服务。 ### 开发备注 diff --git a/packages/web/web-deepseek-api/src/index.ts b/packages/web/web-deepseek-api/src/index.ts index 476dd51256..aeebcdd51f 100644 --- a/packages/web/web-deepseek-api/src/index.ts +++ b/packages/web/web-deepseek-api/src/index.ts @@ -22,7 +22,7 @@ import type {} from '@deepseek-ai/dsh-agent' import { credentialRef, credentialRefConfigured, resolveCredentialRef, type CredentialRef } from '@deepseek-ai/dsh-credentials' import type {} from '@deepseek-ai/dsh-deepseek-account' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' -import { assertUsableApiKey } from '@deepseek-ai/dsh-llm' +import { assertUsableApiKey, type LlmCredentialKind } from '@deepseek-ai/dsh-llm' import type { Session } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-web' import { DeepSeekFetchApiProvider } from './fetch.ts' @@ -127,6 +127,15 @@ const OFFICIAL_PROVIDER = 'deepseek-official' /** Model route whose published credential an operation can send. */ type RouteName = typeof ACCOUNT_PROVIDER | typeof OFFICIAL_PROVIDER +/** + * Credential kind each DeepSeek model route publishes. Billing chooses between the two kinds by route id, so an + * adapter registered under one of these ids that publishes the other kind is not that route. + */ +const ROUTE_CREDENTIAL_KIND = { + [ACCOUNT_PROVIDER]: 'account', + [OFFICIAL_PROVIDER]: 'api-key', +} as const satisfies Record + /** * Launch-environment variable naming the DeepSeek deployment the model routes default to. Without the account route, * its origin receives the signed-in account's credential. @@ -257,13 +266,14 @@ function ruleSources(ctx: Context, capability: Capability, rule: Rule): DeepSeek * @param ctx - context with the optional model service. * @param capability - the capability whose diagnostics a misconfigured source names. * @param provider - the route. - * @returns the source; undefined when no mounted route publishes a credential as `provider`; a misconfigured source - * when the route's settings do not resolve or its published base URL does not parse. + * @returns the source; undefined when no mounted route publishes a credential of that route's kind as `provider`; a + * misconfigured source when the route's settings do not resolve or its published base URL does not parse. */ function routeSource(ctx: Context, capability: Capability, provider: RouteName): DeepSeekWebAuthSource | undefined { try { const credential = ctx.get('llm')?.routeCredential(provider) - return credential === undefined ? undefined : { kind: 'route', baseURL: toolsBase(credential.baseURL), credential } + if (credential === undefined || credential.kind !== ROUTE_CREDENTIAL_KIND[provider]) return undefined + return { kind: 'route', baseURL: toolsBase(credential.baseURL), credential } } catch (error: unknown) { return misconfigured(capability, provider, error) } diff --git a/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts b/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts index ddc6c738d5..04082d58e6 100644 --- a/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts +++ b/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts @@ -646,6 +646,50 @@ describe.each(OPERATIONS)('%s with its own endpoint settings', (operation) => { }) }) +describe.each(OPERATIONS)('%s beside an adapter that publishes the other credential kind under a DeepSeek route id', (operation) => { + const accountUnderOfficial: RouteRow = { provider: 'deepseek-official', publishes: 'account', config: { baseURL: 'https://route.deepseek.test/anthropic' } } + const keyUnderAccount: RouteRow = { provider: 'deepseek-account', publishes: 'api-key', config: { baseURL: 'https://account.deepseek.test/anthropic' } } + + it.each(['api-key', 'auto'])('sends DEEPSEEK_API_KEY to the official base under %s billing, never the account credential published as the API-key route', async (billing) => { + const asked: string[] = [] + const { ctx, sent } = await mount({ + config: { [`${operation}Billing`]: billing }, routes: [accountUnderOfficial], account: signedIn(asked), + environment: { DEEPSEEK_API_KEY: 'chat-key' }, + }) + expect(await ready(ctx, operation, 'deepseek-official')).toBe(true) + await operate(ctx, operation, 'deepseek-official') + expect(sent()).toEqual([{ endpoint: `${OFFICIAL}/${operation}`, authorization: 'Bearer chat-key', token: null }]) + expect(asked).toEqual([]) + }) + + it('is not ready under API-key billing without a key, and never sends that account credential', async () => { + const asked: string[] = [] + const { ctx, sent } = await mount({ config: { [`${operation}Billing`]: 'api-key' }, routes: [accountUnderOfficial], account: signedIn(asked) }) + expect(await ready(ctx, operation, 'deepseek-official')).toBe(false) + await expect(operate(ctx, operation, 'deepseek-official')).rejects.toMatchObject({ code: 'WEB_PROVIDER_CREDENTIAL_MISSING' }) + expect(sent()).toEqual([]) + expect(asked).toEqual([]) + }) + + it('sends the signed-in account token to the default account origin under account billing, never the API key published as the account route', async () => { + const { ctx, sent } = await mount({ + config: { [`${operation}Billing`]: 'account' }, routes: [keyUnderAccount], account: signedIn(), + environment: { DEEPSEEK_API_KEY: 'chat-key' }, + }) + expect(await ready(ctx, operation, 'deepseek-account')).toBe(true) + await operate(ctx, operation, 'deepseek-account') + expect(sent()).toEqual([{ endpoint: `${OFFICIAL}/${operation}`, authorization: null, token: 'account-token' }]) + }) + + it('treats a conversation on that account route id as one without an account route under automatic billing', async () => { + const { ctx, sent } = await mount({ routes: [keyUnderAccount], account: signedIn(), environment: { DEEPSEEK_API_KEY: 'chat-key' } }) + expect(await ready(ctx, operation, 'deepseek-account')).toBe(true) + await operate(ctx, operation, 'deepseek-account') + // The key goes to the official base, not to the base URL that adapter publishes. + expect(sent()).toEqual([{ endpoint: `${OFFICIAL}/${operation}`, authorization: 'Bearer chat-key', token: null }]) + }) +}) + describe('independent capabilities', () => { it('resolves Search from its own settings while Fetch follows the conversation', async () => { const { ctx, sent } = await mount({ diff --git a/packages/web/web-deepseek-api/tests/routes.ts b/packages/web/web-deepseek-api/tests/routes.ts index fff97df6c3..98b82fbf65 100644 --- a/packages/web/web-deepseek-api/tests/routes.ts +++ b/packages/web/web-deepseek-api/tests/routes.ts @@ -25,12 +25,14 @@ export interface RouteRow { throws?: unknown /** Base URL published in place of the resolved one, as a route publishing an unparsable base would. */ publishedBaseURL?: string + /** Credential kind published under this id, as another adapter registered under it can; defaults to the route's own kind. */ + publishes?: 'api-key' | 'account' } /** The credential `route` publishes, resolved from its config as the route plugin resolves it on each call. */ function credentialOf(ctx: Context, route: RouteRow): RouteCredential { const environment = launchEnvironmentOf(ctx) - if (route.provider === 'deepseek-official') { + if ((route.publishes ?? (route.provider === 'deepseek-official' ? 'api-key' : 'account')) === 'api-key') { const resolved = resolveAdapterOptions(plainOptions(OfficialConfig(route.config ?? {})), environment) const ref = resolved.apiKeyEnv return { From 10aed76233436b20f2d95af25d351ad30c615f9f Mon Sep 17 00:00:00 2001 From: _Kerman Date: Fri, 13 Nov 2026 12:58:10 +0800 Subject: [PATCH 23/48] docs: refresh generated dependency graphs after master merge --- docs/event-producer-consumer.md | 6 +----- docs/event-producer-consumer.zh.md | 6 +----- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 1fd7441387..ac2d8cd5f5 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -60,11 +60,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -<<<<<<< HEAD -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | -======= -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) | ->>>>>>> origin/master +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index f569d59b0b..82c9d95cd4 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -62,11 +62,7 @@ | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -<<<<<<< HEAD -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | -======= -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) | ->>>>>>> origin/master +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | From 7dc068057047e23565e0825824f7467d9dec11f3 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Fri, 13 Nov 2026 13:03:46 +0800 Subject: [PATCH 24/48] fix: keep text extraction imports unique after master merge --- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- packages/experimental/claude-code-mods/src/index.ts | 1 - packages/llm/llm/tests/message.spec.ts | 1 - 4 files changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 6304197d85..de1f837b3c 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1104,7 +1104,7 @@ export interface StagehandModelConfig { ## `@deepseek-ai/dsh-experimental-claude-code-mods` - `inject`: `workingDirectory` · `agents` -- `source`: [`packages/experimental/claude-code-mods/src/index.ts:56`](../packages/experimental/claude-code-mods/src/index.ts) +- `source`: [`packages/experimental/claude-code-mods/src/index.ts:55`](../packages/experimental/claude-code-mods/src/index.ts) ```ts config-catalog /** Plugin config: the limits mod hooks run under. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index e05501d811..503bb33fbd 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1106,7 +1106,7 @@ export interface StagehandModelConfig { ## `@deepseek-ai/dsh-experimental-claude-code-mods` - `inject`: `workingDirectory` · `agents` -- `source`: [`packages/experimental/claude-code-mods/src/index.ts:56`](../packages/experimental/claude-code-mods/src/index.ts) +- `source`: [`packages/experimental/claude-code-mods/src/index.ts:55`](../packages/experimental/claude-code-mods/src/index.ts) ```ts config-catalog /** Plugin config: the limits mod hooks run under. */ diff --git a/packages/experimental/claude-code-mods/src/index.ts b/packages/experimental/claude-code-mods/src/index.ts index ee995871b1..08398f4b0b 100644 --- a/packages/experimental/claude-code-mods/src/index.ts +++ b/packages/experimental/claude-code-mods/src/index.ts @@ -19,7 +19,6 @@ import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { AssistantMessage, ContentBlock, TokenUsage } from '@deepseek-ai/dsh-llm' import { brandString } from '@deepseek-ai/dsh-brand' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { UserMessage } from '@deepseek-ai/dsh-session' import { scopeOf } from '@deepseek-ai/dsh-scope' import { validateJsonSchemaValue } from '@deepseek-ai/dsh-tools' diff --git a/packages/llm/llm/tests/message.spec.ts b/packages/llm/llm/tests/message.spec.ts index 8158bb047d..f70710672e 100644 --- a/packages/llm/llm/tests/message.spec.ts +++ b/packages/llm/llm/tests/message.spec.ts @@ -1,5 +1,4 @@ import { describe, expect, expectTypeOf, it } from 'vitest' -import type { AttachmentId } from '@deepseek-ai/dsh-attachment/types' import { brandString } from '@deepseek-ai/dsh-brand' import type { AttachmentId } from '@deepseek-ai/dsh-attachment' import { From 1966a5e2bbc18748428ce83c1e4a53e67426ec82 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 13 Nov 2026 14:13:41 +0800 Subject: [PATCH 25/48] fix(llm-deepseek-account): end requests whose account credential is signed out Unloading the account route removed its sign-out listener and running-task report while a model request it had dispatched kept streaming, so a later sign-out neither closed that request nor cancelled its turn. A route credential grant now carries an optional `revoked` signal. The account service aborts it at each sign-out, after the deepseek-account/signed-out listeners return, and the shared transport runs the model request and its file operations under it. The route plugin names that end ACCOUNT_SIGN_IN_REQUIRED and cancels the route's running Agents from the request's own failure callback, so a turn whose route was disabled mid-turn still ends with the signed-out cause, and disabling the route never waits for a turn. The Search and Fetch API providers and Messages search run their request under the same signal and report WEB_PROVIDER_ERROR with sign-in guidance, keeping WEB_ABORTED for caller cancellation. Account model requests outside an Agent turn and account-billed web requests therefore end at sign-out as well. The web-search-account-signout recorded scenario pins the failure the model sees. While the route is disabled, a task it started that is executing a tool is not reported to the sign-out confirmation and ends at its next model request, which fails because the route is no longer registered. The API-key route README Summary exceeded its 100-word limit; the origin detail moves to the usage section. --- ...6-09-17-account-provider-signout.i18n.yaml | 8 +- .../2026-09-17-account-provider-signout.md | 4 +- .../2026-09-17-account-provider-signout.zh.md | 4 +- ...-11-10-llm-route-credential-seam.i18n.yaml | 12 +- .../2026-11-10-llm-route-credential-seam.md | 20 +- ...2026-11-10-llm-route-credential-seam.zh.md | 20 +- apps/web/tests/cot-translation-paid.e2e.ts | 8 +- docs/persistence-catalog.i18n.yaml | 44 ++-- docs/persistence-catalog.md | 22 +- docs/persistence-catalog.zh.md | 22 +- docs/persistence-schema.json | 22 +- docs/subsystems/account.i18n.yaml | 4 +- docs/subsystems/account.md | 11 +- docs/subsystems/account.zh.md | 11 +- docs/subsystems/llm-streaming.i18n.yaml | 4 +- docs/subsystems/llm-streaming.md | 9 +- docs/subsystems/llm-streaming.zh.md | 9 +- .../llm-route-credential/guide.i18n.yaml | 8 +- .../v0.2.2-rc.2/llm-route-credential/guide.md | 8 +- .../llm-route-credential/guide.zh.md | 8 +- .../account/deepseek-account/README.i18n.yaml | 8 +- packages/account/deepseek-account/README.md | 4 +- .../account/deepseek-account/README.zh.md | 4 +- .../account/deepseek-account/src/index.ts | 25 ++- .../account/deepseek-account/src/types.ts | 6 + .../deepseek-account/tests/account-stub.ts | 10 +- .../deepseek-account/tests/account.spec.ts | 61 ++++++ .../extensions/tool-cordis/src/api-catalog.ts | 8 +- .../llm/llm-deepseek-account/README.i18n.yaml | 12 +- packages/llm/llm-deepseek-account/README.md | 5 +- .../llm/llm-deepseek-account/README.zh.md | 5 +- .../llm-deepseek-account/src/account-tasks.ts | 25 ++- .../llm/llm-deepseek-account/src/index.ts | 30 ++- .../tests/account-signout.spec.ts | 148 ++++++++++++++ .../llm/llm-deepseek-api-key/README.i18n.yaml | 8 +- packages/llm/llm-deepseek-api-key/README.md | 4 +- .../llm/llm-deepseek-api-key/README.zh.md | 4 +- packages/llm/llm-deepseek/README.i18n.yaml | 12 +- packages/llm/llm-deepseek/README.md | 6 +- packages/llm/llm-deepseek/README.zh.md | 6 +- packages/llm/llm-deepseek/package.json | 1 + packages/llm/llm-deepseek/src/adapter.ts | 18 +- packages/llm/llm-deepseek/src/types.ts | 12 +- .../tests/account-signout-composition.spec.ts | 190 ++++++++++++++++++ .../llm/llm-deepseek/tests/adapter.spec.ts | 31 ++- packages/llm/llm-deepseek/tests/files.spec.ts | 22 +- .../tests/route-credential.spec.ts | 8 +- packages/llm/llm/src/types.ts | 7 + .../web/web-deepseek-api/README.i18n.yaml | 8 +- packages/web/web-deepseek-api/README.md | 4 +- packages/web/web-deepseek-api/README.zh.md | 4 +- .../web/web-deepseek-api/src/transport.ts | 56 +++++- .../tests/composition.spec.ts | 37 +++- .../web-deepseek-api/tests/transport.spec.ts | 83 +++++++- .../web/web-search-deepseek/README.i18n.yaml | 8 +- packages/web/web-search-deepseek/README.md | 4 +- packages/web/web-search-deepseek/README.zh.md | 4 +- .../web/web-search-deepseek/src/provider.ts | 60 +++++- .../tests/deepseek.spec.ts | 61 +++++- pnpm-lock.yaml | 3 + .../web-search-billing-fixture.mjs | 13 +- .../runtime.cordis.yml | 4 + .../session.v4.jsonl | 22 ++ .../web-search-account-signout/snapshot.yml | 11 + 64 files changed, 1086 insertions(+), 234 deletions(-) create mode 100644 packages/llm/llm-deepseek-account/tests/account-signout.spec.ts create mode 100644 packages/llm/llm-deepseek/tests/account-signout-composition.spec.ts create mode 100644 snapshots/session/web-search-account-signout/runtime.cordis.yml create mode 100644 snapshots/session/web-search-account-signout/session.v4.jsonl create mode 100644 snapshots/session/web-search-account-signout/snapshot.yml diff --git a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml index 883bb12bc0..0b8f4fca6a 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml @@ -9,11 +9,11 @@ en: 8d4d00e33af763b2 zh: 61977c82d66ae9bf /agent-note-account-provider-and-active-request-cancellation/decision: - en: d5eb12a1644c6226 - zh: 513d4f22ab74e039 + en: 6f5463ecf88c1435 + zh: 2097b8829e410c6b /agent-note-account-provider-and-active-request-cancellation/alternatives-considered: - en: a072026c1495a1ca - zh: bf053cc04fb33914 + en: 7ed93136cf11074a + zh: aea8dcf2e521a9c2 /agent-note-account-provider-and-active-request-cancellation/consequences: en: 8fd00b6d69b380c0 zh: 3830dc3a93d5de3c diff --git a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.md b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.md index 6b8ef842c5..8ea62952ed 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.md +++ b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.md @@ -14,11 +14,11 @@ Selecting credentials from login state changes the billing identity of an existi Account cancellation reads each running Agent’s latest `Session.requestContext()` instead of maintaining another provider field. This logged value remains through tools and retries and follows the next bound request. Idle Agents are excluded. During a new turn’s first preparation it can still name the previous turn’s account route, so sign-out can also interrupt an API-key turn that has not bound its new request yet. A missing account credential rejects a first request without a previous context before transport. -Successful local sign-out publishes an account event. The platform account provider installs the account module’s listener, which enumerates the Agent registry and cancels matching account routes through `Agent.cancel`, preserving inboxes. The account controller shares its predicate for sign-out confirmation. Each registered child is classified independently; existing parent-owned cancellation still applies to children whose lifetime is attached to a cancelled parent. The existing HTTP signal carries cancellation to transport. +Successful local sign-out publishes an account event. The account route plugin installs a listener, which enumerates the Agent registry and cancels matching account routes through `Agent.cancel`, preserving inboxes. It registers the same predicate with the account service as the running-task report behind sign-out confirmation. Each registered child is classified independently; existing parent-owned cancellation still applies to children whose lifetime is attached to a cancelled parent. The existing HTTP signal carries cancellation to transport. Requests this listener cannot reach end through the withdrawal signal of their credential, which the [route credential decision](2026-11-10-llm-route-credential-seam.md) owns. ## Alternatives considered -A historical set of providers wrongly cancels a turn after it switches to an API-key route. Current settings misclassify an older in-flight request. A second provider field or module-global map duplicates information already recorded in request context. A login-level cancellation signal duplicates the existing Agent and HTTP cancellation chain. +A historical set of providers wrongly cancels a turn after it switches to an API-key route. Current settings misclassify an older in-flight request. A second provider field or module-global map duplicates information already recorded in request context. A login-level cancellation signal in place of this chain duplicates the existing Agent and HTTP cancellation; the credential's withdrawal signal only supplements it. ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md index 588dd38bf9..a7a8d2d6fc 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md @@ -14,11 +14,11 @@ Status: implemented 账号取消读取运行中 Agent 最近的 `Session.requestContext()`,不维护额外提供方字段。该已记录值在工具和重试阶段保留,随下一次绑定请求更新;空闲 Agent 不计入。新轮次首次准备期间,它仍可能指向上一轮的账号路由,因此退登也可能打断尚未绑定新请求的 API key 轮次。没有历史上下文的首请求若缺少账号凭据,会在传输前失败。 -本地退登成功后发布账号事件。Platform 账号提供方安装账号模块的监听器,遍历 Agent 注册表,通过 `Agent.cancel` 取消匹配的账号路由并保留收件箱。账号控制器的退登确认复用同一判断函数。每个已注册子代理独立分类;生命周期绑定到已取消父代理的子代理仍受现有父级取消规则约束。现有 HTTP 信号将取消传递到传输层。 +本地退登成功后发布账号事件。账号路由插件安装监听器,遍历 Agent 注册表,通过 `Agent.cancel` 取消匹配的账号路由并保留收件箱。它把同一判断函数注册到账号服务,作为退登确认所依据的运行中任务报告。每个已注册子代理独立分类;生命周期绑定到已取消父代理的子代理仍受现有父级取消规则约束。现有 HTTP 信号将取消传递到传输层。该监听器到达不了的请求通过其凭据的收回信号结束,这一信号由[路由凭据决策](2026-11-10-llm-route-credential-seam.zh.md)负责。 ## Alternatives considered -历史提供方集合会在轮次切换到 API Key 路由后仍错误取消它。当前设置会误判更早的在途请求。额外的提供方字段或模块级全局映射重复保存请求上下文中已有的信息。登录级取消信号重复现有 Agent 与 HTTP 取消链路。 +历史提供方集合会在轮次切换到 API Key 路由后仍错误取消它。当前设置会误判更早的在途请求。额外的提供方字段或模块级全局映射重复保存请求上下文中已有的信息。用登录级取消信号取代这条链路,会重复现有的 Agent 与 HTTP 取消;凭据的收回信号只是对它的补充。 ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index ab73ce9fc2..3ea538f271 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -9,11 +9,11 @@ en: 9665e1879893fe76 zh: 9da30ad0be6fc38d /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision: - en: 964d66432578805a - zh: 90b93fb955b60afb + en: 339c58ce1afd8225 + zh: 00b0b683d6de2edc /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered: - en: 8177946a6bfa1a6d - zh: f523f9057b4b47c5 + en: d6b2de393add9887 + zh: b5351f9a49387bd6 /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/consequences: - en: f96508aa7cea1e87 - zh: 3eb61bdce43590bc + en: 748f306d720ade43 + zh: 792386be47105525 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md index 08eaef0f5a..b41afa2b2b 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -10,15 +10,15 @@ Several packages shared one DeepSeek credential without an owner. `@deepseek-ai/ ## Decision -`@deepseek-ai/dsh-llm` owns the Service Definition. `LlmAdapter.routeCredential(provider)` publishes a `RouteCredential`: the route's `kind` (merge-extensible, with `api-key` and `account` declared), its resolved `baseURL`, an optional credential `reference` for diagnostics, `configured(endpoint)` for presence checks that neither validate the credential nor contact the destination, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with the protocol `headers`, the bare `value` for destinations that render it differently, and an optional `reject()` for HTTP 401. `LlmRuntime.routeCredential(provider)` forwards to the owning adapter; an unregistered route answers `undefined`, and a route whose configuration does not resolve propagates the adapter's failure. The adapter reads one configuration generation per call, as it does per model request. +`@deepseek-ai/dsh-llm` owns the Service Definition. `LlmAdapter.routeCredential(provider)` publishes a `RouteCredential`: the route's `kind` (merge-extensible, with `api-key` and `account` declared), its resolved `baseURL`, an optional credential `reference` for diagnostics, `configured(endpoint)` for presence checks that neither validate the credential nor contact the destination, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with the protocol `headers`, the bare `value` for destinations that render it differently, an optional `reject()` for HTTP 401, and an optional `revoked` signal that aborts when the owner withdraws the credential while requests carry it. `LlmRuntime.routeCredential(provider)` forwards to the owning adapter; an unregistered route answers `undefined`, and a route whose configuration does not resolve propagates the adapter's failure. The adapter reads one configuration generation per call, as it does per model request. -`@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the grant or `undefined`; `missingCredential(connection, provider)` names the failure of a request without one, `MISSING_CREDENTIAL` by default; `credential` declares the published kind, reference, and presence check. The listing cache scopes by endpoint and a hash of the credential headers. +`@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the grant or `undefined`; `missingCredential(connection, provider)` names the failure of a request without one, `MISSING_CREDENTIAL` by default; `credential` declares the published kind, reference, and presence check. The transport runs each model request and its file operations under the grant's `revoked` signal and hands the resulting failure to the provider's failure callback, which names it. The listing cache scopes by endpoint and a hash of the credential headers. -The route plugins own credentials. `llm-deepseek-api-key` reads its key through `resolveCredentialRef` and `credentialRefConfigured`, new in `@deepseek-ai/dsh-credentials`, which treat a mounted credentials service as authoritative and read the launch environment only without one; it publishes kind `api-key` with the `apiKeyEnv` reference and releases the key only for destinations under the origin of its base URL. `llm-deepseek-account` reads `ctx.deepseekAccount.resolveRequestCredential(endpoint)`, maps HTTP 401 to `ACCOUNT_TOKEN_INVALID` and quota failures to `ACCOUNT_QUOTA`, fails without a credential as `ACCOUNT_SIGN_IN_REQUIRED`, publishes kind `account`, and owns the sign-out policy: it cancels its running Agents on `deepseek-account/signed-out` and registers a running-task report with the account service. +The route plugins own credentials. `llm-deepseek-api-key` reads its key through `resolveCredentialRef` and `credentialRefConfigured`, new in `@deepseek-ai/dsh-credentials`, which treat a mounted credentials service as authoritative and read the launch environment only without one; it publishes kind `api-key` with the `apiKeyEnv` reference and releases the key only for destinations under the origin of its base URL. `llm-deepseek-account` reads `ctx.deepseekAccount.resolveRequestCredential(endpoint)`, maps HTTP 401 to `ACCOUNT_TOKEN_INVALID` and quota failures to `ACCOUNT_QUOTA`, fails without a credential as `ACCOUNT_SIGN_IN_REQUIRED`, publishes kind `account`, and owns the sign-out policy: it cancels its running Agents on `deepseek-account/signed-out` and registers a running-task report with the account service. A request in flight at sign-out ends with its grant's `revoked` signal and fails as `ACCOUNT_SIGN_IN_REQUIRED`, and its failure callback cancels the same Agents, so a request that outlives the plugin still ends its turn with the signed-out cause. -`@deepseek-ai/dsh-deepseek-account` releases request credentials. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, the bare token, and a `reject()` that removes the grant while it still matches and contains storage failures; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The service inspects no Agents and depends on neither `dsh-agent` nor `dsh-llm`. The package lives in the `packages/account/` group under its unchanged name. +`@deepseek-ai/dsh-deepseek-account` releases request credentials. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, the bare token, a `reject()` that removes the grant while it still matches and contains storage failures, and a `revoked` signal the service aborts at each sign-out after the `deepseek-account/signed-out` listeners have returned; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The service inspects no Agents and depends on neither `dsh-agent` nor `dsh-llm`. The package lives in the `packages/account/` group under its unchanged name. -The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.routeCredential('deepseek-official')` and `routeCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Under each route id it accepts only the kind that route publishes, `api-key` as `deepseek-official` and `account` as `deepseek-account`, so billing by route id never sends the other kind. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account` and the search endpoint has the origin of the route's base URL, and the reference helpers otherwise; it does not request an account credential published for another origin. Both web consumers contain a failed `reject()`, so the HTTP rejection stays the reported error for every credential kind. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. +The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.routeCredential('deepseek-official')` and `routeCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Under each route id it accepts only the kind that route publishes, `api-key` as `deepseek-official` and `account` as `deepseek-account`, so billing by route id never sends the other kind. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account` and the search endpoint has the origin of the route's base URL, and the reference helpers otherwise; it does not request an account credential published for another origin. Both web consumers contain a failed `reject()`, so the HTTP rejection stays the reported error for every credential kind. Both run their request under the grant's `revoked` signal and report a request it ended as `WEB_PROVIDER_ERROR` with sign-in guidance, keeping `WEB_ABORTED` for the caller's cancellation. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. ## Alternatives considered @@ -32,6 +32,16 @@ The web providers consume publications. `web-deepseek-api` builds each operation **Moving the account package into `identity/`.** That group defines anonymous, user-independent ids; a signed-in account is the opposite, so it gets a group of its own. +**Keeping the route plugin's sign-out listener until its tasks end.** Unloading the route then waits for a running turn: disabling the plugin blocks, and every other settings write queues behind that reload, for as long as the turn runs. + +**Cancelling the route's tasks when the route unloads.** A configuration reload or a plugin update would stop turns that no sign-out touched. + +**Returning the sign-out policy to the account service.** The service would again inspect Agents and know route ids, the dependencies this decision removes. + +**Keeping the route's listener or report registered after its plugin unloads.** A registration that outlives the plugin that made it breaks the rule that registrations are effects of their owner, and leaves code of an unloaded plugin running in another scope for as long as the task runs. + ## Consequences Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `routeCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`. + +A sign-out ends the in-flight model, Files, Search, and Fetch requests that carry the account token, including requests no Agent turn owns, such as a model request outside a turn or an account-billed web search; the account listing request keeps its own deadline. The signal supplements the Agent cancellation of the [account sign-out decision](2026-09-17-account-provider-signout.md), which rejected a login-level signal as a duplicate of that chain: the chain reaches a request only through a mounted listener and a running Agent turn. While the account route is disabled, a task it started that still runs is not reported to the sign-out confirmation, and a sign-out ends it only through a model request in flight. A credential released by an account service that has since been replaced is not withdrawn by the replacement's sign-out; the route plugin's listener still cancels Agent turns. diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index 573eafd0e4..d025903ed3 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -10,15 +10,15 @@ Status: implemented ## 决策 -`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.routeCredential(provider)` 发布一个 `RouteCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不校验凭据、不联系目的地的存在性检查 `configured(endpoint)`,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`,以及可选的 HTTP 401 `reject()`。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 +`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.routeCredential(provider)` 发布一个 `RouteCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不校验凭据、不联系目的地的存在性检查 `configured(endpoint)`,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`、可选的 HTTP 401 `reject()`,以及可选的 `revoked` 信号;所有者在请求仍携带凭据时收回凭据,该信号即中止。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 -`@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回授权或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`;`credential` 声明发布的种类、引用和存在性检查。列表缓存以端点和凭据请求头的哈希划分作用域。 +`@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回授权或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`;`credential` 声明发布的种类、引用和存在性检查。传输层让每次模型请求及其文件操作受授权的 `revoked` 信号约束,并把由此产生的失败交给提供方的失败回调命名。列表缓存以端点和凭据请求头的哈希划分作用域。 -路由插件拥有凭据。`llm-deepseek-api-key` 通过 `@deepseek-ai/dsh-credentials` 新增的 `resolveCredentialRef` 和 `credentialRefConfigured` 读取密钥,二者把已挂载的凭据服务视为权威,仅在没有该服务时读取启动环境;它发布种类 `api-key` 并附带 `apiKeyEnv` 引用,且只对其基础地址所在 origin 下的目的地释放密钥。`llm-deepseek-account` 读取 `ctx.deepseekAccount.resolveRequestCredential(endpoint)`,把 HTTP 401 映射为 `ACCOUNT_TOKEN_INVALID`、配额失败映射为 `ACCOUNT_QUOTA`,没有凭据时以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,发布种类 `account`,并拥有退登策略:在 `deepseek-account/signed-out` 时取消其运行中的 Agent,并向账号服务注册运行中任务报告。 +路由插件拥有凭据。`llm-deepseek-api-key` 通过 `@deepseek-ai/dsh-credentials` 新增的 `resolveCredentialRef` 和 `credentialRefConfigured` 读取密钥,二者把已挂载的凭据服务视为权威,仅在没有该服务时读取启动环境;它发布种类 `api-key` 并附带 `apiKeyEnv` 引用,且只对其基础地址所在 origin 下的目的地释放密钥。`llm-deepseek-account` 读取 `ctx.deepseekAccount.resolveRequestCredential(endpoint)`,把 HTTP 401 映射为 `ACCOUNT_TOKEN_INVALID`、配额失败映射为 `ACCOUNT_QUOTA`,没有凭据时以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,发布种类 `account`,并拥有退登策略:在 `deepseek-account/signed-out` 时取消其运行中的 Agent,并向账号服务注册运行中任务报告。退登时在途的请求随其授权的 `revoked` 信号结束,以 `ACCOUNT_SIGN_IN_REQUIRED` 失败;它的失败回调会取消同一批 Agent,因此比插件存活更久的请求仍会以退登原因结束其回合。 -`@deepseek-ai/dsh-deepseek-account` 释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、裸 token 和 `reject()`;`reject()` 仅在授权仍一致时删除它并隔离存储失败。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。该服务不检查任何 Agent,也不依赖 `dsh-agent` 或 `dsh-llm`。包以不变的名字位于 `packages/account/` 组。 +`@deepseek-ai/dsh-deepseek-account` 释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、裸 token、`reject()` 和 `revoked` 信号;`reject()` 仅在授权仍一致时删除它并隔离存储失败,`revoked` 由服务在每次退登时、`deepseek-account/signed-out` 的监听器返回之后中止。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。该服务不检查任何 Agent,也不依赖 `dsh-agent` 或 `dsh-llm`。包以不变的名字位于 `packages/account/` 组。 -Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.routeCredential('deepseek-official')` 和 `routeCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。每个路由 id 下只接受该路由发布的种类(`deepseek-official` 下为 `api-key`,`deepseek-account` 下为 `account`),因此按路由 id 计费不会发出另一种凭据。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类且搜索端点与该路由的基础地址同源时使用其账号凭据,否则使用引用函数;为其他 origin 发布的账号凭据不会被索取。两个 Web 消费方都会隔离失败的 `reject()`,因此对任何凭据种类,报告的都是 HTTP 拒绝。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 +Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.routeCredential('deepseek-official')` 和 `routeCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。每个路由 id 下只接受该路由发布的种类(`deepseek-official` 下为 `api-key`,`deepseek-account` 下为 `account`),因此按路由 id 计费不会发出另一种凭据。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类且搜索端点与该路由的基础地址同源时使用其账号凭据,否则使用引用函数;为其他 origin 发布的账号凭据不会被索取。两个 Web 消费方都会隔离失败的 `reject()`,因此对任何凭据种类,报告的都是 HTTP 拒绝。二者都让请求受授权的 `revoked` 信号约束,把被它结束的请求报告为带登录指引的 `WEB_PROVIDER_ERROR`,`WEB_ABORTED` 仍只表示调用方取消。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 ## 考虑过的替代方案 @@ -32,6 +32,16 @@ Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.route **把账号包并入 `identity/`。** 该组定义匿名、不识别用户的 id;已登录账号与之相反,因此单独成组。 +**让路由插件的退登监听保留到其任务结束。** 这样卸载路由要等待运行中的回合:停用插件会被阻塞,其他设置写入也排在这次重载之后,直到回合结束。 + +**路由卸载时取消其任务。** 配置重载或插件更新会停掉与退登无关的回合。 + +**把退登策略放回账号服务。** 账号服务将重新检查 Agent 并认识路由 id,而这正是本决策去掉的依赖。 + +**插件卸载后仍保留路由的监听或报告注册。** 比注册它的插件存活更久的注册违反“注册是其所有者的 effect”这一规则,并让已卸载插件的代码在任务运行期间留在其他作用域里。 + ## 后果 新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `routeCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 + +退登会结束携带账号 token 的在途模型、Files、Search 与 Fetch 请求,包括不属于任何 Agent 回合的请求,例如回合之外的模型请求或按账号计费的 Web 搜索;账号列表请求仍只受自身期限约束。该信号是对[账号退登决策](2026-09-17-account-provider-signout.zh.md)中 Agent 取消链路的补充;那份决策以重复该链路为由否决了登录级信号,而该链路只能经由已挂载的监听和运行中的 Agent 回合到达请求。账号路由被停用期间,它此前启动且仍在运行的任务不会报告给退登确认,退登也只能通过在途的模型请求结束它。已被替换的账号服务释放的凭据不会被替换后服务的退登收回;路由插件的监听仍会取消 Agent 回合。 diff --git a/apps/web/tests/cot-translation-paid.e2e.ts b/apps/web/tests/cot-translation-paid.e2e.ts index 7648cbe3ff..1e08265e12 100644 --- a/apps/web/tests/cot-translation-paid.e2e.ts +++ b/apps/web/tests/cot-translation-paid.e2e.ts @@ -142,10 +142,12 @@ it.skipIf(MODE === 'record')('reuses saved native Account Flash translations acr const account = scaffold.ctx.get('deepseekAccount') if (account === undefined) throw new Error('Shipped native Account service is absent') // Only credential acquisition is nondeterministic; the Loader-owned native route and wire remain real. + const credential = { + headers: { 'x-dsh-auth-token': 'paid-browser-fixture-token' }, value: 'paid-browser-fixture-token', + revoked: new AbortController().signal, reject: () => Promise.resolve(), + } const auth = vi.spyOn(account, 'resolveRequestCredential').mockImplementation(async (url: string) => - new URL(url).origin === origin - ? { headers: { 'x-dsh-auth-token': 'paid-browser-fixture-token' }, value: 'paid-browser-fixture-token', reject: () => Promise.resolve() } - : undefined) + new URL(url).origin === origin ? credential : undefined) resources.restoreAuth = () => { auth.mockRestore() } scaffold.ctx.emit('llm/adapters-updated') const owner = [...scaffold.ctx.loader.entries()].find(entry => entry.options.id === 'llm-deepseek-account') diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index 0ab9b5b7fe..1d54521a32 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -558,8 +558,8 @@ en: 028791baa24a6a0a zh: 028791baa24a6a0a /session-persistence-event-catalog/resolved-persistence-types/in-history: - en: eef7993dfeef3c9d - zh: 36f6a03a24688113 + en: b952affc9dc40743 + zh: dd5d0872283e3762 /session-persistence-event-catalog/resolved-persistence-types/in-progress: en: 61de2b0c9de8c15b zh: 61de2b0c9de8c15b @@ -1194,8 +1194,8 @@ en: 8d2873c634bf6405 zh: 91e92b5730462cf0 /session-persistence-event-catalog/resolved-persistence-types/replayenvelope: - en: c0559f92b5275c58 - zh: 50616ae676eeee4c + en: 293da0eae99bdbe8 + zh: 244c9cfd281b9451 /session-persistence-event-catalog/resolved-persistence-types/requestcontext: en: 544039047a28b6bb zh: c691f0bb1e23db08 @@ -1245,8 +1245,8 @@ en: 29df35a8cc984e75 zh: 321b4e8bb0ad0850 /session-persistence-event-catalog/resolved-persistence-types/streamchunk: - en: 1585ce86ccaaca53 - zh: b3073eb80e23a11f + en: 71d48d17e3763774 + zh: 8cb0f1d92afa3236 /session-persistence-event-catalog/resolved-persistence-types/subagentcatalogevent: en: 8a56ae8e701509b3 zh: caef4f0223f65470 @@ -1314,8 +1314,8 @@ en: 49fcbb63c824347e zh: 187486d676edfe0e /session-persistence-event-catalog/resolved-persistence-types/toolschema: - en: a1613c3dc1fd1b54 - zh: eb4590c068e2699c + en: d9e99600cd0c02c3 + zh: 9885b7337c349b41 /session-persistence-event-catalog/resolved-persistence-types/toolschema~2: en: 12c14727bb7834e2 zh: b0f3c877873c36db @@ -2007,11 +2007,11 @@ en: bb507524bcc39c53 zh: 8314898562437473 /session-persistence-event-catalog/resolved-persistence-types/type-block-end: - en: c65956b2e4936b98 - zh: 04a10188520dd9e2 + en: 13224de3736d2d48 + zh: 6bf99a32b41f7165 /session-persistence-event-catalog/resolved-persistence-types/type-block-start: - en: 10eec3e1fa456886 - zh: a62e18e8e00a5f18 + en: 598ec19ec3abf6ed + zh: 84efc0177a9fd177 /session-persistence-event-catalog/resolved-persistence-types/type-chunk: en: 4b0ed1fe2caa26fb zh: 8fffdc4f8c3deb79 @@ -2052,8 +2052,8 @@ en: 14e4b48d856bcf57 zh: 72ba176535dc7f3f /session-persistence-event-catalog/resolved-persistence-types/type-finish: - en: df64e36d97f48908 - zh: 86cf679e6b3fdb85 + en: e1b5a95753e1984b + zh: 3a04bd831ff9f12d /session-persistence-event-catalog/resolved-persistence-types/type-goal-change: en: aad2516b62d3ee83 zh: e7204c4dc4e8e408 @@ -2091,8 +2091,8 @@ en: 4bf62582902829c5 zh: c9da9d11402ee1c4 /session-persistence-event-catalog/resolved-persistence-types/type-reasoning-delta: - en: bcafe0c539f6a5e2 - zh: 3be968698a8985bc + en: a2952ab46acfed9d + zh: b4e68befe87800dd /session-persistence-event-catalog/resolved-persistence-types/type-request-context: en: f8addb1a01da9ca1 zh: 4ef11ebddd302c05 @@ -2154,8 +2154,8 @@ en: 28bab22053eabff2 zh: 54c0e424fcb99c05 /session-persistence-event-catalog/resolved-persistence-types/type-text-delta: - en: 908a84e2ee82a7cc - zh: 5d8994c209e864a0 + en: 9856f0f63d3b413c + zh: c3bae6ac9e949696 /session-persistence-event-catalog/resolved-persistence-types/type-todo-write: en: 2fa7ba77598a95b4 zh: 50972b51d77e9155 @@ -2163,8 +2163,8 @@ en: 45ff4145d9e2c7d4 zh: 36a346ff729c4b84 /session-persistence-event-catalog/resolved-persistence-types/type-tool-call-delta: - en: 9663efae6bd28efb - zh: d8765a82a6b537a5 + en: 7c45dcb12f5fedb5 + zh: eea8f79e052f2bf0 /session-persistence-event-catalog/resolved-persistence-types/type-tool-workflow-agent-end: en: 8eb5e1eb95722bc7 zh: 8dd5980029600648 @@ -2196,8 +2196,8 @@ en: 1b045de96172be4b zh: 8a15c6f35b576b37 /session-persistence-event-catalog/resolved-persistence-types/type-usage: - en: 20d2e379fc64c866 - zh: b2d35dba5d3006af + en: 46b4cd2140687d30 + zh: 58103f952fa4ed89 /session-persistence-event-catalog/resolved-persistence-types/type-user-message: en: fd9f5dacef8c0ce8 zh: 79eab747b55dfaac diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index c5f40937d0..203f54c65e 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -2018,7 +2018,7 @@ SHA-256: `ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8` SHA-256: `f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5` -Sources: [`packages/llm/llm/src/types.ts:521`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:528`](../packages/llm/llm/src/types.ts) `"in-history"` @@ -4564,7 +4564,7 @@ Sources: [`packages/llm/llm/src/types.ts:75`](../packages/llm/llm/src/types.ts) SHA-256: `0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555` -Sources: [`packages/llm/llm/src/types.ts:555`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:562`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4878,7 +4878,7 @@ Sources: [`packages/skill/skill/src/index.ts:149`](../packages/skill/skill/src/i SHA-256: `47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180` -Sources: [`packages/llm/llm/src/types.ts:577`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:584`](../packages/llm/llm/src/types.ts) One of: @@ -5307,7 +5307,7 @@ Sources: [`packages/llm/llm/src/message.ts:172`](../packages/llm/llm/src/message SHA-256: `66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2` -Sources: [`packages/llm/llm/src/types.ts:598`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:605`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8314,7 +8314,7 @@ SHA-256: `1033093edd0db80ff410e00830b523405e00bb0c7684948e531ff65095799625` SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d` -Sources: [`packages/llm/llm/src/types.ts:582`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:589`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8328,7 +8328,7 @@ Sources: [`packages/llm/llm/src/types.ts:582`](../packages/llm/llm/src/types.ts) SHA-256: `3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90` -Sources: [`packages/llm/llm/src/types.ts:578`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:585`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8546,7 +8546,7 @@ SHA-256: `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` SHA-256: `a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1` -Sources: [`packages/llm/llm/src/types.ts:584`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:591`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8752,7 +8752,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:27`](../packages/llm/llm/src SHA-256: `2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095` -Sources: [`packages/llm/llm/src/types.ts:580`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:587`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -9088,7 +9088,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:20`](../packages/llm/llm/src SHA-256: `95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65` -Sources: [`packages/llm/llm/src/types.ts:579`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:586`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -9136,7 +9136,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:34`](../packages/llm/llm/src SHA-256: `88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a` -Sources: [`packages/llm/llm/src/types.ts:581`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:588`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -9314,7 +9314,7 @@ SHA-256: `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515` -Sources: [`packages/llm/llm/src/types.ts:583`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:590`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 74ae5c7936..7ada7ea1b8 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -2020,7 +2020,7 @@ SHA-256: `ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8` SHA-256: `f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5` -来源:[`packages/llm/llm/src/types.ts:521`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:528`](../packages/llm/llm/src/types.ts) `"in-history"` @@ -4566,7 +4566,7 @@ SHA-256: `814d9434e1ddf9078612b3b34322f26e9363b469213335007f7e9ba7fee9464e` SHA-256: `0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555` -来源:[`packages/llm/llm/src/types.ts:555`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:562`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4880,7 +4880,7 @@ SHA-256: `672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db` SHA-256: `47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180` -来源:[`packages/llm/llm/src/types.ts:577`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:584`](../packages/llm/llm/src/types.ts) 以下类型之一: @@ -5309,7 +5309,7 @@ SHA-256: `4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731` SHA-256: `66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2` -来源:[`packages/llm/llm/src/types.ts:598`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:605`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8316,7 +8316,7 @@ SHA-256: `1033093edd0db80ff410e00830b523405e00bb0c7684948e531ff65095799625` SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d` -来源:[`packages/llm/llm/src/types.ts:582`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:589`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8330,7 +8330,7 @@ SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d` SHA-256: `3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90` -来源:[`packages/llm/llm/src/types.ts:578`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:585`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8548,7 +8548,7 @@ SHA-256: `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` SHA-256: `a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1` -来源:[`packages/llm/llm/src/types.ts:584`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:591`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8754,7 +8754,7 @@ SHA-256: `71bb3254ec8f1e491ce63b762a7b5f18709de23aa4e8abcc8b886f4b6ce051dd` SHA-256: `2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095` -来源:[`packages/llm/llm/src/types.ts:580`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:587`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -9090,7 +9090,7 @@ SHA-256: `e72269f931559e901e5e8fe1cfcbd0669fb795f43cc038ff39fba62f60403c33` SHA-256: `95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65` -来源:[`packages/llm/llm/src/types.ts:579`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:586`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -9138,7 +9138,7 @@ SHA-256: `3860b4757d512a2869be833acb0faf834335b1b056bf3f83df5474dce95f8fa6` SHA-256: `88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a` -来源:[`packages/llm/llm/src/types.ts:581`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:588`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -9316,7 +9316,7 @@ SHA-256: `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515` -来源:[`packages/llm/llm/src/types.ts:583`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:590`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index 71dc45b012..16a2cf3438 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -88,7 +88,7 @@ {"digest":"0a8a062bc9c3c0d97fd97742262f2ea53dd32297f834e81114870d38ac3dc6da","names":[],"sources":[]}, {"digest":"0a92c5bdfa06c2e2615b777728f3aa95f408d43b9012e7b754568311251db623","names":[],"sources":["packages/experimental/liveshare/src/host/viewer-principal.ts:29"]}, {"digest":"0aa62ab51b36c0e64b134bd03ba8725d758744180a1a447da49beaad194f219f","names":[],"sources":[]}, - {"digest":"0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555","names":["packages/llm/llm/src/types.ts#ReplayEnvelope"],"sources":["packages/llm/llm/src/types.ts:555"]}, + {"digest":"0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555","names":["packages/llm/llm/src/types.ts#ReplayEnvelope"],"sources":["packages/llm/llm/src/types.ts:562"]}, {"digest":"0af3ecfb8c60d416fc40a7cc4fb2c4851a8e46608b2b38ab9e510670c971aa1f","names":[],"sources":[]}, {"digest":"0b6d718c693fdf7f06dcccb0bcbbabe78cc63514eafc62d6b2a3899735279d6f","names":["packages/goal/goal/src/types.ts#GoalRef"],"sources":["packages/goal/goal/src/types.ts:20"]}, {"digest":"0b9b8facbe2c19773b3fb0ecc824ccbcc603d41b8f18069faa3807d449572fce","names":[],"sources":[]}, @@ -180,7 +180,7 @@ {"digest":"297fbd8067d7815adae02b89790ec6ff5fb7c2cb0d0eb026e1746c24ec857761","names":[],"sources":[]}, {"digest":"2aad1179f957631477b582e57cd8f538cb82618fc3fb816bde1171154235b065","names":[],"sources":[]}, {"digest":"2ab12a0e345658f9342816d773fe610f049982bcad82631f43b9205abe43e5ee","names":[],"sources":[]}, - {"digest":"2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095","names":[],"sources":["packages/llm/llm/src/types.ts:580"]}, + {"digest":"2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095","names":[],"sources":["packages/llm/llm/src/types.ts:587"]}, {"digest":"2aed07493b1c65b6d00de5586da1e743cf501684b9ad43a1765fb4007d4ea456","names":[],"sources":[]}, {"digest":"2c4c21f19f426a58f2dac914e34313aa43f8408972de857a486d1f086d5adb6c","names":[],"sources":[]}, {"digest":"2c64d4bc7264fd3f8bed47e96ab8a593bce05a1e4e1c436dcd244a3b7e0c2a9d","names":[],"sources":[]}, @@ -220,7 +220,7 @@ {"digest":"3bca25b2baa6b22be9b577621a7603497f40870ed88a8dac4383d37dc2bb6e18","names":[],"sources":[]}, {"digest":"3bd652ebfa8726b3ce3937a4f1bd2759e02f86b3a08a20f9e41a8513656fbc5f","names":["packages/core/session/src/types.ts#OptionalSessionSeq"],"sources":["packages/core/session/src/types.ts:66"]}, {"digest":"3bdb8dc6989655b0d4ec361edafb8e2629bc263e1ea591819414fdafc1a413b3","names":[],"sources":[]}, - {"digest":"3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90","names":[],"sources":["packages/llm/llm/src/types.ts:578"]}, + {"digest":"3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90","names":[],"sources":["packages/llm/llm/src/types.ts:585"]}, {"digest":"3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1","names":[],"sources":[]}, {"digest":"3c2535ca0a2062f172f15344f8040755002b5ac506cf94fc4ebaa822b15feb8c","names":[],"sources":[]}, {"digest":"3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f","names":["packages/core/tools/src/contracts.ts#ToolRestriction"],"sources":["packages/core/tools/src/contracts.ts:395"]}, @@ -245,7 +245,7 @@ {"digest":"45f2a07ea94573123b6ae14db787a40062dec3834f36d8be92c523d40ba28448","names":[],"sources":["packages/interaction/user-approval/src/types.ts:44"]}, {"digest":"477614bca595a9e7adb5a1870be446b9a8684f3ba8950259d6289f2d3b74f028","names":[],"sources":["packages/compaction/compaction-image-offload/src/projection.ts:25"]}, {"digest":"47e5d84f1a93450a78c7f3954b43990d0f629af7c034a56313e5deb63e772c1b","names":[],"sources":[]}, - {"digest":"47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180","names":["packages/llm/llm/src/types.ts#StreamChunk"],"sources":["packages/llm/llm/src/types.ts:577"]}, + {"digest":"47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180","names":["packages/llm/llm/src/types.ts#StreamChunk"],"sources":["packages/llm/llm/src/types.ts:584"]}, {"digest":"487b65c37bfedb8b72088c4107a0a90a6249701f6b26745f6d98f9b8a22b07c7","names":[],"sources":["packages/llm/llm/src/assistant-stream.ts:43"]}, {"digest":"48e5c9861f16ac07e78cb7b5ae9dabdf7bb85c58baed5a51b4ad275050ea58e3","names":[],"sources":[]}, {"digest":"48f9c19417a1abbedfa59f4667bba36b93ac2db407adf5e84cb3ba0de30942cb","names":[],"sources":[]}, @@ -323,7 +323,7 @@ {"digest":"6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25","names":["packages/team/agent-team/src/types.ts#TeamMemberSnapshot"],"sources":["packages/team/agent-team/src/types.ts:50"]}, {"digest":"65a8400e451e667e5b6e34df72ceb81fca8c12330330fa72083ad40279b189ad","names":["packages/llm/llm/src/message.ts#SystemPromptMessageSource"],"sources":["packages/llm/llm/src/message.ts:34"]}, {"digest":"65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099","names":["packages/skill/tool-skill/src/index.ts#SkillCatalogSource"],"sources":["packages/skill/tool-skill/src/index.ts:36"]}, - {"digest":"66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2","names":["packages/llm/llm/src/types.ts#ToolSchema"],"sources":["packages/llm/llm/src/types.ts:598"]}, + {"digest":"66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2","names":["packages/llm/llm/src/types.ts#ToolSchema"],"sources":["packages/llm/llm/src/types.ts:605"]}, {"digest":"672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db","names":["packages/skill/skill/src/index.ts#SkillInvocationSource"],"sources":["packages/skill/skill/src/index.ts:149"]}, {"digest":"67d5f73ceae82f5265258142ad6cf172de2c1fef93ba551b7f0454e0a93bffe0","names":["packages/llm/llm/src/call-config.ts#LlmCallConfig"],"sources":["packages/llm/llm/src/call-config.ts:30"]}, {"digest":"68141cbe3994a5ffcd064c07c75996538437fd9dbf77ce8a2927e89ec577fabe","names":[],"sources":[]}, @@ -411,7 +411,7 @@ {"digest":"871bfd6f7bb91061246768d3377f3fd58d6b8ea7c31f44c714ae7ab215650d62","names":[],"sources":[]}, {"digest":"87b1a33564b9a4d63b00988a524c12259243953aebb9c9a05127d87b27464df9","names":[],"sources":[]}, {"digest":"88841202942c7683b3b7e5ea6a796047ec326b6701ac23e58cc236d85613b9fa","names":[],"sources":[]}, - {"digest":"88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a","names":[],"sources":["packages/llm/llm/src/types.ts:581"]}, + {"digest":"88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a","names":[],"sources":["packages/llm/llm/src/types.ts:588"]}, {"digest":"8a046b52331959aa3394680d6acbe09b8a5447c6b61375f263445bfcef19b7f1","names":[],"sources":[]}, {"digest":"8a54d228b1b7d8453e4304d32723d489f28b4b33b221f335342146926ad94fc6","names":[],"sources":[]}, {"digest":"8a6e1ec9e8db346b0e02f027db73c07a94f067a26d40c1aef1abd09c47ce7ba0","names":[],"sources":[]}, @@ -440,7 +440,7 @@ {"digest":"93cbbc5a7fd0b1aa1ff1b9a6bb5ec52b073f48e5a5200365c45c0cd54059e1b9","names":[],"sources":["packages/interaction/user-approval/src/types.ts:55"]}, {"digest":"93d38436347f67c9022aacbc4472e283d722bcab8eb73fc376aaf7b6a6b9fb35","names":[],"sources":[]}, {"digest":"94c56aeb1564ad735eb773d88636b40761d063efa1610f1308004d32923f5378","names":[],"sources":[]}, - {"digest":"95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65","names":[],"sources":["packages/llm/llm/src/types.ts:579"]}, + {"digest":"95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65","names":[],"sources":["packages/llm/llm/src/types.ts:586"]}, {"digest":"95a3ffccbf3c8afcf9a2f3b355f724da8e07e98dc47ee741166dde7f9ea058bd","names":[],"sources":[]}, {"digest":"95c0e88fcf0bafb2087f912ad9e2369de6ae6530cc0c4c2772c96205b57f7f60","names":[],"sources":[]}, {"digest":"9645cf93769a6dfb227bd400bd6cb9fa7bab9140f4a851e4ae92514ade6e3114","names":[],"sources":[]}, @@ -474,7 +474,7 @@ {"digest":"a15a19ef63cf5d1b711db1d249821dab0cedcd3a9ad09137b47352c93841fd20","names":[],"sources":[]}, {"digest":"a16e567c8cd2c55cf1e911aed3c200c4e1f6febb1459ff2a9e7adf159afb68cb","names":[],"sources":[]}, {"digest":"a2066bd52f61218ba15b758def2641cc6a8bd3d4a594a488ee4c65be356d7e39","names":[],"sources":[]}, - {"digest":"a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1","names":[],"sources":["packages/llm/llm/src/types.ts:584"]}, + {"digest":"a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1","names":[],"sources":["packages/llm/llm/src/types.ts:591"]}, {"digest":"a2be0f0cb59f0d4a06557d45847d1938aced238baa77a6da416e590b8b958553","names":[],"sources":[]}, {"digest":"a3a259a1aa5401af786ce08c4a8419681d3000d73467991b5fc563389bc4ebd2","names":[],"sources":[]}, {"digest":"a3c6f1ea38e9a61d7a9706057ba65aabe02dfe6d9dd90d4736aa62325d874531","names":[],"sources":[]}, @@ -596,7 +596,7 @@ {"digest":"d0fbb0ca1bbba059830826f33f801da1aced35a2504376d61e020bdfec8d50c0","names":[],"sources":[]}, {"digest":"d28765f87d6b6ab408e0b2f3e7e297791b004b806d8e302c49903ebae815feb2","names":[],"sources":[]}, {"digest":"d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41","names":[],"sources":[]}, - {"digest":"d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d","names":[],"sources":["packages/llm/llm/src/types.ts:582"]}, + {"digest":"d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d","names":[],"sources":["packages/llm/llm/src/types.ts:589"]}, {"digest":"d4c799e3d51cae1040362ba4968efc484739e14416c9c1df20c2f108b4ef2eb5","names":[],"sources":[]}, {"digest":"d4e4d575abeb4b72d616dc65c17ac0eaa943cc135609395044c38d5afcb10e31","names":[],"sources":[]}, {"digest":"d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9","names":[],"sources":[]}, @@ -670,11 +670,11 @@ {"digest":"f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402","names":["packages/core/session/src/types.ts#TurnEndReason"],"sources":["packages/core/session/src/types.ts:238"]}, {"digest":"f1996af2602e6f62b5ab179ca5c4af00d8753938b74cc6ef102de09e99e74a7e","names":[],"sources":[]}, {"digest":"f19bee84bf3d20904553cdcd57465232bc1c2a194f54c4d195292ba0487223a6","names":["packages/attachment/attachment/src/types.ts#FileAttachmentRef"],"sources":["packages/attachment/attachment/src/types.ts:39"]}, - {"digest":"f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515","names":[],"sources":["packages/llm/llm/src/types.ts:583"]}, + {"digest":"f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515","names":[],"sources":["packages/llm/llm/src/types.ts:590"]}, {"digest":"f230c0b583e23b25ee0a61dbe4c05e95c1e2ae44b27939501eb9e03696f0c278","names":[],"sources":[]}, {"digest":"f29d63336e8266d80dd7baeab219436db86341304f6be1cd0edb36f5134c4a47","names":[],"sources":[]}, {"digest":"f2da0f27c1e6add59982c37b15e4a4912c5b33466859cce3b13d503600e24aef","names":["packages/llm/llm/src/types.ts#FileBlock"],"sources":["packages/llm/llm/src/types.ts:105"]}, - {"digest":"f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5","names":["packages/llm/llm/src/types.ts#SystemPromptUpdate"],"sources":["packages/llm/llm/src/types.ts:521"]}, + {"digest":"f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5","names":["packages/llm/llm/src/types.ts#SystemPromptUpdate"],"sources":["packages/llm/llm/src/types.ts:528"]}, {"digest":"f4a66f654996c093aae700ea4c434ff2ee3569fea9c0e5813ccf6afdccabd163","names":[],"sources":[]}, {"digest":"f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1","names":[],"sources":[]}, {"digest":"f56c5b59ca0161310c338d31dd16cf14287ccd602ff4181058df178c1c286d7f","names":["packages/context/session-reference/src/types.ts#SessionReferenceSource"],"sources":["packages/context/session-reference/src/types.ts:13"]}, diff --git a/docs/subsystems/account.i18n.yaml b/docs/subsystems/account.i18n.yaml index b202a8713e..ff6e299f2a 100644 --- a/docs/subsystems/account.i18n.yaml +++ b/docs/subsystems/account.i18n.yaml @@ -6,8 +6,8 @@ en: 2302e2999588bac3 zh: 5e0ac058b50036dc /deepseek-account/request-credentials: - en: 808ace524e0dbc0b - zh: c4268221fa4c1c09 + en: 8b2ab927576926cf + zh: c383046df37bfade /deepseek-account/embedded-platform-credentials: en: 9a651d70acbe83a6 zh: 4624b0299f5fdd8e diff --git a/docs/subsystems/account.md b/docs/subsystems/account.md index b3a20e14ff..a550fc9d13 100644 --- a/docs/subsystems/account.md +++ b/docs/subsystems/account.md @@ -8,9 +8,9 @@ Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/accoun ## Request credentials -`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. The `deepseek-account` model route publishes this credential through `ctx.llm.routeCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `reject()` runs on the account service mounted when it is called, so a reload between a request and the destination's answer still removes the grant; without a mounted service it leaves the grant for the next one to reject. +`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. Its `revoked` signal aborts when the account signs out of the sign-in that token belongs to, by the user or after a rejection, once the `deepseek-account/signed-out` listeners have returned; the account model route and the DeepSeek web providers run each model, Files, Search, and Fetch request that carries the token under it, so a sign-out ends those requests even after the plugin that sent them has unloaded. The `deepseek-account` model route publishes this credential through `ctx.llm.routeCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `reject()` runs on the account service mounted when it is called, so a reload between a request and the destination's answer still removes the grant; without a mounted service it leaves the grant for the next one to reject. A credential released by an account service that has since been replaced keeps an unaborted signal, because the replacement withdraws only the credentials it released. -Model routes that bill the account register a running-task report with `registerRunningTaskReport(report)` inside `ctx.effect()`; `hasRunningAccountTasks()` answers true while any report does, so the sign-out confirmation can warn about work the sign-out interrupts. The route plugin owns cancellation of that work after `deepseek-account/signed-out`. +Model routes that bill the account register a running-task report with `registerRunningTaskReport(report)` inside `ctx.effect()`; `hasRunningAccountTasks()` answers true while any report does, so the sign-out confirmation can warn about work the sign-out interrupts. The route plugin owns cancellation of that work after `deepseek-account/signed-out`; a request that outlives the plugin ends through its credential's `revoked` signal, and the plugin's failure callback for that request cancels the work. ## Embedded Platform credentials @@ -97,7 +97,8 @@ async getPlatformSession(): Promise /** * Release the account credential for one request to `url` as the request * carries it, together with its invalidation, which runs on the account - * service mounted when it is called. Host-only. + * service mounted when it is called, and the signal this service aborts + * when it signs out of that credential. Host-only. * @param url - actual request destination or API base URL. * @returns the request credential, or undefined for other origins or a signed-out account. */ @@ -204,10 +205,10 @@ Source: [`packages/account/deepseek-account/src/types.ts`](../../packages/accoun #### `deepseek-account/signed-out` — emit -Local grant removal has completed. +Local grant removal has completed. After the listeners return, the `revoked` signal of that grant's request credentials aborts. ```ts cordis-catalog -/** Local grant removal has completed. +/** Local grant removal has completed. After the listeners return, the `revoked` signal of that grant's request credentials aborts. * @mode emit */ 'deepseek-account/signed-out'(): void diff --git a/docs/subsystems/account.zh.md b/docs/subsystems/account.zh.md index 341b2923ac..6624963d70 100644 --- a/docs/subsystems/account.zh.md +++ b/docs/subsystems/account.zh.md @@ -8,9 +8,9 @@ ## 请求凭据 -`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。 +`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。其 `revoked` 信号在账号退出该 token 所属的登录时中止,无论退登由用户发起还是由拒绝触发,且在 `deepseek-account/signed-out` 的监听器返回之后;账号模型路由和 DeepSeek Web 提供方让携带该 token 的每个模型、Files、Search 与 Fetch 请求受它约束,因此即使发出请求的插件已卸载,退登仍会结束这些请求。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。已被替换的账号服务释放的凭据,其信号保持未中止,因为替换后的服务只收回自己释放的凭据。 -按账号计费的模型路由在 `ctx.effect()` 内用 `registerRunningTaskReport(report)` 注册运行中任务报告;只要有报告回答 true,`hasRunningAccountTasks()` 就回答 true,使退登确认能够提醒退登将打断的工作。`deepseek-account/signed-out` 之后取消这些工作由路由插件负责。 +按账号计费的模型路由在 `ctx.effect()` 内用 `registerRunningTaskReport(report)` 注册运行中任务报告;只要有报告回答 true,`hasRunningAccountTasks()` 就回答 true,使退登确认能够提醒退登将打断的工作。`deepseek-account/signed-out` 之后取消这些工作由路由插件负责;比插件存活更久的请求通过其凭据的 `revoked` 信号结束,插件为该请求提供的失败回调随后取消这些工作。 ## 内嵌 Platform 凭证 @@ -97,7 +97,8 @@ async getPlatformSession(): Promise /** * Release the account credential for one request to `url` as the request * carries it, together with its invalidation, which runs on the account - * service mounted when it is called. Host-only. + * service mounted when it is called, and the signal this service aborts + * when it signs out of that credential. Host-only. * @param url - actual request destination or API base URL. * @returns the request credential, or undefined for other origins or a signed-out account. */ @@ -204,10 +205,10 @@ Source: [`packages/account/deepseek-account/src/types.ts`](../../packages/accoun #### `deepseek-account/signed-out` — emit -Local grant removal has completed. +Local grant removal has completed. After the listeners return, the `revoked` signal of that grant's request credentials aborts. ```ts cordis-catalog -/** Local grant removal has completed. +/** Local grant removal has completed. After the listeners return, the `revoked` signal of that grant's request credentials aborts. * @mode emit */ 'deepseek-account/signed-out'(): void diff --git a/docs/subsystems/llm-streaming.i18n.yaml b/docs/subsystems/llm-streaming.i18n.yaml index 712c712ab4..ec3c50fe81 100644 --- a/docs/subsystems/llm-streaming.i18n.yaml +++ b/docs/subsystems/llm-streaming.i18n.yaml @@ -36,8 +36,8 @@ en: 58dec2259b0b1c6f zh: fc99fe965acaabf3 /llm-streaming/the-model-request: - en: 1962ba10f5515278 - zh: 9fa56ed8f54136aa + en: a345a763b420ff1a + zh: 10937f0f9b040eea /llm-streaming/the-model-request/the-request-envelope-llmcallconfig-and-the-logged-header: en: b0eb4620c6953646 zh: fabf51c7245a4855 diff --git a/docs/subsystems/llm-streaming.md b/docs/subsystems/llm-streaming.md index 4ab60ea418..2b0427644f 100644 --- a/docs/subsystems/llm-streaming.md +++ b/docs/subsystems/llm-streaming.md @@ -527,7 +527,7 @@ interface LlmNativeAuth { } ``` -A route's adapter can also publish the credential the route currently sends, so consumers that call the same deployment outside the model request path, such as the DeepSeek web providers, reuse it through `ctx.llm.routeCredential(provider)` instead of reading provider configuration or choosing header names. A grant is Host-only and is held for one operation; `kind` is merge-extensible through `LlmCredentialKindMap`, whose declared members are `api-key` and `account`. +A route's adapter can also publish the credential the route currently sends, so consumers that call the same deployment outside the model request path, such as the DeepSeek web providers, reuse it through `ctx.llm.routeCredential(provider)` instead of reading provider configuration or choosing header names. A grant is Host-only and is held for one operation; `kind` is merge-extensible through `LlmCredentialKindMap`, whose declared members are `api-key` and `account`. A grant whose owner can withdraw the credential while requests carry it, as an account sign-out does, has a `revoked` signal: the consumer runs each request it authenticates under that signal and reports a request the signal ended as its own failure, not as the caller's cancellation. ```ts type-equiv /** @@ -554,6 +554,13 @@ interface RouteCredentialGrant { * @returns settlement after the invalidation attempt. */ reject?(): Promise + /** + * Aborts when the owner withdraws this credential while requests carrying it + * may be in flight, as an account sign-out does. A consumer ends each request + * it authenticated with this grant and reports that end as its own failure, + * not as the caller's cancellation. Absent for kinds that are never withdrawn. + */ + readonly revoked?: AbortSignal } ``` diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index 19a694ea5e..67fa37b2f5 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -533,7 +533,7 @@ interface LlmNativeAuth { } ``` -路由的适配器还可以发布该路由当前发送的凭据,使在模型请求路径之外调用同一部署的消费方(如 DeepSeek Web 提供方)通过 `ctx.llm.routeCredential(provider)` 复用它,而不读取提供方配置或自行选择请求头名称。授权仅限 Host,且只在一次操作内持有;`kind` 通过 `LlmCredentialKindMap` 可合并扩展,已声明的成员为 `api-key` 和 `account`。 +路由的适配器还可以发布该路由当前发送的凭据,使在模型请求路径之外调用同一部署的消费方(如 DeepSeek Web 提供方)通过 `ctx.llm.routeCredential(provider)` 复用它,而不读取提供方配置或自行选择请求头名称。授权仅限 Host,且只在一次操作内持有;`kind` 通过 `LlmCredentialKindMap` 可合并扩展,已声明的成员为 `api-key` 和 `account`。所有者可能在请求仍携带凭据时收回它(例如账号退登),这类授权带有 `revoked` 信号:消费方让它鉴权的每个请求都受该信号约束,并把被该信号结束的请求报告为自身的失败,而不是调用方的取消。 ```ts type-equiv /** @@ -560,6 +560,13 @@ interface RouteCredentialGrant { * @returns settlement after the invalidation attempt. */ reject?(): Promise + /** + * Aborts when the owner withdraws this credential while requests carrying it + * may be in flight, as an account sign-out does. A consumer ends each request + * it authenticated with this grant and reports that end as its own failure, + * not as the caller's cancellation. Absent for kinds that are never withdrawn. + */ + readonly revoked?: AbortSignal } ``` diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml index 18492ce96a..1e48e714c7 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml @@ -9,8 +9,8 @@ en: f0139803159ee9c9 zh: 73bd5dfd53ed8d36 /deepseek-routes-publish-the-credential-web-consumers-reuse/change: - en: 47b4fa692d98e1cf - zh: 42869beb3efbe290 + en: 4e77c6f6c622beb2 + zh: 03f3756a54dcbfa8 /deepseek-routes-publish-the-credential-web-consumers-reuse/migration: - en: 64ac045c8d9a1336 - zh: 4712f6eacd85a151 + en: 6d117f2dfd7593d0 + zh: 1c1579fc7d0ccad0 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md index 852212e5c3..f8dcf10eec 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md @@ -9,21 +9,21 @@ English | [中文](guide.zh.md) ## Change -`LlmAdapter.routeCredential(provider)` and `LlmRuntime.routeCredential(provider)` publish a route's current credential as a `RouteCredential`: kind, resolved base URL, optional reference, a `configured(endpoint)` presence check, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with protocol headers, the bare value, and an optional `reject()`. +`LlmAdapter.routeCredential(provider)` and `LlmRuntime.routeCredential(provider)` publish a route's current credential as a `RouteCredential`: kind, resolved base URL, optional reference, a `configured(endpoint)` presence check, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with protocol headers, the bare value, an optional `reject()`, and an optional `revoked` withdrawal signal. `@deepseek-ai/dsh-llm-deepseek` no longer exports `resolveDeepSeekApiKey`, `deepSeekApiKeyConfigured`, `resolveDeepSeekAccountToken`, or `rejectDeepSeekAccountToken`. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns `DeepSeekRequestAuth | undefined`, and `DeepSeekRequestAuth` requires `value` beside `headers`; the new `missingCredential` and `credential` options name the missing-credential failure and the published credential. `createModelListingCache` takes `credential(url)` returning request headers, and its `load` is optional. `@deepseek-ai/dsh-llm-deepseek-api-key` no longer exports `plainOptions` and `resolveAdapterOptions`; `@deepseek-ai/dsh-llm-deepseek-account` no longer exports `plainAccountOptions` and `resolveAccountOptions`. The account route plugin cancels its running Agents after sign-out and registers a running-task report. -`@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)` and makes `resolveToken(url)` and `rejectToken(token)` private; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name. `@deepseek-ai/dsh-credentials` adds `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`. +`@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)` and makes `resolveToken(url)` and `rejectToken(token)` private; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. A sign-out aborts released credentials' `revoked` signal, ending in-flight account requests: model requests outside a turn fail with `ACCOUNT_SIGN_IN_REQUIRED`, Search and Fetch with `WEB_PROVIDER_ERROR`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name. `@deepseek-ai/dsh-credentials` adds `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`. `@deepseek-ai/dsh-web-deepseek-api` drops its peer dependencies on `dsh-llm-deepseek`, both route plugins, and `cordis-plugin-loader`; `@deepseek-ai/dsh-web-search-deepseek` drops `dsh-llm-deepseek` and `dsh-deepseek-account` and adds `dsh-llm`. Both read route credentials through `ctx.llm.routeCredential()`, so an adapter registered under a DeepSeek route id that publishes no credential, or a credential of the other kind, counts as no route. Without the account route, the Search and Fetch APIs send the account credential to the origin `DEEPSEEK_BASE_URL` names and reject a value that is not an HTTP(S) URL without embedded credentials. `DeepSeekSearchProviderOptions` replaces `resolveAccountToken` and `rejectAccountToken` with `resolveAccountCredential(endpoint)`. ## Migration -1. Replace the removed `llm-deepseek` helpers: read keys with `resolveCredentialRef` and `credentialRefConfigured` from `@deepseek-ai/dsh-credentials` and validate them with `assertUsableApiKey`; read account credentials with `ctx.deepseekAccount.resolveRequestCredential(url)` and invalidate through the returned `reject()`. To reuse a mounted route's credential and endpoint, call `ctx.llm.routeCredential(provider)`. +1. Replace the removed `llm-deepseek` helpers: read keys with `resolveCredentialRef` and `credentialRefConfigured` from `@deepseek-ai/dsh-credentials` and validate them with `assertUsableApiKey`; read account credentials with `ctx.deepseekAccount.resolveRequestCredential(url)` and invalidate through the returned `reject()`. To reuse a mounted route's credential and endpoint, call `ctx.llm.routeCredential(provider)`, and run each request under the grant's `revoked` signal. 2. In custom `DeepSeekAdapter` or `registerDeepSeekProvider` consumers, return `undefined` from `resolveAuth` when no credential exists, add `value` to every `DeepSeekRequestAuth`, supply `missingCredential` for a route-specific failure, and declare `credential` to publish the route's credential. Pass credential headers, not a token, to `createModelListingCache`. 3. Replace imports of the route plugins' config exports with the plugins' own `Config`, and read a route's endpoint from its published credential instead of its resolver. -4. Make `deepseekAccount` stand-ins used by the account route or the web providers implement `resolveRequestCredential`; stand-ins that supplied `ctx.agents` for `hasRunningAccountTasks()` register a report instead. +4. Make `deepseekAccount` stand-ins used by the account route or the web providers implement `resolveRequestCredential`, returning a `revoked` signal; stand-ins that supplied `ctx.agents` for `hasRunningAccountTasks()` register a report instead. 5. Update workspace references to `packages/account/deepseek-account`; the npm package name, Remote namespace, and configuration keys are unchanged. 6. Replace `resolveAccountToken` and `rejectAccountToken` in `DeepSeekSearchProviderOptions` with `resolveAccountCredential` returning a `RouteCredentialGrant`. diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md index f4edae7d39..de47c7df60 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md @@ -9,21 +9,21 @@ description: "DeepSeek 模型路由通过 ctx.llm.routeCredential() 发布自己 ## 变更 -`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、`configured(endpoint)` 存在性检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值和可选的 `reject()`。 +`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、`configured(endpoint)` 存在性检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值、可选的 `reject()`,以及可选的 `revoked` 收回信号。 `@deepseek-ai/dsh-llm-deepseek` 不再导出 `resolveDeepSeekApiKey`、`deepSeekApiKeyConfigured`、`resolveDeepSeekAccountToken` 和 `rejectDeepSeekAccountToken`。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回 `DeepSeekRequestAuth | undefined`,且 `DeepSeekRequestAuth` 在 `headers` 之外要求 `value`;新增的 `missingCredential` 与 `credential` 选项分别命名凭据缺失的失败和发布的凭据。`createModelListingCache` 的 `credential(url)` 返回请求头,其 `load` 变为可选。 `@deepseek-ai/dsh-llm-deepseek-api-key` 不再导出 `plainOptions` 和 `resolveAdapterOptions`;`@deepseek-ai/dsh-llm-deepseek-account` 不再导出 `plainAccountOptions` 和 `resolveAccountOptions`。账号路由插件在退登后取消其运行中的 Agent,并注册运行中任务报告。 -`@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`,并将 `resolveToken(url)` 与 `rejectToken(token)` 改为私有;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。该包移除 `dsh-agent` 与 `dsh-llm` peer 依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。`@deepseek-ai/dsh-credentials` 新增 `resolveCredentialRef(ctx, ref)` 与 `credentialRefConfigured(ctx, ref)`。 +`@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`,并将 `resolveToken(url)` 与 `rejectToken(token)` 改为私有;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。退登会中止已释放凭据的 `revoked` 信号,从而结束在途的账号请求:回合之外的模型请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,Search 与 Fetch 以 `WEB_PROVIDER_ERROR` 失败。该包移除 `dsh-agent` 与 `dsh-llm` peer 依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。`@deepseek-ai/dsh-credentials` 新增 `resolveCredentialRef(ctx, ref)` 与 `credentialRefConfigured(ctx, ref)`。 `@deepseek-ai/dsh-web-deepseek-api` 移除对 `dsh-llm-deepseek`、两个路由插件和 `cordis-plugin-loader` 的 peer 依赖;`@deepseek-ai/dsh-web-search-deepseek` 移除 `dsh-llm-deepseek` 与 `dsh-deepseek-account`,新增 `dsh-llm`。两者都通过 `ctx.llm.routeCredential()` 读取路由凭据,因此以 DeepSeek 路由 id 注册但不发布凭据、或发布另一种凭据的适配器视为没有路由。没有账号路由时,Search 与 Fetch API 把账号凭据发往 `DEEPSEEK_BASE_URL` 所指的 origin,并拒绝不是不含内嵌凭据的 HTTP(S) URL 的值。`DeepSeekSearchProviderOptions` 用 `resolveAccountCredential(endpoint)` 替换 `resolveAccountToken` 与 `rejectAccountToken`。 ## 迁移 -1. 替换被移除的 `llm-deepseek` 辅助函数:用 `@deepseek-ai/dsh-credentials` 的 `resolveCredentialRef` 与 `credentialRefConfigured` 读取密钥并用 `assertUsableApiKey` 校验;用 `ctx.deepseekAccount.resolveRequestCredential(url)` 读取账号凭据并通过返回的 `reject()` 作废。要复用已挂载路由的凭据和端点,调用 `ctx.llm.routeCredential(provider)`。 +1. 替换被移除的 `llm-deepseek` 辅助函数:用 `@deepseek-ai/dsh-credentials` 的 `resolveCredentialRef` 与 `credentialRefConfigured` 读取密钥并用 `assertUsableApiKey` 校验;用 `ctx.deepseekAccount.resolveRequestCredential(url)` 读取账号凭据并通过返回的 `reject()` 作废。要复用已挂载路由的凭据和端点,调用 `ctx.llm.routeCredential(provider)`,并让每个请求受授权的 `revoked` 信号约束。 2. 在自定义的 `DeepSeekAdapter` 或 `registerDeepSeekProvider` 消费方中,没有凭据时让 `resolveAuth` 返回 `undefined`,为每个 `DeepSeekRequestAuth` 加上 `value`,为路由专属的失败提供 `missingCredential`,并声明 `credential` 以发布路由凭据。向 `createModelListingCache` 传递凭据请求头而不是 token。 3. 用路由插件自身的 `Config` 替换对其配置导出的导入,并从路由发布的凭据而非其解析函数读取端点。 -4. 让账号路由或 Web 提供方使用的 `deepseekAccount` 替身实现 `resolveRequestCredential`;为 `hasRunningAccountTasks()` 提供 `ctx.agents` 的替身改为注册报告。 +4. 让账号路由或 Web 提供方使用的 `deepseekAccount` 替身实现 `resolveRequestCredential` 并返回 `revoked` 信号;为 `hasRunningAccountTasks()` 提供 `ctx.agents` 的替身改为注册报告。 5. 把工作区引用更新为 `packages/account/deepseek-account`;npm 包名、Remote 命名空间和配置键均不变。 6. 把 `DeepSeekSearchProviderOptions` 中的 `resolveAccountToken` 与 `rejectAccountToken` 替换为返回 `RouteCredentialGrant` 的 `resolveAccountCredential`。 diff --git a/packages/account/deepseek-account/README.i18n.yaml b/packages/account/deepseek-account/README.i18n.yaml index e9ec42ad16..791db541dc 100644 --- a/packages/account/deepseek-account/README.i18n.yaml +++ b/packages/account/deepseek-account/README.i18n.yaml @@ -6,8 +6,8 @@ en: 9dbb9bc3960a11fe zh: ed58987926489d3e /deepseek-ai-dsh-deepseek-account: - en: d5aad878bc7d3059 - zh: 3573506e849ad4d4 + en: cc98cb1949c9fe0f + zh: bbb0b8fa319b9abc /deepseek-ai-dsh-deepseek-account/summary: en: 28bcca957bf6abf4 zh: 4a3fc8a59f2925bc @@ -15,8 +15,8 @@ en: af856ba79fe31b8e zh: 15b7d1a5d1856de2 /deepseek-ai-dsh-deepseek-account/use-this-package: - en: 210ba1bd070bb8c4 - zh: 4e1286bff076a3b6 + en: 68071ab7db44e807 + zh: a9efa62ee12d3fdd /deepseek-ai-dsh-deepseek-account/understand-the-implementation: en: 76d2da2dab100ac3 zh: 2c9404f27915daab diff --git a/packages/account/deepseek-account/README.md b/packages/account/deepseek-account/README.md index b26272b1d0..e9f9a41998 100644 --- a/packages/account/deepseek-account/README.md +++ b/packages/account/deepseek-account/README.md @@ -13,7 +13,7 @@ getPlatformSession exports the stored grant only when its issuer matches platfor `desktopPlatform` defaults to `null`, which sends `x-client-platform: web`; the Desktop profile supplies `darwin` or `win32`, becoming `desktop-mac` or `desktop-win`. The service owns all five headers, so deployment configuration cannot override them; `x-client-bundle-id` is intentionally empty, and `x-client-locale` reduces the caller's language to `zh_CN` or `en_US`. PlatformSession carries deployment headers only, and the embedding client composes the same five headers for the Platform documents and API requests it opens, only at the configured origin. -Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. `resolveRequestCredential(url)` releases the credential for one allowed destination as the request headers, the bare token, and a `reject()` that removes the stored grant after an HTTP 401 while it still matches that token, containing storage failures; the removal runs on the account service mounted when `reject()` is called, so a reload between the request and the destination's answer still removes the grant. The account model route and the DeepSeek web providers use it instead of composing headers themselves. +Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. `resolveRequestCredential(url)` releases the credential for one allowed destination as the request headers, the bare token, a `reject()` that removes the stored grant after an HTTP 401 while it still matches that token, containing storage failures, and a `revoked` signal; the removal runs on the account service mounted when `reject()` is called, so a reload between the request and the destination's answer still removes the grant. The account model route and the DeepSeek web providers use it instead of composing headers themselves, and end the request that carries the token when `revoked` aborts. ## Summary @@ -42,7 +42,7 @@ The `/client-metadata` entry provides pure Platform header and cookie helpers fo The profile projection maps `id_profile.picture` to `avatarUrl`, using null when no picture is configured. -Token resolution refuses requests while local sign-out is in progress. Successful local removal publishes `deepseek-account/signed-out` before returning the signed-out snapshot; remote revocation remains independent. +Token resolution refuses requests while local sign-out is in progress. Successful local removal publishes `deepseek-account/signed-out`, then aborts the `revoked` signal of the request credentials released for that sign-in, before returning the signed-out snapshot; a rejected token signs out the same way. Remote revocation remains independent. getProfile / getBalance sends the stored grant in the x-dsh-auth-token header to GET /auth-api/v0/users/current and GET /api/v0/users/get_user_summary on platformOrigin. The grant issuer must match that origin. Host projects only the account UID, profile name, avatar URL, phone or email exactly as masked by Platform, and normal_wallets / bonus_wallets currency/balance strings; response tokens and other fields are discarded. A balance or bonus-amount string is accepted when it matches the numeric grammar Platform's Web client already passes to big.js, which allows an omitted integer or fraction part and a decimal exponent, so values such as 0E-16 and 5.0000000000000000 stay valid; the original string is retained and NaN, Infinity and malformed text are rejected. Bonus wallets remain separate from recharge balances. Credential changes and disposal invalidate in-flight queries. diff --git a/packages/account/deepseek-account/README.zh.md b/packages/account/deepseek-account/README.zh.md index d219131533..db777bbe7c 100644 --- a/packages/account/deepseek-account/README.zh.md +++ b/packages/account/deepseek-account/README.zh.md @@ -13,7 +13,7 @@ getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导 `desktopPlatform` 默认为 `null`,此时携带 `x-client-platform: web`;Desktop profile 提供 `darwin` 或 `win32`,改为 `desktop-mac` 或 `desktop-win`。五个请求头均由 provider 拥有,部署配置无法覆盖;`x-client-bundle-id` 有意保持为空,`x-client-locale` 将调用方语言归约为 `zh_CN` 或 `en_US`。PlatformSession 只携带部署请求头,内嵌客户端为自行打开的 Platform 文档和 API 请求组装同样的五个请求头,且仅在配置来源发送。 -资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。`resolveRequestCredential(url)` 把一个允许目标的凭据以请求头、裸 token 和 `reject()` 的形式释放;`reject()` 在 HTTP 401 后、且存储的授权仍匹配该 token 时清除它并隔离存储失败;清除在 `reject()` 被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会清除授权。账号模型路由和 DeepSeek Web 提供方使用它,而不自行组装请求头。 +资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。`resolveRequestCredential(url)` 把一个允许目标的凭据以请求头、裸 token、`reject()` 和 `revoked` 信号的形式释放;`reject()` 在 HTTP 401 后、且存储的授权仍匹配该 token 时清除它并隔离存储失败;清除在 `reject()` 被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会清除授权。账号模型路由和 DeepSeek Web 提供方使用它,而不自行组装请求头,并在 `revoked` 中止时结束携带该 token 的请求。 ## 概述 @@ -42,7 +42,7 @@ getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导 账号资料投影将 `id_profile.picture` 映射为 `avatarUrl`,没有配置头像时返回 null。 -本地退出登录期间拒绝解析 token。本地授权成功删除后,先发布 `deepseek-account/signed-out`,再返回已退出的状态快照;远程撤销独立执行。 +本地退出登录期间拒绝解析 token。本地授权成功删除后,先发布 `deepseek-account/signed-out`,接着中止为该次登录释放的请求凭据的 `revoked` 信号,再返回已退出的状态快照;token 被拒绝时的退登同样如此。远程撤销独立执行。 getProfile / getBalance 将保存的授权 token 通过 x-dsh-auth-token 请求头,向 platformOrigin 上的 GET /auth-api/v0/users/current 和 GET /api/v0/users/get_user_summary 发起请求。授权签发来源必须与该来源一致。Host 只投影账号 UID、资料名称、头像 URL、由 Platform 脱敏的手机号或邮箱(原样保留),以及 normal_wallets / bonus_wallets 的币种和余额字符串,丢弃响应 token 与其他字段。余额和赠金金额字符串只要符合 Platform Web 客户端交给 big.js 的数字文法即可通过,该文法和 big.js 一致,允许省略整数或小数部分以及十进制指数,因此 0E-16、5.0000000000000000 这类值仍然有效;原始字符串会保留,NaN、Infinity 和非法文本仍被拒绝。赠送钱包不计入充值余额。凭证变化和销毁会使进行中的查询失效。 diff --git a/packages/account/deepseek-account/src/index.ts b/packages/account/deepseek-account/src/index.ts index cee5f107e4..4a490edf23 100644 --- a/packages/account/deepseek-account/src/index.ts +++ b/packages/account/deepseek-account/src/index.ts @@ -22,7 +22,7 @@ export type * from './types.ts' declare module '@deepseek-ai/cordis' { interface Context { deepseekAccount: DeepSeekAccount } interface Events { - /** Local grant removal has completed. + /** Local grant removal has completed. After the listeners return, the `revoked` signal of that grant's request credentials aborts. * @mode emit */ 'deepseek-account/signed-out'(): void @@ -128,6 +128,8 @@ export class DeepSeekAccount extends TypertRemoteService { */ private lastProfile: { readonly token: string; readonly profile: Extract } | undefined private detailsLifetime = new AbortController() + /** Aborted at the next sign-out; request credentials of the current sign-in carry its signal. */ + private signedOut = new AbortController() private closed = false private removing: Promise | undefined @@ -390,7 +392,7 @@ export class DeepSeekAccount extends TypertRemoteService { await this.ctx.credentials.deleteRecord(KEY) this.ctx.emit('deepseek-account/session-expired') this.attempt = undefined - this.ctx.emit('deepseek-account/signed-out') + this.publishSignedOut() this.changed('snapshot') return this.getState() })().finally(() => { this.removing = undefined }) @@ -471,11 +473,14 @@ export class DeepSeekAccount extends TypertRemoteService { /** * Release the account credential for one request to `url` as the request * carries it, together with its invalidation, which runs on the account - * service mounted when it is called. Host-only. + * service mounted when it is called, and the signal this service aborts + * when it signs out of that credential. Host-only. * @param url - actual request destination or API base URL. * @returns the request credential, or undefined for other origins or a signed-out account. */ async resolveRequestCredential(url: string): Promise { + // Captured before the token is read, so a sign-out that completes during the read aborts this credential's signal. + const revoked = this.signedOut.signal const token = await this.resolveToken(url) if (token === undefined) return undefined // The destination answers after a reload may have replaced this instance, so the rejection runs on the account @@ -484,6 +489,7 @@ export class DeepSeekAccount extends TypertRemoteService { return { headers: { [ACCOUNT_TOKEN_HEADER]: token }, value: token, + revoked, reject: async () => { try { await ctx.get('deepseekAccount')?.rejectToken(token) } catch (_credentialRemovalFailed) { /* The destination's rejection is the failure to report; the next rejection retries. */ } @@ -585,7 +591,7 @@ export class DeepSeekAccount extends TypertRemoteService { this.revoke(parsed.data.token, platformClientHeaders(this.platform, client)) } this.attempt = undefined - this.ctx.emit('deepseek-account/signed-out') + this.publishSignedOut() this.changed('snapshot') return this.getState() })().finally(() => { this.removing = undefined }) @@ -699,6 +705,17 @@ export class DeepSeekAccount extends TypertRemoteService { this.revocations.add(revocation) } + /** + * Announce a completed sign-out. Listeners run first, so a turn they cancel records that cause before the requests + * still carrying the signed-out token end. A listener that throws does not keep those requests open. + */ + private publishSignedOut(): void { + const signedOut = this.signedOut + this.signedOut = new AbortController() + try { this.ctx.emit('deepseek-account/signed-out') } + finally { signedOut.abort() } + } + private invalidateDetails(): void { this.lastProfile = undefined this.detailsLifetime.abort() diff --git a/packages/account/deepseek-account/src/types.ts b/packages/account/deepseek-account/src/types.ts index e49c4455ce..eac08b8a4a 100644 --- a/packages/account/deepseek-account/src/types.ts +++ b/packages/account/deepseek-account/src/types.ts @@ -130,6 +130,12 @@ export interface AccountRequestCredential { * @returns settlement after the removal attempt. */ reject(): Promise + /** + * Aborts when the account signs out of the sign-in this token belongs to, by the user or after a rejection, once + * `deepseek-account/signed-out` listeners have run. A consumer ends the request that carries the token. It stays + * unaborted when the account service that released it has been unloaded, because no sign-out reaches it then. + */ + readonly revoked: AbortSignal } /** Host-only credentials for an embedded Platform document; never expose through account RPC. */ diff --git a/packages/account/deepseek-account/tests/account-stub.ts b/packages/account/deepseek-account/tests/account-stub.ts index a04352bbac..3f0459dcc8 100644 --- a/packages/account/deepseek-account/tests/account-stub.ts +++ b/packages/account/deepseek-account/tests/account-stub.ts @@ -8,15 +8,18 @@ export interface AccountStubOptions { readonly token: (url: string) => string | undefined | Promise /** Observes each rejected token; a throw is contained, as the service contains storage failures. */ readonly reject?: (token: string) => void | Promise + /** The sign-out signal released credentials carry; without one they carry a signal that never aborts. */ + readonly signedOut?: AbortSignal } /** - * An account service releasing request credentials as the real one does: the token header, the bare token, and an - * invalidation that reports no failure. - * @param options - token policy and rejection observer. + * An account service releasing request credentials as the real one does: the token header, the bare token, the + * sign-out signal, and an invalidation that reports no failure. + * @param options - token policy, rejection observer, and sign-out signal. * @returns the stand-in, typed as the service for `ctx.provide`. */ export function accountStub(options: AccountStubOptions): DeepSeekAccount { + const signedOut = options.signedOut ?? new AbortController().signal const stub: Pick = { async resolveRequestCredential(url) { const token = await options.token(url) @@ -24,6 +27,7 @@ export function accountStub(options: AccountStubOptions): DeepSeekAccount { return { headers: { [ACCOUNT_TOKEN_HEADER]: token }, value: token, + revoked: signedOut, reject: async () => { try { await options.reject?.(token) } catch (_storageFailure) { /* The destination's rejection is the failure to report, as in the service. */ } diff --git a/packages/account/deepseek-account/tests/account.spec.ts b/packages/account/deepseek-account/tests/account.spec.ts index 33d4bfd029..ceabf9491c 100644 --- a/packages/account/deepseek-account/tests/account.spec.ts +++ b/packages/account/deepseek-account/tests/account.spec.ts @@ -503,6 +503,67 @@ it('publishes sign-out only after local grant removal and refuses token resoluti expect((await f.account.getState()).status).toBe('signed-out') }) +it.each(['user sign-out', 'rejected token'] as const)('withdraws released request credentials at a %s, after its listeners ran', async (cause) => { + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) + await storeAccount(f) + const credential = await storedCredential(f) + const observed: boolean[] = [] + f.ctx.on('deepseek-account/signed-out', () => { observed.push(credential.revoked.aborted) }) + expect(credential.revoked.aborted).toBe(false) + if (cause === 'user sign-out') await f.account.signOut(clientMetadata()) + else await (await storedCredential(f)).reject() + expect(observed).toEqual([false]) + expect(credential.revoked.aborted).toBe(true) + // The next sign-in releases its credentials on a signal of its own. + await storeAccount(f) + const next = await storedCredential(f) + expect(next.revoked).not.toBe(credential.revoked) + expect(next.revoked.aborted).toBe(false) +}) + +it('withdraws released request credentials when a sign-out listener throws', async () => { + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) + await storeAccount(f) + const credential = await storedCredential(f) + f.ctx.on('deepseek-account/signed-out', () => { throw new Error('listener failed') }) + await expect(f.account.signOut(clientMetadata())).rejects.toThrow('listener failed') + expect(credential.revoked.aborted).toBe(true) +}) + +it('releases a withdrawn credential when sign-out completes while its token is being read', async () => { + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) + await storeAccount(f) + const original = f.ctx.credentials.readRecord.bind(f.ctx.credentials) + const reading = Promise.withResolvers() + const release = Promise.withResolvers() + const read = vi.spyOn(f.ctx.credentials, 'readRecord').mockImplementationOnce(async (requested) => { + const record = await original(requested) + reading.resolve(undefined) + await release.promise + return record + }) + try { + const pending = f.account.resolveRequestCredential(`${PRIVATE_INFERENCE}/v1/messages`) + await reading.promise + await f.account.signOut(clientMetadata()) + release.resolve(undefined) + // The token was read before the sign-out removed it, so the credential must not authenticate a request. + expect(await pending).toMatchObject({ value: 'test-platform-grant', revoked: { aborted: true } }) + } finally { read.mockRestore() } +}) + +it('keeps released request credentials when the account service is replaced', async () => { + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) + await storeAccount(f) + const credential = await storedCredential(f) + const replacement = await f.remount() + expect(credential.revoked.aborted).toBe(false) + // The replacement withdraws only the credentials it released itself. + const current = await replacement.resolveRequestCredential(`${PRIVATE_INFERENCE}/v1/messages`) + await replacement.signOut(clientMetadata()) + expect({ replaced: credential.revoked.aborted, current: current?.revoked.aborted }).toEqual({ replaced: false, current: true }) +}) + it('discards account details when sign-out races the Platform response', async () => { const f = await fixture() await storeAccount(f) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 00404c88c6..c8f1716276 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1051,7 +1051,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'async resolveRequestCredential(url: string): Promise', - description: 'Release the account credential for one request to `url` as the request carries it, together with its invalidation, which runs on the account service mounted when it is called. Host-only.', + description: 'Release the account credential for one request to `url` as the request carries it, together with its invalidation, which runs on the account service mounted when it is called, and the signal this service aborts when it signs out of that credential. Host-only.', parameters: [{ name: 'url', description: 'actual request destination or API base URL.' }], returns: 'the request credential, or undefined for other origins or a signed-out account.', }, @@ -5321,7 +5321,7 @@ export const EVENT_API: readonly EventApiEntry[] = [ mode: 'emit', signature: '\'deepseek-account/signed-out\'(): void', summary: 'Local grant removal has completed.', - description: 'Local grant removal has completed.', + description: 'Local grant removal has completed. After the listeners return, the `revoked` signal of that grant\'s request credentials aborts.', parameters: [], }, { @@ -5846,7 +5846,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'AccountRequestCredential', - declaration: 'export interface AccountRequestCredential {\n readonly headers: Readonly>;\n readonly value: string;\n reject(): Promise;\n}', + declaration: 'export interface AccountRequestCredential {\n readonly headers: Readonly>;\n readonly value: string;\n reject(): Promise;\n readonly revoked: AbortSignal;\n}', }, { name: 'AccountUpdate', @@ -8710,7 +8710,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'RouteCredentialGrant', - declaration: 'export interface RouteCredentialGrant {\n readonly headers: Readonly>;\n readonly value: string;\n reject?(): Promise;\n}', + declaration: 'export interface RouteCredentialGrant {\n readonly headers: Readonly>;\n readonly value: string;\n reject?(): Promise;\n readonly revoked?: AbortSignal;\n}', }, { name: 'RpcId', diff --git a/packages/llm/llm-deepseek-account/README.i18n.yaml b/packages/llm/llm-deepseek-account/README.i18n.yaml index 580d4e4d87..0b1592817f 100644 --- a/packages/llm/llm-deepseek-account/README.i18n.yaml +++ b/packages/llm/llm-deepseek-account/README.i18n.yaml @@ -15,11 +15,11 @@ en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 /deepseek-ai-dsh-llm-deepseek-account/use-this-package: - en: 3d952599a9b0bf85 - zh: 231c0331a7d217e3 + en: a6a05e40662f10ed + zh: eb19e4706ab10515 /deepseek-ai-dsh-llm-deepseek-account/understand-the-implementation: - en: 37319d3b3317b0cf - zh: 90362d4dff489e35 + en: d8253a04dce699e1 + zh: 264f36b1b96d0241 /deepseek-ai-dsh-llm-deepseek-account/further-exploration: en: 30a69b9c66d89580 zh: fcc026a6373c1bee @@ -39,8 +39,8 @@ en: 2ecaa7bbbdd638e9 zh: bb067520885d877b /deepseek-ai-dsh-llm-deepseek-account/known-limitations-and-deferred-work: - en: ee8b7ff23c806e18 - zh: bd26832c8d455012 + en: abf049d0c4c84f80 + zh: add1d6f237ca83ef /deepseek-ai-dsh-llm-deepseek-account/known-limitations-and-deferred-work/dev-note: en: 0525041e573e96b6 zh: b05ed8d852498e6b diff --git a/packages/llm/llm-deepseek-account/README.md b/packages/llm/llm-deepseek-account/README.md index 17322210bb..b534844f32 100644 --- a/packages/llm/llm-deepseek-account/README.md +++ b/packages/llm/llm-deepseek-account/README.md @@ -56,14 +56,14 @@ An offered model shows the badge its listing entry declares under `client_metada | `modelsMaxAgeMs` | `600,000` | Automatic refresh interval after first use, also used after failure; `0` refreshes on access only | | `modelOverrides` | `{}` | Field overrides by model id | -An account request HTTP 401 maps to `ACCOUNT_TOKEN_INVALID` independently of the response body. The account service removes the credential only if it still matches the request token. HTTP 403 and other failures do not clear the login. After `deepseek-account/signed-out`, this plugin cancels running Agents whose latest bound request used this route, keeping their inboxes; it publishes `deepseek-account/model-sign-in-required` for a request that fails with `ACCOUNT_SIGN_IN_REQUIRED`, and registers a running-task report with the account service so its sign-out confirmation knows about that work. +An account request HTTP 401 maps to `ACCOUNT_TOKEN_INVALID` independently of the response body. The account service removes the credential only if it still matches the request token. HTTP 403 and other failures do not clear the login. After `deepseek-account/signed-out`, this plugin cancels running Agents whose latest bound request used this route, keeping their inboxes; it publishes `deepseek-account/model-sign-in-required` for a request that fails with `ACCOUNT_SIGN_IN_REQUIRED`, and registers a running-task report with the account service so its sign-out confirmation knows about that work. A model request or file operation in flight when the account signs out ends with its credential's `revoked` signal and fails with `ACCOUNT_SIGN_IN_REQUIRED`; a listing request keeps its `modelsTimeoutMs` deadline. That request's failure callback cancels the same Agents, so a request that outlives this plugin, after the route was disabled mid-turn, still ends its turn with the signed-out cause. The settings namespace is the Cordis entry id, or the plugin name without an entry. Product profiles retain the official entry id `llm-deepseek` and use `llm-deepseek-account` for the account route. ## Understand the implementation -Account credential lookup and invalidation go through the account service's `resolveRequestCredential`; this plugin retains HTTP error classification and owns the sign-out policy over running Agents in [`account-tasks.ts`](src/account-tasks.ts). Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport, which the API-key route also uses; the cache lives in memory and is keyed by endpoint and a SHA-256 of the credential headers. +Account credential lookup and invalidation go through the account service's `resolveRequestCredential`; this plugin retains HTTP error classification and owns the sign-out policy over running Agents in [`account-tasks.ts`](src/account-tasks.ts). Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request; a model request in flight keeps its credential and failure callback until it ends, so both can run after disposal. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport, which the API-key route also uses; the cache lives in memory and is keyed by endpoint and a SHA-256 of the credential headers. A failed request the shared transport classifies as `QUOTA` is rewritten to `ACCOUNT_QUOTA` before it leaves this provider, covering an HTTP 402 response and an in-band SSE error alike. The shared transport and the `deepseek-official` route keep `QUOTA`, so the account route's top-up action never appears for an API-key or third-party failure. @@ -99,6 +99,7 @@ Credentials and catalog availability do not enter model input; the protocol tran - The listing's effort levels are ignored. - When the current version can serve no listed model, the account offers no models, and model selectors show their generic empty state rather than an upgrade prompt. - An override can set but not remove `systemPromptUpdate` and `toolUpdate` declarations. +- While this plugin is disabled, a task it started that still runs is not reported to the account's sign-out confirmation, and a sign-out ends it only through a model request in flight. A task that is executing a tool at that moment runs until its next model request, which fails because the route is no longer registered. ### Dev Note diff --git a/packages/llm/llm-deepseek-account/README.zh.md b/packages/llm/llm-deepseek-account/README.zh.md index 26d6694096..c0614c8907 100644 --- a/packages/llm/llm-deepseek-account/README.zh.md +++ b/packages/llm/llm-deepseek-account/README.zh.md @@ -56,14 +56,14 @@ kind: "package-reference" | `modelsMaxAgeMs` | `600,000` | 首次使用后的自动刷新间隔,失败后也按此间隔重试;`0` 表示只在访问时刷新 | | `modelOverrides` | `{}` | 按模型 id 的字段覆盖 | -账号请求的 HTTP 401 与响应正文无关:映射为 `ACCOUNT_TOKEN_INVALID`,并要求账号服务仅在当前 token 仍与请求所用 token 相同时清除凭据。403 和其他错误不会触发清除。`deepseek-account/signed-out` 之后,本插件取消最近一次绑定请求使用本路由的运行中 Agent 并保留其收件箱;请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败时发布 `deepseek-account/model-sign-in-required`,并向账号服务注册运行中任务报告,供其退登确认了解这些工作。 +账号请求的 HTTP 401 与响应正文无关:映射为 `ACCOUNT_TOKEN_INVALID`,并要求账号服务仅在当前 token 仍与请求所用 token 相同时清除凭据。403 和其他错误不会触发清除。`deepseek-account/signed-out` 之后,本插件取消最近一次绑定请求使用本路由的运行中 Agent 并保留其收件箱;请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败时发布 `deepseek-account/model-sign-in-required`,并向账号服务注册运行中任务报告,供其退登确认了解这些工作。账号退登时仍在途的模型请求或文件操作随其凭据的 `revoked` 信号结束,并以 `ACCOUNT_SIGN_IN_REQUIRED` 失败;列表请求仍只受 `modelsTimeoutMs` 期限约束。该请求的失败回调会取消同一批 Agent,因此比本插件存活更久的请求(路由在回合进行中被停用)仍会以退登原因结束其回合。 设置命名空间采用 Cordis entry id,没有 entry 时采用插件名。产品保留 official 的 `llm-deepseek` entry id,账号使用 `llm-deepseek-account`。 ## 理解实现 -账号凭据的读取与作废经由账号服务的 `resolveRequestCredential`;本插件保留 HTTP 错误分类,并在 [`account-tasks.ts`](src/account-tasks.ts) 中拥有针对运行中 Agent 的退登策略。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入目录和门控。列表请求、缓存和目录解析来自共享传输包,API key 路由也使用它们;缓存只在内存中,以端点和凭据请求头的 SHA-256 为键。 +账号凭据的读取与作废经由账号服务的 `resolveRequestCredential`;本插件保留 HTTP 错误分类,并在 [`account-tasks.ts`](src/account-tasks.ts) 中拥有针对运行中 Agent 的退登策略。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求;在途的模型请求会把它的凭据和失败回调保留到请求结束,因此二者可能在释放之后执行。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入目录和门控。列表请求、缓存和目录解析来自共享传输包,API key 路由也使用它们;缓存只在内存中,以端点和凭据请求头的 SHA-256 为键。 共享传输判定为 `QUOTA` 的失败请求离开本提供方前会被改写为 `ACCOUNT_QUOTA`,HTTP 402 响应与流内 SSE 错误都适用。共享传输与 `deepseek-official` 路由保留 `QUOTA`,因此账号路由的充值操作不会出现在 API Key 或第三方失败上。 @@ -99,6 +99,7 @@ kind: "package-reference" - 列表中的推理档位被忽略。 - 当前版本能用的已列出模型一个都没有时,账号不提供任何模型,模型选择器显示通用的空状态,而不是升级提示。 - 覆盖可以设置、但不能移除 `systemPromptUpdate` 与 `toolUpdate` 声明。 +- 本插件被停用期间,它此前启动且仍在运行的任务不会报告给账号的退登确认,退登也只能通过在途的模型请求结束该任务。此时正在执行工具的任务会运行到它的下一次模型请求,该请求因路由已不再注册而失败。 ### 开发备注 diff --git a/packages/llm/llm-deepseek-account/src/account-tasks.ts b/packages/llm/llm-deepseek-account/src/account-tasks.ts index 00843ce2be..e77b5d8617 100644 --- a/packages/llm/llm-deepseek-account/src/account-tasks.ts +++ b/packages/llm/llm-deepseek-account/src/account-tasks.ts @@ -9,11 +9,26 @@ function isRunningAccountTask(agent: Pick, provider return agent.status === 'running' && agent.session.requestContext()?.provider === provider } +/** + * End the running Agents whose latest request used the account route `provider`, keeping their inboxes. + * @param ctx - context whose optional Agent registry is read when this runs; without one nothing is cancelled. + * @param provider - the account route id. + */ +export function cancelAccountTasks(ctx: Context, provider: string): void { + for (const agent of ctx.get('agents')?.list() ?? []) { + if (isRunningAccountTask(agent, provider)) { + agent.cancel({ kind: 'hook', reason: 'deepseek-account/signed-out' }, { keepInbox: true }) + } + } +} + /** * Cancel signed-out account tasks, publish sign-in guidance for rejected * requests, and report running account work to the account service's * sign-out confirmation. Each listener attaches once the service it needs is - * mounted and detaches with this plugin. + * mounted and detaches with this plugin; a request that outlives the plugin + * ends its tasks through {@link cancelAccountTasks} when its credential is + * signed out. * @param ctx - account route plugin lifetime; Agents and the account service may attach later. * @param provider - the account route id this plugin registers. */ @@ -24,13 +39,7 @@ export function installAccountTaskCancellation(ctx: Context, provider: string): scope.emit('deepseek-account/model-sign-in-required') } }) - scope.on('deepseek-account/signed-out', () => { - for (const agent of scope.agents.list()) { - if (isRunningAccountTask(agent, provider)) { - agent.cancel({ kind: 'hook', reason: 'deepseek-account/signed-out' }, { keepInbox: true }) - } - } - }) + scope.on('deepseek-account/signed-out', () => { cancelAccountTasks(scope, provider) }) scope.inject(['deepseekAccount'], (reporting) => { reporting.effect(() => reporting.deepseekAccount.registerRunningTaskReport( () => reporting.agents.list().some(agent => isRunningAccountTask(agent, provider)), diff --git a/packages/llm/llm-deepseek-account/src/index.ts b/packages/llm/llm-deepseek-account/src/index.ts index e4d77e1e6e..d9ea06b2db 100644 --- a/packages/llm/llm-deepseek-account/src/index.ts +++ b/packages/llm/llm-deepseek-account/src/index.ts @@ -8,7 +8,7 @@ import { catalogModelInfo, createModelListingCache, refuseListedModel, registerDeepSeekProvider, resolveAdapterOptions, resolveListedCatalog, } from '@deepseek-ai/dsh-llm-deepseek' import type { DeepSeekRequestAuth, ListedCatalog, ListingView, ModelListing, ResolvedDeepSeekOptions } from '@deepseek-ai/dsh-llm-deepseek' -import { installAccountTaskCancellation } from './account-tasks.ts' +import { cancelAccountTasks, installAccountTaskCancellation } from './account-tasks.ts' import { Config, plainAccountOptions, resolveAccountOptions } from './config.ts' export { Config } from './config.ts' @@ -32,20 +32,34 @@ export function apply(ctx: Context, config: Config): void { /** The account credential released for one destination; absent without an allowed signed-in account or without the account service. */ const requestCredential = async (endpoint: string): Promise => await ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint) + /** The failure of a request whose account signed out before it finished: the code a request made after the sign-out fails with. */ + const signedOutMidRequest = (cause: unknown) => new LlmError( + 'The DeepSeek account signed out before this request finished. Sign in to DeepSeek to use the account provider.', + 'ACCOUNT_SIGN_IN_REQUIRED', + { cause }, + ) const resolveAuth = async (_connection: ResolvedDeepSeekOptions, endpoint: string): Promise => { const credential = await requestCredential(endpoint) if (credential === undefined) return undefined return { ...credential, onRequestError: async (error) => { - if (!(error instanceof LlmError)) return error - if (error.code === QUOTA_EXCEEDED_CODE) { - return new LlmError(error.message, ACCOUNT_QUOTA_EXCEEDED_CODE, { ...error.failure, cause: error }) + try { + // A sign-out ends the requests that carry its token, so it is the failure of any request that fails after it. + if (credential.revoked.aborted) return signedOutMidRequest(error) + if (!(error instanceof LlmError)) return error + if (error.code === QUOTA_EXCEEDED_CODE) { + return new LlmError(error.message, ACCOUNT_QUOTA_EXCEEDED_CODE, { ...error.failure, cause: error }) + } + if (error.failure.status !== 401) return error + const rejected = new LlmError(error.message, 'ACCOUNT_TOKEN_INVALID', { ...error.failure, cause: error }) + await credential.reject() + return rejected + } finally { + // A request can outlive this plugin and the sign-out listener it mounts. Once the credential it carried is + // signed out, by the user or by the rejection above, the request ends this route's tasks itself. + if (credential.revoked.aborted) cancelAccountTasks(ctx, PROVIDER) } - if (error.failure.status !== 401) return error - const rejected = new LlmError(error.message, 'ACCOUNT_TOKEN_INVALID', { ...error.failure, cause: error }) - await credential.reject() - return rejected }, } } diff --git a/packages/llm/llm-deepseek-account/tests/account-signout.spec.ts b/packages/llm/llm-deepseek-account/tests/account-signout.spec.ts new file mode 100644 index 0000000000..07f773d8dd --- /dev/null +++ b/packages/llm/llm-deepseek-account/tests/account-signout.spec.ts @@ -0,0 +1,148 @@ +/** A request the account route authenticated ends with the sign-out of its credential and ends the route's running tasks. */ +import { Context } from '@deepseek-ai/cordis' +import { BlockAssembler, LlmRuntime } from '@deepseek-ai/dsh-llm' +import { afterEach, expect, it, vi } from 'vitest' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' +import * as Account from '../src/index.ts' + +const contexts: Context[] = [] +afterEach(async () => { + for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() + vi.restoreAllMocks() +}) + +const SIGNED_OUT_CANCEL = [{ kind: 'hook', reason: 'deepseek-account/signed-out' }, { keepInbox: true }] +const SIGNED_OUT_FAILURE = { + code: 'ACCOUNT_SIGN_IN_REQUIRED', + message: 'The DeepSeek account signed out before this request finished. Sign in to DeepSeek to use the account provider.', +} + +/** + * Mount the runtime, an account whose sign-out the test drives, a registry holding one running account task and one + * running API-key task, and the account route. + * @param options.reject - observes a rejected token, as the account service does before it signs out. + * @param options.agents - false mounts no Agent registry, as a composition without Agents does. + */ +async function route(options: { reject?: (token: string) => void; agents?: boolean } = {}) { + const { reject } = options + const ctx = new Context() + contexts.push(ctx) + await ctx.plugin(LlmRuntime) + const signedOut = new AbortController() + const cancelAccountTask = vi.fn() + const cancelApiKeyTask = vi.fn() + if (options.agents !== false) { + ctx.provide('agents', { list: () => [ + { status: 'running', session: { requestContext: () => ({ provider: 'deepseek-account' }) }, cancel: cancelAccountTask }, + { status: 'running', session: { requestContext: () => ({ provider: 'deepseek-official' }) }, cancel: cancelApiKeyTask }, + ] } as never) + } + // The route registers its running-task report once Agents and the account service are both mounted. + ctx.provide('deepseekAccount', Object.assign( + accountStub({ token: () => 'account-token', signedOut: signedOut.signal, ...reject === undefined ? {} : { reject } }), + { registerRunningTaskReport: () => () => {} }, + )) + const plugin = ctx.plugin(Account) + await plugin + return { ctx, signedOut, cancelAccountTask, cancelApiKeyTask, plugin } +} + +/** Answer the Messages request through `messages`; the model listing fails fast, so the route serves its bundled catalog. */ +function upstream(messages: (signal: AbortSignal) => Promise) { + vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => { + const url = new URL(input instanceof Request ? input.url : input) + return url.pathname === '/models' ? Promise.resolve(new Response(null, { status: 404 })) : messages(init!.signal!) + }) +} + +/** Hold the Messages request open until its signal aborts, as an open provider response does. */ +function heldUpstream() { + const sent = Promise.withResolvers() + upstream((signal) => { + sent.resolve(signal) + return new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => { reject(signal.reason as Error) }, { once: true }) + }) + }) + return sent.promise +} + +/** Drive one streamed request through the runtime and return its terminal outcome. */ +async function finishOf(ctx: Context) { + const assembler = new BlockAssembler() + for await (const chunk of ctx.llm.stream({ provider: 'deepseek-account', model: 'deepseek-flash', messages: [] })) assembler.push(chunk) + return assembler.finish +} + +it.each([ + { route: 'mounted', unload: false }, + { route: 'unloaded', unload: true }, +])('ends an open request and the running account tasks when its credential is signed out while the route is $route', async ({ unload }) => { + const { ctx, signedOut, cancelAccountTask, cancelApiKeyTask, plugin } = await route() + const sent = heldUpstream() + const finish = finishOf(ctx) + const request = await sent + if (unload) await plugin.dispose() + expect(request.aborted).toBe(false) + // The account service runs the sign-out listeners first; an unloaded route has none left. + ctx.emit('deepseek-account/signed-out') + expect(cancelAccountTask.mock.calls).toEqual(unload ? [] : [SIGNED_OUT_CANCEL]) + signedOut.abort() + expect(request.aborted).toBe(true) + await expect(finish).resolves.toMatchObject({ kind: 'error', failure: SIGNED_OUT_FAILURE }) + // The request that carried the signed-out token ends the tasks itself; a task cancelled twice keeps its first cause. + expect(cancelAccountTask.mock.calls).toEqual(unload ? [SIGNED_OUT_CANCEL] : [SIGNED_OUT_CANCEL, SIGNED_OUT_CANCEL]) + expect(cancelApiKeyTask).not.toHaveBeenCalled() +}) + +it('ends an open request at sign-out in a composition without Agents, which has no task to end', async () => { + const { ctx, signedOut } = await route({ agents: false }) + const sent = heldUpstream() + const finish = finishOf(ctx) + const request = await sent + signedOut.abort() + await expect(finish).resolves.toMatchObject({ kind: 'error', failure: SIGNED_OUT_FAILURE }) + expect(request.aborted).toBe(true) +}) + +it('does not send a request whose credential was signed out before dispatch', async () => { + const { ctx, signedOut, cancelAccountTask } = await route() + const messages = vi.fn(() => Promise.resolve(new Response(null, { status: 500 }))) + upstream(messages) + signedOut.abort() + await expect(finishOf(ctx)).resolves.toMatchObject({ kind: 'error', failure: SIGNED_OUT_FAILURE }) + expect(messages).not.toHaveBeenCalled() + expect(cancelAccountTask.mock.calls).toEqual([SIGNED_OUT_CANCEL]) +}) + +it('reports a provider failure that arrives after the sign-out as the sign-out, without rejecting the token', async () => { + const rejectToken = vi.fn() + const { ctx, signedOut, cancelAccountTask } = await route({ reject: rejectToken }) + upstream(() => { + signedOut.abort() + return Promise.resolve(new Response('Unauthorized', { status: 401 })) + }) + await expect(finishOf(ctx)).resolves.toMatchObject({ kind: 'error', failure: SIGNED_OUT_FAILURE }) + expect(rejectToken).not.toHaveBeenCalled() + expect(cancelAccountTask.mock.calls).toEqual([SIGNED_OUT_CANCEL]) +}) + +it('ends the running account tasks when the rejection of its token signs the account out', async () => { + const signOut: Array<() => void> = [] + const { ctx, signedOut, cancelAccountTask, cancelApiKeyTask } = await route({ reject: () => { for (const run of signOut) run() } }) + signOut.push(() => { signedOut.abort() }) + upstream(() => Promise.resolve(new Response('Unauthorized', { status: 401 }))) + await expect(finishOf(ctx)).resolves.toMatchObject({ kind: 'error', failure: { code: 'ACCOUNT_TOKEN_INVALID' } }) + expect(cancelAccountTask.mock.calls).toEqual([SIGNED_OUT_CANCEL]) + expect(cancelApiKeyTask).not.toHaveBeenCalled() +}) + +it.each([ + { failure: 'a provider error', status: 500, code: 'SERVER' }, + { failure: 'a rejected token whose removal did not sign out', status: 401, code: 'ACCOUNT_TOKEN_INVALID' }, +])('leaves running tasks alone after $failure while the account stays signed in', async ({ status, code }) => { + const { ctx, cancelAccountTask } = await route() + upstream(() => Promise.resolve(new Response('failed', { status }))) + await expect(finishOf(ctx)).resolves.toMatchObject({ kind: 'error', failure: { code } }) + expect(cancelAccountTask).not.toHaveBeenCalled() +}) diff --git a/packages/llm/llm-deepseek-api-key/README.i18n.yaml b/packages/llm/llm-deepseek-api-key/README.i18n.yaml index f1bae2778c..b88b876c62 100644 --- a/packages/llm/llm-deepseek-api-key/README.i18n.yaml +++ b/packages/llm/llm-deepseek-api-key/README.i18n.yaml @@ -9,14 +9,14 @@ en: b6871195e386cc64 zh: 742b05a3ca80883c /deepseek-ai-dsh-llm-deepseek-api-key/summary: - en: ea0a35b73d3b8f2c - zh: 7e404ed4617c2789 + en: 735e39ebfef73dcb + zh: 42036db3ae53de0f /deepseek-ai-dsh-llm-deepseek-api-key/table-of-contents: en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 /deepseek-ai-dsh-llm-deepseek-api-key/use-this-package: - en: 78c395041b12b9cc - zh: 289f789926a0fe43 + en: f342f3bba7246464 + zh: 8073e5bf0c760fc6 /deepseek-ai-dsh-llm-deepseek-api-key/understand-the-implementation: en: 2fe0f32c15603cd9 zh: 984ce05b82e8e679 diff --git a/packages/llm/llm-deepseek-api-key/README.md b/packages/llm/llm-deepseek-api-key/README.md index d387b0b36b..a4cb98c257 100644 --- a/packages/llm/llm-deepseek-api-key/README.md +++ b/packages/llm/llm-deepseek-api-key/README.md @@ -11,7 +11,7 @@ English | [中文](README.zh.md) Register authentication, model discovery, and the official model listing for `deepseek-official`. This plugin shares the [Messages transport](../llm-deepseek/README.md) and owns credential resolution, catalog availability, and model admission. -Authentication resolution returns the validated API key in `x-api-key` for Messages, Files, and listing requests, and publishes the same key through `ctx.llm.routeCredential('deepseek-official')` with the route's base URL and `apiKeyEnv` reference, so the DeepSeek web providers send it as a bearer token to the same deployment. The published credential releases the key only for destinations under the origin of that base URL: for another origin, or a URL that embeds credentials, `configured()` answers false and `resolve()` releases nothing, and neither reads the credential store. +Authentication resolution returns the validated API key in `x-api-key` for Messages, Files, and listing requests, and publishes the same key through `ctx.llm.routeCredential('deepseek-official')` with the route's base URL and `apiKeyEnv` reference, so the DeepSeek web providers send it as a bearer token to the same deployment. The published credential releases the key only for destinations under the origin of that base URL. ## Table of Contents @@ -35,7 +35,7 @@ Authentication resolution returns the validated API key in `x-api-key` for Messa apiKeyEnv: DEEPSEEK_API_KEY ``` -The endpoint and credential reference come from one configuration resolution. In-flight requests retain that snapshot; subsequent updates affect subsequent calls. Account login state cannot change this route’s credential. +The endpoint and credential reference come from one configuration resolution. In-flight requests retain that snapshot; subsequent updates affect subsequent calls. Account login state cannot change this route’s credential. For a destination at another origin, or a URL that embeds credentials, the published credential's `configured()` answers false and its `resolve()` releases nothing, and neither reads the credential store. `models` is an independently configurable catalog for this provider; defaults and protocol capabilities come from the shared transport. While `models` equals the built-in catalog and the Messages origin is the official API, `https://api.deepseek.com`, the route serves the official `GET https://api.deepseek.com/models` listing instead. Listing requests carry the API key in `x-api-key` and the harness `User-Agent`, and reject redirects; without an API key the route requests nothing. Any other endpoint, including one named by `baseURL` or `$DEEPSEEK_BASE_URL`, serves `models` and requests no listing. Discovery does not probe inference endpoints. diff --git a/packages/llm/llm-deepseek-api-key/README.zh.md b/packages/llm/llm-deepseek-api-key/README.zh.md index b0f724fe8a..f47bbed9cc 100644 --- a/packages/llm/llm-deepseek-api-key/README.zh.md +++ b/packages/llm/llm-deepseek-api-key/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" 为 `deepseek-official` 注册鉴权、模型发现和官方模型列表。通过 [llm-deepseek](../llm-deepseek/README.zh.md) 共用 Messages 请求实现;本包拥有凭据解析、目录可用性判断和模型准入。 -鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages、Files 和列表请求使用,并通过 `ctx.llm.routeCredential('deepseek-official')` 连同路由的基础地址和 `apiKeyEnv` 引用发布同一密钥,使 DeepSeek Web 提供方以 Bearer 令牌把它发往同一部署。发布的凭据只对该基础地址所在 origin 下的目的地释放密钥:对其他 origin 或内嵌凭据的 URL,`configured()` 回答 false,`resolve()` 不释放任何内容,二者都不读取凭据存储。 +鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages、Files 和列表请求使用,并通过 `ctx.llm.routeCredential('deepseek-official')` 连同路由的基础地址和 `apiKeyEnv` 引用发布同一密钥,使 DeepSeek Web 提供方以 Bearer 令牌把它发往同一部署。发布的凭据只对该基础地址所在 origin 下的目的地释放密钥。 ## 目录 @@ -35,7 +35,7 @@ kind: "package-reference" apiKeyEnv: DEEPSEEK_API_KEY ``` -端点和凭据引用来自同一次配置解析;进行中的请求保留该快照,后续配置更新仅影响后续请求。账号登录态不影响该路由使用的凭据。 +端点和凭据引用来自同一次配置解析;进行中的请求保留该快照,后续配置更新仅影响后续请求。账号登录态不影响该路由使用的凭据。对其他 origin 的目的地或内嵌凭据的 URL,发布的凭据的 `configured()` 回答 false,`resolve()` 不释放任何内容,二者都不读取凭据存储。 `models` 是该 provider 独立的可配置目录;默认值和协议能力来自共享传输包。当 `models` 等于内置目录、且 Messages 的 origin 是官方 API `https://api.deepseek.com` 时,路由改为提供官方 `GET https://api.deepseek.com/models` 列表。列表请求用 `x-api-key` 携带 API key,带上 harness 的 `User-Agent`,并拒绝重定向;没有 API key 时不发任何请求。其他端点,包括由 `baseURL` 或 `$DEEPSEEK_BASE_URL` 指定的端点,提供 `models`,不请求列表。目录判断不探测推理端点。 diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index 47f19261a6..d5e9b834e9 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -27,8 +27,8 @@ en: 2a634ead5b47fe97 zh: 46f199ee79a8c5dc /deepseek-ai-dsh-llm-deepseek/use-this-package/account-credentials: - en: 98b9a8d297095e32 - zh: b8f8eb46038214cb + en: bcb58fd33f59dbf2 + zh: ceafdef88eb66b30 /deepseek-ai-dsh-llm-deepseek/use-this-package/streaming-with-thinking-and-images: en: 81bf213499f015ba zh: e9107ef322213e56 @@ -39,8 +39,8 @@ en: f13f24b504dcfb50 zh: 69b0ed9e2adf3394 /deepseek-ai-dsh-llm-deepseek/use-this-package/failures-and-recovery: - en: 63b17e204a764a7d - zh: dafcd75c80796d35 + en: 7c78ea559cef349b + zh: 242d690e3e461337 /deepseek-ai-dsh-llm-deepseek/understand-the-implementation: en: 1598ac8a8bb9b6bf zh: fdd089c5ae7722cd @@ -87,5 +87,5 @@ en: 05fe57d81d8d8202 zh: 61e85a6f610842dd /deepseek-ai-dsh-llm-deepseek/known-limitations-and-deferred-work/dev-note: - en: 267aab8281b59242 - zh: 491b454fe920a17e + en: ddc6cf85ac5d9520 + zh: f5dd039bb67ef8db diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 04404624b7..8ae1b83fec 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -91,7 +91,7 @@ Messages sends text, thinking, tool calls, and tool results as content blocks, r Messages and Files requests send account tokens as `x-dsh-auth-token` without a Bearer prefix; API keys use `x-api-key`. Neither credential mode follows redirects. The account route owns HTTP 401 classification and the account service the credential invalidation; the transport passes failures to the credential's callback. -Provider plugins own credentials through three adapter hooks. `resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: the headers the Messages, Files, and listing requests send, the bare value, and an optional failure callback, or `undefined` when none is configured. `missingCredential(connection, provider)` names the failure of a request without one; the default is `MISSING_CREDENTIAL`. `credential` publishes the route's credential kind, optional reference, and presence check through `ctx.llm.routeCredential(provider)` together with the route's base URL, so web providers call the same deployment with the same credential without reading provider configuration. The plugins read API keys through the [credential reference helpers](../../credentials/credentials/README.md) of `dsh-credentials` and account credentials through the [account service](../../account/deepseek-account/README.md); this transport reads neither. +Provider plugins own credentials through three adapter hooks. `resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: the headers the Messages, Files, and listing requests send, the bare value, an optional failure callback, and an optional `revoked` signal, or `undefined` when none is configured. The signal ends the model request and its file operations when the credential's owner withdraws it, and the failure callback names that end. `missingCredential(connection, provider)` names the failure of a request without one; the default is `MISSING_CREDENTIAL`. `credential` publishes the route's credential kind, optional reference, and presence check through `ctx.llm.routeCredential(provider)` together with the route's base URL, so web providers call the same deployment with the same credential without reading provider configuration. The plugins read API keys through the [credential reference helpers](../../credentials/credentials/README.md) of `dsh-credentials` and account credentials through the [account service](../../account/deepseek-account/README.md); this transport reads neither. ### Streaming with thinking and images @@ -119,7 +119,7 @@ Configuration accepts Messages only and has no `protocol` field. If resolution r Successful Files responses must contain valid JSON. JSON decoding failures from upload, list, retrieve, and delete throw `INVALID_RESPONSE` with the operation and HTTP status in the message, the status in `LlmError.failure`, and the original parser error as `cause`. Body-read transport and cancellation errors retain their identity. -Non-2xx responses fail with stable codes: `AUTH` (401/403), `QUOTA`, `RATE_LIMIT`, `CONTEXT_WINDOW_EXCEEDED`, `INVALID_REQUEST`, `SERVER`, and `HTTP_` otherwise; pre-response transport failures throw `TRANSPORT`, caller aborts throw `ABORTED`, and stream-idle expiry throws `TIMEOUT`. A request-extension field collision, or a rejected preparation from a directly supplied `prepareExtensions`, fails with `REQUEST_EXTENSION` and appends the cause chain to the message; a post-2xx acceptance failure is logged and the response still streams. A normalized-image rejection names every plausible attachment and its durable position when the provider does not identify a file id. Stale-file rejection removes every named mapping (or every mapping used by the attempt) in one upload-index update and permits one replacement model request. Protocol violations throw `STREAM_CLOSED` or `MALFORMED_RESPONSE`, and a terminal `stop` with no content blocks becomes `EMPTY_RESPONSE`, which the default retry policy retries. A request on the official route without an API key fails with `MISSING_CREDENTIAL`, and a malformed credential fails with `INVALID_CREDENTIAL` naming the reference to fix — never any part of the key. +Non-2xx responses fail with stable codes: `AUTH` (401/403), `QUOTA`, `RATE_LIMIT`, `CONTEXT_WINDOW_EXCEEDED`, `INVALID_REQUEST`, `SERVER`, and `HTTP_` otherwise; pre-response transport failures throw `TRANSPORT`, caller aborts throw `ABORTED`, and stream-idle expiry throws `TIMEOUT`. A request ended by its credential's `revoked` signal fails as the provider's failure callback names it, and as `TRANSPORT` without one. A request-extension field collision, or a rejected preparation from a directly supplied `prepareExtensions`, fails with `REQUEST_EXTENSION` and appends the cause chain to the message; a post-2xx acceptance failure is logged and the response still streams. A normalized-image rejection names every plausible attachment and its durable position when the provider does not identify a file id. Stale-file rejection removes every named mapping (or every mapping used by the attempt) in one upload-index update and permits one replacement model request. Protocol violations throw `STREAM_CLOSED` or `MALFORMED_RESPONSE`, and a terminal `stop` with no content blocks becomes `EMPTY_RESPONSE`, which the default retry policy retries. A request on the official route without an API key fails with `MISSING_CREDENTIAL`, and a malformed credential fails with `INVALID_CREDENTIAL` naming the reference to fix — never any part of the key. Provider plugins own catalog availability. While its API key resolves, the API-key route serves its configured `models`, or the official model listing while `models` is the built-in catalog on the official endpoint; the account route serves its account listing while signed in (see the [API-key](../llm-deepseek-api-key/README.md) and [account](../llm-deepseek-account/README.md) providers). The transport supplies the bundled catalog, the catalog-entry field schemas, and capability resolution, plus the listing machinery both routes share: `requestModelListing`, the credential-scoped `ModelListingCache` (owned by `createModelListingCache` for automatic refresh, notifications, and plugin cleanup), and `resolveListedCatalog` with its client-version gate, listed badges, and `refuseListedModel`; `catalogModelInfo` attaches a listed badge to the advertised entry. Badge text rejects controls, Unicode line separators, bidi controls, and strings made only of whitespace or default-ignorable characters; joined emoji remain valid. A provider may also supply `connect(signal)`, which resolves the connection for exact-model lookups and prepared calls after provider-owned work such as a catalog load, and `admit(connection, model)`, which refuses a model before network I/O. @@ -218,4 +218,4 @@ These limits define where the adapter stops and future work begins. They are cur None. -`deepseek-official` uses only its configured API-key reference; `deepseek-account` uses only the stored DSH grant for the account provider’s allowed inference origin. Both routes share the Messages transport with independently configured model and file settings. Missing or ineligible account credentials reject the request with a sign-in prompt; neither route falls back to the other. Chat and Files requests reject redirects. The account service owns sign-out cancellation using running Agents’ logged request contexts, including tool execution; the transport receives the existing request abort signal. +`deepseek-official` uses only its configured API-key reference; `deepseek-account` uses only the stored DSH grant for the account provider’s allowed inference origin. Both routes share the Messages transport with independently configured model and file settings. Missing or ineligible account credentials reject the request with a sign-in prompt; neither route falls back to the other. Chat and Files requests reject redirects. The account route plugin owns sign-out cancellation using running Agents’ logged request contexts, including tool execution; the transport receives the existing request abort signal and ends a request whose credential is withdrawn. diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index 142674331c..82209fba3f 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -91,7 +91,7 @@ Messages 以内容块发送文本、思考、工具调用和工具结果,以 ` Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 Bearer 前缀;API Key 使用 `x-api-key`。两种凭据模式均拒绝重定向。账号路由负责 HTTP 401 分类,账号服务负责凭据失效处理;传输层将错误交给凭据的回调。 -提供方插件通过三个适配器钩子拥有凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、裸凭据值以及可选的失败回调;未配置时返回 `undefined`。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。`credential` 通过 `ctx.llm.routeCredential(provider)` 发布路由的凭据种类、可选引用和存在性检查,并附带路由的基础地址,使 Web 提供方无需读取提供方配置即可用同一凭据调用同一部署。插件通过 `dsh-credentials` 的[凭据引用函数](../../credentials/credentials/README.zh.md)读取 API Key,通过[账号服务](../../account/deepseek-account/README.zh.md)读取账号凭据;本传输层两者都不读取。 +提供方插件通过三个适配器钩子拥有凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、裸凭据值、可选的失败回调以及可选的 `revoked` 信号;未配置时返回 `undefined`。凭据的所有者收回凭据时,该信号结束模型请求及其文件操作,失败回调为这次结束命名。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。`credential` 通过 `ctx.llm.routeCredential(provider)` 发布路由的凭据种类、可选引用和存在性检查,并附带路由的基础地址,使 Web 提供方无需读取提供方配置即可用同一凭据调用同一部署。插件通过 `dsh-credentials` 的[凭据引用函数](../../credentials/credentials/README.zh.md)读取 API Key,通过[账号服务](../../account/deepseek-account/README.zh.md)读取账号凭据;本传输层两者都不读取。 ### 带 thinking 与图片的流式调用 @@ -119,7 +119,7 @@ Files 模式通过 `maxRequestFilesBytes` 与 `maxImagesPerRequest` 限制保留 成功的 Files 响应必须包含有效 JSON。上传、列举、获取和删除操作的 JSON 解码失败抛出 `INVALID_RESPONSE`,消息包含操作名称与 HTTP 状态,`LlmError.failure` 保留该状态,`cause` 保留原始解析错误。读取响应体时的传输和取消错误保留其原有身份。 -非 2xx 响应以稳定 code 失败:`AUTH`(401/403)、`QUOTA`、`RATE_LIMIT`、`CONTEXT_WINDOW_EXCEEDED`、`INVALID_REQUEST`、`SERVER` 以及其他情况的 `HTTP_`;响应前传输失败抛出 `TRANSPORT`,调用方中止抛出 `ABORTED`,流空闲超时抛出 `TIMEOUT`。请求扩展字段冲突,或直接提供的 `prepareExtensions` 拒绝准备时,使用 `REQUEST_EXTENSION` 失败,并在消息中附上原因链;2xx 后接受失败只记录告警,响应仍会继续流式返回。当提供方未指出 file id 时,规范化图片拒绝会列出所有可能附件及其持久位置。陈旧文件拒绝会在一次上传索引更新中删除全部点名映射(或该次尝试使用的全部映射),并允许一次替换模型请求。协议违规抛出 `STREAM_CLOSED` 或 `MALFORMED_RESPONSE`;不带内容块的终止 `stop` 变成 `EMPTY_RESPONSE`,默认重试策略会重试它。官方路由缺少 API Key 的请求以 `MISSING_CREDENTIAL` 失败;格式错误的凭据以 `INVALID_CREDENTIAL` 失败,并点名需要修复的引用——绝不包含密钥的任何部分。 +非 2xx 响应以稳定 code 失败:`AUTH`(401/403)、`QUOTA`、`RATE_LIMIT`、`CONTEXT_WINDOW_EXCEEDED`、`INVALID_REQUEST`、`SERVER` 以及其他情况的 `HTTP_`;响应前传输失败抛出 `TRANSPORT`,调用方中止抛出 `ABORTED`,流空闲超时抛出 `TIMEOUT`。被凭据的 `revoked` 信号结束的请求按提供方失败回调命名的失败上报,没有回调时为 `TRANSPORT`。请求扩展字段冲突,或直接提供的 `prepareExtensions` 拒绝准备时,使用 `REQUEST_EXTENSION` 失败,并在消息中附上原因链;2xx 后接受失败只记录告警,响应仍会继续流式返回。当提供方未指出 file id 时,规范化图片拒绝会列出所有可能附件及其持久位置。陈旧文件拒绝会在一次上传索引更新中删除全部点名映射(或该次尝试使用的全部映射),并允许一次替换模型请求。协议违规抛出 `STREAM_CLOSED` 或 `MALFORMED_RESPONSE`;不带内容块的终止 `stop` 变成 `EMPTY_RESPONSE`,默认重试策略会重试它。官方路由缺少 API Key 的请求以 `MISSING_CREDENTIAL` 失败;格式错误的凭据以 `INVALID_CREDENTIAL` 失败,并点名需要修复的引用——绝不包含密钥的任何部分。 提供方插件负责目录可用性:API key 路由在能解析到 API key 时提供配置中的 `models`,在官方端点上且 `models` 为内置目录时改为提供官方模型列表;账号路由在登录时提供账号的模型列表(见 [API key](../llm-deepseek-api-key/README.zh.md) 与[账号](../llm-deepseek-account/README.zh.md)提供方)。传输层提供内置目录、目录条目字段的 schema 和能力解析,以及两条路由共用的列表机制:`requestModelListing`、按凭据区分的 `ModelListingCache`(由 `createModelListingCache` 持有,负责自动刷新、通知与插件清理),以及带客户端版本门控和列表角标的 `resolveListedCatalog` 与 `refuseListedModel`;`catalogModelInfo` 把列表角标附到公布的条目上。角标文字拒绝控制字符、Unicode 行分隔符、双向控制符及仅由空白或默认可忽略字符组成的字符串,组合 emoji 仍有效。提供方还可以提供 `connect(signal)`:在提供方自己的工作(例如加载目录)完成后,为精确模型查询和预备调用解析连接;以及 `admit(connection, model)`:在网络请求之前拒绝某个模型。 @@ -218,4 +218,4 @@ loop 保留的响应块会追加到下一个请求,并保留其更早的可复 无。 -`deepseek-official` 仅使用配置的 API Key 引用;`deepseek-account` 仅在账号提供方允许的推理来源使用已保存的 DSH 授权。两条路由共享 Messages 传输,模型与文件设置独立配置。账号凭证缺失或不适用于目标时拒绝请求并提示登录;两条路由均不回退到另一凭证。Chat 和 Files 请求拒绝重定向。账号提供方根据运行中 Agent 已记录的请求上下文负责退登取消,包括工具执行阶段;传输层接收现有请求的中止信号。 +`deepseek-official` 仅使用配置的 API Key 引用;`deepseek-account` 仅在账号提供方允许的推理来源使用已保存的 DSH 授权。两条路由共享 Messages 传输,模型与文件设置独立配置。账号凭证缺失或不适用于目标时拒绝请求并提示登录;两条路由均不回退到另一凭证。Chat 和 Files 请求拒绝重定向。账号路由插件根据运行中 Agent 已记录的请求上下文负责退登取消,包括工具执行阶段;传输层接收现有请求的中止信号,并结束凭据已被收回的请求。 diff --git a/packages/llm/llm-deepseek/package.json b/packages/llm/llm-deepseek/package.json index ca145eb85f..e86db5e922 100644 --- a/packages/llm/llm-deepseek/package.json +++ b/packages/llm/llm-deepseek/package.json @@ -59,6 +59,7 @@ "@deepseek-ai/dsh-atomic-write": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-attachment-local": "workspace:*", + "@deepseek-ai/dsh-authorization": "workspace:*", "@deepseek-ai/dsh-credentials": "workspace:*", "@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:*", "@deepseek-ai/dsh-fs": "workspace:*", diff --git a/packages/llm/llm-deepseek/src/adapter.ts b/packages/llm/llm-deepseek/src/adapter.ts index 8529f69988..5500aaa91b 100644 --- a/packages/llm/llm-deepseek/src/adapter.ts +++ b/packages/llm/llm-deepseek/src/adapter.ts @@ -64,7 +64,11 @@ export class DeepSeekAdapter extends LlmAdapt if (auth === undefined) return undefined // The adapter's failure classification stays behind the seam. const reject = auth.reject?.bind(auth) - return { headers: auth.headers, value: auth.value, ...reject === undefined ? {} : { reject } } + return { + headers: auth.headers, value: auth.value, + ...reject === undefined ? {} : { reject }, + ...auth.revoked === undefined ? {} : { revoked: auth.revoked }, + } }, } } @@ -123,14 +127,16 @@ export class DeepSeekAdapter extends LlmAdapt ) const auth = await this.dependencies.resolveAuth(connection, connection.baseURL) if (auth === undefined) throw this.missingCredential(connection, options.provider) + // The request ends with its credential: a withdrawal closes the upstream response as the caller's cancellation does. + const live = auth.revoked === undefined ? signal : AbortSignal.any([signal, auth.revoked]) try { const files = new RequestFiles(this.files, { baseURL: connection.baseURL, headers: auth.headers, }, - connection.filePolicy, connection.filesApiTimeoutMs, signal, activity) + connection.filePolicy, connection.filesApiTimeoutMs, live, activity) let inline = false while (true) { - signal.throwIfAborted() + live.throwIfAborted() files.beginAttempt() let fileIds: Awaited> | undefined if (!inline) { @@ -147,7 +153,7 @@ export class DeepSeekAdapter extends LlmAdapt this.dependencies.onReplayDegrade?.({ provider: options.provider, model: options.model, reason }) }, fileIds) const requestIdentity: Omit = { - signal, + signal: live, ...options.sessionId === undefined ? {} : { sessionId: String(options.sessionId) }, ...options.purpose === undefined ? {} : { purpose: options.purpose }, } @@ -159,7 +165,7 @@ export class DeepSeekAdapter extends LlmAdapt this.dependencies.onExtensionsUnaccepted?.({ provider: options.provider, model: options.model, error }) }, ) - signal.throwIfAborted() + live.throwIfAborted() const betas = [ ...fileIds !== undefined && fileIds.size > 0 ? [MESSAGES_FILES_BETA] : [], ...body.messages.some(message => message.content.some(block => block.type === 'tool_addition' || block.type === 'tool_removal')) @@ -167,7 +173,7 @@ export class DeepSeekAdapter extends LlmAdapt : [], ] const response = await fetch(`${messagesApiRoot(connection.baseURL)}/messages`, { - method: 'POST', signal, body: extensions.payload, redirect: 'error', + method: 'POST', signal: live, body: extensions.payload, redirect: 'error', headers: { ...attributionHeaders(), 'content-type': 'application/json', 'accept': 'text/event-stream', diff --git a/packages/llm/llm-deepseek/src/types.ts b/packages/llm/llm-deepseek/src/types.ts index 60444fc85e..7b37ff1616 100644 --- a/packages/llm/llm-deepseek/src/types.ts +++ b/packages/llm/llm-deepseek/src/types.ts @@ -87,10 +87,14 @@ export interface DeepSeekConnectionOptions { /** * Authentication released for one request and its file operations: the route * credential grant the provider plugin builds, plus the request-failure - * classification bound to that credential. + * classification bound to that credential. The grant's `revoked` signal ends + * the request and its file operations as the caller's cancellation does. */ export interface DeepSeekRequestAuth extends RouteCredentialGrant { - /** Classify a failure using the captured credential; callback failure preserves the original error. */ + /** + * Classify a failure using the captured credential; callback failure preserves the original error. The end a + * withdrawn credential causes arrives here too, for the provider plugin to name. + */ onRequestError?: (error: unknown) => Promise } @@ -143,8 +147,8 @@ export interface DeepSeekAdapterOptions LlmError /** - * Publish the route's credential through `routeCredential()`, whose `resolve` forwards the headers, value, and - * rejection of {@link resolveAuth} without its failure classification; omission publishes none. + * Publish the route's credential through `routeCredential()`, whose `resolve` forwards the headers, value, + * rejection, and withdrawal signal of {@link resolveAuth} without its failure classification; omission publishes none. */ credential?: DeepSeekRouteCredentialOptions /** Resolve the harness-home anonymous id shared with telemetry and feedback. */ diff --git a/packages/llm/llm-deepseek/tests/account-signout-composition.spec.ts b/packages/llm/llm-deepseek/tests/account-signout-composition.spec.ts new file mode 100644 index 0000000000..469cd3be6d --- /dev/null +++ b/packages/llm/llm-deepseek/tests/account-signout-composition.spec.ts @@ -0,0 +1,190 @@ +/** + * Real Loader composition of the account service, the account route, and the Agent loop against a loopback DeepSeek + * stand-in: a sign-out ends the requests that carry its token, whether or not their route is still mounted. + */ +import { once } from 'node:events' +import { createServer } from 'node:http' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { afterEach, expect, it, vi } from 'vitest' +import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native' +import { Context } from '@deepseek-ai/cordis' +import Include from '@deepseek-ai/cordis-plugin-include' +import Loader from '@deepseek-ai/cordis-plugin-loader' +import AgentRegistry from '@deepseek-ai/dsh-agent' +import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import AuthorizationService from '@deepseek-ai/dsh-authorization' +import { brandString } from '@deepseek-ai/dsh-brand' +import { credentialKey } from '@deepseek-ai/dsh-credentials' +import LocalCredentials from '@deepseek-ai/dsh-credentials-local' +import DeepSeekAccount, { type AccountClientMetadata } from '@deepseek-ai/dsh-deepseek-account' +import LlmRuntime, { type StreamChunk } from '@deepseek-ai/dsh-llm' +import * as AccountRoute from '@deepseek-ai/dsh-llm-deepseek-account' +import SessionStore, { type SessionId } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRuntime from '@deepseek-ai/dsh-tools' +import { profileComposition } from '../../../settings/settings/tests/profile-composition.ts' +import { sourceModuleLoader, sse, start, user } from './helpers.ts' + +const PROVIDER = 'deepseek-account' +const MODEL = 'deepseek-flash' +const CLIENT: AccountClientMetadata = { version: '1.2.3', locale: 'en', timezoneOffsetSeconds: 28_800 } +const SIGNED_OUT = { kind: 'aborted', reason: { kind: 'hook', reason: 'deepseek-account/signed-out' } } + +const cleanup: Array<() => Promise> = [] +afterEach(async () => { + while (cleanup.length) await cleanup.pop()!() + vi.unstubAllEnvs() +}) + +/** One open Messages response of the stand-in. */ +interface OpenResponse { + /** Text deltas written so far. */ + deltas: number + /** Settles when the client closes the response. */ + closed: Promise +} + +/** Loopback DeepSeek stand-in: the account listing, the logout call, and Messages responses that stream until closed. */ +async function upstream() { + const responses: OpenResponse[] = [] + const http = createServer((request, response) => { + request.resume() + request.once('end', () => { + if (request.method === 'GET' && request.url === '/models') { + response.setHeader('content-type', 'application/json') + response.end(JSON.stringify({ data: [{ + id: MODEL, name: 'DeepSeek-V4.1-Flash', context_window: 1_048_576, max_output_tokens: 100_000, + input_modalities: ['text'], output_modalities: ['text'], api_capabilities: { anthropic_messages: {} }, + }] })) + return + } + if (request.url === '/auth-api/v0/users/logout') { + response.setHeader('content-type', 'application/json') + response.end(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: null } })) + return + } + if (request.url !== '/anthropic/v1/messages') { response.writeHead(404).end('{}'); return } + const closed = Promise.withResolvers() + const open: OpenResponse = { deltas: 0, closed: closed.promise } + responses.push(open) + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.write(sse([start, { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }])) + const timer = setInterval(() => { + response.write(sse([{ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'x' } }])) + open.deltas += 1 + }, 10) + response.once('close', () => { clearInterval(timer); closed.resolve(undefined) }) + }) + }) + http.listen(0, '127.0.0.1') + await once(http, 'listening') + const address = http.address() + if (address === null || typeof address === 'string') throw new Error('missing loopback port') + cleanup.push(async () => { + http.closeAllConnections() + await new Promise((resolve) => { http.close(() => { resolve() }) }) + }) + /** The first Messages response once it has streamed `count` more deltas. */ + const streaming = async (count: number): Promise => { + const from = responses[0]?.deltas ?? 0 + await vi.waitFor(() => { expect(responses[0]?.deltas).toBeGreaterThanOrEqual(from + count) }, { timeout: 10_000, interval: 5 }) + return responses[0]! + } + return { origin: `http://127.0.0.1:${String(address.port)}`, streaming } +} + +/** Boot the profile through the Loader with a signed-in account whose inference origin is the stand-in. */ +async function boot(origin: string) { + const home = await mkdtemp(join(tmpdir(), 'dsh-account-signout-')) + cleanup.push(() => rm(home, { recursive: true, force: true })) + vi.stubEnv('DSH_HOME', home) + vi.stubEnv('DEEPSEEK_BASE_URL', '') + const ctx = new Context() + cleanup.push(() => ctx.fiber.dispose()) + const modules = new Map([ + ['@deepseek-ai/dsh-llm', { module: LlmRuntime }], ['@deepseek-ai/dsh-session', { module: SessionStore }], + ['@deepseek-ai/dsh-session-projection', { module: SessionProjectionRegistry }], ['@deepseek-ai/dsh-system-prompt', { module: SystemPrompt }], + ['@deepseek-ai/dsh-tools', { module: ToolRuntime }], ['@deepseek-ai/dsh-tool-executor-native', { module: NativeToolExecutor }], + ['@deepseek-ai/dsh-agent', { module: AgentRegistry }], ['@deepseek-ai/dsh-agent-loop', { module: AgentLoop, config: { agents: [] } }], + ['@deepseek-ai/dsh-credentials-local', { module: LocalCredentials, config: { path: join(home, '.credentials.yaml'), watch: false } }], + ['@deepseek-ai/dsh-authorization', { module: AuthorizationService }], + ['@deepseek-ai/dsh-deepseek-account', { module: DeepSeekAccount, config: { + platformOrigin: origin, inferenceOrigin: origin, allowLoopbackHttp: true, logoutRetryDelayMs: 1, + } }], + ['@deepseek-ai/dsh-llm-deepseek-account', { module: AccountRoute, config: { baseURL: `${origin}/anthropic` } }], + ]) + await writeFile(join(home, 'cordis.yml'), JSON.stringify( + [...modules].map(([name, { config }]) => ({ name, ...config === undefined ? {} : { config } })), + )) + // The importer supplies source modules while Loader still owns configuration and effects. + for (const name of modules.keys()) { + const directory = join(home, 'node_modules', name) + await mkdir(directory, { recursive: true }) + await writeFile(join(directory, 'package.json'), JSON.stringify({ name, version: '0.1.3-alpha.1', type: 'module' })) + } + ctx.baseUrl = pathToFileURL(home).href + '/' + await ctx.plugin(Loader) + ctx.loader.builtins.include = Include + ctx.loader.internal = sourceModuleLoader(async (name) => { + const found = modules.get(name) + if (found === undefined) throw new Error(`unexpected module ${name}`) + return found.module + }) + const patchPath = await profileComposition(ctx, home, join(home, 'cordis.yml')) + await ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ + kind: 'grant', payload: { version: 1, issuer: origin, token: 'test-platform-grant' }, + })) + /** Switch the account route off through the profile patch, as the plugin switch does. */ + const disableRoute = async (): Promise => { + await writeFile(patchPath, '- id: llm-deepseek-account\n disabled: true\n') + await ctx.hmr.runExclusive(() => ctx.hmr.reconcileProfile()) + } + return { ctx, disableRoute } +} + +const routeListed = (ctx: Context): boolean => ctx.llm.listProviders().some(provider => provider.id === PROVIDER) + +it.each([ + { route: 'mounted', disable: false }, + { route: 'disabled', disable: true }, +])('ends a streaming account turn at sign-out with the signed-out cause while its route is $route', async ({ disable }) => { + const http = await upstream() + const { ctx, disableRoute } = await boot(http.origin) + const agent = await ctx.agentLoop.create(brandString(`signout-${String(disable)}`), { provider: PROVIDER, model: MODEL }) + agent.followup(user()) + await http.streaming(2) + if (disable) { + // Disabling returns while the turn runs, and neither stops the turn nor closes its response. + await disableRoute() + expect(routeListed(ctx)).toBe(false) + await http.streaming(2) + expect(agent.status).toBe('running') + } + const response = await http.streaming(0) + await ctx.deepseekAccount.signOut(CLIENT) + await agent.whenIdle() + await response.closed + const end = agent.session.snapshotEvents().at(-1) + expect({ type: end?.type, reason: (end?.data as { reason?: unknown }).reason }).toEqual({ type: 'turn/end', reason: SIGNED_OUT }) +}) + +it('ends an account model request outside an Agent turn at sign-out, as a sign-in failure', async () => { + const http = await upstream() + const { ctx } = await boot(http.origin) + const chunks: StreamChunk[] = [] + const consumed = (async () => { + for await (const chunk of ctx.llm.stream({ provider: PROVIDER, model: MODEL, messages: [user()] })) chunks.push(chunk) + })() + const response = await http.streaming(2) + await ctx.deepseekAccount.signOut(CLIENT) + await consumed + await response.closed + expect(chunks.at(-1)).toMatchObject({ type: 'finish', reason: { kind: 'error', failure: { + code: 'ACCOUNT_SIGN_IN_REQUIRED', + message: 'The DeepSeek account signed out before this request finished. Sign in to DeepSeek to use the account provider.', + } } }) +}) diff --git a/packages/llm/llm-deepseek/tests/adapter.spec.ts b/packages/llm/llm-deepseek/tests/adapter.spec.ts index 767e8f24d9..7665bed167 100644 --- a/packages/llm/llm-deepseek/tests/adapter.spec.ts +++ b/packages/llm/llm-deepseek/tests/adapter.spec.ts @@ -19,7 +19,7 @@ import { brandString } from '@deepseek-ai/dsh-brand' import type { AttachmentId } from '@deepseek-ai/dsh-attachment/types' import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' -import LlmRuntime, { createAssistantMessage, createDeveloperMessage, createSystemMessage, createToolResultMessage, createUserMessage, type ToolCallId } from '@deepseek-ai/dsh-llm' +import LlmRuntime, { createAssistantMessage, createDeveloperMessage, createSystemMessage, createToolResultMessage, createUserMessage, LlmError, type ToolCallId } from '@deepseek-ai/dsh-llm' import type { Message } from '@deepseek-ai/dsh-llm' import { credentialRef } from '@deepseek-ai/dsh-credentials' import LocalCredentials from '@deepseek-ai/dsh-credentials-local' @@ -240,6 +240,35 @@ describe('direct Messages HTTP', () => { await stopped }) + it('ends an open provider response when its credential is withdrawn and lets the provider name the failure', async () => { + const stopped = Promise.withResolvers() + const http = await endpoint((response) => { + response.once('close', () => { stopped.resolve(undefined) }) + response.write(sse(textEvents.slice(0, 3))) + }) + const withdrawn = new AbortController() + const onRequestError = vi.fn(async (error: unknown) => new LlmError('credential withdrawn', 'ACCOUNT_SIGN_IN_REQUIRED', { cause: error })) + const stream = adapter({ baseURL: http.url }, { + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' }, value: 'test-key', revoked: withdrawn.signal, onRequestError }), + }).stream(options())[Symbol.asyncIterator]() + expect((await stream.next()).value).toMatchObject({ type: 'block-start' }) + expect((await stream.next()).value).toMatchObject({ type: 'text-delta' }) + const failed = expect(stream.next()).rejects.toMatchObject({ code: 'ACCOUNT_SIGN_IN_REQUIRED', message: 'credential withdrawn' }) + withdrawn.abort() + await failed + await stopped.promise + expect(onRequestError).toHaveBeenCalledExactlyOnceWith(withdrawn.signal.reason) + }) + + it('reports a withdrawal the provider does not name as a transport failure, without contacting the provider', async () => { + const http = await endpoint() + const llm = adapter({ baseURL: http.url }, { + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' }, value: 'test-key', revoked: AbortSignal.abort() }), + }) + await expect(chunks(llm.stream(options()))).rejects.toMatchObject({ code: 'TRANSPORT' }) + expect(http.requests).toEqual([]) + }) + it('times out an idle HTTP response and closes the connection', async () => { const stopped = Promise.withResolvers() const http = await endpoint((response) => { diff --git a/packages/llm/llm-deepseek/tests/files.spec.ts b/packages/llm/llm-deepseek/tests/files.spec.ts index f6e5b79fb8..032cdf1299 100644 --- a/packages/llm/llm-deepseek/tests/files.spec.ts +++ b/packages/llm/llm-deepseek/tests/files.spec.ts @@ -28,7 +28,7 @@ function body(init: RequestInit | undefined): string { return init.body } const rejected = (message: string, status = 400) => new Response(JSON.stringify({ error: { type: 'invalid_request_error', message } }), { status }) -function harness(config: Config = {}) { +function harness(config: Config = {}, revoked?: AbortSignal) { const ensureUploaded = vi.fn(async image => ({ record: { fileId: brandString(image.attachment.attachmentId === ref.attachmentId ? 'file-a' : 'file-b') }, uploaded: false, } as Awaited>)) @@ -40,7 +40,8 @@ function harness(config: Config = {}) { const prepare = vi.fn(prepareExtensions) const adapter = new DeepSeekAdapter({ options: () => resolveAdapterOptions(Object.assign({ baseURL: 'https://gateway.example/custom' }, config)), - resolveAuth: async () => ({ headers: { 'x-api-key': 'test-key' }, value: 'test-key' }), resolveUserId: () => 'test-user' as AnonymousUserId, resolveAttachments: () => attachments, + resolveAuth: async () => ({ headers: { 'x-api-key': 'test-key' }, value: 'test-key', ...revoked === undefined ? {} : { revoked } }), + resolveUserId: () => 'test-user' as AnonymousUserId, resolveAttachments: () => attachments, resolveImageAccess: () => ({ readonlyPath: '/workspace/image.png' }), resolveFiles: () => files, prepareExtensions: prepare, }) return { adapter, ensureUploaded, invalidate, readImageRequest, prepare } @@ -208,6 +209,23 @@ describe('Messages Files requests', () => { expect(fetchImpl).toHaveBeenCalledTimes(1) }) + it('ends a pending upload with its withdrawn credential and sends no request', async () => { + const fetchImpl = vi.fn(async () => success()) + vi.stubGlobal('fetch', fetchImpl) + const withdrawn = new AbortController() + const h = harness({}, withdrawn.signal) + const uploading = Promise.withResolvers() + h.ensureUploaded.mockImplementation(async (_version, _connection, _policy, signal) => new Promise((_resolve, reject) => { + signal!.addEventListener('abort', () => { reject(new Error('upload aborted', { cause: signal!.reason })) }, { once: true }) + uploading.resolve(undefined) + })) + const result = expect(chunks(h.adapter.stream(request()))).rejects.toMatchObject({ code: 'TRANSPORT' }) + await uploading.promise + withdrawn.abort() + await result + expect(fetchImpl).not.toHaveBeenCalled() + }) + it('classifies Files recovery only from provider error fields', () => { expect(providerErrorDetail({ extra: 'file-a expired', error: { message: 'invalid request' } })).toBe('invalid request') expect(providerErrorDetail({ error: { code: 'file_not_found', type: 'invalid_request_error', message: 'missing' } })).toBe('file_not_found invalid_request_error missing') diff --git a/packages/llm/llm-deepseek/tests/route-credential.spec.ts b/packages/llm/llm-deepseek/tests/route-credential.spec.ts index 404927a098..3314455d4e 100644 --- a/packages/llm/llm-deepseek/tests/route-credential.spec.ts +++ b/packages/llm/llm-deepseek/tests/route-credential.spec.ts @@ -53,8 +53,9 @@ it('publishes no credential for a provider that declares none', async () => { it('publishes the declared credential from one configuration generation and resolves it per endpoint', async () => { const reject = vi.fn(() => Promise.resolve()) + const revoked = new AbortController().signal const resolveAuth = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string): Promise => - endpoint === ALLOWED ? { headers: { 'x-fixture': 'k' }, value: 'k', reject, onRequestError: error => Promise.resolve(error) } : undefined) + endpoint === ALLOWED ? { headers: { 'x-fixture': 'k' }, value: 'k', reject, revoked, onRequestError: error => Promise.resolve(error) } : undefined) const configured = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string) => endpoint === ALLOWED) const ctx = await route({ resolveAuth, credential: { kind: 'api-key', reference: () => 'FIXTURE_KEY', configured } }) const credential = ctx.llm.routeCredential('fixture-route') @@ -63,8 +64,9 @@ it('publishes the declared credential from one configuration generation and reso await expect(credential!.configured(OTHER)).resolves.toBe(false) // The grant carries the seam's fields only; the adapter's failure classification stays behind it. const grant = await credential!.resolve(ALLOWED) - expect(Object.keys(grant!)).toEqual(['headers', 'value', 'reject']) + expect(Object.keys(grant!)).toEqual(['headers', 'value', 'reject', 'revoked']) expect(grant).toMatchObject({ headers: { 'x-fixture': 'k' }, value: 'k' }) + expect(grant!.revoked).toBe(revoked) await grant!.reject!() expect(reject).toHaveBeenCalledTimes(1) await expect(credential!.resolve(OTHER)).resolves.toBeUndefined() @@ -73,7 +75,7 @@ it('publishes the declared credential from one configuration generation and reso expect(configured.mock.calls.map(([{ baseURL }]) => baseURL)).toEqual([BASE_URL, BASE_URL]) }) -it('omits the reference of a credential kind without one and the rejection of a grant without one', async () => { +it('omits the reference of a credential kind without one and the rejection and withdrawal of a grant without them', async () => { const ctx = await route({ resolveAuth: () => Promise.resolve({ headers: { 'x-fixture': 'k' }, value: 'k' }), credential: { kind: 'account', configured: () => Promise.resolve(false) }, diff --git a/packages/llm/llm/src/types.ts b/packages/llm/llm/src/types.ts index 33c924aefd..60b576c1aa 100644 --- a/packages/llm/llm/src/types.ts +++ b/packages/llm/llm/src/types.ts @@ -330,6 +330,13 @@ export interface RouteCredentialGrant { * @returns settlement after the invalidation attempt. */ reject?(): Promise + /** + * Aborts when the owner withdraws this credential while requests carrying it + * may be in flight, as an account sign-out does. A consumer ends each request + * it authenticated with this grant and reports that end as its own failure, + * not as the caller's cancellation. Absent for kinds that are never withdrawn. + */ + readonly revoked?: AbortSignal } /** diff --git a/packages/web/web-deepseek-api/README.i18n.yaml b/packages/web/web-deepseek-api/README.i18n.yaml index 67b48ecaed..db6f262828 100644 --- a/packages/web/web-deepseek-api/README.i18n.yaml +++ b/packages/web/web-deepseek-api/README.i18n.yaml @@ -21,8 +21,8 @@ en: 8923728d77eb1256 zh: 85d1b8408cf1f325 /deepseek-ai-dsh-web-deepseek-api/use-this-package/results-and-failures: - en: 7dbb34d960c1344c - zh: 51a1459415857ab5 + en: e7a5d332ebababe7 + zh: 5020eabd799ebb5c /deepseek-ai-dsh-web-deepseek-api/understand-the-implementation: en: 597dab3fe52fa59d zh: 4370d01d5a58f2f9 @@ -33,8 +33,8 @@ en: dfd3b61aff4a8aa8 zh: 06e2b6cc71f461e2 /deepseek-ai-dsh-web-deepseek-api/model-experience/conversation-tool-results/what-the-model-sees: - en: a9fbb78ffe886f0b - zh: 813dc7ee283018d2 + en: 84b1c849ae37668b + zh: 5a747293d8775f5e /deepseek-ai-dsh-web-deepseek-api/model-experience/conversation-tool-results/token-effect: en: 1f33560e768d18c5 zh: edeedeef2662e4bb diff --git a/packages/web/web-deepseek-api/README.md b/packages/web/web-deepseek-api/README.md index 737cf87336..80b0b68b57 100644 --- a/packages/web/web-deepseek-api/README.md +++ b/packages/web/web-deepseek-api/README.md @@ -74,7 +74,7 @@ Each provider's `ready()` answers whether its next operation for that route has The Search API receives `query`, `count` (the configured count, or the request's smaller `maxResults`), `need_content: false`, and, unless `sendOriginalQuestion` is off, `ori_question`: the text of the initiating Session's latest human prompt with whitespace collapsed and cut to 128 characters. A search outside a Session or without such a prompt omits it. The provider maps `results[].snippet` as the display excerpt and `results[].summary` as the model-facing excerpt, and maps nullable `date` to optional `publishedAt`; `dsh-tool-web` caps each summary. An empty results array is successful. Fetch sends `url` and returns the original Markdown as a text body with HTTP status 200, because the API answers with an error status when the target yields no usable content. Its URL is the requested URL: the API reports no final redirected URL. -An unparseable own base URL makes that capability's provider unavailable; and a `count` outside 1 to 50 makes Search unavailable. A missing credential fails with `WEB_PROVIDER_CREDENTIAL_MISSING`; a needed model route whose settings do not resolve fails with `WEB_PROVIDER_MISCONFIGURED`, naming the resolver failure, the Models page, and the capability's `*BaseURL` and `*ApiKeyEnv`; cancellation uses `WEB_ABORTED`; transport, HTTP, and malformed response failures use `WEB_PROVIDER_ERROR`. Redirects are rejected before contacting their target. Non-success Fetch API statuses are retrieval failures, not target-page statuses. Account-authenticated HTTP 401 responses invalidate only the token sent by that request and provide sign-in guidance; a newer sign-in is preserved, and credential-removal failure does not replace the HTTP error. API-key failures and HTTP 403 never invalidate an account token; other dispatch failures identify the endpoint and say where it came from: for a route endpoint they guide the user to that provider's base URL on the Models page or to the capability's `*BaseURL` and `*ApiKeyEnv`, and for own settings to correcting or removing those fields. No automatic retry or provider fallback occurs. +An unparseable own base URL makes that capability's provider unavailable; and a `count` outside 1 to 50 makes Search unavailable. A missing credential fails with `WEB_PROVIDER_CREDENTIAL_MISSING`; a needed model route whose settings do not resolve fails with `WEB_PROVIDER_MISCONFIGURED`, naming the resolver failure, the Models page, and the capability's `*BaseURL` and `*ApiKeyEnv`; cancellation uses `WEB_ABORTED`; transport, HTTP, and malformed response failures use `WEB_PROVIDER_ERROR`. A request ends when the credential it carries is withdrawn, as an account sign-out does through the grant's `revoked` signal: it fails with `WEB_PROVIDER_ERROR` and guidance to sign in again, or for another credential kind to check that credential on the Models page, unless the caller cancelled as well, which stays `WEB_ABORTED`. Redirects are rejected before contacting their target. Non-success Fetch API statuses are retrieval failures, not target-page statuses. Account-authenticated HTTP 401 responses invalidate only the token sent by that request and provide sign-in guidance; a newer sign-in is preserved, and credential-removal failure does not replace the HTTP error. API-key failures and HTTP 403 never invalidate an account token; other dispatch failures identify the endpoint and say where it came from: for a route endpoint they guide the user to that provider's base URL on the Models page or to the capability's `*BaseURL` and `*ApiKeyEnv`, and for own settings to correcting or removing those fields. No automatic retry or provider fallback occurs. ----- @@ -99,7 +99,7 @@ See the [web subsystem](../../../docs/subsystems/web.md) for service types and [ #### What the model sees -The `web_search` and `web_fetch` tools render sources or Markdown with an external-content notice. Fetch results carry the requested URL and HTTP 200. Errors retain actionable credential or endpoint guidance. Search sends the query, with the triggering question, directly to the Search API. +The `web_search` and `web_fetch` tools render sources or Markdown with an external-content notice. Fetch results carry the requested URL and HTTP 200. Errors retain actionable credential or endpoint guidance; a request the account's sign-out ended reports `The DeepSeek account signed out before this web request finished. Guide the user to sign in to DeepSeek again; the endpoint does not need changing.` Search sends the query, with the triggering question, directly to the Search API. #### Token effect diff --git a/packages/web/web-deepseek-api/README.zh.md b/packages/web/web-deepseek-api/README.zh.md index 9075dfe2c5..6243b8359b 100644 --- a/packages/web/web-deepseek-api/README.zh.md +++ b/packages/web/web-deepseek-api/README.zh.md @@ -74,7 +74,7 @@ Search 与 Fetch 每次操作各自从同一份设置快照解析端点和凭据 Search API 接收 `query`、`count`(配置的结果数,或请求中更小的 `maxResults`)、`need_content: false`,以及在 `sendOriginalQuestion` 未关闭时的 `ori_question`:发起会话中最近一条用户提示的文本,空白折叠后截取至 128 个字符。在会话之外或没有此类提示的搜索不发送该字段。提供者将 `results[].snippet` 映射为展示用摘录,将 `results[].summary` 映射为面向模型的摘录,并将可为 null 的 `date` 映射为可选的 `publishedAt`;`dsh-tool-web` 限制每条摘要的长度。空结果数组表示成功。Fetch 发送 `url`,以文本正文返回原始 Markdown,并报告 HTTP 状态 200,因为目标没有可用内容时 API 会返回错误状态。返回 URL 为请求 URL:API 不报告重定向后的最终 URL。 -单独配置的基础地址无法解析时,该能力的提供者不可用;`count` 不在 1 至 50 之间时,Search 不可用。凭据缺失以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败;所需模型路由的设置无法解析时以 `WEB_PROVIDER_MISCONFIGURED` 失败,并点名解析器的失败原因、模型页面以及该能力的 `*BaseURL` 与 `*ApiKeyEnv`;取消使用 `WEB_ABORTED`;传输、HTTP 和响应格式错误使用 `WEB_PROVIDER_ERROR`。重定向在联系目标前即被拒绝。Fetch API 的非成功状态表示抓取失败,不代表目标页面的状态。账号鉴权的 HTTP 401 响应只作废该请求实际发送的 token,并提供重新登录指引;更新的登录不受影响,凭据删除失败不会替换原 HTTP 错误。API 密钥失败与 HTTP 403 从不作废账号 token;其他请求失败指出端点及其来源:路由端点指导用户在模型页面检查该提供方的基础地址,或设置该能力的 `*BaseURL` 与 `*ApiKeyEnv`;单独配置指导用户修改或删除这两个字段。不会自动重试或回退至其他提供者。 +单独配置的基础地址无法解析时,该能力的提供者不可用;`count` 不在 1 至 50 之间时,Search 不可用。凭据缺失以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败;所需模型路由的设置无法解析时以 `WEB_PROVIDER_MISCONFIGURED` 失败,并点名解析器的失败原因、模型页面以及该能力的 `*BaseURL` 与 `*ApiKeyEnv`;取消使用 `WEB_ABORTED`;传输、HTTP 和响应格式错误使用 `WEB_PROVIDER_ERROR`。请求携带的凭据被收回时(例如账号退登通过授权的 `revoked` 信号收回),请求随即结束:以 `WEB_PROVIDER_ERROR` 失败并提供重新登录的指引,其他种类的凭据则指引用户在模型页面检查该凭据;调用方同时取消时仍为 `WEB_ABORTED`。重定向在联系目标前即被拒绝。Fetch API 的非成功状态表示抓取失败,不代表目标页面的状态。账号鉴权的 HTTP 401 响应只作废该请求实际发送的 token,并提供重新登录指引;更新的登录不受影响,凭据删除失败不会替换原 HTTP 错误。API 密钥失败与 HTTP 403 从不作废账号 token;其他请求失败指出端点及其来源:路由端点指导用户在模型页面检查该提供方的基础地址,或设置该能力的 `*BaseURL` 与 `*ApiKeyEnv`;单独配置指导用户修改或删除这两个字段。不会自动重试或回退至其他提供者。 ----- @@ -99,7 +99,7 @@ Search API 接收 `query`、`count`(配置的结果数,或请求中更小的 #### 模型看到什么 -`web_search` 和 `web_fetch` 工具在外部内容提示下呈现搜索来源或 Markdown。Fetch 结果包含请求 URL 和 HTTP 200。错误保留可操作的凭据或端点指引。Search 将查询连同触发问题直接发送给 Search API。 +`web_search` 和 `web_fetch` 工具在外部内容提示下呈现搜索来源或 Markdown。Fetch 结果包含请求 URL 和 HTTP 200。错误保留可操作的凭据或端点指引;被账号退登结束的请求报告 `The DeepSeek account signed out before this web request finished. Guide the user to sign in to DeepSeek again; the endpoint does not need changing.`Search 将查询连同触发问题直接发送给 Search API。 #### Token 影响 diff --git a/packages/web/web-deepseek-api/src/transport.ts b/packages/web/web-deepseek-api/src/transport.ts index 2508e2c714..befc4d4b65 100644 --- a/packages/web/web-deepseek-api/src/transport.ts +++ b/packages/web/web-deepseek-api/src/transport.ts @@ -163,6 +163,8 @@ interface SearchAuth { readonly headers: Readonly> /** Request-bound invalidation of the sent credential, present when its grant offers one; the dispatch contains its failure. */ readonly reject?: () => Promise + /** Withdrawal of the sent credential, present when its grant offers one; it ends the request. */ + readonly revoked?: AbortSignal } /** Dispatch one operation using a single settings and credential snapshot: one request, with the first present source. @@ -183,6 +185,17 @@ export async function dispatchDeepSeekWeb( throwIfSearchAborted(signal) let response: Response /* jscpd:ignore-start */ + const live = requestSignal(signal, auth.revoked) + /** + * The failure of an interrupted request: the caller's cancellation first, then the withdrawal of the sent credential. + * @param error - what the interrupted fetch or body read threw. + * @returns the failure to report, or undefined when `error` is no interruption. + */ + const interrupted = (error: unknown): WebError | undefined => { + if (signal?.aborted === true) return searchAborted(signal, error) + if (auth.revoked?.aborted === true) return credentialWithdrawnError(auth.kind, error) + return isAbortError(error) ? searchAborted(signal, error) : undefined + } try { response = await fetch(endpoint, { method: 'POST', @@ -195,11 +208,10 @@ export async function dispatchDeepSeekWeb( 'user-agent': USER_AGENT, }, body: JSON.stringify(body), - ...signal !== undefined ? { signal } : {}, + ...live !== undefined ? { signal: live } : {}, }) } catch (error: unknown) { - if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error) - throw searchEndpointError( + throw interrupted(error) ?? searchEndpointError( guidance, endpoint, `DeepSeek web request failed: ${String(error)}`, @@ -219,10 +231,10 @@ export async function dispatchDeepSeekWeb( if (typeof detail === 'string' && detail.length > 0) message += `: ${detail}` } } catch (error: unknown) { - // An abort fired mid-body must surface as WEB_ABORTED, not be swallowed + // An interruption mid-body must surface as itself, not be swallowed // into a generic HTTP-error message — cancellation is not a provider // error (the seam's cancellation contract). - if (signal?.aborted === true || isAbortError(error)) aborted = searchAborted(signal, error) + aborted = interrupted(error) // Otherwise: the HTTP status is already captured in `message` above; a // malformed/non-JSON error body (normal for gateway 5xx/429s) can only // cost a richer provider message, never the real error. @@ -246,7 +258,8 @@ export async function dispatchDeepSeekWeb( throwIfSearchAborted(signal) return decode(payload) } catch (error: unknown) { - if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error) + const stopped = interrupted(error) + if (stopped !== undefined) throw stopped const message = error instanceof WebError ? error.message : `DeepSeek returned an unprocessable response body: ${String(error)}` @@ -254,6 +267,36 @@ export async function dispatchDeepSeekWeb( } } +/** + * The signal one request runs under: the caller's cancellation and the withdrawal of the credential it carries. + * @param signal - caller cancellation, when the caller supplies one. + * @param revoked - withdrawal of the sent credential, when its grant offers one. + * @returns the composed signal, or undefined when neither exists. + */ +function requestSignal(signal: AbortSignal | undefined, revoked: AbortSignal | undefined): AbortSignal | undefined { + if (signal === undefined || revoked === undefined) return signal ?? revoked + return AbortSignal.any([signal, revoked]) +} + +/** + * Report a request that ended because the owner withdrew the credential it carried. The caller did not cancel, so the + * failure is the provider's. + * @param kind - kind of the withdrawn credential. + * @param cause - what the interrupted fetch or body read threw. + * @returns the provider failure, with sign-in guidance for an account credential. + */ +function credentialWithdrawnError(kind: LlmCredentialKind, cause: unknown): WebError { + return new WebError( + kind === 'account' + ? 'The DeepSeek account signed out before this web request finished. Guide the user to sign in to DeepSeek again;' + + ' the endpoint does not need changing.' + : 'The credential this web request carried was withdrawn before the request finished. Guide the user to check that' + + ' credential on the Models page.', + 'WEB_PROVIDER_ERROR', + { cause }, + ) +} + /** Replace endpoint guidance with sign-in guidance when DeepSeek rejects the account token. */ function accountRejectedError(message: string): WebError { return new WebError( @@ -318,6 +361,7 @@ async function authHeaders( kind, endpoint, headers: kind === 'api-key' ? { ...request.apiKeyHeaders?.(grant.value), authorization: `Bearer ${grant.value}` } : grant.headers, ...invalidate === undefined ? {} : { reject: invalidate }, + ...grant.revoked === undefined ? {} : { revoked: grant.revoked }, } } case 'api-key': { diff --git a/packages/web/web-deepseek-api/tests/composition.spec.ts b/packages/web/web-deepseek-api/tests/composition.spec.ts index 71f01ee2b9..123d645bc7 100644 --- a/packages/web/web-deepseek-api/tests/composition.spec.ts +++ b/packages/web/web-deepseek-api/tests/composition.spec.ts @@ -44,12 +44,17 @@ interface Sent { * Boot the composition with a fixed launch environment and a stubbed network. * @param web - web-deepseek-api config. * @param environment - launch-environment variables. + * @param account - the sign-out signal of the stubbed account and the answer to Search requests, when not the default. * @returns the booted root context and the Search and Fetch API requests sent so far. */ -async function bootComposition(web: Record, environment: Record) { +async function bootComposition( + web: Record, environment: Record, + account: { signedOut?: AbortSignal; search?: (signal: AbortSignal) => Promise } = {}, +) { // The providers and model listings dispatch to a string endpoint. - const fetchMock = vi.fn(async (url: string, _init?: RequestInit) => { + const fetchMock = vi.fn(async (url: string, init?: RequestInit) => { if (url.endsWith('/models')) return Response.json({ object: 'list', data: [] }) + if (url.endsWith('/search') && account.search !== undefined) return await account.search(init!.signal!) return Response.json(url.endsWith('/search') ? { results: [] } : { content: '# Page' }) }) vi.stubGlobal('fetch', fetchMock) @@ -83,7 +88,9 @@ async function bootComposition(web: Record, environment: Record } host.loader.internal = modules host.provide('launchEnvironment', createLaunchEnvironmentSnapshot([{ source: 'process', values: environment }])) - host.provide('deepseekAccount', accountStub({ token: () => 'account-token' })) + host.provide('deepseekAccount', accountStub({ + token: () => 'account-token', ...account.signedOut === undefined ? {} : { signedOut: account.signedOut }, + })) }) cleanups.push(async () => { await ctx.fiber.dispose() }) const sent = (): Sent[] => fetchMock.mock.calls.flatMap(([endpoint, init]) => { @@ -147,6 +154,30 @@ describe('web-deepseek-api over the real model routes', () => { ]) }) + it('ends an account-billed search in flight when the account signs out, with sign-in guidance', async () => { + const signedOut = new AbortController() + const sent = Promise.withResolvers() + const { ctx } = await bootComposition({ searchBilling: 'account' }, { DEEPSEEK_API_KEY: 'chat-key' }, { + signedOut: signedOut.signal, + search: (signal) => { + sent.resolve(signal) + return new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => { reject(signal.reason as Error) }, { once: true }) + }) + }, + }) + const search = ctx.web.search({ query: 'q' }) + const request = await sent.promise + expect(request.aborted).toBe(false) + signedOut.abort() + await expect(search).rejects.toMatchObject({ + code: 'WEB_PROVIDER_ERROR', + message: 'The DeepSeek account signed out before this web request finished. Guide the user to sign in to DeepSeek again;' + + ' the endpoint does not need changing.', + }) + expect(request.aborted).toBe(true) + }) + it('withholds API-key billing without a key despite a sign-in', async () => { const { ctx, sent } = await bootComposition({ searchBilling: 'api-key' }, {}) expect(await ctx.web.searchReady('deepseek-account')).toBe(false) diff --git a/packages/web/web-deepseek-api/tests/transport.spec.ts b/packages/web/web-deepseek-api/tests/transport.spec.ts index 3a082c938f..554d1f7671 100644 --- a/packages/web/web-deepseek-api/tests/transport.spec.ts +++ b/packages/web/web-deepseek-api/tests/transport.spec.ts @@ -19,26 +19,31 @@ function keyRef(resolve: () => Promise, configured: () => Pr /** * A route source on {@link ACCOUNT_BASE} whose account credential releases `resolveToken(endpoint)` as the token header; * an empty token releases nothing. `rejectToken` observes each invalidated token, and its failure rejects the grant's - * invalidation, as an owner that does not contain its storage failures does. + * invalidation, as an owner that does not contain its storage failures does. `revoked` is the sign-out signal the + * grant carries, when given. */ function accountSource( resolveToken: (endpoint: string) => Promise, rejectToken: (token: string) => Promise = async () => {}, + revoked?: AbortSignal, ): DeepSeekWebAuthSource { const grant = async (endpoint: string) => { const token = await resolveToken(endpoint) if (token === undefined || token.length === 0) return undefined - return { headers: { 'x-dsh-auth-token': token }, value: token, reject: () => rejectToken(token) } + return { headers: { 'x-dsh-auth-token': token }, value: token, reject: () => rejectToken(token), ...revoked === undefined ? {} : { revoked } } } return { kind: 'route', baseURL: ACCOUNT_BASE, credential: { kind: 'account', configured: async endpoint => (await grant(endpoint)) !== undefined, resolve: grant, } } } -/** A route source on {@link API_BASE} whose API-key credential releases `key`, sent as a bearer token. */ -function keyRouteSource(key: string | undefined, reference = 'ROUTE_KEY'): DeepSeekWebAuthSource { +/** + * A route source on {@link API_BASE} whose API-key credential releases `key`, sent as a bearer token, with the + * withdrawal signal `revoked` when given. + */ +function keyRouteSource(key: string | undefined, reference = 'ROUTE_KEY', revoked?: AbortSignal): DeepSeekWebAuthSource { return { kind: 'route', baseURL: API_BASE, credential: { kind: 'api-key', reference, configured: async () => key !== undefined, - resolve: async () => key === undefined ? undefined : { headers: { 'x-api-key': key }, value: key }, + resolve: async () => key === undefined ? undefined : { headers: { 'x-api-key': key }, value: key, ...revoked === undefined ? {} : { revoked } }, } } } const misconfigured: DeepSeekWebAuthSource = { kind: 'misconfigured', message: 'route settings do not resolve' } @@ -388,6 +393,74 @@ describe('DeepSeek web account authentication', () => { }) }) +describe('DeepSeek web credential withdrawal', () => { + const ACCOUNT_SIGNED_OUT = 'The DeepSeek account signed out before this web request finished. Guide the user to sign in to DeepSeek' + + ' again; the endpoint does not need changing.' + const KEY_WITHDRAWN = 'The credential this web request carried was withdrawn before the request finished. Guide the user to check' + + ' that credential on the Models page.' + + /** Hold each request open until its signal aborts, as an unanswered endpoint does. */ + function holdRequests() { + const sent = Promise.withResolvers() + vi.stubGlobal('fetch', vi.fn((_input: string, init?: RequestInit) => { + const signal = init!.signal! + sent.resolve(signal) + return new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => { reject(signal.reason as Error) }, { once: true }) + }) + })) + return sent.promise + } + + it.each<[string, (revoked: AbortSignal) => DeepSeekWebAuthSource, string]>([ + ['an account sign-out', revoked => accountSource(async () => 'account-token', undefined, revoked), ACCOUNT_SIGNED_OUT], + ['the withdrawal of a route key', revoked => keyRouteSource('route-key', 'ROUTE_KEY', revoked), KEY_WITHDRAWN], + ])('ends an open request at %s and reports the withdrawal instead of a cancellation', async (_label, source, message) => { + for (const signal of [undefined, new AbortController().signal]) { + const withdrawn = new AbortController() + const sent = holdRequests() + const pending = rejectedWebError(search([source(withdrawn.signal)], signal)) + const request = await sent + expect(request.aborted).toBe(false) + withdrawn.abort() + const error = await pending + expect(error).toMatchObject({ code: 'WEB_PROVIDER_ERROR', message }) + expect(error.cause).toBe(withdrawn.signal.reason) + expect(request.aborted).toBe(true) + } + }) + + it.each([200, 500])('reports a withdrawal that interrupts reading an HTTP %i body', async (status) => { + const withdrawn = new AbortController() + const body = new Response('', { status }) + vi.spyOn(body, 'json').mockImplementation(async (): Promise => { + withdrawn.abort() + throw new DOMException('The operation was aborted.', 'AbortError') + }) + vi.stubGlobal('fetch', vi.fn(async () => body)) + const error = await rejectedWebError(search([accountSource(async () => 'account-token', undefined, withdrawn.signal)])) + expect(error).toMatchObject({ code: 'WEB_PROVIDER_ERROR', message: ACCOUNT_SIGNED_OUT }) + }) + + it('reports the caller\'s cancellation when the caller and the withdrawal both ended the request', async () => { + const withdrawn = new AbortController() + const controller = new AbortController() + vi.stubGlobal('fetch', vi.fn(async () => { + withdrawn.abort() + controller.abort(new Error('caller stopped')) + throw new DOMException('The operation was aborted.', 'AbortError') + })) + await expect(search([accountSource(async () => 'account-token', undefined, withdrawn.signal)], controller.signal)) + .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' })) + }) + + it('keeps reporting a failure of a request whose credential stays in force', async () => { + vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new TypeError('connection refused')))) + const error = await rejectedWebError(search([accountSource(async () => 'account-token', undefined, new AbortController().signal)])) + expect(error.message).toContain('DeepSeek web request failed: TypeError: connection refused') + }) +}) + describe('DeepSeek web cancellation and failures', () => { it('does not start credential resolution or dispatch for a pre-aborted call', async () => { const resolve = vi.fn(async () => 'late-key') diff --git a/packages/web/web-search-deepseek/README.i18n.yaml b/packages/web/web-search-deepseek/README.i18n.yaml index d25d04cf27..76e5c0a067 100644 --- a/packages/web/web-search-deepseek/README.i18n.yaml +++ b/packages/web/web-search-deepseek/README.i18n.yaml @@ -24,8 +24,8 @@ en: 3ed88edabdf63c8d zh: c66176c8a7c9a434 /deepseek-ai-dsh-web-search-deepseek/use-this-package/authentication: - en: b9d2e372face46f1 - zh: cc8e5820d6aada38 + en: 5bd18e6e586eb4f0 + zh: 133927c4db79ac71 /deepseek-ai-dsh-web-search-deepseek/use-this-package/what-a-search-returns: en: e30442c90365357b zh: 9c9e2f1182963a8a @@ -69,8 +69,8 @@ en: 666f5753c99783ab zh: b44328e99bcc45c9 /deepseek-ai-dsh-web-search-deepseek/model-experience/conversation-tool-result-indirectly/what-the-model-sees: - en: 0764d19c9b82aa98 - zh: 88b0ba22ef64225b + en: fbe717bd9c6c43a5 + zh: 598ad961a5561ae1 /deepseek-ai-dsh-web-search-deepseek/model-experience/conversation-tool-result-indirectly/token-effect: en: 01ec43a9b616139d zh: 0a5b7c28fde34bcf diff --git a/packages/web/web-search-deepseek/README.md b/packages/web/web-search-deepseek/README.md index 91411478f7..741d92499a 100644 --- a/packages/web/web-search-deepseek/README.md +++ b/packages/web/web-search-deepseek/README.md @@ -58,7 +58,7 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a ### Authentication -A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names a model route that publishes an account credential through `ctx.llm.routeCredential`, the `deepseek-account` route, the search endpoint has the origin of that route's base URL, and that credential resolves for the search endpoint. The provider asks a route for its credential only at that origin, so an account credential published for another deployment is never sent to the search endpoint. The account service releases one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only the credential's headers, `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the credential that search sent through the credential's own invalidation: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. +A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names a model route that publishes an account credential through `ctx.llm.routeCredential`, the `deepseek-account` route, the search endpoint has the origin of that route's base URL, and that credential resolves for the search endpoint. The provider asks a route for its credential only at that origin, so an account credential published for another deployment is never sent to the search endpoint. The account service releases one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only the credential's headers, `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the credential that search sent through the credential's own invalidation: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. An account-authenticated search in flight when the account signs out ends through the credential's `revoked` signal and fails as `WEB_PROVIDER_ERROR` with sign-in guidance. The provider's `ready()` answers whether the search a model request would make has a credential, on any model route: the request's route publishes an account credential for the origin of the configured search endpoint that reports itself configured for that endpoint, or a literal `apiKey` is set or `ctx.credentials.describe` reports the `apiKeyEnv` reference configured (without that service, the process environment must carry it). It checks them in the order a search resolves them, and a route whose settings do not resolve or whose published base URL does not parse, or a failed account-credential or credential-store read, answers false, because the search fails there instead of trying the next credential. While this provider is the selected search provider, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and its prompt guidance from each request for which it answers false. Only presence is checked: a wrong key, or an endpoint that does not serve the native `web_search_20250305` server tool, counts as ready and fails each call. A call that still arrives resolves credentials when it runs. @@ -147,7 +147,7 @@ Independent of the conversation request cache. The auxiliary instruction and nat #### What the model sees -Through `dsh-tool-web`, the conversation model sees deduplicated URLs, titles, dates, and citation snippets from structured search blocks; provider prose is not trusted as an answer. This provider's exact failures include the actionable missing-credential message, which also names DeepSeek Account sign-in, `DeepSeek search credential resolution failed: `, and `DeepSeek search aborted`. An HTTP 401 to an account-authenticated search appends an instruction to guide the user to sign in to DeepSeek again. Other request, HTTP, native-search, and response-body failures append the resolved endpoint and the conditional configuration instruction described above. The consumer owns the error wrapper. +Through `dsh-tool-web`, the conversation model sees deduplicated URLs, titles, dates, and citation snippets from structured search blocks; provider prose is not trusted as an answer. This provider's exact failures include the actionable missing-credential message, which also names DeepSeek Account sign-in, `DeepSeek search credential resolution failed: `, and `DeepSeek search aborted`. An HTTP 401 to an account-authenticated search appends an instruction to guide the user to sign in to DeepSeek again. A search the account's sign-out ended reports `The DeepSeek account signed out before this web search finished. Guide the user to sign in to DeepSeek again; the search endpoint does not need changing.` Other request, HTTP, native-search, and response-body failures append the resolved endpoint and the conditional configuration instruction described above. The consumer owns the error wrapper. #### Token effect diff --git a/packages/web/web-search-deepseek/README.zh.md b/packages/web/web-search-deepseek/README.zh.md index c4908267e8..7b7c8ac43c 100644 --- a/packages/web/web-search-deepseek/README.zh.md +++ b/packages/web/web-search-deepseek/README.zh.md @@ -58,7 +58,7 @@ kind: "package-reference" ### 鉴权 -当发起会话最近的 `request/context` 事件指明的模型路由通过 `ctx.llm.routeCredential` 发布账号凭据(即 `deepseek-account` 路由),搜索端点与该路由的基础地址同源,且该凭据为搜索端点解析成功时,搜索使用 DeepSeek 账号鉴权。提供方只在同源时向路由索取凭据,因此为其他部署发布的账号凭据不会发往搜索端点。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)释放凭据。这类搜索只发送该凭据的请求头 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并通过凭据自身的失效操作只作废该搜索实际发送的凭据:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。 +当发起会话最近的 `request/context` 事件指明的模型路由通过 `ctx.llm.routeCredential` 发布账号凭据(即 `deepseek-account` 路由),搜索端点与该路由的基础地址同源,且该凭据为搜索端点解析成功时,搜索使用 DeepSeek 账号鉴权。提供方只在同源时向路由索取凭据,因此为其他部署发布的账号凭据不会发往搜索端点。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)释放凭据。这类搜索只发送该凭据的请求头 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并通过凭据自身的失效操作只作废该搜索实际发送的凭据:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。账号退登时仍在途的账号鉴权搜索会通过凭据的 `revoked` 信号结束,并以 `WEB_PROVIDER_ERROR` 失败,附带登录指引。 提供方的 `ready()` 回答模型请求将发起的搜索是否有凭据,不论模型路由:该请求的路由为配置的搜索端点所在 origin 发布了账号凭据且该凭据报告自身已为该端点配置,或者设置了字面 `apiKey`,或 `ctx.credentials.describe` 报告 `apiKeyEnv` 引用已配置(没有该服务时,进程环境中必须存在该变量)。它按搜索解析凭据的顺序检查;路由设置无法解析或其发布的基础地址无法解析,或读取账号凭据或凭据存储失败时回答 false,因为搜索会在那里失败,而不会尝试下一种凭据。本提供方是选中的搜索提供方时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它回答 false 的每个请求中撤下 `web_search` 及其提示词说明。这里只检查凭据是否存在:错误的密钥,或不提供原生 `web_search_20250305` 服务器工具的端点,都视为就绪并使每次调用失败。仍然到达的调用会在运行时解析凭据。 @@ -147,7 +147,7 @@ kind: "package-reference" #### 模型看到的内容 -通过 `dsh-tool-web`,会话模型会看到结构化搜索块中去重后的 URL、标题、日期与引用 snippet;提供方文本不会作为答案受到信任。该提供方的具体失败消息包括带有处理指引的凭据缺失消息(其中也提到 DeepSeek 账号登录)、`DeepSeek search credential resolution failed: ` 和 `DeepSeek search aborted`。账号鉴权的搜索收到 HTTP 401 时,会追加引导用户重新登录 DeepSeek 的指引。其他请求、HTTP、原生搜索和响应正文失败会追加已解析端点及前述条件式配置指引。错误包装属于消费方。 +通过 `dsh-tool-web`,会话模型会看到结构化搜索块中去重后的 URL、标题、日期与引用 snippet;提供方文本不会作为答案受到信任。该提供方的具体失败消息包括带有处理指引的凭据缺失消息(其中也提到 DeepSeek 账号登录)、`DeepSeek search credential resolution failed: ` 和 `DeepSeek search aborted`。账号鉴权的搜索收到 HTTP 401 时,会追加引导用户重新登录 DeepSeek 的指引。被账号退登结束的搜索报告 `The DeepSeek account signed out before this web search finished. Guide the user to sign in to DeepSeek again; the search endpoint does not need changing.`其他请求、HTTP、原生搜索和响应正文失败会追加已解析端点及前述条件式配置指引。错误包装属于消费方。 #### Token 影响 diff --git a/packages/web/web-search-deepseek/src/provider.ts b/packages/web/web-search-deepseek/src/provider.ts index 5472a8f2b9..5813d1f2d5 100644 --- a/packages/web/web-search-deepseek/src/provider.ts +++ b/packages/web/web-search-deepseek/src/provider.ts @@ -97,7 +97,8 @@ export interface DeepSeekSearchProviderOptions { * Resolve the DeepSeek account credential for one search endpoint. A credential takes * precedence over every API key and is sent only through the headers of its grant, which * also invalidates it after HTTP 401; a failure of that invalidation is contained, and the - * search reports the HTTP rejection. `undefined` selects API-key authentication. + * search reports the HTTP rejection. The grant's `revoked` signal ends the search when the + * account signs out. `undefined` selects API-key authentication. */ resolveAccountCredential?: (endpoint: string) => Promise /** Literal DeepSeek API key; when present it wins over {@link resolveApiKey}. */ @@ -195,6 +196,8 @@ interface SearchAuth { readonly headers: Readonly> /** Request-bound invalidation, present when the sent account credential offers one. */ readonly reject?: () => Promise + /** Sign-out of the sent account credential, present when its grant offers one; it ends the request. */ + readonly revoked?: AbortSignal } /** @@ -257,6 +260,17 @@ export class DeepSeekSearchProvider implements WebSearchProvider { }) throwIfSearchAborted(signal) let response: Response + const live = requestSignal(signal, auth.revoked) + /** + * The failure of an interrupted request: the caller's cancellation first, then the sign-out of the sent account. + * @param error - what the interrupted fetch or body read threw. + * @returns the failure to report, or undefined when `error` is no interruption. + */ + const interrupted = (error: unknown): WebError | undefined => { + if (signal?.aborted === true) return searchAborted(signal, error) + if (auth.revoked?.aborted === true) return accountSignedOutError(error) + return isAbortError(error) ? searchAborted(signal, error) : undefined + } try { response = await fetch(endpoint, { method: 'POST', @@ -269,11 +283,10 @@ export class DeepSeekSearchProvider implements WebSearchProvider { 'user-agent': USER_AGENT, }, body: JSON.stringify(body), - ...signal !== undefined ? { signal } : {}, + ...live !== undefined ? { signal: live } : {}, }) } catch (error: unknown) { - if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error) - throw searchEndpointError( + throw interrupted(error) ?? searchEndpointError( endpoint, `DeepSeek search request failed: ${String(error)}`, error, @@ -289,10 +302,10 @@ export class DeepSeekSearchProvider implements WebSearchProvider { const detail = typeof parsed.error === 'string' ? parsed.error : parsed.error?.message ?? parsed.message if (detail !== undefined && detail.length > 0) message += `: ${detail}` } catch (error: unknown) { - // An abort fired mid-body must surface as WEB_ABORTED, not be swallowed + // An interruption mid-body must surface as itself, not be swallowed // into a generic HTTP-error message — cancellation is not a provider // error (the seam's cancellation contract). - if (signal?.aborted === true || isAbortError(error)) aborted = searchAborted(signal, error) + aborted = interrupted(error) // Otherwise: the HTTP status is already captured in `message` above; a // malformed/non-JSON error body (normal for gateway 5xx/429s) can only // cost a richer provider message, never the real error. @@ -314,7 +327,8 @@ export class DeepSeekSearchProvider implements WebSearchProvider { const payload = await response.json() as AnthropicResponse return mapAnthropicResponse(payload) } catch (error: unknown) { - if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error) + const stopped = interrupted(error) + if (stopped !== undefined) throw stopped const message = error instanceof WebError ? error.message : `DeepSeek returned an unprocessable response body: ${String(error)}` @@ -338,7 +352,11 @@ export class DeepSeekSearchProvider implements WebSearchProvider { : await resolveCredential(() => resolveAccountCredential(endpoint), signal) if (credential !== undefined) { const invalidate = credential.reject?.bind(credential) - return { kind: 'account', headers: credential.headers, ...invalidate === undefined ? {} : { reject: invalidate } } + return { + kind: 'account', headers: credential.headers, + ...invalidate === undefined ? {} : { reject: invalidate }, + ...credential.revoked === undefined ? {} : { revoked: credential.revoked }, + } } const apiKey = await this.apiKey(options, signal) // Official DeepSeek expects `x-api-key`; an Anthropic-compatible proxy @@ -391,6 +409,32 @@ async function resolveCredential(resolve: () => Promise, signal?: AbortSig } } +/** + * The signal one search runs under: the caller's cancellation and the sign-out of the account credential it carries. + * @param signal - caller cancellation, when the caller supplies one. + * @param revoked - sign-out of the sent account credential, when its grant offers one. + * @returns the composed signal, or undefined when neither exists. + */ +function requestSignal(signal: AbortSignal | undefined, revoked: AbortSignal | undefined): AbortSignal | undefined { + if (signal === undefined || revoked === undefined) return signal ?? revoked + return AbortSignal.any([signal, revoked]) +} + +/** + * Report a search that ended because the account it authenticated with signed out. The caller did not cancel, so the + * failure is the provider's. + * @param cause - what the interrupted fetch or body read threw. + * @returns the provider failure with sign-in guidance. + */ +function accountSignedOutError(cause: unknown): WebError { + return new WebError( + 'The DeepSeek account signed out before this web search finished. Guide the user to sign in to DeepSeek again;' + + ' the search endpoint does not need changing.', + 'WEB_PROVIDER_ERROR', + { cause }, + ) +} + /** Replace endpoint guidance with sign-in guidance when DeepSeek rejects the account token. */ function accountRejectedError(message: string): WebError { return new WebError( diff --git a/packages/web/web-search-deepseek/tests/deepseek.spec.ts b/packages/web/web-search-deepseek/tests/deepseek.spec.ts index 9e383dfe08..76c26394da 100644 --- a/packages/web/web-search-deepseek/tests/deepseek.spec.ts +++ b/packages/web/web-search-deepseek/tests/deepseek.spec.ts @@ -35,14 +35,19 @@ const searchProvider = (options: DeepSeekSearchProviderOptions): DeepSeekSearchP /** * The account credential resolver a route publishes over `token`, with `reject` observing each invalidated token; * a throwing observer rejects the grant's invalidation, as an owner that does not contain its storage failures does. + * `revoked` is the sign-out signal the grant carries, when given. */ function accountCredential( - token: (endpoint: string) => Promise, reject?: (token: string) => Promise, + token: (endpoint: string) => Promise, reject?: (token: string) => Promise, revoked?: AbortSignal, ): (endpoint: string) => Promise { return async (endpoint) => { const value = await token(endpoint) if (value === undefined || value.length === 0) return undefined - return { headers: { 'x-dsh-auth-token': value }, value, ...reject === undefined ? {} : { reject: () => reject(value) } } + return { + headers: { 'x-dsh-auth-token': value }, value, + ...reject === undefined ? {} : { reject: () => reject(value) }, + ...revoked === undefined ? {} : { revoked }, + } } } @@ -367,6 +372,58 @@ describe('DeepSeekSearchProvider account authentication', () => { expect(rejectAccountToken).toHaveBeenCalledExactlyOnceWith('sent-token') }) + const ACCOUNT_SIGNED_OUT = 'The DeepSeek account signed out before this web search finished. Guide the user to sign in to DeepSeek' + + ' again; the search endpoint does not need changing.' + /** A provider authenticating with an account credential whose sign-out signal is `revoked`. */ + const signedIn = (revoked: AbortSignal): DeepSeekSearchProvider => + searchProvider({ ...options, resolveAccountCredential: accountCredential(async () => 'account-token', undefined, revoked) }) + + it('ends an open search when the account signs out and reports sign-in guidance instead of a cancellation', async () => { + for (const signal of [undefined, new AbortController().signal]) { + const signedOut = new AbortController() + const sent = Promise.withResolvers() + vi.stubGlobal('fetch', vi.fn((_input: string, init?: RequestInit) => { + const request = init!.signal! + sent.resolve(request) + return new Promise((_resolve, reject) => { + request.addEventListener('abort', () => { reject(request.reason as Error) }, { once: true }) + }) + })) + const pending = rejectedWebError(signedIn(signedOut.signal).search({ query: 'q' }, signal)) + const request = await sent.promise + expect(request.aborted).toBe(false) + signedOut.abort() + const error = await pending + expect(error).toMatchObject({ code: 'WEB_PROVIDER_ERROR', message: ACCOUNT_SIGNED_OUT }) + expect(error.cause).toBe(signedOut.signal.reason) + expect(request.aborted).toBe(true) + } + }) + + it.each([200, 500])('reports a sign-out that interrupts reading an HTTP %i body', async (status) => { + const signedOut = new AbortController() + const body = new Response('', { status }) + vi.spyOn(body, 'json').mockImplementation(async (): Promise => { + signedOut.abort() + throw new DOMException('The operation was aborted.', 'AbortError') + }) + vi.stubGlobal('fetch', vi.fn(async () => body)) + const error = await rejectedWebError(signedIn(signedOut.signal).search({ query: 'q' })) + expect(error).toMatchObject({ code: 'WEB_PROVIDER_ERROR', message: ACCOUNT_SIGNED_OUT }) + }) + + it('reports the caller\'s cancellation when the caller and the sign-out both ended the search', async () => { + const signedOut = new AbortController() + const controller = new AbortController() + vi.stubGlobal('fetch', vi.fn(async () => { + signedOut.abort() + controller.abort(new Error('caller stopped')) + throw new DOMException('The operation was aborted.', 'AbortError') + })) + await expect(signedIn(signedOut.signal).search({ query: 'q' }, controller.signal)) + .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' })) + }) + it('keeps endpoint guidance for other account-authenticated HTTP failures', async () => { vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({}, { status: 503 }))) const error = await rejectedWebError(searchProvider({ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f16be97700..2bb50f3f77 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -13931,6 +13931,9 @@ importers: '@deepseek-ai/dsh-attachment-local': specifier: workspace:* version: link:../../attachment/attachment-local + '@deepseek-ai/dsh-authorization': + specifier: workspace:* + version: link:../../credentials/authorization '@deepseek-ai/dsh-credentials': specifier: workspace:* version: link:../../credentials/credentials diff --git a/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs b/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs index c2fcfcf89b..760695f765 100644 --- a/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs +++ b/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs @@ -1,6 +1,7 @@ /** * Signed-in DeepSeek account stand-in and Search API endpoint for the billing snapshots. The account releases one fixed - * token, and the endpoint answers only a request that carries that token and no API key. + * token, and the endpoint answers only a request that carries that token and no API key. With the plugin config + * `signOutDuringSearch: true`, the account signs out when that request arrives and the endpoint leaves it unanswered. */ import { applyLoopbackServerEffect } from '../loopback-fixture-server.mjs' @@ -32,10 +33,11 @@ function transportInput(input, transportEndpoint) { } /** Provide the signed-in account and start the Search endpoint; both end with the plugin fiber. */ -export async function apply(ctx) { +export async function apply(ctx, config) { + const signedOut = new AbortController() ctx.provide('deepseekAccount', { resolveRequestCredential: async endpoint => endpoint.startsWith('https://api.deepseek.com/') - ? { headers: { 'x-dsh-auth-token': ACCOUNT_TOKEN }, value: ACCOUNT_TOKEN, reject: async () => {} } + ? { headers: { 'x-dsh-auth-token': ACCOUNT_TOKEN }, value: ACCOUNT_TOKEN, revoked: signedOut.signal, reject: async () => {} } : undefined, }) let restoreFetch = () => {} @@ -49,6 +51,11 @@ export async function apply(ctx) { return } request.resume() + if (config?.signOutDuringSearch === true) { + // The sign-out withdraws the credential this request carries, which ends the request on the client side. + signedOut.abort() + return + } response.writeHead(200, { 'content-type': 'application/json' }) response.end(JSON.stringify({ results: [{ diff --git a/snapshots/session/web-search-account-signout/runtime.cordis.yml b/snapshots/session/web-search-account-signout/runtime.cordis.yml new file mode 100644 index 0000000000..d291c27192 --- /dev/null +++ b/snapshots/session/web-search-account-signout/runtime.cordis.yml @@ -0,0 +1,4 @@ +# The stand-in account signs out while the account-billed Search request is in flight. +- id: web-search-billing-fixture + config: + signOutDuringSearch: true diff --git a/snapshots/session/web-search-account-signout/session.v4.jsonl b/snapshots/session/web-search-account-signout/session.v4.jsonl new file mode 100644 index 0000000000..f6f31a5f0c --- /dev/null +++ b/snapshots/session/web-search-account-signout/session.v4.jsonl @@ -0,0 +1,22 @@ +{"type":"session","version":4,"id":"{{session:1}}","createdAt":1785078727712,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0} +{"type":"permission/preset","data":{"preset":"danger-full-access"}} +{"type":"sandbox/mode","data":{"mode":"danger-full-access"}} +{"type":"approval/policy","data":{"policy":"never"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Use the web_search tool exactly once to search for DSH sign-out snapshot, then reply with exactly DONE. Do not describe the results."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} +{"type":"turn/start","data":{"turn":1}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":1,"step":1}} +{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Use the web_search tool exactly once to search for DSH sign-out snapshot, then reply with exactly DONE. Do not describe the results."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"snapshot-other","model":"other-model"},"tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","data":{"provider":"snapshot-other","model":"other-model"}} +{"type":"session/title","data":{"title":"Use the web_search tool exactly","messageSeqs":[8],"source":{"kind":"fallback"}}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"Search once, then reply DONE."},{"type":"tool-call","id":"call_00_signout","name":"web_search","arguments":"{\"queries\": [\"DSH sign-out snapshot\"]}"}],"source":{"kind":"model","provider":"snapshot-other","model":"other-model"},"id":"{{message:4}}"},"usage":{"inputTokens":100,"outputTokens":10,"cacheReadTokens":0},"stream":[{"type":"chunk","time":1788699449132,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788699449132,"index":0,"dt":[],"texts":["Search once, then reply DONE."]},{"type":"chunk","time":1788699449132,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1788699449132,"index":1,"dt":[],"id":"call_00_signout","name":"web_search","args":["{\"queries\": [\"DSH sign-out snapshot\"]}"]},{"type":"chunk","time":1788699449132,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"Search once, then reply DONE."}}},{"type":"chunk","time":1788699449132,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_signout","name":"web_search","arguments":"{\"queries\": [\"DSH sign-out snapshot\"]}"}}},{"type":"chunk","time":1788699449132,"chunk":{"type":"usage","usage":{"inputTokens":100,"outputTokens":10,"cacheReadTokens":0}}},{"type":"chunk","time":1788699449132,"chunk":{"type":"finish","reason":{"kind":"tool-use"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_00_signout","name":"web_search","arguments":"{\"queries\": [\"DSH sign-out snapshot\"]}"}} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_signout"},"toolCallId":"call_00_signout","content":[{"type":"text","text":"Error: The DeepSeek account signed out before this web request finished. Guide the user to sign in to DeepSeek again; the endpoint does not need changing."}],"isError":true,"id":"{{message:5}}"},"error":{"name":"WebError","code":"WEB_PROVIDER_ERROR"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":1}} +{"type":"step/start","data":{"turn":1,"step":2}} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The search failed because the account signed out; reply DONE."},{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"snapshot-other","model":"other-model"},"id":"{{message:6}}"},"usage":{"inputTokens":100,"outputTokens":10,"cacheReadTokens":0},"stream":[{"type":"chunk","time":1788699449132,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788699449132,"index":0,"dt":[],"texts":["The search failed because the account signed out; reply DONE."]},{"type":"chunk","time":1788699449132,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1788699449132,"index":1,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1788699449132,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The search failed because the account signed out; reply DONE."}}},{"type":"chunk","time":1788699449132,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1788699449132,"chunk":{"type":"usage","usage":{"inputTokens":100,"outputTokens":10,"cacheReadTokens":0}}},{"type":"chunk","time":1788699449132,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":2}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/web-search-account-signout/snapshot.yml b/snapshots/session/web-search-account-signout/snapshot.yml new file mode 100644 index 0000000000..bf9c21abec --- /dev/null +++ b/snapshots/session/web-search-account-signout/snapshot.yml @@ -0,0 +1,11 @@ +version: 1 +scenario: web-search-account-signout +profile: headless +composition: web-search-account-billing +recording: authored +header: + class: web-search-account-billing +environment: + # No DeepSeek API key, and a fixed DeepSeek origin for the account token. + DEEPSEEK_API_KEY: '' + DEEPSEEK_BASE_URL: https://api.deepseek.com/anthropic From 1baaf819d7adf5a43e0530ba3bd5619551653336 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 13 Nov 2026 15:30:20 +0800 Subject: [PATCH 26/48] docs(llm-route-credential): use the established Chinese term for a withdrawn credential MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Chinese pages of the route credential change rendered "withdraw" as 收回. The bilingual pages on master render it as 撤回 in most places, so the seven pages this branch edited now use that term. The English pages are unchanged; only the Chinese hashes of the pairing records move. --- .../2026-09-17-account-provider-signout.i18n.yaml | 4 ++-- .../architecture/2026-09-17-account-provider-signout.zh.md | 4 ++-- .../2026-11-10-llm-route-credential-seam.i18n.yaml | 4 ++-- .../architecture/2026-11-10-llm-route-credential-seam.zh.md | 4 ++-- docs/subsystems/account.i18n.yaml | 2 +- docs/subsystems/account.zh.md | 2 +- docs/subsystems/llm-streaming.i18n.yaml | 2 +- docs/subsystems/llm-streaming.zh.md | 2 +- .../v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml | 2 +- .../v0.2.2-rc.2/llm-route-credential/guide.zh.md | 2 +- packages/llm/llm-deepseek/README.i18n.yaml | 4 ++-- packages/llm/llm-deepseek/README.zh.md | 4 ++-- packages/web/web-deepseek-api/README.i18n.yaml | 2 +- packages/web/web-deepseek-api/README.zh.md | 2 +- 14 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml index 0b8f4fca6a..75d406fe23 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml @@ -10,10 +10,10 @@ zh: 61977c82d66ae9bf /agent-note-account-provider-and-active-request-cancellation/decision: en: 6f5463ecf88c1435 - zh: 2097b8829e410c6b + zh: 7c9e46f90c8ccffb /agent-note-account-provider-and-active-request-cancellation/alternatives-considered: en: 7ed93136cf11074a - zh: aea8dcf2e521a9c2 + zh: 1ee997e271e919ad /agent-note-account-provider-and-active-request-cancellation/consequences: en: 8fd00b6d69b380c0 zh: 3830dc3a93d5de3c diff --git a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md index a7a8d2d6fc..2fc0872a4b 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md @@ -14,11 +14,11 @@ Status: implemented 账号取消读取运行中 Agent 最近的 `Session.requestContext()`,不维护额外提供方字段。该已记录值在工具和重试阶段保留,随下一次绑定请求更新;空闲 Agent 不计入。新轮次首次准备期间,它仍可能指向上一轮的账号路由,因此退登也可能打断尚未绑定新请求的 API key 轮次。没有历史上下文的首请求若缺少账号凭据,会在传输前失败。 -本地退登成功后发布账号事件。账号路由插件安装监听器,遍历 Agent 注册表,通过 `Agent.cancel` 取消匹配的账号路由并保留收件箱。它把同一判断函数注册到账号服务,作为退登确认所依据的运行中任务报告。每个已注册子代理独立分类;生命周期绑定到已取消父代理的子代理仍受现有父级取消规则约束。现有 HTTP 信号将取消传递到传输层。该监听器到达不了的请求通过其凭据的收回信号结束,这一信号由[路由凭据决策](2026-11-10-llm-route-credential-seam.zh.md)负责。 +本地退登成功后发布账号事件。账号路由插件安装监听器,遍历 Agent 注册表,通过 `Agent.cancel` 取消匹配的账号路由并保留收件箱。它把同一判断函数注册到账号服务,作为退登确认所依据的运行中任务报告。每个已注册子代理独立分类;生命周期绑定到已取消父代理的子代理仍受现有父级取消规则约束。现有 HTTP 信号将取消传递到传输层。该监听器到达不了的请求通过其凭据的撤回信号结束,这一信号由[路由凭据决策](2026-11-10-llm-route-credential-seam.zh.md)负责。 ## Alternatives considered -历史提供方集合会在轮次切换到 API Key 路由后仍错误取消它。当前设置会误判更早的在途请求。额外的提供方字段或模块级全局映射重复保存请求上下文中已有的信息。用登录级取消信号取代这条链路,会重复现有的 Agent 与 HTTP 取消;凭据的收回信号只是对它的补充。 +历史提供方集合会在轮次切换到 API Key 路由后仍错误取消它。当前设置会误判更早的在途请求。额外的提供方字段或模块级全局映射重复保存请求上下文中已有的信息。用登录级取消信号取代这条链路,会重复现有的 Agent 与 HTTP 取消;凭据的撤回信号只是对它的补充。 ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index 3ea538f271..763a04ece1 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -10,10 +10,10 @@ zh: 9da30ad0be6fc38d /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision: en: 339c58ce1afd8225 - zh: 00b0b683d6de2edc + zh: d82a5074d7849cc8 /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered: en: d6b2de393add9887 zh: b5351f9a49387bd6 /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/consequences: en: 748f306d720ade43 - zh: 792386be47105525 + zh: c28734e1d072feb3 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index d025903ed3..b47687c8b8 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.routeCredential(provider)` 发布一个 `RouteCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不校验凭据、不联系目的地的存在性检查 `configured(endpoint)`,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`、可选的 HTTP 401 `reject()`,以及可选的 `revoked` 信号;所有者在请求仍携带凭据时收回凭据,该信号即中止。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 +`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.routeCredential(provider)` 发布一个 `RouteCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不校验凭据、不联系目的地的存在性检查 `configured(endpoint)`,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`、可选的 HTTP 401 `reject()`,以及可选的 `revoked` 信号;所有者在请求仍携带凭据时撤回凭据,该信号即中止。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 `@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回授权或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`;`credential` 声明发布的种类、引用和存在性检查。传输层让每次模型请求及其文件操作受授权的 `revoked` 信号约束,并把由此产生的失败交给提供方的失败回调命名。列表缓存以端点和凭据请求头的哈希划分作用域。 @@ -44,4 +44,4 @@ Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.route 新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `routeCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 -退登会结束携带账号 token 的在途模型、Files、Search 与 Fetch 请求,包括不属于任何 Agent 回合的请求,例如回合之外的模型请求或按账号计费的 Web 搜索;账号列表请求仍只受自身期限约束。该信号是对[账号退登决策](2026-09-17-account-provider-signout.zh.md)中 Agent 取消链路的补充;那份决策以重复该链路为由否决了登录级信号,而该链路只能经由已挂载的监听和运行中的 Agent 回合到达请求。账号路由被停用期间,它此前启动且仍在运行的任务不会报告给退登确认,退登也只能通过在途的模型请求结束它。已被替换的账号服务释放的凭据不会被替换后服务的退登收回;路由插件的监听仍会取消 Agent 回合。 +退登会结束携带账号 token 的在途模型、Files、Search 与 Fetch 请求,包括不属于任何 Agent 回合的请求,例如回合之外的模型请求或按账号计费的 Web 搜索;账号列表请求仍只受自身期限约束。该信号是对[账号退登决策](2026-09-17-account-provider-signout.zh.md)中 Agent 取消链路的补充;那份决策以重复该链路为由否决了登录级信号,而该链路只能经由已挂载的监听和运行中的 Agent 回合到达请求。账号路由被停用期间,它此前启动且仍在运行的任务不会报告给退登确认,退登也只能通过在途的模型请求结束它。已被替换的账号服务释放的凭据不会被替换后服务的退登撤回;路由插件的监听仍会取消 Agent 回合。 diff --git a/docs/subsystems/account.i18n.yaml b/docs/subsystems/account.i18n.yaml index ff6e299f2a..d54fbdfdf8 100644 --- a/docs/subsystems/account.i18n.yaml +++ b/docs/subsystems/account.i18n.yaml @@ -7,7 +7,7 @@ zh: 5e0ac058b50036dc /deepseek-account/request-credentials: en: 8b2ab927576926cf - zh: c383046df37bfade + zh: a41a275c39103347 /deepseek-account/embedded-platform-credentials: en: 9a651d70acbe83a6 zh: 4624b0299f5fdd8e diff --git a/docs/subsystems/account.zh.md b/docs/subsystems/account.zh.md index 6624963d70..ce7e1c5f31 100644 --- a/docs/subsystems/account.zh.md +++ b/docs/subsystems/account.zh.md @@ -8,7 +8,7 @@ ## 请求凭据 -`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。其 `revoked` 信号在账号退出该 token 所属的登录时中止,无论退登由用户发起还是由拒绝触发,且在 `deepseek-account/signed-out` 的监听器返回之后;账号模型路由和 DeepSeek Web 提供方让携带该 token 的每个模型、Files、Search 与 Fetch 请求受它约束,因此即使发出请求的插件已卸载,退登仍会结束这些请求。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。已被替换的账号服务释放的凭据,其信号保持未中止,因为替换后的服务只收回自己释放的凭据。 +`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。其 `revoked` 信号在账号退出该 token 所属的登录时中止,无论退登由用户发起还是由拒绝触发,且在 `deepseek-account/signed-out` 的监听器返回之后;账号模型路由和 DeepSeek Web 提供方让携带该 token 的每个模型、Files、Search 与 Fetch 请求受它约束,因此即使发出请求的插件已卸载,退登仍会结束这些请求。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。已被替换的账号服务释放的凭据,其信号保持未中止,因为替换后的服务只撤回自己释放的凭据。 按账号计费的模型路由在 `ctx.effect()` 内用 `registerRunningTaskReport(report)` 注册运行中任务报告;只要有报告回答 true,`hasRunningAccountTasks()` 就回答 true,使退登确认能够提醒退登将打断的工作。`deepseek-account/signed-out` 之后取消这些工作由路由插件负责;比插件存活更久的请求通过其凭据的 `revoked` 信号结束,插件为该请求提供的失败回调随后取消这些工作。 diff --git a/docs/subsystems/llm-streaming.i18n.yaml b/docs/subsystems/llm-streaming.i18n.yaml index ec3c50fe81..d432290702 100644 --- a/docs/subsystems/llm-streaming.i18n.yaml +++ b/docs/subsystems/llm-streaming.i18n.yaml @@ -37,7 +37,7 @@ zh: fc99fe965acaabf3 /llm-streaming/the-model-request: en: a345a763b420ff1a - zh: 10937f0f9b040eea + zh: c3e0adef1b1036ef /llm-streaming/the-model-request/the-request-envelope-llmcallconfig-and-the-logged-header: en: b0eb4620c6953646 zh: fabf51c7245a4855 diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index 67fa37b2f5..cd6ea6501b 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -533,7 +533,7 @@ interface LlmNativeAuth { } ``` -路由的适配器还可以发布该路由当前发送的凭据,使在模型请求路径之外调用同一部署的消费方(如 DeepSeek Web 提供方)通过 `ctx.llm.routeCredential(provider)` 复用它,而不读取提供方配置或自行选择请求头名称。授权仅限 Host,且只在一次操作内持有;`kind` 通过 `LlmCredentialKindMap` 可合并扩展,已声明的成员为 `api-key` 和 `account`。所有者可能在请求仍携带凭据时收回它(例如账号退登),这类授权带有 `revoked` 信号:消费方让它鉴权的每个请求都受该信号约束,并把被该信号结束的请求报告为自身的失败,而不是调用方的取消。 +路由的适配器还可以发布该路由当前发送的凭据,使在模型请求路径之外调用同一部署的消费方(如 DeepSeek Web 提供方)通过 `ctx.llm.routeCredential(provider)` 复用它,而不读取提供方配置或自行选择请求头名称。授权仅限 Host,且只在一次操作内持有;`kind` 通过 `LlmCredentialKindMap` 可合并扩展,已声明的成员为 `api-key` 和 `account`。所有者可能在请求仍携带凭据时撤回它(例如账号退登),这类授权带有 `revoked` 信号:消费方让它鉴权的每个请求都受该信号约束,并把被该信号结束的请求报告为自身的失败,而不是调用方的取消。 ```ts type-equiv /** diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml index 1e48e714c7..7577d27ae0 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml @@ -10,7 +10,7 @@ zh: 73bd5dfd53ed8d36 /deepseek-routes-publish-the-credential-web-consumers-reuse/change: en: 4e77c6f6c622beb2 - zh: 03f3756a54dcbfa8 + zh: 2c119f567ff411ff /deepseek-routes-publish-the-credential-web-consumers-reuse/migration: en: 6d117f2dfd7593d0 zh: 1c1579fc7d0ccad0 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md index de47c7df60..712e402000 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md @@ -9,7 +9,7 @@ description: "DeepSeek 模型路由通过 ctx.llm.routeCredential() 发布自己 ## 变更 -`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、`configured(endpoint)` 存在性检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值、可选的 `reject()`,以及可选的 `revoked` 收回信号。 +`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、`configured(endpoint)` 存在性检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值、可选的 `reject()`,以及可选的 `revoked` 撤回信号。 `@deepseek-ai/dsh-llm-deepseek` 不再导出 `resolveDeepSeekApiKey`、`deepSeekApiKeyConfigured`、`resolveDeepSeekAccountToken` 和 `rejectDeepSeekAccountToken`。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回 `DeepSeekRequestAuth | undefined`,且 `DeepSeekRequestAuth` 在 `headers` 之外要求 `value`;新增的 `missingCredential` 与 `credential` 选项分别命名凭据缺失的失败和发布的凭据。`createModelListingCache` 的 `credential(url)` 返回请求头,其 `load` 变为可选。 diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index 0495666d6b..76fde08e07 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -28,7 +28,7 @@ zh: 46f199ee79a8c5dc /deepseek-ai-dsh-llm-deepseek/use-this-package/account-credentials: en: bcb58fd33f59dbf2 - zh: ceafdef88eb66b30 + zh: ff512a17c15aeadf /deepseek-ai-dsh-llm-deepseek/use-this-package/streaming-with-thinking-and-images: en: f880b79feebb9e63 zh: 0dbbb2378e6f9af3 @@ -88,4 +88,4 @@ zh: bf838648f8ba4e62 /deepseek-ai-dsh-llm-deepseek/known-limitations-and-deferred-work/dev-note: en: ddc6cf85ac5d9520 - zh: f5dd039bb67ef8db + zh: d61436104184ce7c diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index 0ae617f627..24595d9603 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -91,7 +91,7 @@ Messages 以内容块发送文本、思考、工具调用和工具结果,以 ` Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 Bearer 前缀;API Key 使用 `x-api-key`。两种凭据模式均拒绝重定向。账号路由负责 HTTP 401 分类,账号服务负责凭据失效处理;传输层将错误交给凭据的回调。 -提供方插件通过三个适配器钩子拥有凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、裸凭据值、可选的失败回调以及可选的 `revoked` 信号;未配置时返回 `undefined`。凭据的所有者收回凭据时,该信号结束模型请求及其文件操作,失败回调为这次结束命名。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。`credential` 通过 `ctx.llm.routeCredential(provider)` 发布路由的凭据种类、可选引用和存在性检查,并附带路由的基础地址,使 Web 提供方无需读取提供方配置即可用同一凭据调用同一部署。插件通过 `dsh-credentials` 的[凭据引用函数](../../credentials/credentials/README.zh.md)读取 API Key,通过[账号服务](../../account/deepseek-account/README.zh.md)读取账号凭据;本传输层两者都不读取。 +提供方插件通过三个适配器钩子拥有凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、裸凭据值、可选的失败回调以及可选的 `revoked` 信号;未配置时返回 `undefined`。凭据的所有者撤回凭据时,该信号结束模型请求及其文件操作,失败回调为这次结束命名。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。`credential` 通过 `ctx.llm.routeCredential(provider)` 发布路由的凭据种类、可选引用和存在性检查,并附带路由的基础地址,使 Web 提供方无需读取提供方配置即可用同一凭据调用同一部署。插件通过 `dsh-credentials` 的[凭据引用函数](../../credentials/credentials/README.zh.md)读取 API Key,通过[账号服务](../../account/deepseek-account/README.zh.md)读取账号凭据;本传输层两者都不读取。 ### 带 thinking 与图片的流式调用 @@ -220,4 +220,4 @@ loop 保留的响应块会追加到下一个请求,并保留其更早的可复 无。 -`deepseek-official` 仅使用配置的 API Key 引用;`deepseek-account` 仅在账号提供方允许的推理来源使用已保存的 DSH 授权。两条路由共享 Messages 传输,模型与文件设置独立配置。账号凭证缺失或不适用于目标时拒绝请求并提示登录;两条路由均不回退到另一凭证。Chat 和 Files 请求拒绝重定向。账号路由插件根据运行中 Agent 已记录的请求上下文负责退登取消,包括工具执行阶段;传输层接收现有请求的中止信号,并结束凭据已被收回的请求。 +`deepseek-official` 仅使用配置的 API Key 引用;`deepseek-account` 仅在账号提供方允许的推理来源使用已保存的 DSH 授权。两条路由共享 Messages 传输,模型与文件设置独立配置。账号凭证缺失或不适用于目标时拒绝请求并提示登录;两条路由均不回退到另一凭证。Chat 和 Files 请求拒绝重定向。账号路由插件根据运行中 Agent 已记录的请求上下文负责退登取消,包括工具执行阶段;传输层接收现有请求的中止信号,并结束凭据已被撤回的请求。 diff --git a/packages/web/web-deepseek-api/README.i18n.yaml b/packages/web/web-deepseek-api/README.i18n.yaml index db6f262828..6d2f73adfb 100644 --- a/packages/web/web-deepseek-api/README.i18n.yaml +++ b/packages/web/web-deepseek-api/README.i18n.yaml @@ -22,7 +22,7 @@ zh: 85d1b8408cf1f325 /deepseek-ai-dsh-web-deepseek-api/use-this-package/results-and-failures: en: e7a5d332ebababe7 - zh: 5020eabd799ebb5c + zh: 6ea098d53d4e9616 /deepseek-ai-dsh-web-deepseek-api/understand-the-implementation: en: 597dab3fe52fa59d zh: 4370d01d5a58f2f9 diff --git a/packages/web/web-deepseek-api/README.zh.md b/packages/web/web-deepseek-api/README.zh.md index 6243b8359b..3dbe337001 100644 --- a/packages/web/web-deepseek-api/README.zh.md +++ b/packages/web/web-deepseek-api/README.zh.md @@ -74,7 +74,7 @@ Search 与 Fetch 每次操作各自从同一份设置快照解析端点和凭据 Search API 接收 `query`、`count`(配置的结果数,或请求中更小的 `maxResults`)、`need_content: false`,以及在 `sendOriginalQuestion` 未关闭时的 `ori_question`:发起会话中最近一条用户提示的文本,空白折叠后截取至 128 个字符。在会话之外或没有此类提示的搜索不发送该字段。提供者将 `results[].snippet` 映射为展示用摘录,将 `results[].summary` 映射为面向模型的摘录,并将可为 null 的 `date` 映射为可选的 `publishedAt`;`dsh-tool-web` 限制每条摘要的长度。空结果数组表示成功。Fetch 发送 `url`,以文本正文返回原始 Markdown,并报告 HTTP 状态 200,因为目标没有可用内容时 API 会返回错误状态。返回 URL 为请求 URL:API 不报告重定向后的最终 URL。 -单独配置的基础地址无法解析时,该能力的提供者不可用;`count` 不在 1 至 50 之间时,Search 不可用。凭据缺失以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败;所需模型路由的设置无法解析时以 `WEB_PROVIDER_MISCONFIGURED` 失败,并点名解析器的失败原因、模型页面以及该能力的 `*BaseURL` 与 `*ApiKeyEnv`;取消使用 `WEB_ABORTED`;传输、HTTP 和响应格式错误使用 `WEB_PROVIDER_ERROR`。请求携带的凭据被收回时(例如账号退登通过授权的 `revoked` 信号收回),请求随即结束:以 `WEB_PROVIDER_ERROR` 失败并提供重新登录的指引,其他种类的凭据则指引用户在模型页面检查该凭据;调用方同时取消时仍为 `WEB_ABORTED`。重定向在联系目标前即被拒绝。Fetch API 的非成功状态表示抓取失败,不代表目标页面的状态。账号鉴权的 HTTP 401 响应只作废该请求实际发送的 token,并提供重新登录指引;更新的登录不受影响,凭据删除失败不会替换原 HTTP 错误。API 密钥失败与 HTTP 403 从不作废账号 token;其他请求失败指出端点及其来源:路由端点指导用户在模型页面检查该提供方的基础地址,或设置该能力的 `*BaseURL` 与 `*ApiKeyEnv`;单独配置指导用户修改或删除这两个字段。不会自动重试或回退至其他提供者。 +单独配置的基础地址无法解析时,该能力的提供者不可用;`count` 不在 1 至 50 之间时,Search 不可用。凭据缺失以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败;所需模型路由的设置无法解析时以 `WEB_PROVIDER_MISCONFIGURED` 失败,并点名解析器的失败原因、模型页面以及该能力的 `*BaseURL` 与 `*ApiKeyEnv`;取消使用 `WEB_ABORTED`;传输、HTTP 和响应格式错误使用 `WEB_PROVIDER_ERROR`。请求携带的凭据被撤回时(例如账号退登通过授权的 `revoked` 信号撤回),请求随即结束:以 `WEB_PROVIDER_ERROR` 失败并提供重新登录的指引,其他种类的凭据则指引用户在模型页面检查该凭据;调用方同时取消时仍为 `WEB_ABORTED`。重定向在联系目标前即被拒绝。Fetch API 的非成功状态表示抓取失败,不代表目标页面的状态。账号鉴权的 HTTP 401 响应只作废该请求实际发送的 token,并提供重新登录指引;更新的登录不受影响,凭据删除失败不会替换原 HTTP 错误。API 密钥失败与 HTTP 403 从不作废账号 token;其他请求失败指出端点及其来源:路由端点指导用户在模型页面检查该提供方的基础地址,或设置该能力的 `*BaseURL` 与 `*ApiKeyEnv`;单独配置指导用户修改或删除这两个字段。不会自动重试或回退至其他提供者。 ----- From 76d7a49e9fa1383d5cdf78bf67c38febcd88c70d Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 13 Nov 2026 15:52:07 +0800 Subject: [PATCH 27/48] docs(upgrade-guide): move the route credential guide to v0.2.2-rc.3 master released 0.2.2-rc.3, which freezes docs/upgrade-guide/v0.2.2-rc.2. The guide of this unmerged change moves to the directory of the current root version, and the route credential Agent Note links to its new path. The guide text is unchanged. --- .../2026-11-10-llm-route-credential-seam.i18n.yaml | 4 ++-- .../architecture/2026-11-10-llm-route-credential-seam.md | 2 +- .../architecture/2026-11-10-llm-route-credential-seam.zh.md | 2 +- .../llm-route-credential/guide.i18n.yaml | 6 +++--- .../llm-route-credential/guide.md | 0 .../llm-route-credential/guide.zh.md | 0 6 files changed, 7 insertions(+), 7 deletions(-) rename docs/upgrade-guide/{v0.2.2-rc.2 => v0.2.2-rc.3}/llm-route-credential/guide.i18n.yaml (87%) rename docs/upgrade-guide/{v0.2.2-rc.2 => v0.2.2-rc.3}/llm-route-credential/guide.md (100%) rename docs/upgrade-guide/{v0.2.2-rc.2 => v0.2.2-rc.3}/llm-route-credential/guide.zh.md (100%) diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index 763a04ece1..c46edc0386 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -15,5 +15,5 @@ en: d6b2de393add9887 zh: b5351f9a49387bd6 /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/consequences: - en: 748f306d720ade43 - zh: c28734e1d072feb3 + en: ff4e2a7346097e54 + zh: 7881f404099276b3 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md index b41afa2b2b..fc30a5a383 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -42,6 +42,6 @@ The web providers consume publications. `web-deepseek-api` builds each operation ## Consequences -Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `routeCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`. +Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `routeCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`. A sign-out ends the in-flight model, Files, Search, and Fetch requests that carry the account token, including requests no Agent turn owns, such as a model request outside a turn or an account-billed web search; the account listing request keeps its own deadline. The signal supplements the Agent cancellation of the [account sign-out decision](2026-09-17-account-provider-signout.md), which rejected a login-level signal as a duplicate of that chain: the chain reaches a request only through a mounted listener and a running Agent turn. While the account route is disabled, a task it started that still runs is not reported to the sign-out confirmation, and a sign-out ends it only through a model request in flight. A credential released by an account service that has since been replaced is not withdrawn by the replacement's sign-out; the route plugin's listener still cancels Agent turns. diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index b47687c8b8..b370391879 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -42,6 +42,6 @@ Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.route ## 后果 -新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `routeCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 +新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `routeCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 退登会结束携带账号 token 的在途模型、Files、Search 与 Fetch 请求,包括不属于任何 Agent 回合的请求,例如回合之外的模型请求或按账号计费的 Web 搜索;账号列表请求仍只受自身期限约束。该信号是对[账号退登决策](2026-09-17-account-provider-signout.zh.md)中 Agent 取消链路的补充;那份决策以重复该链路为由否决了登录级信号,而该链路只能经由已挂载的监听和运行中的 Agent 回合到达请求。账号路由被停用期间,它此前启动且仍在运行的任务不会报告给退登确认,退登也只能通过在途的模型请求结束它。已被替换的账号服务释放的凭据不会被替换后服务的退登撤回;路由插件的监听仍会取消 Agent 回合。 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.i18n.yaml similarity index 87% rename from docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml rename to docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.i18n.yaml index 7577d27ae0..5a217379ea 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.i18n.yaml @@ -1,13 +1,13 @@ # Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading # section, a hash of its English and Chinese blocks outside code blocks and generated regions. # After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md /: en: f0cf30e5430471e8 zh: 2e6e871797dfdd6b /deepseek-routes-publish-the-credential-web-consumers-reuse: - en: f0139803159ee9c9 - zh: 73bd5dfd53ed8d36 + en: b5392bcd81f69488 + zh: 68cd945f2dde46af /deepseek-routes-publish-the-credential-web-consumers-reuse/change: en: 4e77c6f6c622beb2 zh: 2c119f567ff411ff diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md similarity index 100% rename from docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md rename to docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md similarity index 100% rename from docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md rename to docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md From 1ae70efcde103c1f09fb831e43f3de2a5d25feda Mon Sep 17 00:00:00 2001 From: Shigma Date: Fri, 13 Nov 2026 16:45:54 +0800 Subject: [PATCH 28/48] chore(cordis): sync loader 1.0.0-rc.9 and include 1.2.0 --- .../guide.i18n.yaml | 16 + .../cordis-loader-entry-validation/guide.md | 27 ++ .../guide.zh.md | 27 ++ .../app-boot/src/compatibility-preflight.ts | 4 +- .../app-boot/src/config-schema/collect.ts | 8 +- packages/boot/app-boot/src/index.ts | 12 +- packages/boot/app-boot/src/profile.ts | 2 +- packages/boot/app-boot/tests/app-boot.spec.ts | 4 +- .../boot/app-boot/tests/config-dump.spec.ts | 28 +- .../boot/app-boot/tests/config-schema.spec.ts | 11 +- .../boot/app-boot/tests/user-patches.spec.ts | 8 +- .../boot/plugin-manager/tests/patch.spec.ts | 2 +- .../web-app/tests/browser-defaults.spec.ts | 2 +- .../web-app/tests/document-conversion.e2e.ts | 2 +- .../web-app/tests/document-preview.spec.ts | 2 +- .../plugin-inventory/tests/inventory.spec.ts | 2 +- .../src/assembly/bundle-roster.ts | 2 +- pnpm-lock.yaml | 71 ++++- scripts/cordis-entry-commit.spec.ts | 4 +- scripts/cordis-entry-yaml.spec.ts | 8 +- scripts/cordis-loader-rc9.spec.ts | 106 +++++++ scripts/cordis-loader-resolve.spec.ts | 7 +- scripts/verify-default-product-isolation.ts | 2 +- scripts/verify-product-use.ts | 2 +- vendor/README.md | 19 +- vendor/include/README.md | 12 +- vendor/include/package.json | 2 +- vendor/include/src/index.ts | 284 ++++++++++++++---- vendor/include/src/patch.ts | 283 ++++++++--------- vendor/loader/README.md | 10 +- vendor/loader/src/config/entry.ts | 76 +++-- vendor/loader/src/config/group.ts | 42 ++- vendor/loader/src/config/tree.ts | 91 +++++- vendor/loader/src/config/utils.ts | 132 +++++++- vendor/loader/src/index.ts | 23 +- vendor/loader/src/resolve.ts | 34 ++- 36 files changed, 1072 insertions(+), 295 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.zh.md create mode 100644 scripts/cordis-loader-rc9.spec.ts diff --git a/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.i18n.yaml new file mode 100644 index 0000000000..2d20fa39db --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.md +/: + en: b414093b29c38765 + zh: 2a69f37a40e35a99 +/loader-validates-entry-options-and-include-parses-yaml-1-2: + en: 0ba0b666924ce1f0 + zh: 0c5668ee67163d00 +/loader-validates-entry-options-and-include-parses-yaml-1-2/change: + en: b0d2ae6a748cab50 + zh: a2521c4dc48e4d3d +/loader-validates-entry-options-and-include-parses-yaml-1-2/migration: + en: 2c167e1042c952a5 + zh: aec49a7754befae0 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.md new file mode 100644 index 0000000000..336418a559 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.md @@ -0,0 +1,27 @@ +--- +kind: upgrade-guide +description: "Cordis Loader 1.0.0-rc.9 and Include 1.2.0 parse YAML 1.2, reject malformed entries, and return PatchResult from applyEntryPatches." +--- + +# Loader validates entry options, and Include parses YAML 1.2 + +English | [中文](guide.zh.md) + +## Change + +`@deepseek-ai/cordis-plugin-loader` now carries upstream Loader 1.0.0-rc.9, and `@deepseek-ai/cordis-plugin-include` carries Include 1.2.0. Hand-written `cordis.yml`, `cordis.patch.yml` and overlay files, and code that calls the Include or Loader exports, are affected: + +- Include and `parseEntryYaml` parse YAML 1.2 under the core schema instead of the js-yaml JSON schema. A binary integer such as `0b101` now reads as the string `'0b101'`. An empty `!!js` scalar now reads as an empty expression, which evaluates to `undefined`, instead of failing to parse. +- Entry options are validated before an entry is created or updated. `name` must be a string; `group` a boolean; `disabled` a boolean or `!!js` expression; a group's `config` a list; `inject` a string list or a mapping; `isolate` a mapping whose values are `true` or a string. An entry that loaded before with such a value is now rejected and logged, and its siblings still start. An Include file with an entry that is not a mapping is rejected as a whole. Ids containing `:` remain accepted. +- Parse, entry option and config validation errors name the file position as `file:line:column`. When an entry's own module cannot be found, the error is a `ModuleNotFoundError` without Node's `imported from` part; its `code` is still `ERR_MODULE_NOT_FOUND`. +- A patch that replaces a group's `config` brings child entries that later patches can address, and the children it replaces can no longer be patched. +- `applyEntryPatches(data, patches, warn)` returns `{ data, index }` instead of the entry list, and writes generated ids into the anonymous entries of a replaced group `config` in `patches`. `parseEntryYaml` throws the `YAMLError` of the `yaml` package instead of a js-yaml `YAMLException`. + +## Migration + +1. Write binary integers that must stay numbers in decimal or hexadecimal. +2. Run `dsh --dump-config` for each profile. A parse error now names its line and column; fix the reported value. +3. Start the profile and check the log for `invalid entry options` and `invalid config`. Correct each listed path at the position shown. +4. Where a later patch addressed a child of a group whose `config` an earlier patch replaced, check that the child now receives the patch. +5. In code, read `applyEntryPatches(...).data`, and pass `structuredClone(patches)` where the patch list must stay unchanged. Catch parse errors without depending on js-yaml types; `entryYamlErrorPosition(error)` still returns the position. +6. Confirm that `dsh --dump-config` prints the expected entries and that the profile starts without those diagnostics. diff --git a/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.zh.md new file mode 100644 index 0000000000..d1e3170659 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.zh.md @@ -0,0 +1,27 @@ +--- +kind: upgrade-guide +description: "Cordis Loader 1.0.0-rc.9 与 Include 1.2.0 按 YAML 1.2 解析、拒绝格式错误的条目,applyEntryPatches 改为返回 PatchResult。" +--- + +# Loader 校验条目选项,Include 按 YAML 1.2 解析 + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/cordis-plugin-loader` 现在包含上游 Loader 1.0.0-rc.9,`@deepseek-ai/cordis-plugin-include` 包含 Include 1.2.0。受影响的是手写的 `cordis.yml`、`cordis.patch.yml` 与 overlay 文件,以及调用 Include 或 Loader 导出的代码: + +- Include 和 `parseEntryYaml` 按 YAML 1.2 core schema 解析,不再使用 js-yaml 的 JSON schema。`0b101` 这样的二进制整数现在读作字符串 `'0b101'`。空的 `!!js` 标量现在读作空表达式,求值结果为 `undefined`,不再解析失败。 +- 创建或更新条目前会校验条目选项。`name` 必须是字符串;`group` 必须是布尔值;`disabled` 必须是布尔值或 `!!js` 表达式;group 的 `config` 必须是列表;`inject` 必须是字符串列表或映射;`isolate` 必须是映射,其值为 `true` 或字符串。此前能加载但含有这类值的条目现在会被拒绝并记录日志,同级条目仍会启动。Include 文件中只要有一个条目不是映射,整个文件都会被拒绝。含 `:` 的 id 仍然可以使用。 +- 解析错误、条目选项错误和配置校验错误都会以 `file:line:column` 指出文件位置。条目自身的模块找不到时,错误为 `ModuleNotFoundError`,不含 Node 的 `imported from` 部分;其 `code` 仍为 `ERR_MODULE_NOT_FOUND`。 +- 替换 group `config` 的 patch 带来的子条目可以被后续 patch 定位,被替换掉的子条目则不能再被 patch。 +- `applyEntryPatches(data, patches, warn)` 返回 `{ data, index }`,不再直接返回条目列表;它会把生成的 id 写入 `patches` 中被替换的 group `config` 里的匿名条目。`parseEntryYaml` 抛出 `yaml` 包的 `YAMLError`,不再抛出 js-yaml 的 `YAMLException`。 + +## 迁移 + +1. 必须保持为数字的二进制整数改写为十进制或十六进制。 +2. 对每个 profile 运行 `dsh --dump-config`。解析错误现在会给出行号和列号;按提示修正对应的值。 +3. 启动 profile,检查日志中的 `invalid entry options` 和 `invalid config`,在给出的位置修正列出的每个路径。 +4. 如果后续 patch 针对的是某个 group 的子条目,而该 group 的 `config` 已被前面的 patch 替换,确认该子条目现在会应用这个 patch。 +5. 在代码中读取 `applyEntryPatches(...).data`;如果 patch 列表必须保持不变,传入 `structuredClone(patches)`。捕获解析错误时不要依赖 js-yaml 的类型;`entryYamlErrorPosition(error)` 仍会返回错误位置。 +6. 确认 `dsh --dump-config` 输出预期的条目,且 profile 启动时不再出现上述诊断。 diff --git a/packages/boot/app-boot/src/compatibility-preflight.ts b/packages/boot/app-boot/src/compatibility-preflight.ts index c8aeedf2ad..0cfe31d15b 100644 --- a/packages/boot/app-boot/src/compatibility-preflight.ts +++ b/packages/boot/app-boot/src/compatibility-preflight.ts @@ -156,7 +156,7 @@ function preflight( data = config.initial } if (!Array.isArray(data)) return undefined - const children = applyEntryPatches(data as EntryOptions[], config.patches, patchWarning(ctx)) + const children = applyEntryPatches(data as EntryOptions[], structuredClone(config.patches), patchWarning(ctx)).data return check(children, pathToFileURL(filename).href) ? `its included file ${filename} reaches an incompatible plugin, and that file is never rewritten` : undefined @@ -180,7 +180,7 @@ export function prepareProfilePatches( ctx: Context, patches: PatchOptions[], parentURL: string, binName = 'dsh', ): PatchOptions[] { if (ctx.get('profileContext') === undefined) return patches - const entries = applyEntryPatches([], patches, patchWarning(ctx)) + const entries = applyEntryPatches([], structuredClone(patches), patchWarning(ctx)).data const rows = prepareProfileEntries(ctx, entries, parentURL, binName) return rows.length === 0 ? [] : [{ insert: rows }] } diff --git a/packages/boot/app-boot/src/config-schema/collect.ts b/packages/boot/app-boot/src/config-schema/collect.ts index 0eed38de5c..dead6f222f 100644 --- a/packages/boot/app-boot/src/config-schema/collect.ts +++ b/packages/boot/app-boot/src/config-schema/collect.ts @@ -52,6 +52,10 @@ function entryList(value: unknown): unknown[] { return value as unknown[] } +function hasNonRecordEntry(rows: readonly unknown[]): boolean { + return rows.some(row => !record(row) || (row.group === true && Array.isArray(row.config) && hasNonRecordEntry(row.config))) +} + function includePatches(value: unknown): PatchOptions[] | undefined { if (value === undefined) return undefined if (!Array.isArray(value)) throw new Error('include patches must be a literal patch list; config expressions are not evaluated') @@ -157,9 +161,11 @@ export async function collectConfigSchemas( } const patches = includePatches(config.patches) const rows = entryList(source) + // Include rejects the whole file when any entry, including a group child, is not a mapping. + if (hasNonRecordEntry(rows)) throw new Error(`include ${filename} has an entry that is not a mapping; child declarations are unavailable`) let children: EntryOptions[] try { - children = applyEntryPatches(rows as EntryOptions[], patches, warn(path)) + children = applyEntryPatches(rows as EntryOptions[], patches, warn(path)).data } catch (error) { throw new Error(`include patches could not be composed for ${filename}; child declarations are unavailable`, { cause: error }) } diff --git a/packages/boot/app-boot/src/index.ts b/packages/boot/app-boot/src/index.ts index 13b3ff792c..52cf730d18 100644 --- a/packages/boot/app-boot/src/index.ts +++ b/packages/boot/app-boot/src/index.ts @@ -480,7 +480,7 @@ function rowIds(patches: readonly PatchOptions[]): Set { } } // Patch warnings are logged when the generation itself is prepared. - visit(applyEntryPatches([], patches as PatchOptions[], () => {})) + visit(applyEntryPatches([], patches as PatchOptions[], () => {}).data) return ids } @@ -614,9 +614,9 @@ export interface ConfigDumpLayer { * Compose the configured entry list: parse the base config file with the * include's entry-list dialect, apply every layer's patches as ONE flattened * list through the include's own patch algorithm (`applyEntryPatches`) — the - * same call `boot()` makes, so even patch-visibility corner cases (a later - * layer targeting a group child a plain config replacement introduced, which - * the single-pass id index never sees) compose identically — then render the + * same call `boot()` makes, so patch-visibility cases (a later layer + * targeting a group child that a group config replacement introduced or + * removed) compose identically — then render the * result as YAML in the same dialect (`!!js` expressions print verbatim, * unevaluated). Row admission is a later stage: a plugin row the compatibility * policy denies still appears here, while a denied bundle contributes no layer. @@ -673,14 +673,14 @@ export function renderConfigDump( // The patches are cloned per call: applyEntryPatches clones entries and // inserted rows but assigns override values such as `config` by reference, // so each snapshot keeps its own copies of those values. - const snapshot = (count: number, warnings: string[]): ReturnType => { + const snapshot = (count: number, warnings: string[]): ReturnType['data'] => { const flattened = structuredClone(layers.slice(0, count).flatMap(layer => layer.patches)) return applyEntryPatches(base, flattened, (message: string, ...args: unknown[]) => { // The include logs through cordis's printf-style logger (`%C` = code); a // dump has no logger, so substitute inline for a plain line. let index = 0 warnings.push(message.replace(/%C/g, () => JSON.stringify(args[index++]))) - }) + }).data } let previous = base let previousWarnings: string[] = [] diff --git a/packages/boot/app-boot/src/profile.ts b/packages/boot/app-boot/src/profile.ts index 32719f2484..86caac54a0 100644 --- a/packages/boot/app-boot/src/profile.ts +++ b/packages/boot/app-boot/src/profile.ts @@ -758,5 +758,5 @@ export function composeEntries( return applyEntryPatches([], structuredClone(layers.flat()), (message: string, ...args: unknown[]) => { let index = 0 warn(message.replace(/%C/g, () => JSON.stringify(args[index++]))) - }) + }).data } diff --git a/packages/boot/app-boot/tests/app-boot.spec.ts b/packages/boot/app-boot/tests/app-boot.spec.ts index e46864210f..b4eded6e9c 100644 --- a/packages/boot/app-boot/tests/app-boot.spec.ts +++ b/packages/boot/app-boot/tests/app-boot.spec.ts @@ -887,7 +887,7 @@ describe('loadOverlayPatches', () => { expect(loadOverlayPatches(NAME, valid)).toEqual([{ id: 'target', config: { value: { __jsExpr: 'process.env.VALUE' } } }]) expect(() => loadOverlayPatches(NAME, join(dir, 'missing.yml'))).toThrow(`${NAME}: failed to read overlay`) const malformed = join(dir, 'malformed.yml') - writeFileSync(malformed, ': bad') + writeFileSync(malformed, '- [bad\n') expect(() => loadOverlayPatches(NAME, malformed)).toThrow(`${NAME}: failed to parse overlay`) const mapping = join(dir, 'mapping.yml') writeFileSync(mapping, 'id: target\n') @@ -1202,7 +1202,7 @@ describe('boot', () => { it.each([ ['missing', undefined, 'config file not found'], - ['malformed', 'invalid: [unclosed\n', 'unexpected end'], + ['malformed', 'invalid: [unclosed\n', 'must be sufficiently indented and end with a ] (at '], ['non-array', 'entries: []\n', 'top-level array'], ])('rejects a %s root configuration', async (_kind, content, message) => { const dir = tmp() diff --git a/packages/boot/app-boot/tests/config-dump.spec.ts b/packages/boot/app-boot/tests/config-dump.spec.ts index 8a56d57e34..c3bc3bf88a 100644 --- a/packages/boot/app-boot/tests/config-dump.spec.ts +++ b/packages/boot/app-boot/tests/config-dump.spec.ts @@ -115,12 +115,9 @@ describe('renderConfigDump', () => { }) it('composes all layers as one flattened patch list, exactly like boot()', () => { - // boot() flattens every layer into ONE applyEntryPatches call, whose id - // index sees inserted rows but NOT children introduced by a plain group - // `config` replacement. A per-layer composition would rebuild the index - // between layers and let the second layer patch that child — a tree the - // real boot never mounts. Pin the single-call semantics: the child patch - // is skipped (with the layer-labeled warning), matching boot. + // boot() flattens every layer into ONE applyEntryPatches call. Children + // supplied by a group `config` replacement join the id index, so a later + // layer can patch them, and the dump lists that layer on the group row. const dir = tmp() const base = join(dir, 'base.yml') writeFileSync(base, [ @@ -138,14 +135,23 @@ describe('renderConfigDump', () => { }, { label: 'b.yml', patches: [{ id: 'child', config: { v: 2 } }] }, ], line => void warnings.push(line)) - expect(warnings).toEqual([`${NAME}: [b.yml] patch: entry "child" not found`]) + expect(warnings).toEqual([]) const parsed = parseEntryYaml(dump) as { config?: { config?: { v?: number } }[] }[] - expect(parsed[0]?.config?.[0]?.config?.v).toBe(1) - // The skipped layer did not change the row, so the comment does not list it. - expect(dump).toContain('# == base.yml, patched by a.yml\n- id: g') - expect(dump).not.toContain('b.yml\n- id: g') + expect(parsed[0]?.config?.[0]?.config?.v).toBe(2) + expect(dump).toContain('# == base.yml, patched by a.yml, b.yml\n- id: g') + }) + + it('drops the children of a replaced group config from the patch index', () => { + const dir = tmp() + const base = join(dir, 'base.yml') + writeFileSync(base, '- id: g\n name: ./group.mjs\n group: true\n config:\n - id: child\n name: ./noop.mjs\n') + const warnings: string[] = [] + renderConfigDump(NAME, base, [ + { label: 'a.yml', patches: [{ id: 'g', config: [] }, { id: 'child', disabled: true }] }, + ], line => void warnings.push(line)) + expect(warnings).toEqual([`${NAME}: [a.yml] patch: entry "child" not found`]) }) it('reports a patch whose target row is absent through warn with its layer label and keeps composing', () => { diff --git a/packages/boot/app-boot/tests/config-schema.spec.ts b/packages/boot/app-boot/tests/config-schema.spec.ts index debb11641a..04ae5a3e9c 100644 --- a/packages/boot/app-boot/tests/config-schema.spec.ts +++ b/packages/boot/app-boot/tests/config-schema.spec.ts @@ -418,15 +418,18 @@ describe('collectConfigSchemas', () => { expect(validates(result, [{ name: 'good', config: 3 }])).toBe(true) }) - it('keeps healthy group and include siblings after malformed child rows', async () => { + it('keeps healthy group siblings after a malformed child row and rejects an include with a non-mapping entry', async () => { modules.set('good', { Config: Schema.string() }) const result = await collectConfigSchemas(profile, [ row('cordis:group', [{ name: false }, row('good')]), - row('cordis:include', { path: './missing.yml', initial: [null, row('good')] }), + row('cordis:include', { path: './missing.yml', initial: [row('good'), { ...row('cordis:group', [null]), group: true }] }), ], resolution) - expect(result['x-cordis'].diagnostics.map(item => item.path)).toEqual(['/0/config/0', '/1/include/0']) + expect(result['x-cordis'].diagnostics.map(item => [item.path, item.message])).toEqual([ + ['/0/config/0', expect.any(String)], + ['/1', expect.stringContaining('has an entry that is not a mapping')], + ]) expect(result['x-cordis'].entries.filter(entry => entry.status === 'schema').map(entry => entry.path)) - .toEqual(['/0/config/1', '/1/include/1']) + .toEqual(['/0/config/1']) }) it.each([ diff --git a/packages/boot/app-boot/tests/user-patches.spec.ts b/packages/boot/app-boot/tests/user-patches.spec.ts index 5b0257aac1..a974eaddec 100644 --- a/packages/boot/app-boot/tests/user-patches.spec.ts +++ b/packages/boot/app-boot/tests/user-patches.spec.ts @@ -132,12 +132,12 @@ describe('loadOptionalPatches', () => { .toThrow(new RegExp(`^${NAME}: failed to read patches `)) }) - it('fails loud on unparsable YAML and on a !!js tag with no expression body', () => { + it('fails loud on unparsable YAML and on an unknown tag', () => { const dir = tmp() writeFileSync(join(dir, PROFILE_PATCH_FILENAME), 'invalid: [unclosed\n') expect(() => loadOptionalPatches(NAME, join(dir, PROFILE_PATCH_FILENAME))) .toThrow(new RegExp(`^${NAME}: failed to parse patches `)) - writeFileSync(join(dir, PROFILE_PATCH_FILENAME), '- id: x\n config:\n a: !!js\n') + writeFileSync(join(dir, PROFILE_PATCH_FILENAME), '- id: x\n config:\n a: !js process.env.A\n') expect(() => loadOptionalPatches(NAME, join(dir, PROFILE_PATCH_FILENAME))) .toThrow(new RegExp(`^${NAME}: failed to parse patches `)) }) @@ -343,8 +343,8 @@ describe('profile reconciliation settlement', () => { const ctx = await boot(NAME, join(dir, 'cordis.yml'), patches) onTestFinished(() => ctx.fiber.dispose()) // Reload diagnostics carry the import error's message without stack frames. - const prefix = 'missing-plugin \\(\\./missing\\.mjs\\): failed to import: Error \\[ERR_MODULE_NOT_FOUND\\]' - const diagnostic = new RegExp(`^${prefix}: Cannot find module '[^']*missing\\.mjs' imported from [^\\n]*$`, 'u') + const prefix = 'missing-plugin \\(\\./missing\\.mjs\\): failed to import: ModuleNotFoundError' + const diagnostic = new RegExp(`^${prefix}: Cannot find module '[^']*missing\\.mjs'$`, 'u') expect(await reconcileProfilePatches(ctx, patches, NAME)).toEqual([expect.stringMatching(diagnostic)]) }) diff --git a/packages/boot/plugin-manager/tests/patch.spec.ts b/packages/boot/plugin-manager/tests/patch.spec.ts index 9580da1e52..9ee0b9ec87 100644 --- a/packages/boot/plugin-manager/tests/patch.spec.ts +++ b/packages/boot/plugin-manager/tests/patch.spec.ts @@ -86,7 +86,7 @@ it('updates the last matching named override and leaves mismatched names untouch { id: 'tool', name: 'package', config: { value: { __jsExpr: 'process.platform' } }, disabled: false }, { id: 'tool', name: 'another-package', disabled: true }, ]) - expect(applyEntryPatches([{ id: 'tool', name: 'package' }], patches, () => {})) + expect(applyEntryPatches([{ id: 'tool', name: 'package' }], patches, () => {}).data) .toMatchObject([{ id: 'tool', name: 'package', disabled: false }]) expect(await writePluginEnabled(profile, 'tool', 'package', true)).toBe(false) expect(await readFile(profile.patchPath, 'utf8')).toBe(text) diff --git a/packages/bundle/web-app/tests/browser-defaults.spec.ts b/packages/bundle/web-app/tests/browser-defaults.spec.ts index 73ee9b1a82..b831a0f68f 100644 --- a/packages/bundle/web-app/tests/browser-defaults.spec.ts +++ b/packages/bundle/web-app/tests/browser-defaults.spec.ts @@ -20,7 +20,7 @@ it.each([ expect(rows).toHaveLength(1) expect(rows[0]!.name).toBe('@deepseek-ai/dsh-client-ui-sidebar-browser') const configured = applyEntryPatches(rows, override === undefined ? [] : [{ id: 'ui-sidebar-browser', disabled: override }], - (message) => { throw new Error(message) }) + (message) => { throw new Error(message) }).data const ctx = new Context() onTestFinished(() => ctx.fiber.dispose()) if (profile !== undefined) { diff --git a/packages/bundle/web-app/tests/document-conversion.e2e.ts b/packages/bundle/web-app/tests/document-conversion.e2e.ts index e5b4f130d9..b59841f3a2 100644 --- a/packages/bundle/web-app/tests/document-conversion.e2e.ts +++ b/packages/bundle/web-app/tests/document-conversion.e2e.ts @@ -28,7 +28,7 @@ it('loads one shared conversion row and retains caller-owned PDFs after disposal .filter(row => row.name === '@deepseek-ai/dsh-office-kit') expect(rows.map(row => row.id)).toEqual(['office-kit']) const configured = applyEntryPatches(rows, [{ id: 'office-kit', config: { maxConcurrentConversions: 1, outputDirectory } }], - (message) => { throw new Error(message) }) + (message) => { throw new Error(message) }).data const configPath = join(directory, 'cordis.yml') await writeFile(configPath, JSON.stringify(configured)) ctx.baseUrl = pathToFileURL(directory).href + '/' diff --git a/packages/bundle/web-app/tests/document-preview.spec.ts b/packages/bundle/web-app/tests/document-preview.spec.ts index ae78c1aa59..852b8c15f6 100644 --- a/packages/bundle/web-app/tests/document-preview.spec.ts +++ b/packages/bundle/web-app/tests/document-preview.spec.ts @@ -52,7 +52,7 @@ it('loads the shipped Office rows with separately patched settings and authorize const configured = applyEntryPatches(rows, [ { id: 'office-kit', config: providerConfig }, { id: 'ui-sidebar-documentpreview', config: clientConfig }, - ], (message) => { throw new Error(message) }) + ], (message) => { throw new Error(message) }).data expect(configured.find(row => row.id === 'ui-sidebar-documentpreview')!.config).toEqual(clientConfig) await writeFile(configPath, JSON.stringify([ { name: '@deepseek-ai/dsh-session' }, diff --git a/packages/host/plugin-inventory/tests/inventory.spec.ts b/packages/host/plugin-inventory/tests/inventory.spec.ts index 6e022ea922..980f9e6fda 100644 --- a/packages/host/plugin-inventory/tests/inventory.spec.ts +++ b/packages/host/plugin-inventory/tests/inventory.spec.ts @@ -181,7 +181,7 @@ describe('PluginInventoryGateway', () => { name: 'cordis:not-installed', disabled: true, }) - await ctx.loader.create({ name: 'cordis:active', group: true }) + await ctx.loader.create({ name: 'cordis:active', group: true, config: [] }) const snapshot = await inventory.list() // No agent-preset roster is composed, so the snapshot carries no presets. diff --git a/packages/test-support/client-runtime/src/assembly/bundle-roster.ts b/packages/test-support/client-runtime/src/assembly/bundle-roster.ts index d31ab8c876..98c6e46e24 100644 --- a/packages/test-support/client-runtime/src/assembly/bundle-roster.ts +++ b/packages/test-support/client-runtime/src/assembly/bundle-roster.ts @@ -56,7 +56,7 @@ export function bundleRoster( const layers = bundles.map(name => readLayer(name, anchor)) const entries = applyEntryPatches([], layers.flatMap(layer => layer.patches), (message: string, ...args: unknown[]) => { throw new Error(`client-test-runtime: bundle patch ${describe(message, args)}`) - }) + }).data const anchors = layers.map(layer => layer.manifestPath) const rows: ClientRosterRow[] = [] const seen = new Set() diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 680fd27625..754929b4b4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -18572,7 +18572,7 @@ importers: version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) vitest: specifier: ^4.1.11 - version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.1)(@vitest/coverage-v8@4.1.11)(happy-dom@20.11.6)(jsdom@29.1.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.0)) + version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.1)(@vitest/coverage-v8@4.1.11)(happy-dom@20.11.6)(jsdom@29.1.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1)) devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ @@ -18792,7 +18792,7 @@ importers: version: 4.3.2 vitest: specifier: ^4.1.11 - version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.1)(@vitest/coverage-v8@4.1.11)(happy-dom@20.11.6)(jsdom@29.1.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.0)) + version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.1)(@vitest/coverage-v8@4.1.11)(happy-dom@20.11.6)(jsdom@29.1.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1)) devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ @@ -20156,9 +20156,9 @@ importers: '@deepseek-ai/cosmokit': specifier: link:../cosmokit version: link:../cosmokit - js-yaml: - specifier: ^4.1.0 - version: 4.3.2 + yaml: + specifier: ^2.9.1 + version: 2.9.1 vendor/loader: dependencies: @@ -27905,6 +27905,11 @@ packages: engines: {node: '>= 14.6'} hasBin: true + yaml@2.9.1: + resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} + engines: {node: '>= 14.6'} + hasBin: true + yargs-parser@20.2.9: resolution: {integrity: sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==} engines: {node: '>=10'} @@ -30910,6 +30915,14 @@ snapshots: optionalDependencies: vite: 8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.0) + '@vitest/mocker@4.1.11(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1))': + dependencies: + '@vitest/spy': 4.1.11 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1) + '@vitest/pretty-format@4.1.11': dependencies: tinyrainbow: 3.1.0 @@ -35661,6 +35674,21 @@ snapshots: tsx: 4.23.13 yaml: 2.9.0 + vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.28 + rolldown: 1.2.7 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 22.20.1 + esbuild: 0.28.2 + fsevents: 2.3.3 + jiti: 2.7.0 + tsx: 4.23.13 + yaml: 2.9.1 + vitepress-plugin-mermaid@2.0.17(mermaid@11.17.2)(vitepress@1.6.4(@algolia/client-search@5.55.2)(@types/node@22.20.1)(@types/react@18.3.31)(lightningcss@1.33.0)(postcss@8.5.28)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(search-insights@2.17.3)(typescript@6.0.3)): dependencies: mermaid: 11.17.2 @@ -35780,6 +35808,37 @@ snapshots: transitivePeerDependencies: - msw + vitest@4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.1)(@vitest/coverage-v8@4.1.11)(happy-dom@20.11.6)(jsdom@29.1.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1)): + dependencies: + '@vitest/expect': 4.1.11 + '@vitest/mocker': 4.1.11(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1)) + '@vitest/pretty-format': 4.1.11 + '@vitest/runner': 4.1.11 + '@vitest/snapshot': 4.1.11 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 + es-module-lexer: 2.1.0 + expect-type: 1.3.0 + magic-string: 0.30.21 + obug: 2.1.3 + pathe: 2.0.3 + picomatch: 4.0.7 + std-env: 4.1.0 + tinybench: 2.9.0 + tinyexec: 1.2.4 + tinyglobby: 0.2.17 + tinyrainbow: 3.1.0 + vite: 8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1) + why-is-node-running: 2.3.0 + optionalDependencies: + '@opentelemetry/api': 1.9.1 + '@types/node': 22.20.1 + '@vitest/coverage-v8': 4.1.11(vitest@4.1.11) + happy-dom: 20.11.6 + jsdom: 29.1.1(@noble/hashes@2.4.0) + transitivePeerDependencies: + - msw + vscode-jsonrpc@5.0.1: {} vscode-jsonrpc@9.0.1: {} @@ -35908,6 +35967,8 @@ snapshots: yaml@2.9.0: {} + yaml@2.9.1: {} + yargs-parser@20.2.9: {} yargs-parser@21.1.1: {} diff --git a/scripts/cordis-entry-commit.spec.ts b/scripts/cordis-entry-commit.spec.ts index e915af7b29..98e68ea8b4 100644 --- a/scripts/cordis-entry-commit.spec.ts +++ b/scripts/cordis-entry-commit.spec.ts @@ -99,7 +99,7 @@ describe('Loader tree mutation reports', () => { describe('Include patch data ownership', () => { it('detaches file entries even with no patches', () => { const data: EntryOptions[] = [{ id: 'x', name: 'example', config: { value: 1 } }] - const result = applyEntryPatches(data, undefined, vi.fn()) + const result = applyEntryPatches(data, undefined, vi.fn()).data result[0]!.disabled = true ;(result[0]!.config as { value: number }).value = 2 expect(data).toEqual([{ id: 'x', name: 'example', config: { value: 1 } }]) @@ -109,7 +109,7 @@ describe('Include patch data ownership', () => { const insert: EntryOptions[] = [{ id: 'g', name: 'group', group: true, config: [{ id: 'x', name: 'example', config: { value: 1 } }] }] const warn = vi.fn() - const result = applyEntryPatches([], [{ insert }, { id: 'x', disabled: true }], warn) + const result = applyEntryPatches([], [{ insert }, { id: 'x', disabled: true }], warn).data const children = result[0]!.config as Array<{ disabled?: boolean; config: { value: number } }> expect(children[0]!.disabled).toBe(true) children[0]!.config.value = 2 diff --git a/scripts/cordis-entry-yaml.spec.ts b/scripts/cordis-entry-yaml.spec.ts index 75d938e84b..13f670487f 100644 --- a/scripts/cordis-entry-yaml.spec.ts +++ b/scripts/cordis-entry-yaml.spec.ts @@ -10,11 +10,15 @@ describe('Include YAML dialect', () => { expect(stringifyEntryYaml(parsed)).toBe(source) }) - it('reads binary integers as numbers and dates as strings', () => { - expect(parseEntryYaml('- 0b101\n- 2001-01-01\n- ~\n')).toEqual([5, '2001-01-01', null]) + it('reads scalars under the YAML 1.2 core schema', () => { + expect(parseEntryYaml('- 0b101\n- 0o17\n- 0x1F\n- yes\n- 2001-01-01\n- ~\n')).toEqual(['0b101', 15, 31, 'yes', '2001-01-01', null]) expect(parseEntryYaml('')).toBeUndefined() }) + it('rejects unknown tags', () => { + expect(() => parseEntryYaml('- !!binary aGVsbG8=\n- !custom value\n')).toThrow() + }) + it('writes repeated references in full', () => { const shared = { value: 1 } expect(stringifyEntryYaml([{ config: shared }, { config: shared }])).toBe('- config:\n value: 1\n- config:\n value: 1\n') diff --git a/scripts/cordis-loader-rc9.spec.ts b/scripts/cordis-loader-rc9.spec.ts new file mode 100644 index 0000000000..8c5fa3eb80 --- /dev/null +++ b/scripts/cordis-loader-rc9.spec.ts @@ -0,0 +1,106 @@ +/** Loader rc.9 and Include 1.2 entry validation, located config errors and module lookup failures. */ +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { Context, FiberState } from '@deepseek-ai/cordis' +import Loader, { EntryValidationError, Group, ModuleNotFoundError, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader' +import Include, { ConfigFileError } from '@deepseek-ai/cordis-plugin-include' +import Schema from '@deepseek-ai/schemastery' +import { describe, expect, it, onTestFinished } from 'vitest' + +const Typed = Object.assign((_ctx: Context, _config: { value: number }) => {}, { + Config: Schema.object({ value: Schema.number().required() }), +}) + +async function fixture(filename: string, content: string) { + const dir = await mkdtemp(join(tmpdir(), 'dsh-loader-rc9-')) + const ctx = new Context() + onTestFinished(async () => { + await ctx.fiber.dispose() + await rm(dir, { recursive: true, force: true, maxRetries: 3 }) + }) + ctx.baseUrl = pathToFileURL(dir).href + '/' + await ctx.plugin(Loader) + ctx.loader.builtins.include = Include + ctx.loader.builtins.group = Group + ctx.loader.builtins.example = () => {} + ctx.loader.builtins.typed = Typed + const path = join(dir, filename) + await writeFile(path, content) + const errors: unknown[] = [] + const warnings: unknown[] = [] + ctx.logger.exporter({ + export: ({ type, args }: { type: string; args: unknown[] }) => { + if (type === 'error') errors.push(...args) + if (type === 'warn') warnings.push(...args) + }, + }) + const id = await ctx.loader.create({ name: 'cordis:include', config: { path: `./${filename}` } }) + await ctx.loader.await() + const entry = ctx.loader.resolve(id) + return { ctx, path, entry, include: entry.subtree as Include | undefined, errors, warnings } +} + +describe('Loader 1.0.0-rc.9 entry options', () => { + it('rejects invalid options before a tree changes', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await ctx.plugin(Loader) + ctx.loader.builtins.example = () => {} + // Options read from a file are untyped; set the invalid values past the compiler. + const invalid = { name: 'cordis:example' } as EntryOptions + Reflect.set(invalid, 'disabled', 'yes') + Reflect.set(invalid, 'isolate', { svc: 1 }) + const error = await ctx.loader.create(invalid).catch((caught: unknown) => caught) + expect(error).toBeInstanceOf(EntryValidationError) + expect((error as EntryValidationError).issues).toEqual([ + { message: 'disabled must be a boolean', path: ['disabled'] }, + { message: 'isolate.svc must be true or a string', path: ['isolate', 'svc'] }, + ]) + expect(ctx.loader.root.data).toEqual([]) + await expect(ctx.loader.create({ name: 'cordis:example', group: true })).rejects.toThrow('config is required') + }) + + it('accepts explicit ids containing the separator from a file', async () => { + const app = await fixture('rows.yml', '- id: pkg:row\n name: cordis:example\n') + expect(app.include!.store['pkg:row']!.fiber!.state).toBe(FiberState.ACTIVE) + }) +}) + +describe('Include 1.2.0 config files', () => { + it('reports invalid entries and config values at their file positions', async () => { + const app = await fixture('rows.yml', [ + '- id: bad', + ' name: cordis:example', + ' disabled: 1', + '- id: typed', + ' name: cordis:typed', + ' config:', + ' value: text', + '', + ].join('\n')) + const messages = app.errors.map(String).join('\n') + expect(messages).toContain(`disabled must be a boolean (at disabled, ${app.path}:3:13)`) + expect(messages).toContain(`${app.path}:7:12`) + expect(app.include!.store['bad']).toBeUndefined() + expect(app.include!.store['typed']!.fiber!.state).not.toBe(FiberState.ACTIVE) + }) + + it('reports an unknown plugin module at its name position', async () => { + const app = await fixture('rows.yml', '- id: missing\n name: ./missing-plugin.js\n') + const error = app.errors.find(error => error instanceof ModuleNotFoundError) + expect(error?.specifier).toBe('./missing-plugin.js') + expect(error?.message).toContain(`(at name, ${app.path}:2:9)`) + }) + + it('parses YAML 1.2 core scalars and locates syntax errors', async () => { + const app = await fixture('rows.yml', '- id: typed\n name: cordis:typed\n config:\n value: 0x10\n') + expect(app.include!.store['typed']!.fiber!.effectiveConfig).toEqual({ value: 16 }) + await writeFile(app.path, '- id: typed\n name: [\n') + await app.include!.refresh() + const error = app.warnings.find(warning => warning instanceof ConfigFileError) + expect(error).toBeInstanceOf(ConfigFileError) + expect((error as ConfigFileError).issues[0]!.location).toMatchObject({ filename: app.path, line: 3 }) + }) +}) diff --git a/scripts/cordis-loader-resolve.spec.ts b/scripts/cordis-loader-resolve.spec.ts index 44febb061d..fac3fcb8ff 100644 --- a/scripts/cordis-loader-resolve.spec.ts +++ b/scripts/cordis-loader-resolve.spec.ts @@ -84,15 +84,18 @@ describe('Loader project resolution', () => { await expect(tree.import('./missing.js')).rejects.toThrow() }) - it('retains native import when helper creation is denied', async () => { + it('retains native import while helper creation is denied and retries it later', async () => { const { root, baseUrl } = await fixture() const tree = await treeFor(baseUrl) - const denied = vi.mocked(fs.mkdir).mockRejectedValueOnce(Object.assign(new Error('read-only project'), { code: 'EACCES' })) + const denied = vi.mocked(fs.mkdir).mockRejectedValue(Object.assign(new Error('read-only project'), { code: 'EACCES' })) onTestFinished(() => { denied.mockReset() }) expect(await createResolve(baseUrl)).toBeUndefined() expect(await tree.import('node:path')).toMatchObject({ join }) await expect(tree.import('fixture-dep')).rejects.toThrow() expect(existsSync(join(root, '.cordis'))).toBe(false) + denied.mockReset() + expect(await tree.import('fixture-dep')).toMatchObject({ tag: 'bare-dep' }) + expect(existsSync(join(root, '.cordis', 'resolve.mjs'))).toBe(true) }) it('retains native import without a file-backed package scope', async () => { diff --git a/scripts/verify-default-product-isolation.ts b/scripts/verify-default-product-isolation.ts index da405afe5e..aace669cc1 100644 --- a/scripts/verify-default-product-isolation.ts +++ b/scripts/verify-default-product-isolation.ts @@ -219,7 +219,7 @@ export function verifyDefaultProductIsolation(root: string): ProductIsolationRes failures.push(`${display(filename)}: included composition must contain an entry array`) return } - const entries = applyEntryPatches(content as EntryOptions[], entry.config.patches as PatchOptions[] | undefined, () => {}) + const entries = applyEntryPatches(content as EntryOptions[], entry.config.patches as PatchOptions[] | undefined, () => {}).data scanEntries(entries, filename, true, nestedStack) } } diff --git a/scripts/verify-product-use.ts b/scripts/verify-product-use.ts index dee30a0727..d4a1f0a73b 100644 --- a/scripts/verify-product-use.ts +++ b/scripts/verify-product-use.ts @@ -179,7 +179,7 @@ export function verifyProductUse( const content: unknown = existsSync(filename) ? loadCordisYaml(readFileSync(filename, 'utf8')) : row.config.initial configs.add(filename) if (!Array.isArray(content)) { failures.push(`${display(filename)}: Include requires an entry array or initial entries`); continue } - const entries = applyEntryPatches(content as EntryOptions[], row.config.patches as PatchOptions[] | undefined, () => {}) + const entries = applyEntryPatches(content as EntryOptions[], row.config.patches as PatchOptions[] | undefined, () => {}).data scanEntries(entries, filename, reach, new Set([...stack, filename])) } } diff --git a/vendor/README.md b/vendor/README.md index 2edebc8b40..06f3affe18 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -13,14 +13,14 @@ This file covers the manifest, the local-modification log, and the procedure for | `cosmokit/` | `@deepseek-ai/cosmokit` | `cosmokit` | 1.8.1 | https://github.com/shigma/cosmokit | `02e691c5aa7f37f6e0b1cee7ee8f4a21c2e34507` | | `schemastery/` | `@deepseek-ai/schemastery` | `schemastery` | 3.18.0 | https://github.com/shigma/schemastery (`packages/core`) | `cf0b7e5481d0e31d10cdc30bc45c09366c332f27` | | `cordis/` | `@deepseek-ai/cordis` | `cordis` | 4.0.0-rc.12 | https://github.com/cordiverse/cordis (`packages/core`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | -| `loader/` | `@deepseek-ai/cordis-plugin-loader` | `@cordisjs/plugin-loader` | 1.0.0-rc.8 | https://github.com/cordiverse/cordis (`packages/loader`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` | -| `include/` | `@deepseek-ai/cordis-plugin-include` | `@cordisjs/plugin-include` | 1.1.1 | https://github.com/cordiverse/cordis (`packages/include`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` | +| `loader/` | `@deepseek-ai/cordis-plugin-loader` | `@cordisjs/plugin-loader` | 1.0.0-rc.9 | https://github.com/cordiverse/cordis (`packages/loader`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | +| `include/` | `@deepseek-ai/cordis-plugin-include` | `@cordisjs/plugin-include` | 1.2.0 | https://github.com/cordiverse/cordis (`packages/include`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | | `group/` | `@deepseek-ai/cordis-plugin-group` | `@cordisjs/plugin-group` | 1.0.0 | https://github.com/cordiverse/cordis (`packages/group`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | | `timer/` | `@deepseek-ai/cordis-plugin-timer` | `@cordisjs/plugin-timer` | 1.1.4 | https://github.com/cordiverse/cordis (`packages/timer`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | | `hmr/` | `@deepseek-ai/cordis-plugin-hmr` | `@cordisjs/plugin-hmr` | 1.0.15 | https://github.com/cordiverse/cordis (`packages/hmr`) | `ed8a7755c26a27a72064a21dea036ad1d1d6833c` | | `logger-console/` | `@deepseek-ai/cordis-plugin-logger-console` | `@cordisjs/plugin-logger-console` | 1.0.0 | https://github.com/cordiverse/cordis (`packages/logger-console`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | -Third-party dependencies of the vendored packages stay on npm: `@standard-schema/spec`, `js-yaml`, `chokidar`, `picomatch`, `@babel/code-frame`, `supports-color`, `node-addon-require-builtin`. +Third-party dependencies of the vendored packages stay on npm: `@standard-schema/spec`, `yaml`, `chokidar`, `picomatch`, `@babel/code-frame`, `supports-color`, `node-addon-require-builtin`. Intentionally **not** vendored (verified unused by this set): `reggol`, `@cordisjs/utils`, `@cordisjs/element`, `@cordisjs/unyaml` (dev-time YAML import hook only). @@ -34,10 +34,10 @@ Keep this log exhaustive — every divergence from upstream must be listed. Each - **V4 · Vendored TypeScript source internal specifiers**: changed local relative imports/exports from upstream's specifier shape to explicit `.ts` specifiers so TypeScript rewrites emitted JS to `.js` while declarations keep explicit, NodeNext-safe `.ts` specifiers. This includes `loader/src/config/isolate.ts` using `declare module './entry.ts'`. Core's upstream source already uses explicit `.ts` specifiers. Type-only dependencies use `import type` or inline `type` modifiers so ESM output does not retain erased interfaces. - **V5 · `schemastery/tsdown.config.ts` and `logger-console/tsdown.config.ts`**: ours, not upstream files — per-package build-shape overrides (dual ESM+CJS output; separate node/browser entries) for the repo-root tsdown build. They read the JS emitted under `lib/types` and then write the publish runtime entries under `lib/`. Like the regenerated tsconfigs, they are not part of the upstream sync surface. - **V6 · `cordis/src/fiber.ts` lifecycle hardening**: locally closes three reentrant disposal gaps. An effect's owner-list wrapper is registered before its setup body runs, so an unload begun from inside setup awaits setup and every collected cleanup; synchronous setup failure removes the wrapper and rolls back collected cleanup. Async cleanup stays owner-visible until quiescence, and Cordis's internal effect composition joins an already-running cleanup while repeated public disposer calls retain their upstream single-shot result. Effect creation is rejected while the owner is `UNLOADING` (while `PENDING` and `LOADING` remain legal), preventing cleanup-time registrations from escaping the unload snapshot. Child fibers register and receive their parent-owned disposer before `internal/plugin` publication, resolve dependency declarations added by that notification before activation, drain effects attached while pending, and contain teardown-notification failures per observer so one callback cannot starve peers or interrupt ownership cleanup. -- **V7 · JSDoc enrichment**: added `@param`/`@returns` tags and contract documentation (disposal semantics, waterfall veto, bail conditions, error cases) across the public plugin-author surface — `Context` (class, statics, the `isolate()` rule that isolated scopes never fall back to an injected view, and the `Context` interface properties incl. `[Context.root]`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `ValidationError` and its path helpers, `RegistryService`, `ReflectService`, `Service` and its intercept-metadata members, `LoggerService` and their `declare module './context.ts'` overloads. The upstream line comment on `reflect.ts`'s exported `locate()` is rewritten as JSDoc. Loader documentation covers `loader/src/{index,internal,config/entry,config/group,config/isolate,config/tree,config/utils}.ts`, including entry ownership, tree mutation methods, and the `!!js` discriminator. The upstream `EventsService.dispatch()` deprecation annotation is omitted: DSH enumerates callbacks to contain each observer failure independently, which the typed dispatch methods do not provide. Timer retains its local class and helper summaries; its README is local documentation because the upstream package has none. Cosmokit and Schemastery add summaries to their exported helpers, types and namespaces, logger-console to its exporters and config namespace, and HMR to its build-failure logger in `hmr/src/error.ts`. Comment-only; no code changes. Motivation: the website API-reference generator renders these docs and hard-errors on undocumented members. Retire this entry when the enrichment is upstreamed. +- **V7 · JSDoc enrichment**: added `@param`/`@returns` tags and contract documentation (disposal semantics, waterfall veto, bail conditions, error cases) across the public plugin-author surface — `Context` (class, statics, the `isolate()` rule that isolated scopes never fall back to an injected view, and the `Context` interface properties incl. `[Context.root]`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `ValidationError` and its path helpers, `RegistryService`, `ReflectService`, `Service` and its intercept-metadata members, `LoggerService` and their `declare module './context.ts'` overloads. The upstream line comment on `reflect.ts`'s exported `locate()` is rewritten as JSDoc. Loader documentation covers `loader/src/{index,internal,config/entry,config/group,config/isolate,config/tree,config/utils}.ts`, including entry ownership, tree mutation methods, the `!!js` discriminator, entry option validation, source positions and `ModuleNotFoundError`. The upstream `EventsService.dispatch()` deprecation annotation is omitted: DSH enumerates callbacks to contain each observer failure independently, which the typed dispatch methods do not provide. Timer retains its local class and helper summaries; its README is local documentation because the upstream package has none. Cosmokit and Schemastery add summaries to their exported helpers, types and namespaces, logger-console to its exporters and config namespace, and HMR to its build-failure logger in `hmr/src/error.ts`. Comment-only; no code changes. Motivation: the website API-reference generator renders these docs and hard-errors on undocumented members. Retire this entry when the enrichment is upstreamed. - **V9 · `hmr/src/index.ts` module-watcher readiness and native paths**: realpath the existing watch base, classify framework modules and attach listeners before reporting readiness, and compare config paths using both canonical and configured spellings. This preserves Node module-cache identity across Windows short-name paths and filesystem aliases. The main watcher uses `ignoreInitial: true` so startup reads do not trigger another refresh; exact profile patch watching is owned by `packages/boot/hmr/src/watch-config.ts`. The Include change listener logs a rejected `Include.refresh()` instead of leaving the rejection unhandled; the rejection reports unsaved runtime changes while Include keeps its running tree. Covered by `packages/boot/hmr/tests/watch-config.spec.ts` and `scripts/cordis-vendor-hmr-include.spec.ts`. - **V10 · Vendored Node-compatible TypeScript**: marked erased imports explicitly across `cordis`, `loader`, `include`, `hmr`, and `schemastery` so Node's native TypeScript transform does not request types as runtime exports. Schemastery's source uses an ESM default export and its package declares `type: module`. Conditional exports select `.mjs` for import and `.cjs` for require; without them, concurrent imports under module-hook hosts reach the CJS entry and can race its require of ESM Cosmokit (`ERR_REQUIRE_ESM_RACE_CONDITION`). -- **V11 · Include patch and YAML exports**: `include/src/index.ts` exports upstream `applyPatches` as `applyEntryPatches`, so `dsh --dump-config` composes entries with the same algorithm that mounting uses. It also exports `parseEntryYaml`, `stringifyEntryYaml` and `entryYamlErrorPosition` over the `!!js` YAML dialect, and `_read()` parses through `parseEntryYaml`, so every DSH reader and writer of Include-dialect YAML uses Include's parser; `stringifyEntryYaml` always writes with `noRefs` and offers no option to emit aliases, while Include's own writer keeps upstream's options. Covered by `packages/boot/app-boot/tests/config-reload.spec.ts`, `scripts/cordis-entry-commit.spec.ts` and `scripts/cordis-entry-yaml.spec.ts`. +- **V11 · Include patch and YAML exports**: `include/src/index.ts` exports upstream `applyPatches` as `applyEntryPatches` with its `PatchResult` type, so `dsh --dump-config` composes entries with the same algorithm that mounting uses. It also exports `parseEntryYaml`, `stringifyEntryYaml` and `entryYamlErrorPosition` over the `!!js` YAML dialect, using the `yaml` options with which `_read()` parses Include's own file, so every DSH reader and writer of Include-dialect YAML uses Include's parser. `parseEntryYaml` throws the first parse error or warning, such as an unknown tag, and returns `undefined` for an empty document; `stringifyEntryYaml` always writes with `aliasDuplicateObjects: false`, matching the previous `noRefs` output, and offers no option to emit aliases, while Include's own writer keeps upstream's options. Covered by `packages/boot/app-boot/tests/config-reload.spec.ts`, `scripts/cordis-entry-commit.spec.ts` and `scripts/cordis-entry-yaml.spec.ts`. - **V14 · Include persistence results**: `include/src/index.ts` keeps an error for unsaved journal changes. `flush()` retries pending writes and rejects while changes remain unsaved; `stop()` returns the same result and always stops the child tree; a later successful flush clears previous errors. A failed `refresh()` can also reject while runtime changes remain unsaved. Patch-owned changes route to the parent Include, so callers that need them persisted must flush that parent too. The constructor omits upstream's `ctx.hmr.watch(this.filename, () => this.refresh())` registration because neither HMR provider exposes `watch()`; both find each Include by scanning loader entries for its `filename` and call `refresh()`. Ordinary Fiber teardown keeps its error containment. Covered by `scripts/cordis-include-journal.spec.ts` and `packages/host/directory-picker-auto/tests/loader-composition.spec.ts`. - **V15 · Configuration access across Core, Loader, Include and HMR**: rc.11 Core owns raw `Fiber.config`, `internal/config(fiber, next)`, `internal/commit` and awaited `internal/update(config, next)`. Root-fiber candidate resolution remains available without a plugin schema. Local `rawConfig`, `resolveConfig(candidate)` and `effectiveConfig` accessors retain the DSH consumer API. Fiber caches the object passed to activation or a successful update that keeps the instance; candidate resolution is pure, failed or superseded updates cannot replace the cache, and volatile updates retain references. Loader resolves only entry roots and excludes Group/Include tree carriers, so nested `!!js` expressions wait for their own injections. Include retains its tree-carrier marker and public patch exports, and HMR transfers raw config through the accessors. Covered by `scripts/cordis-config-access.spec.ts`, `scripts/cordis-core-lifecycle.spec.ts` and the boot/HMR suites. - **V16 · `cordis/package.json` publishes `src`**: added `src` to the `files` list, joining the other eight vendored packages. Cordis declares `"./src/*": "./src/*"` in its exports, so a tarball without `src` publishes an export map pointing at absent files; the release change judgement also reads `files` to decide whether a diff reaches the payload, and a package whose only published paths are build output has no tracked path to match. @@ -46,15 +46,14 @@ Keep this log exhaustive — every divergence from upstream must be listed. Each - **V23 · `loader/src/config/entry.ts` module identity**: retains each entry's raw import result as `moduleNamespace`, before plugin export normalization. HMR matches that object to Node's cached module namespace and updates it after a successful reload. `EntryTree.import()` keeps its existing arguments and return value; `loader/README.md` documents the additive field. - **V24 · `timer/locale/{en,zh}.json` display metadata**: local English and Chinese titles and descriptions for the Settings plugin inventory. `timer/package.json` exports and publishes these locale resources. - **V25 · Loader lifecycle adaptations**: before a combined context/config update, Loader refreshes dependencies locally, which prevents activation against stale isolation bindings; disabled-entry updates await disposal. Failed fibers require an explicit update after correcting their input or dependencies. Core retains the effect hardening in V6; rc.11 owns dependency teardown ordering and superseded-activation handling. -- **V26 · `loader/src/config/tree.ts` cross-tree moves**: backports [cordiverse/cordis#271](https://github.com/cordiverse/cordis/pull/271), merged after `v4.0.0-rc.11`. When `EntryTree.update()` moves an entry into a group of another tree, the entry and the same-tree members of its group move their store registrations to the target tree, and the move is rejected before either tree changes when the target tree already holds one of their ids. The source tree receives a removal and the target tree a creation, without `legacy` or `from`. In rc.11 the entry stays registered in the source tree and the target receives an update with `legacy`, so the Include journal writes a partial row and reconciling the target file creates a second Entry. Retire this entry when the vendored Loader includes the upstream fix. Covered by `scripts/cordis-include-journal.spec.ts`. -- **V27 · `loader/src/config/tree.ts` explicit ids with `:`**: `ensureId()` accepts explicit ids containing `EntryTree.sep`; upstream rejects them. Generated bundles from `@deepseek-ai/dsh-creation-recommendations` prefix their row ids with `:`, and installed profiles already contain such rows. `resolve()` still splits ids on `:`, so these entries cannot be addressed by nested path. Covered by `scripts/cordis-entry-commit.spec.ts` and `packages/experimental/creation-recommendations/tests/loader-composition.spec.ts`. -- **V28 · Core rc.12 compatibility in Loader and Include**: `loader/src/index.ts` declares `[Service.metadata]`, resolves its intercept through `[Service.resolveIntercept]` and logs through `ctx[Context.root]`; `include/src/index.ts` logs through `ctx[Context.root]`. These lines match the `v4.0.0-rc.12` tag while the rest of both packages keeps its rc.11 baseline. Retire this entry when Loader and Include are synchronized to that tag. +- **V26 · `loader/src/config/tree.ts` cross-tree moves**: backports [cordiverse/cordis#271](https://github.com/cordiverse/cordis/pull/271), merged after `v4.0.0-rc.12`. When `EntryTree.update()` moves an entry into a group of another tree, the entry and the same-tree members of its group move their store registrations to the target tree, and the move is rejected before either tree changes when the target tree already holds one of their ids. The source tree receives a removal and the target tree a creation, without `legacy` or `from`. Upstream at `v4.0.0-rc.12` keeps the entry registered in the source tree and the target receives an update with `legacy`, so the Include journal writes a partial row and reconciling the target file creates a second Entry. Retire this entry when the vendored Loader includes the upstream fix. Covered by `scripts/cordis-include-journal.spec.ts`. +- **V27 · `loader/src/config/utils.ts` explicit ids with `:`**: `validateOptions()` accepts ids containing `EntryTree.sep`, so `EntryTree.create()`, `EntryTree.update()` and group reconciliation admit them; upstream rejects them with an `id must not contain` issue. `validateOptions()` keeps its upstream `sep` parameter. Generated bundles from `@deepseek-ai/dsh-creation-recommendations` prefix their row ids with `:`, and installed profiles already contain such rows. `resolve()` still splits ids on `:`, so these entries cannot be addressed by nested path. Covered by `scripts/cordis-entry-commit.spec.ts`, `scripts/cordis-loader-rc9.spec.ts` and `packages/experimental/creation-recommendations/tests/loader-composition.spec.ts`. ### Resolver adaptations -Relative to the resolver source in Cordis `v4.0.0-rc.11`: +Relative to the resolver source in Cordis `v4.0.0-rc.12`: -- **Web build imports:** `loader/src/resolve.ts` uses default imports for Node builtin modules to support the Web shell's browser externalization. The shell supplies its own module loader. +- **Web build imports:** `loader/src/resolve.ts` and `loader/src/config/tree.ts` use default imports for Node builtin modules to support the Web shell's browser externalization. The shell supplies its own module loader. - **Package-scope cache keys:** `loader/src/resolve.ts` normalizes directory paths with `path.resolve()` before finding the package scope. A root config and a nested config in the same package therefore share the same cached resolver promise and helper-file write. Covered by `scripts/cordis-loader-resolve.spec.ts`. ## Sync procedure diff --git a/vendor/include/README.md b/vendor/include/README.md index 1ce78ec9a9..997f1857df 100644 --- a/vendor/include/README.md +++ b/vendor/include/README.md @@ -35,16 +35,22 @@ Example `cordis.yml`: | Field | Description | | --- | --- | -| `path` | YAML or JSON file path resolved from `ctx.baseUrl`. | +| `path` | YAML or JSON file path resolved from `ctx.baseUrl`; on Windows a drive-letter path is used as a file path. | | `initial` | Entry list written when the file is missing. | | `patches` | Runtime patches applied after reading the file. | | `enableLogs` | Enables loader apply, reload, and unload logs. | -Patches can insert entries or override fields on entries with a matching `id`. +Patches can insert entries or override fields on entries with a matching `id`. A patch that replaces a group's `config` brings its own child entries, which later patches can address; the children it replaces can no longer be patched. + +## File format and errors + +YAML files are parsed as YAML 1.2 under the core schema with the `yaml` package, plus the `!!js` tag for Loader expressions. Unknown tags are rejected. The file must be a top-level array whose entries, including the entries of each group, are mappings. A file that cannot be read, parsed or validated rejects with `ConfigFileError`; parse and validation errors carry `issues`, each with a message and a `file:line:column` location, and JSON files report the position of their syntax error. Include implements `getLocation(id, path)` for its entries: values written in the file resolve to the file, values supplied by a patch resolve through the parent entry to that patch, and values changed at runtime but not yet written resolve to nothing. + +Anonymous entries receive ids before the Loader sees them. An anonymous entry identical to one named on the previous read, under the same parent, keeps that id unless the file or an inserted patch row now uses it explicitly. ## Patch composition and persistence -`applyEntryPatches(data, patches, warn)` uses the same upstream algorithm as mounting. It clones file entries even without patches and clones inserted entry lists before indexing them, so later patches can address inserted rows without mutating those input lists. `parseEntryYaml(content)` and `stringifyEntryYaml(value, options)` read and write Include’s YAML dialect for configuration tools, and `entryYamlErrorPosition(error)` locates a parse error. `stringifyEntryYaml` writes repeated references in full instead of as aliases. Nested entry expressions remain literal until their owning Loader entry evaluates them. +`applyEntryPatches(data, patches, warn)` uses the same upstream algorithm as mounting and returns a `PatchResult`: the composed entries as `data`, and as `index` the owner of every entry and key, built from the patches that apply. It clones file entries even without patches and clones inserted entry lists and replaced group configs before indexing them, so later patches can address those rows without mutating the input lists. It writes generated ids for anonymous entries of a replaced group config into the patch itself, so callers that keep their patches unchanged pass clones. `parseEntryYaml(content)` and `stringifyEntryYaml(value, options)` read and write Include’s YAML dialect for configuration tools with the options Include uses for its own file, and `entryYamlErrorPosition(error)` locates a parse error. `stringifyEntryYaml` writes repeated references in full instead of as aliases; Include’s own writer may write a repeated reference as an alias. Nested entry expressions remain literal until their owning Loader entry evaluates them. Tree mutations arrive through `commit(change)` and enter a journal. Include merges them with the latest file before writing; file edits win conflicts on the same fields and produce a diagnostic. Patch-owned fields and inserted entries update the parent Include’s patches instead of the included file. Invalid, missing or read-only files leave unsaved changes in memory. diff --git a/vendor/include/package.json b/vendor/include/package.json index 4788d0a828..37afb43bb3 100644 --- a/vendor/include/package.json +++ b/vendor/include/package.json @@ -35,6 +35,6 @@ }, "dependencies": { "@deepseek-ai/cosmokit": "workspace:~", - "js-yaml": "^4.1.0" + "yaml": "^2.9.1" } } diff --git a/vendor/include/src/index.ts b/vendor/include/src/index.ts index ae489afeaa..8e9add4f8b 100644 --- a/vendor/include/src/index.ts +++ b/vendor/include/src/index.ts @@ -1,27 +1,40 @@ -import { type EntryChange, type EntryOptions, EntryTree, EntryGroup, isJsExpr } from '@deepseek-ai/cordis-plugin-loader' +import { type EntryChange, type EntryOptions, EntryTree, EntryGroup, isJsExpr, type SourceLocation } from '@deepseek-ai/cordis-plugin-loader' import { Context, Service } from '@deepseek-ai/cordis' import { deepEqual } from '@deepseek-ai/cosmokit' import { basename, dirname, extname, join } from 'node:path' import { access, constants, readFile, rename, rm, writeFile } from 'node:fs/promises' import { setTimeout as sleep } from 'node:timers/promises' import { fileURLToPath, pathToFileURL } from 'node:url' -import * as yaml from 'js-yaml' +import { + isAlias, isMap, isNode, isScalar, isSeq, LineCounter, parseDocument, Scalar, stringify, YAMLError, + type Document, type Range, type ScalarTag, type SchemaOptions, +} from 'yaml' +import { stringifyString } from 'yaml/util' import { applyJournal, flatten, type Journal, merge, reconcile, record } from './journal.ts' -import { applyPatches, ensureIds, ensureInsertIds, PatchIndex, type PatchOptions, routeJournal } from './patch.ts' +import { applyPatches, ensureIds, ensureInsertIds, type PatchIndex, type PatchOptions, routeJournal } from './patch.ts' /** Shared patch semantics used by config dumps and mounting. */ export { applyPatches as applyEntryPatches } from './patch.ts' -/** Serialized entry patch options. */ -export type { PatchOptions } from './patch.ts' +/** Serialized entry patch options and the composed result of applying them. */ +export type { PatchOptions, PatchResult } from './patch.ts' -const JsExpr = new yaml.Type('tag:yaml.org,2002:js', { - kind: 'scalar', - resolve: (data) => typeof data === 'string', - construct: (data) => ({ __jsExpr: data }), - predicate: isJsExpr, - represent: (data) => data['__jsExpr'], -}) +// A Windows drive-letter path, e.g. `C:\app\cordis.yml` or `C:/app/cordis.yml`. +const driveLetter = /^[A-Za-z]:[\\/]/ -const schema = yaml.JSON_SCHEMA.extend(JsExpr) +const JsExpr: ScalarTag = { + tag: 'tag:yaml.org,2002:js', + identify: isJsExpr, + resolve: (source) => ({ __jsExpr: source }), + // quoted like any other string + stringify: (item, ctx, onComment, onChompKeep) => { + const scalar = new Scalar((item.value as any).__jsExpr) + return stringifyString(Object.assign(scalar, { type: item.type }), ctx, onComment, onChompKeep) + }, +} + +const yamlOptions: SchemaOptions = { + schema: 'core', + customTags: [JsExpr], +} /** Options for {@link stringifyEntryYaml}. */ export interface EntryYamlStringifyOptions { @@ -30,14 +43,18 @@ export interface EntryYamlStringifyOptions { } /** - * Parse text in Include's YAML dialect. A `!!js` scalar becomes a child-owned JavaScript expression node that stays - * literal until its owning Loader entry evaluates it. + * Parse text in Include's YAML dialect: YAML 1.2 under the core schema, plus `!!js`. A `!!js` scalar becomes a + * child-owned JavaScript expression node that stays literal until its owning Loader entry evaluates it. Include + * reads its own file with the same options. * @param content - YAML source text. * @returns the parsed value, or `undefined` for an empty document. - * @throws the parser's syntax error; {@link entryYamlErrorPosition} reads its location. + * @throws the first parse error, or the first warning such as an unknown tag; {@link entryYamlErrorPosition} reads its location. */ export function parseEntryYaml(content: string): unknown { - return yaml.load(content, { schema }) + const document = parseDocument(content, yamlOptions) + const [error] = [...document.errors, ...document.warnings] + if (error) throw error + return document.contents === null ? undefined : document.toJS() } /** @@ -48,17 +65,18 @@ export function parseEntryYaml(content: string): unknown { * @returns YAML text ending with a newline. */ export function stringifyEntryYaml(value: unknown, options: EntryYamlStringifyOptions = {}): string { - return yaml.dump(value, { schema, noRefs: true, lineWidth: options.lineWidth ?? 80 }) + return stringify(value, { ...yamlOptions, singleQuote: true, aliasDuplicateObjects: false, lineWidth: options.lineWidth ?? 80 }) } /** - * Locate a syntax error thrown by {@link parseEntryYaml}. + * Locate a parse error thrown by {@link parseEntryYaml}. * @param error - any caught value; only a parse error thrown by {@link parseEntryYaml} yields a position. * @returns the one-based line and column of the error, or `undefined` when the error carries no source location. */ export function entryYamlErrorPosition(error: unknown): { line: number; column: number } | undefined { - if (!(error instanceof yaml.YAMLException) || !error.mark) return undefined - return { line: error.mark.line + 1, column: error.mark.column + 1 } + if (!(error instanceof YAMLError) || !error.linePos) return undefined + const [{ line, col }] = error.linePos + return { line, column: col } } const types: Record = { @@ -69,16 +87,40 @@ const types: Record = { type ConfigStage = 'read' | 'parse' | 'validate' +/** JSON is parsed as YAML too, for node ranges and line positions. */ +interface Syntax { + document: Document + lines: LineCounter +} + +function parseSyntax(content: string): Syntax { + const lines = new LineCounter() + const document = parseDocument(content, { ...yamlOptions, prettyErrors: false, lineCounter: lines }) + return { document, lines } +} + interface Snapshot { content: string data: EntryOptions[] + /** Parsed on first use. */ + syntax?: Syntax +} + +// e.g. `at position 17 (line 2 column 16)` +const jsonPosition = /\s+at position (\d+)(?: \(line \d+ column \d+\))?$/ + +export interface ConfigIssue { + message: string + location: SourceLocation } export class ConfigFileError extends Error { name = 'ConfigFileError' - constructor(public stage: ConfigStage, path: string, cause: unknown) { - super(`failed to ${stage} config file ${path}`, { cause }) + constructor(public stage: ConfigStage, path: string, cause: unknown, public issues: ConfigIssue[] = []) { + super([`failed to ${stage} config file ${path}`, ...issues.map(({ message, location }) => { + return ` - ${message} (at ${location.filename}:${location.line}:${location.column})` + })].join('\n'), { cause }) } } @@ -119,6 +161,50 @@ export namespace Include { } } +/** Index path of an entry in a nested entry list. */ +function findEntry(entries: EntryOptions[], id: string): PropertyKey[] | undefined { + for (const [index, options] of entries.entries()) { + if (options.id === id) return [index] + if (!options.group || !Array.isArray(options.config)) continue + const path = findEntry(options.config, id) + if (path) return [index, 'config', ...path] + } +} + +function findInvalidEntries(entries: unknown[], prefix: PropertyKey[] = []): PropertyKey[][] { + return entries.flatMap((options: any, index) => { + if (!options || typeof options !== 'object' || Array.isArray(options)) return [[...prefix, index]] + if (!options.group || !Array.isArray(options.config)) return [] + return findInvalidEntries(options.config, [...prefix, index, 'config']) + }) +} + +/** + * Range of the node at `path`, or of its deepest ancestor. A collection is + * represented by the key that holds it. + */ +function seek(document: Document, path: PropertyKey[]): Range | null | undefined { + let node: unknown = document.contents + let anchor = isNode(node) ? node.range : undefined + for (const key of path) { + if (isAlias(node)) node = node.resolve(document) + if (isMap(node)) { + const pair = node.items.find(pair => String(isScalar(pair.key) ? pair.key.value : pair.key) === String(key)) + if (!pair) break + node = pair.value + if (isNode(pair.key)) anchor = pair.key.range + } else if (isSeq(node)) { + const item = node.items[key as number] + if (!isNode(item)) break + node = item + anchor = item.range + } else { + break + } + } + return isScalar(node) ? node.range : anchor +} + export class Include extends EntryTree { static inject = ['loader'] @@ -132,6 +218,8 @@ export class Include extends EntryTree { private cache?: Snapshot /** Tree-side changes that have not reached the file yet. */ private journal: Journal = new Map() + /** Where the entries of the applied tree come from. */ + private index?: PatchIndex /** Ids we assigned to entries the file leaves anonymous. */ private anonymous = new Map() @@ -150,7 +238,11 @@ export class Include extends EntryTree { constructor(ctx: Context, public config: Include.Config) { super(ctx) this.enableLogs = config.enableLogs ?? ctx.fiber.entry?.parent.tree.enableLogs ?? false - this.filename = fileURLToPath(new URL(this.config.path, this.ctx.baseUrl)) + // On Windows, a drive-letter path is converted with `pathToFileURL`. + // `new URL()` would read its `C:` as a URL scheme, which `fileURLToPath` rejects. + this.filename = fileURLToPath(process.platform === 'win32' && driveLetter.test(this.config.path) + ? pathToFileURL(this.config.path) + : new URL(this.config.path, this.ctx.baseUrl)) const ext = extname(this.filename) if (!types[ext]) { throw new Error(`extension "${ext}" not supported`) @@ -289,30 +381,59 @@ export class Include extends EntryTree { if (content === this.cache?.content) return let data: any - try { - data = this.type === 'application/yaml' - ? parseEntryYaml(content) - : JSON.parse(content) - } catch (error) { - throw new ConfigFileError('parse', this.filename, error) + let syntax: Syntax | undefined + if (this.type === 'application/yaml') { + syntax = parseSyntax(content) + const { document, lines } = syntax + // unknown tags are only warnings to the parser, but leave the data incomplete + const errors: YAMLError[] = [...document.errors, ...document.warnings] + if (errors.length) { + const issues = errors.map(error => ({ message: error.message, location: this._locate(lines, error.pos[0]) })) + throw new ConfigFileError('parse', this.filename, undefined, issues) + } + data = document.toJS() + } else { + try { + data = JSON.parse(content) + } catch (error) { + const match = error instanceof SyntaxError && error.message.match(jsonPosition) + if (!match) throw new ConfigFileError('parse', this.filename, error) + const message = error.message.slice(0, match.index) + const location = this._locate(parseSyntax(content).lines, +match[1]) + throw new ConfigFileError('parse', this.filename, undefined, [{ message, location }]) + } } // An empty or truncated file (routine mid-edit) parses to `undefined`, so // every non-array shape is rejected here as one "invalid file" signal. if (!Array.isArray(data)) { - throw new ConfigFileError('validate', this.filename, new TypeError('config file must be a top-level array')) + const message = 'config file must be a top-level array' + const { document, lines } = syntax ?? parseSyntax(content) + const range = document.contents?.range + if (!range) throw new ConfigFileError('validate', this.filename, new TypeError(message)) + throw new ConfigFileError('validate', this.filename, undefined, [{ message, location: this._locate(lines, range[0]) }]) + } + // ids, patches and the journal all assume an entry is an object + const invalid = findInvalidEntries(data) + if (invalid.length) { + const { document, lines } = syntax ?? parseSyntax(content) + const issues = invalid.map((path) => { + const range = seek(document, path) + return { message: 'entry must be an object', location: this._locate(lines, range?.[0] ?? 0) } + }) + throw new ConfigFileError('validate', this.filename, undefined, issues) } this._assignIds(data) if (this.cache) { - const index = new PatchIndex(this.config.patches ?? []) + const { index } = applyPatches(data, this.config.patches) const conflicts = reconcile(this.journal, flatten(this.cache.data), flatten(data), (id, key) => index.fileOwned(id, key)) for (const { id, reason } of conflicts) { this.ctx.logger.error('config conflict in %C: entry %C %s; file wins', this.filename, id, reason) } } - this.cache = { content, data } + this.cache = { content, data, syntax } this._scheduleApply() // the file changed while tree-side changes were pending: write the merge if (this.journal.size) this.dirtyWrite = true @@ -430,60 +551,91 @@ export class Include extends EntryTree { private dump(data: EntryOptions[]) { return this.type === 'application/yaml' - ? yaml.dump(data, { schema }) + ? stringify(data, { ...yamlOptions, singleQuote: true }) : JSON.stringify(data, null, 2) } + getLocation(id: string, path: PropertyKey[]): SourceLocation | undefined { + if (!this.cache || !this.index) return + // values changed at runtime are not written anywhere yet + const record = this.journal.get(id) + if (record?.kind === 'remove') return + if (path.length && record && String(path[0]) in record.changes) return + + const owner = path.length ? this.index.key(id, String(path[0])) : this.index.entry(id) + if (owner.type === 'patch') { + return this.ctx.fiber.entry?.getLocation(['config', 'patches', owner.index, ...path]) + } else if (owner.type === 'embedded') { + const prefix = findEntry(this.config.patches![owner.index][owner.key], id) + if (!prefix) return + return this.ctx.fiber.entry?.getLocation(['config', 'patches', owner.index, owner.key, ...prefix, ...path]) + } + const prefix = findEntry(this.cache.data, id) + if (!prefix) return + const { document, lines } = this.cache.syntax ??= parseSyntax(this.cache.content) + const range = seek(document, [...prefix, ...path]) + if (range) return this._locate(lines, range[0]) + } + + private _locate(lines: LineCounter, offset: number): SourceLocation { + const { line, col } = lines.linePos(offset) + return { filename: this.filename, line, column: col } + } + /** * Entries the file leaves anonymous get an id here, before the loader sees * them. One that looks exactly like an entry we named on the previous read - * keeps that id, so editing a neighbor does not restart it; anything else - * gets a fresh id. Assigned ids stay in memory until the next write. + * keeps that id, unless it is already explicitly owned, so editing a + * neighbor does not restart it; anything else gets a fresh id. Assigned + * ids stay in memory until the next write. */ private _assignIds(data: EntryOptions[]) { const used = new Set() - const pending: { options: EntryOptions; parent: string | null }[] = [] - const walk = (entries: EntryOptions[], parent: string | null) => { + const collect = (entries: EntryOptions[]) => { for (const options of entries) { - if (options.id) { - used.add(options.id) - } else { - pending.push({ options, parent }) - } - if (options.group && Array.isArray(options.config)) { - walk(options.config, options.id ?? null) - } + if (options.id) used.add(options.id) + if (options.group && Array.isArray(options.config)) collect(options.config) } } - walk(data, null) + collect(data) + for (const patch of this.config.patches ?? []) { + if (patch.insert) collect(patch.insert) + } const previous = this.anonymous this.anonymous = new Map() - for (const { options, parent } of pending) { - let id: string | undefined - for (const [candidate, info] of previous) { - if (info.parent !== parent || !deepEqual(info.options, options)) continue - id = candidate - previous.delete(candidate) - break + const assign = (entries: EntryOptions[], parent: string | null) => { + for (const options of entries) { + if (!options.id) { + let id: string | undefined + for (const [candidate, info] of previous) { + if (info.parent !== parent || used.has(candidate) || !deepEqual(info.options, options)) continue + id = candidate + previous.delete(candidate) + break + } + if (!id) { + do { + id = Math.random().toString(16).slice(2, 10) + } while (used.has(id) || this.store[id]) + } + used.add(id) + this.anonymous.set(id, { parent, options: structuredClone(options) }) + const rest = { ...options } + for (const key of Object.keys(options)) delete options[key] + Object.assign(options, { id }, rest) + } + if (options.group && Array.isArray(options.config)) assign(options.config, options.id) } - if (!id) { - do { - id = Math.random().toString(16).slice(2, 10) - } while (used.has(id) || this.store[id]) - } - used.add(id) - this.anonymous.set(id, { parent, options: structuredClone(options) }) - const rest = { ...options } - for (const key of Object.keys(options)) delete options[key] - Object.assign(options, { id }, rest) } + assign(data, null) } private _scheduleApply() { if (this._disposed || !this.cache) return - const tree = applyPatches(this.cache.data, this.config.patches, this.warn) - this._pendingTree = applyJournal(tree, this.journal, undefined, this.warn) + const { data, index } = applyPatches(this.cache.data, this.config.patches, this.warn) + this.index = index + this._pendingTree = applyJournal(data, this.journal, undefined, this.warn) this._applyTask ??= (async () => { try { while (this._pendingTree) { diff --git a/vendor/include/src/patch.ts b/vendor/include/src/patch.ts index 45a4700bfe..c132f0a29d 100644 --- a/vendor/include/src/patch.ts +++ b/vendor/include/src/patch.ts @@ -1,5 +1,5 @@ import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader' -import { type Dict, omit } from '@deepseek-ai/cosmokit' +import type { Dict } from '@deepseek-ai/cosmokit' import { applyChanges, detach, flatten, type Journal, place } from './journal.ts' export interface PatchOptions { @@ -41,79 +41,10 @@ export function ensureInsertIds(patches: PatchOptions[] | undefined, used: (id: } /** - * Overlay `patches` onto a fresh clone of `data`. Inserted entries are cloned - * too, so the tree owns every object it mounts. + * Who supplies an entry, or one key of it, in the patched tree: the file, a + * patch that overrides that key, or the patch the entry is written in. */ -export function applyPatches(data: EntryOptions[], patches: PatchOptions[] | undefined, warn: Warn): EntryOptions[] { - data = structuredClone(data) - if (!patches?.length) return data - - const entryMap = new Map() - const buildMap = (entries: EntryOptions[]) => { - for (const entry of entries) { - if (entry.id) entryMap.set(entry.id, entry) - if (entry.group && Array.isArray(entry.config)) { - buildMap(entry.config) - } - } - } - buildMap(data) - - for (const patch of patches) { - const { id, insert, name, ...overrides } = patch - - if (insert) { - const clone = structuredClone(insert) - if (id) { - const target = entryMap.get(id) - if (!target) { - warn('patch insert: entry %C not found', id) - continue - } - if (!target.group) { - warn('patch insert: entry %C is not a group', id) - continue - } - if (!Array.isArray(target.config)) target.config = [] - target.config.push(...clone) - } else { - data.push(...clone) - } - buildMap(clone) - continue - } - - if (!id) { - warn('patch: id is required for non-insert patches') - continue - } - - const target = entryMap.get(id) - if (!target) { - warn('patch: entry %C not found', id) - continue - } - - if (name && name !== target.name) { - warn('patch: name mismatch for %C (expected %C, got %C), skipping', id, target.name, name) - continue - } - - for (const [key, value] of Object.entries(overrides)) { - if (key === 'id') continue - target[key] = value - } - } - - return data -} - -/** - * Who owns an entry, or one key of it, in the patched tree: the file, a patch - * that overrides that key (the last one wins), or the patch that inserted the - * whole entry. - */ -export type EntryOwner = EntryOwner.File | EntryOwner.Patch | EntryOwner.Insert +export type EntryOwner = EntryOwner.File | EntryOwner.Patch | EntryOwner.Embedded export namespace EntryOwner { export interface File { @@ -126,56 +57,34 @@ export namespace EntryOwner { index: number } - export interface Insert { - type: 'insert' + /** An entry written in `patches[index][key]`. */ + export interface Embedded { + type: 'embedded' /** Index into the patch list. */ index: number - /** The insert list (or nested group config) holding the entry. */ - list: EntryOptions[] - options: EntryOptions - /** The group the entry is inserted into (`null` for the root). */ - parent: string | null + key: 'insert' | 'config' } } -export class PatchIndex { - private keys = new Map>() - private inserts = new Map() +const FILE: EntryOwner.File = { type: 'file' } - constructor(public patches: PatchOptions[]) { - patches.forEach((patch, index) => { - const { id, insert } = patch - if (insert) { - const walk = (list: EntryOptions[], parent: string | null) => { - for (const options of list) { - this.inserts.set(options.id, { type: 'insert', index, list, options, parent }) - if (options.group && Array.isArray(options.config)) walk(options.config, options.id) - } - } - walk(insert, id ?? null) - return - } - if (!id) return - const keys = this.keys.get(id) ?? new Map() - for (const key of Object.keys(omit(patch, ['id', 'insert', 'name']))) { - keys.set(key, index) - } - this.keys.set(id, keys) - }) - } +/** Where every entry and key of a patched tree comes from. */ +export class PatchIndex { + constructor( + private owners: Map, + private keys: Map>, + ) {} /** Owner of the entry as a whole. */ - entry(id: string | null): EntryOwner { - if (id === null) return { type: 'file' } - return this.inserts.get(id) ?? { type: 'file' } + entry(id: string | null) { + if (id === null) return FILE + return this.owners.get(id) ?? FILE } /** Owner of one key of an entry. */ key(id: string, key: string): EntryOwner { - const insert = this.inserts.get(id) - if (insert) return insert const index = this.keys.get(id)?.get(key) - return index === undefined ? { type: 'file' } : { type: 'patch', index } + return index === undefined ? this.entry(id) : { type: 'patch', index } } fileOwned(id: string, key: string | null) { @@ -183,21 +92,131 @@ export class PatchIndex { } } +export interface PatchResult { + data: EntryOptions[] + index: PatchIndex +} + +/** + * Overlay `patches` onto a fresh clone of `data`. Entry lists from patches + * are cloned too, so the tree owns every entry it mounts. The index is built + * in the same pass, so a patch that does not apply owns nothing. + */ +export function applyPatches(data: EntryOptions[], patches: PatchOptions[] | undefined, warn: Warn = () => {}): PatchResult { + data = structuredClone(data) + const entries = new Map() + const owners = new Map() + const keys = new Map>() + + const mount = (list: EntryOptions[], owner: EntryOwner.File | EntryOwner.Embedded) => { + for (const options of list) { + if (options.id) { + entries.set(options.id, options) + owners.set(options.id, owner) + // earlier overrides were aimed at the entry this one replaces + keys.delete(options.id) + } + if (options.group && Array.isArray(options.config)) mount(options.config, owner) + } + } + + const unmount = (list: EntryOptions[]) => { + for (const options of list) { + if (options.id) { + entries.delete(options.id) + owners.delete(options.id) + keys.delete(options.id) + } + if (options.group && Array.isArray(options.config)) unmount(options.config) + } + } + + mount(data, FILE) + + patches?.forEach((patch, index) => { + const { id, insert, name, ...overrides } = patch + const target = id ? entries.get(id) : undefined + + if (insert) { + if (id && !target) return warn('patch insert: entry %C not found', id) + if (target && !target.group) return warn('patch insert: entry %C is not a group', id) + const clone = structuredClone(insert) + if (target) { + if (!Array.isArray(target.config)) target.config = [] + target.config.push(...clone) + } else { + data.push(...clone) + } + mount(clone, { type: 'embedded', index, key: 'insert' }) + return + } + + if (!id) return warn('patch: id is required for non-insert patches') + if (!target) return warn('patch: entry %C not found', id) + if (name && name !== target.name) { + return warn('patch: name mismatch for %C (expected %C, got %C), skipping', id, target.name, name) + } + + // the entries of a group config the patch replaces go away with it + if ('config' in overrides && target.group && Array.isArray(target.config)) { + unmount(target.config) + } + + const overridden = keys.get(id) ?? new Map() + keys.set(id, overridden) + for (const [key, value] of Object.entries(overrides)) { + target[key] = value + overridden.set(key, index) + } + + // entries of a group config the patch supplies can be patched in turn + if ('config' in overrides && target.group && Array.isArray(target.config)) { + // ids go on the patch itself, before the tree takes its own copy + ensureIds(target.config, id => entries.has(id)) + target.config = structuredClone(target.config) + mount(target.config, { type: 'embedded', index, key: 'config' }) + } + }) + + return { data, index: new PatchIndex(owners, keys) } +} + /** * Route a journal to its owners: file-owned changes are applied to `data`, * patch-owned ones to `patches`. Both are mutated in place, so pass clones. * Returns whether any patch changed. */ export function routeJournal(journal: Journal, data: EntryOptions[], patches: PatchOptions[], warn: Warn) { - const index = new PatchIndex(patches) + let { index } = applyPatches(data, patches) let patched = false - const insertList = (owner: EntryOwner.Insert) => owner.options.config ??= [] + // entries that move, appear or go away change the owners of later records + const reindex = () => { + index = applyPatches(data, patches).index + } + + // the list an entry is written in, and the group its top level belongs to + const container = (owner: EntryOwner.File | EntryOwner.Embedded) => { + if (owner.type === 'file') return { list: data, parent: null } + const patch = patches[owner.index] + return { list: patch[owner.key] as EntryOptions[], parent: patch.id ?? null } + } + + // the list holding the entries of a group, when a patch supplies them + const children = (parent: string) => { + const owner = index.key(parent, 'config') + if (owner.type === 'file') return + if (owner.type === 'patch') { + const config = patches[owner.index].config + return Array.isArray(config) ? config : undefined + } + const found = flatten(container(owner).list).get(parent) + return found && (found.options.config ??= []) + } const placeAt = (options: EntryOptions, parent: string | null, position: number) => { - const owner = index.entry(parent) - if (owner.type === 'insert') { - const list = insertList(owner) + const list = parent === null ? undefined : children(parent) + if (list) { list.splice(Math.min(position, list.length), 0, options) patched = true } else if (!place(data, options, parent, position)) { @@ -207,40 +226,33 @@ export function routeJournal(journal: Journal, data: EntryOptions[], patches: Pa for (const [id, record] of journal) { const owner = index.entry(id) + const { list, parent: base } = container(owner) + const embedded = owner.type === 'embedded' + if (record.kind === 'remove') { - if (owner.type === 'insert') { - owner.list.splice(owner.list.indexOf(owner.options), 1) - patched = true - } else { - detach(data, id) - } + detach(list, id) + patched ||= embedded + reindex() continue } - const current = owner.type === 'insert' ? owner : flatten(data).get(id) + const current = flatten(list).get(id) if (!current) { const options = { id } as EntryOptions applyChanges(options, record.changes) placeAt(options, record.parent ?? null, record.position) + reindex() continue } - if (record.parent !== undefined && current.parent !== record.parent) { + // an entry at the top of a patch list belongs to the group the patch targets + if (record.parent !== undefined && (current.parent ?? base) !== record.parent) { // moving across owners: carry the full options over - if (owner.type === 'insert') { - owner.list.splice(owner.list.indexOf(owner.options), 1) - patched = true - } else { - detach(data, id) - } + detach(list, id) + patched ||= embedded applyChanges(current.options, record.changes) placeAt(current.options, record.parent, record.position) - continue - } - - if (owner.type === 'insert') { - applyChanges(current.options, record.changes) - patched = true + reindex() continue } @@ -251,6 +263,7 @@ export function routeJournal(journal: Journal, data: EntryOptions[], patches: Pa ;(patchChanges[keyOwner.index] ??= {})[key] = record.changes[key] return false }) + patched ||= embedded for (const [i, changes] of Object.entries(patchChanges)) { applyChanges(patches[i] as any, changes) patched = true diff --git a/vendor/loader/README.md b/vendor/loader/README.md index 2b71deba01..f745df38bb 100644 --- a/vendor/loader/README.md +++ b/vendor/loader/README.md @@ -48,13 +48,21 @@ root.loader.update(id, { config: { enabled: false } }) For file-backed trees, use `@cordisjs/plugin-include`. +## Entry validation and source positions + +`create()` and `update()` check the resulting options with `validateOptions()` before the tree changes and reject with `EntryValidationError`, whose `issues` list each rejected path. `id` and `name` must be strings, and `name` is required; `group` must be a boolean; `disabled` a boolean or `!!js` expression; a group's `config` an array; `inject` a string array or a mapping; `intercept` and `isolate` mappings, with each `isolate` value `true` or a string. `create()` and `update()` also check the entries of a group's `config`. A group checks each entry again as it creates it; an invalid entry is logged, any running entry with its id is disposed, and its siblings still start. Explicit ids may contain `:`. + +`EntryTree.getLocation(id, path)` returns where an entry option is written; the base tree returns `undefined`, and Include implements it. Config validation errors and entry option errors of an entry with a source list each issue with its `file:line:column`, and their stack frames name the entry ids from the innermost tree outward. A config passed at runtime has no source position, so its validation errors keep their original message. + ## Module resolution Without Node module internals, Loader resolves bare specifiers, package imports and self-references in the nearest package scope containing the configuration file. Relative specifiers use the configuration URL directly, and `cordis:` builtins bypass filesystem resolution. Other specifiers, including `node:` builtins and absolute URLs, initialize an ignored `.cordis/resolve.mjs` helper in that scope to preserve native ESM import conditions. If no scope exists or writing the helper files fails, Loader uses its native import fallback. This fallback emits no diagnostic of its own; project-only dependencies can remain unavailable, and the resulting import error can name the Loader module rather than the configuration project. Failure to import a written helper propagates to the caller without this fallback. -Initialization results are cached for the lifetime of the resolver module, including failed writes and rejected helper imports. Fixing the filesystem does not retry initialization for an already cached scope. Concurrent initialization through filesystem aliases of the same package can contend for the temporary helper files and cause a write failure. +A successful initialization is cached for the lifetime of the resolver module, and so is a rejected helper import. A scope whose helper files cannot be written is not cached, so a later import retries the initialization. A helper file that already holds the expected content is not rewritten, and a rename blocked by a transient `EACCES`, `EPERM` or `EBUSY` lock is retried with a bounded backoff. Concurrent initialization through filesystem aliases of the same package can contend for the temporary helper files and cause a write failure. + +On Windows, an entry `name` that is a drive-letter path such as `C:\app\plugin.js` is imported as its file URL. When the entry's own module cannot be found, the import rejects with `ModuleNotFoundError`, whose `specifier` is the entry `name` and whose message keeps Node's description and hints without the importer; an entry with a source position reports it as `(at name, file:line:column)`. A missing module imported by the plugin propagates Node's original error. Node module internals are classified by their available APIs, including the v1 API used by Node 24.0–24.11. diff --git a/vendor/loader/src/config/entry.ts b/vendor/loader/src/config/entry.ts index b73c116d3f..f8f3ed241c 100644 --- a/vendor/loader/src/config/entry.ts +++ b/vendor/loader/src/config/entry.ts @@ -1,9 +1,9 @@ -import { Context, Fiber, FiberState, Inject } from '@deepseek-ai/cordis' +import { Context, Fiber, FiberState, Inject, ValidationError } from '@deepseek-ai/cordis' import { deepEqual, isNullable, updateVolatile, volatileEntries, type Volatile } from '@deepseek-ai/cosmokit' import { Loader } from '../index.ts' import { EntryGroup } from './group.ts' -import { EntryTree } from './tree.ts' -import { evaluate, isJsExpr } from './utils.ts' +import { EntryTree, ModuleNotFoundError } from './tree.ts' +import { evaluate, formatIssues, formatLocation, isJsExpr, relocate } from './utils.ts' import { equalExceptVolatile } from './diff.ts' /** Serialized plugin entry options stored in loader config files. */ @@ -60,6 +60,23 @@ export class Entry { this.context.emit('loader/entry-init', this) } + /** + * Merge partial options into `target`; a nullish value deletes its key. + * @param target - Options to modify in place. + * @param options - Changes to apply. + * @returns `target`. + */ + static merge(target: Partial, options: Partial) { + for (const [key, value] of Object.entries(options)) { + if (isNullable(value)) { + delete target[key] + } else { + target[key] = value + } + } + return target + } + get context(): Context { return this.ctx } @@ -125,13 +142,7 @@ export class Entry { if (create) { this.options = options as EntryOptions } else { - for (const [key, value] of Object.entries(options)) { - if (isNullable(value)) { - delete this.options[key] - } else { - this.options[key] = value - } - } + Entry.merge(this.options, options) } sortKeys(this.options) @@ -199,14 +210,41 @@ export class Entry { return true } - getOuterStack = () => { - let entry: Entry | undefined = this - const result: string[] = [] - do { - result.push(` at ${entry.parent.tree.ctx.baseUrl}#${entry.options.id}`) - entry = entry.parent.ctx.fiber.entry - } while (entry) - return result + /** + * Where a value of this entry's options is written. + * @param path - Path inside the entry options; empty for the entry itself. + * @returns The source position, or undefined when the tree has no source. + */ + getLocation(path: PropertyKey[] = []) { + return this.parent.tree.getLocation(this.options.id, path) + } + + /** Stack frames from this entry out through its owning entries, each with its source position when known. */ + getOuterStack = () => this.parent.getOuterStack(this.options.id) + + /** + * Rewrite a config validation error to list each issue with its source position, when this entry has a source. + * @param error - Error to rewrite in place. + */ + traceValidation(error: ValidationError) { + const frames = this.getOuterStack() + // an entry outside any source has nothing to point to + if (!frames.length) return + const issues = error.issues.map(({ message, path }) => ({ message, path: ValidationError.normalizePath(path) })) + const locate = (path: PropertyKey[]) => this.getLocation(['config', ...path]) + relocate(error, formatIssues('invalid config', issues, locate), frames) + } + + private _reportImport(error: unknown) { + if (error instanceof ModuleNotFoundError) { + const location = this.getLocation(['name']) + if (location) { + // before Node's hints + const [first, ...hints] = error.message.split('\n') + relocate(error, [`${first} (at name, ${formatLocation(location)})`, ...hints].join('\n'), this.getOuterStack()) + } + } + this.ctx.logger.error(error) } /** Import and start the configured plugin if it is not already running. */ @@ -227,7 +265,7 @@ export class Entry { try { moduleNamespace = await this.parent.tree.import(this.options.name, this.getOuterStack) } catch (error) { - this.ctx.logger.error(error) + this._reportImport(error) return } const plugin = this.loader.unwrapExports(moduleNamespace) diff --git a/vendor/loader/src/config/group.ts b/vendor/loader/src/config/group.ts index 448f3a3588..d8c205ef95 100644 --- a/vendor/loader/src/config/group.ts +++ b/vendor/loader/src/config/group.ts @@ -1,6 +1,8 @@ import { Context, Service } from '@deepseek-ai/cordis' +import { isNullable } from '@deepseek-ai/cosmokit' import { Entry, type EntryOptions } from './entry.ts' import { EntryTree } from './tree.ts' +import { EntryValidationError, formatIssues, formatLocation, relocate, validateOptions, type Issue } from './utils.ts' /** Runtime owner for a list of child loader entries. */ export class EntryGroup { @@ -17,7 +19,13 @@ export class EntryGroup { return this.ctx } + /** + * Create or replace the entry for `options`. Invalid options reject with `EntryValidationError` and dispose any entry already registered under their id. + * @returns The full entry id. + */ async create(options: Omit) { + const issues = validateOptions(options, EntryTree.sep) + if (issues.length) throw this._reject(options as EntryOptions, issues) const id = this.tree.ensureId(options) const entry: Entry = this.tree.store[id] ??= new Entry(this.ctx.loader) // Entry may be moved from another group, @@ -28,6 +36,35 @@ export class EntryGroup { return entry.id } + /** + * Stack frames for an entry of this group, followed by those of the owning entries. + * @param id - Tree-local entry id. + * @returns Frames that point at the entries' source positions. + */ + getOuterStack(id: string): string[] { + const location = this.tree.getLocation(id, []) + const frames = location ? [` at ${id} (${formatLocation(location)})`] : [] + return [...frames, ...this.ctx.fiber.entry?.getOuterStack() ?? []] + } + + private _reject(options: EntryOptions, issues: Issue[]) { + const error = new EntryValidationError(issues) + const id = options?.id + if (isNullable(id)) return error + // unregistered first, so the disposal is not taken for a self-dispose + const entry = this.tree.store[id] + if (entry) { + delete this.tree.store[id] + entry.fiber?.dispose() + this.context.emit('loader/partial-dispose', entry, entry.options, false) + } + const frames = this.getOuterStack(id) + if (!frames.length) return error + const locate = (path: PropertyKey[]) => this.tree.getLocation(id, path) + relocate(error, formatIssues('invalid entry options', issues, locate), frames) + return error + } + unlink(options: EntryOptions) { const config = this.data const index = config.indexOf(options) @@ -49,8 +86,9 @@ export class EntryGroup { async update(config: EntryOptions[]) { const oldConfig = this.data as EntryOptions[] this.data = config - const oldMap = Object.fromEntries(oldConfig.map(options => [options.id, options])) - const newMap = Object.fromEntries(config.map(options => [options.id ?? Symbol('anonymous'), options])) + const oldMap = Object.fromEntries(oldConfig.map(options => [options?.id, options])) + // non-objects are rejected by `create` + const newMap = Object.fromEntries(config.map(options => [options?.id ?? Symbol('anonymous'), options])) // update inner plugins const ids = Reflect.ownKeys({ ...oldMap, ...newMap }) as string[] diff --git a/vendor/loader/src/config/tree.ts b/vendor/loader/src/config/tree.ts index 5b5648f576..b0db124059 100644 --- a/vendor/loader/src/config/tree.ts +++ b/vendor/loader/src/config/tree.ts @@ -1,9 +1,46 @@ import { composeError, Context } from '@deepseek-ai/cordis' import { isNonNullable, type Dict } from '@deepseek-ai/cosmokit' +import url from 'node:url' import { Entry, type EntryOptions } from './entry.ts' import { EntryGroup } from './group.ts' +import { EntryValidationError, validateOptions, type SourceLocation } from './utils.ts' import { createResolve } from '../resolve.ts' +// A Windows drive-letter path, e.g. `C:\app\plugin.js` or `C:/app/plugin.js`. +const driveLetter = /^[A-Za-z]:[\\/]/ + +// Node names the modules only in the message: +// `Cannot find (module|package) '' imported from ` +function parseNotFound(error: any) { + if (error?.code !== 'ERR_MODULE_NOT_FOUND' || typeof error.message !== 'string') return + // later lines are hints, e.g. `Did you mean to import ...?` + const [first, ...hints] = error.message.split('\n') as string[] + const match = first.match(/^(Cannot find (?:module|package) '.*') imported from (.*)$/) + if (match) return { description: match[1], parent: match[2], hints } +} + +function toPath(href: string) { + try { + return href.startsWith('file:') ? url.fileURLToPath(href) : href + } catch { + return href + } +} + +/** A configured plugin module that cannot be found, as opposed to a missing module imported by that plugin. */ +export class ModuleNotFoundError extends Error { + name = 'ModuleNotFoundError' + code = 'ERR_MODULE_NOT_FOUND' + + /** + * @param specifier - Entry `name` that failed to resolve. + * @param message - Node's description and hints, without its importer. + */ + constructor(public specifier: string, message: string) { + super(message) + } +} + /** * One tree-side mutation, reported to `EntryTree.commit()` synchronously after * it has been applied to `entry.options` / `group.data`. @@ -125,6 +162,8 @@ export abstract class EntryTree { /** Create an entry in the root group or a nested group. */ async create(options: Omit, parent: string | null = null, position = Infinity) { const group = this.resolveGroup(parent) + const issues = validateOptions(options, EntryTree.sep, true) + if (issues.length) throw new EntryValidationError(issues) const id = group.tree.ensureId(options) group.data.splice(position, 0, options as EntryOptions) group.tree.commit({ id, group, options: options as EntryOptions }) @@ -145,6 +184,8 @@ export abstract class EntryTree { const entry = this.resolve(id) const source = entry.parent const legacy = { ...entry.options } + const issues = validateOptions(Entry.merge({ ...legacy }, options), EntryTree.sep, true) + if (issues.length) throw new EntryValidationError(issues) if (parent !== undefined) { const target = this.resolveGroup(parent) const moved = target.tree === source.tree ? [] : members(entry) @@ -178,28 +219,70 @@ export abstract class EntryTree { return task } - /** Import a plugin module from a specifier or `cordis:` builtin. */ + /** + * Import a plugin module from a specifier or `cordis:` builtin. On Windows a drive-letter path is imported as a file URL. + * Rejects with `ModuleNotFoundError` when the specifier itself cannot be found; other import errors propagate unchanged. + */ import(name: string, getOuterStack?: () => string[]) { if (name.startsWith('cordis:')) { return this.ctx.loader.builtins[name.slice(7)] } + // On Windows, a drive-letter path is converted with `pathToFileURL`. + if (process.platform === 'win32' && driveLetter.test(name)) { + name = url.pathToFileURL(name).href + } + // to tell `name` apart from a module it imports + let parent: string | undefined + // the helper resolves `name` only + let unresolved: unknown return composeError(async (info) => { // ModuleJob.run // onImport.tracePromise.__proto__ // internal.import info.offset += 3 if (this.ctx.loader.internal) { - return await this.ctx.loader.internal.import(name, this.ctx.baseUrl!, {}) + parent = this.ctx.baseUrl! + return await this.ctx.loader.internal.import(name, parent, {}) } else if (name.startsWith('.')) { + parent = import.meta.url return await import(/* @vite-ignore */new URL(name, this.ctx.baseUrl).href) } else { const resolve = await createResolve(this.ctx.baseUrl) - const url = resolve ? resolve(name) : name + let url = name + if (resolve) { + try { + url = resolve(name) + } catch (error) { + unresolved = error + throw error + } + } + parent = import.meta.url return await import(/* @vite-ignore */ url) } - }, getOuterStack) + }, getOuterStack).catch((error: unknown) => { + const notFound = parseNotFound(error) + if (!notFound) throw error + if (error !== unresolved && (!parent || notFound.parent !== toPath(parent))) throw error + const result = new ModuleNotFoundError(name, [notFound.description, ...notFound.hints].join('\n')) + const frames = getOuterStack?.() ?? [] + // Node's frames are those of its resolver + if (frames.length) result.stack = [`${result.name}: ${result.message}`, ...frames].join('\n') + throw result + }) } /** Report an applied mutation synchronously. In-memory trees may use a no-op. */ abstract commit(change: EntryChange): void + + /** + * Where a value of the entry options is written. A path that leaves the + * source falls back to its deepest written ancestor. + * @param _id - Tree-local entry id. + * @param _path - Path inside the entry options. + * @returns The source position, or undefined for trees without a source file. + */ + getLocation(_id: string, _path: PropertyKey[]): SourceLocation | undefined { + return undefined + } } diff --git a/vendor/loader/src/config/utils.ts b/vendor/loader/src/config/utils.ts index 8e28be0c4c..bcc3e912a8 100644 --- a/vendor/loader/src/config/utils.ts +++ b/vendor/loader/src/config/utils.ts @@ -23,10 +23,140 @@ export function interpolate(ctx: object, value: any) { /** Return true when a value is a serialized loader JavaScript expression. */ export function isJsExpr(value: any): value is JsExpr { - return value instanceof Object && '__jsExpr' in value + return value instanceof Object && typeof value.__jsExpr === 'string' } /** Serialized JavaScript expression produced by the include YAML tag. */ export interface JsExpr { __jsExpr: string } + +/** Source position of a config value: 1-based, with columns in UTF-16 code units. */ +export interface SourceLocation { + /** Path of the config file that writes the value. */ + filename: string + line: number + column: number +} + +/** + * Format a source position as `file:line:column`. + * @param location - Position to format. + * @returns The formatted position. + */ +export function formatLocation(location: SourceLocation) { + return `${location.filename}:${location.line}:${location.column}` +} + +/** + * Format one validation issue as an indented list item. + * @param message - Issue description. + * @param location - Source position of the value, when known. + * @param path - Dotted option path of the value, when not the root. + * @returns The list item, with its path and position in parentheses. + */ +export function formatIssue(message: string, location?: SourceLocation, path?: string) { + const where = [path, location && formatLocation(location)].filter(Boolean).join(', ') + return where ? ` - ${message} (at ${where})` : ` - ${message}` +} + +/** One rejected entry option. */ +export interface Issue { + message: string + /** Path from the entry options to the rejected value; empty for the entry itself. */ + path: PropertyKey[] +} + +/** Map an option path to the source position that writes it. */ +export type Locate = (path: PropertyKey[]) => SourceLocation | undefined + +/** + * Format a titled list of validation issues. + * @param title - First line of the message. + * @param issues - Issues to list in order. + * @param locate - Resolves each issue path to a source position. + * @returns The multi-line message. + */ +export function formatIssues(title: string, issues: readonly Issue[], locate?: Locate) { + const lines = issues.map(({ message, path }) => { + return formatIssue(message, locate?.(path), path.length ? path.map(String).join('.') : undefined) + }) + return `${title}:\n${lines.join('\n')}` +} + +/** + * Replace an error's message and stack frames, so the error points at the config source instead of the loader internals. + * @param error - Error to rewrite in place. + * @param message - New message. + * @param frames - Stack frames listed after the message line. + */ +export function relocate(error: Error, message: string, frames: string[]) { + error.message = message + error.stack = [`${error.name}: ${message}`, ...frames].join('\n') +} + +/** Entry options rejected by `validateOptions()`; `issues` lists every rejected option. */ +export class EntryValidationError extends TypeError { + name = 'EntryValidationError' + + constructor(public issues: Issue[]) { + super(formatIssues('invalid entry options', issues)) + } +} + +// only `disabled` takes an expression +function isPlainObject(value: unknown): value is Record { + return !!value && typeof value === 'object' && !Array.isArray(value) && !isJsExpr(value) +} + +/** + * Check entry options before an entry is created or updated. Explicit ids may contain `sep`. + * @param options - Candidate entry options. + * @param sep - Tree id separator; kept for the upstream signature. + * @param deep - Also check the entries of a group's `config`. + * @returns Every issue found; empty when the options are valid. + */ +export function validateOptions(options: unknown, sep: string, deep = false): Issue[] { + if (!isPlainObject(options)) return [{ message: 'entry must be an object', path: [] }] + const issues: Issue[] = [] + const check = (key: string, expected: string, valid: (value: any) => boolean, required = false) => { + const value = options[key] + if (value === undefined || value === null) { + if (required) issues.push({ message: `${key} is required`, path: [key] }) + } else if (!valid(value)) { + issues.push({ message: `${key} must be ${expected}`, path: [key] }) + } + } + + check('id', 'a string', value => typeof value === 'string') + check('name', 'a string', value => typeof value === 'string', true) + check('group', 'a boolean', value => typeof value === 'boolean') + check('disabled', 'a boolean', value => typeof value === 'boolean' || isJsExpr(value)) + // a group's config is its entry list + if (options.group === true) check('config', 'an array', Array.isArray, true) + + check('inject', 'an array or an object', value => Array.isArray(value) || isPlainObject(value)) + if (Array.isArray(options.inject)) { + options.inject.forEach((name, index) => { + if (typeof name === 'string') return + issues.push({ message: `inject.${index} must be a string`, path: ['inject', index] }) + }) + } + check('intercept', 'an object', isPlainObject) + check('isolate', 'an object', isPlainObject) + if (isPlainObject(options.isolate)) { + for (const [name, label] of Object.entries(options.isolate)) { + if (label === true || typeof label === 'string') continue + issues.push({ message: `isolate.${name} must be true or a string`, path: ['isolate', name] }) + } + } + // from a source, each entry is checked as its group creates it + if (deep && options.group === true && Array.isArray(options.config)) { + options.config.forEach((child, index) => { + for (const { message, path } of validateOptions(child, sep, true)) { + issues.push({ message, path: ['config', index, ...path] }) + } + }) + } + return issues +} diff --git a/vendor/loader/src/index.ts b/vendor/loader/src/index.ts index 2a9e1bb9a3..3582bc1360 100644 --- a/vendor/loader/src/index.ts +++ b/vendor/loader/src/index.ts @@ -1,4 +1,4 @@ -import { Context, FiberState, Inject, Service } from '@deepseek-ai/cordis' +import { Context, FiberState, Inject, Service, ValidationError, type Fiber } from '@deepseek-ai/cordis' import { defineProperty, isNullable, type Awaitable, type Dict } from '@deepseek-ai/cosmokit' import { ModuleLoader } from './internal.ts' import { Entry, type EntryOptions } from './config/entry.ts' @@ -101,9 +101,30 @@ export class Loader extends EntryTree { ctx.reflect.provide('loader', this, this[Service.check]) + // the source config each entry fiber last resolved + const sources = new WeakMap() + + // Registered before the built-in validation listener, so validation + // failures can be traced to the config source. A config passed in at + // runtime is not written anywhere yet, so its failures are left as is. + ctx.on('internal/config', (fiber, next) => { + if (!fiber.entry || fiber.parent.fiber?.entry === fiber.entry) return next() + try { + return next() + } catch (error) { + if (ValidationError.is(error) && sources.get(fiber) === fiber.entry.options.config) { + fiber.entry.traceValidation(error) + } + throw error + } + }, { prepend: true }) + + // Registered after the built-in validation listener, so interpolation runs + // on the source config and validation sees the interpolated result. ctx.on('internal/config', (fiber, next) => { const config = next() if (!fiber.entry || fiber.parent.fiber?.entry === fiber.entry) return config + sources.set(fiber, config) // Tree carriers preserve the expressions owned by their child entries. if (fiber.runtime?.callback[EntryGroup.key]) return config return interpolate(fiber.ctx, config) diff --git a/vendor/loader/src/resolve.ts b/vendor/loader/src/resolve.ts index 6d5aadcf8b..9aa014d9f2 100644 --- a/vendor/loader/src/resolve.ts +++ b/vendor/loader/src/resolve.ts @@ -1,6 +1,7 @@ import fs from 'node:fs' import fsPromises from 'node:fs/promises' import path from 'node:path' +import timers from 'node:timers/promises' import url from 'node:url' import type { Dict } from '@deepseek-ai/cosmokit' @@ -19,6 +20,18 @@ const HELPER_FILES = { const cache: Dict> = Object.create(null) +const RENAME_RETRIES = 10 +const RENAME_BACKOFF = 20 + +/** + * On Windows a rename over a file that another process holds open fails with + * one of these; the lock is normally gone within milliseconds. + */ +function isTransientRenameError(error: unknown) { + const code = (error as NodeJS.ErrnoException | undefined)?.code + return code === 'EACCES' || code === 'EPERM' || code === 'EBUSY' +} + /** Nearest ancestor of `dir` that owns a `package.json`, if any. */ function findScope(dir: string) { while (true) { @@ -41,11 +54,25 @@ function resolveScope(baseUrl: string | undefined) { } async function write(filename: string, content: string) { + // The helper content is constant; skipping an identical rewrite avoids + // repeating the rename that another process may have blocked. + if (await fsPromises.readFile(filename, 'utf8').catch(() => undefined) === content) return // Another process may be writing the same path; `rename` is atomic, so a // concurrent reader only ever observes the complete helper. const temp = `${filename}.${process.pid}` await fsPromises.writeFile(temp, content) - await fsPromises.rename(temp, filename) + for (let attempt = 0; ; attempt++) { + try { + await fsPromises.rename(temp, filename) + return + } catch (error) { + if (attempt >= RENAME_RETRIES || !isTransientRenameError(error)) { + await fsPromises.rm(temp, { force: true }).catch(() => {}) + throw error + } + } + await timers.setTimeout(RENAME_BACKOFF * (attempt + 1)) + } } async function _createResolve(scope: string): Promise { @@ -71,5 +98,8 @@ async function _createResolve(scope: string): Promise { export async function createResolve(baseUrl: string | undefined) { const scope = resolveScope(baseUrl) if (!scope) return - return await (cache[scope] ??= _createResolve(scope)) + const resolve = await (cache[scope] ??= _createResolve(scope)) + // A scope that cannot be prepared may succeed on a later attempt. + if (!resolve) delete cache[scope] + return resolve } From 9ce0c815b5e0a8183f55fb46a3018f6be716d862 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 13 Nov 2026 18:08:28 +0800 Subject: [PATCH 29/48] refactor(deepseek-account): declare the account token header before its first use platformHeaders() reads ACCOUNT_TOKEN_HEADER about a hundred lines above the constant's declaration. The call only runs after the module has loaded, so behavior is unchanged; the declaration now sits with the module's imports. --- packages/account/deepseek-account/src/protocol.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/account/deepseek-account/src/protocol.ts b/packages/account/deepseek-account/src/protocol.ts index 2a0160e65e..7a3a46058a 100644 --- a/packages/account/deepseek-account/src/protocol.ts +++ b/packages/account/deepseek-account/src/protocol.ts @@ -2,6 +2,9 @@ import { z } from 'zod' import type { AccountNotificationEvent, AccountNotificationId, SignInErrorCode } from './types.ts' +/** Request header carrying the account token on every request the token authenticates. */ +export const ACCOUNT_TOKEN_HEADER = 'x-dsh-auth-token' + /** Protocol errors expose a stable code, never a response body or authorization URL. */ export class PlatformAuthError extends Error { /** @param code - safe error classification. */ @@ -161,9 +164,6 @@ export function requestNotificationEvent(origin: string, token: string, id: Acco }, signal) } -/** Request header carrying the account token on every request the token authenticates. */ -export const ACCOUNT_TOKEN_HEADER = 'x-dsh-auth-token' - // The grant is provider-owned; deployment requestHeaders cannot override it or the client identity. function accountHeaders(headers: Record, token: string): Record { return { ...headers, [ACCOUNT_TOKEN_HEADER]: token } From fc0abf3f37c6e137733b34293659bede1ecbf0cc Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 13 Nov 2026 19:51:35 +0800 Subject: [PATCH 30/48] refactor(llm): rename routeCredential to providerCredential Reviewers found `routeCredential` unclear. The method takes a provider route id, as `providerInfo()` and `providerRetryPolicy()` on the same adapter do, so the method and its types now carry that prefix: `LlmAdapter.providerCredential()`, `LlmRuntime.providerCredential()`, `ProviderCredential`, `ProviderCredentialGrant`, and `DeepSeekProviderCredentialOptions`. Behavior is unchanged. master never had the old names, so no released surface is renamed; the upgrade guide for this change names the new ones. --- ...ch-offered-by-provider-readiness.i18n.yaml | 4 ++-- ...eb-search-offered-by-provider-readiness.md | 2 +- ...search-offered-by-provider-readiness.zh.md | 2 +- ...026-10-29-web-provider-selection.i18n.yaml | 4 ++-- .../2026-10-29-web-provider-selection.md | 4 ++-- .../2026-10-29-web-provider-selection.zh.md | 4 ++-- ...-11-10-llm-route-credential-seam.i18n.yaml | 8 +++---- .../2026-11-10-llm-route-credential-seam.md | 6 ++--- ...2026-11-10-llm-route-credential-seam.zh.md | 6 ++--- ...-10-15-deepseek-search-fetch-api.i18n.yaml | 4 ++-- .../2026-10-15-deepseek-search-fetch-api.md | 2 +- ...2026-10-15-deepseek-search-fetch-api.zh.md | 2 +- docs/subsystems/account.i18n.yaml | 4 ++-- docs/subsystems/account.md | 2 +- docs/subsystems/account.zh.md | 2 +- docs/subsystems/llm-streaming.i18n.yaml | 8 +++---- docs/subsystems/llm-streaming.md | 18 +++++++------- docs/subsystems/llm-streaming.zh.md | 18 +++++++------- .../llm-route-credential/guide.i18n.yaml | 12 +++++----- .../v0.2.2-rc.3/llm-route-credential/guide.md | 10 ++++---- .../llm-route-credential/guide.zh.md | 10 ++++---- .../extensions/tool-cordis/src/api-catalog.ts | 24 +++++++++---------- .../llm/llm-deepseek-account/README.i18n.yaml | 4 ++-- packages/llm/llm-deepseek-account/README.md | 2 +- .../llm/llm-deepseek-account/README.zh.md | 2 +- .../tests/provider.spec.ts | 6 ++--- .../llm/llm-deepseek-api-key/README.i18n.yaml | 4 ++-- packages/llm/llm-deepseek-api-key/README.md | 2 +- .../llm/llm-deepseek-api-key/README.zh.md | 2 +- .../tests/discovery.spec.ts | 4 ++-- packages/llm/llm-deepseek/README.i18n.yaml | 4 ++-- packages/llm/llm-deepseek/README.md | 2 +- packages/llm/llm-deepseek/README.zh.md | 2 +- packages/llm/llm-deepseek/src/adapter.ts | 4 ++-- packages/llm/llm-deepseek/src/index.ts | 2 +- packages/llm/llm-deepseek/src/types.ts | 14 +++++------ .../tests/route-credential.spec.ts | 6 ++--- packages/llm/llm/src/index.ts | 10 ++++---- packages/llm/llm/src/types.ts | 8 +++---- packages/llm/llm/tests/topology.spec.ts | 18 +++++++------- .../web/web-deepseek-api/README.i18n.yaml | 12 +++++----- packages/web/web-deepseek-api/README.md | 8 +++---- packages/web/web-deepseek-api/README.zh.md | 8 +++---- packages/web/web-deepseek-api/src/index.ts | 4 ++-- .../web/web-deepseek-api/src/transport.ts | 4 ++-- packages/web/web-deepseek-api/tests/routes.ts | 10 ++++---- .../web/web-search-deepseek/README.i18n.yaml | 8 +++---- packages/web/web-search-deepseek/README.md | 4 ++-- packages/web/web-search-deepseek/README.zh.md | 4 ++-- packages/web/web-search-deepseek/src/index.ts | 10 ++++---- .../web/web-search-deepseek/src/provider.ts | 4 ++-- .../tests/deepseek.spec.ts | 10 ++++---- scripts/gen-cordis-catalog.ts | 2 +- scripts/type-equiv.manifest.json | 4 ++-- 54 files changed, 172 insertions(+), 172 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml index 8344fd2eb2..24af686ace 100644 --- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml @@ -9,8 +9,8 @@ en: 32ba2b2b42e8deb5 zh: 6a6532561f81b8e2 /agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/decision: - en: 8513348797d8b8c3 - zh: 13d4066e07db0fb9 + en: 023c6db0af5f9424 + zh: 7bdf40c49e381ee3 /agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/alternatives-considered: en: 6da221f6b821ea44 zh: b15774011abed7ed diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md index ed8c3c2803..72b06f6f77 100644 --- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md +++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md @@ -13,7 +13,7 @@ English | [中文](2026-09-27-web-search-offered-by-provider-readiness.zh.md) Each role of the web capability seam owns one part of a per-step check: - **Service Definition.** `WebSearchProvider` and `WebFetchProvider` have an optional `ready(llmProvider)` that answers whether an operation made for a model request on that chat route has a credential to send. It checks configuration only and makes no network calls. `ctx.web.searchReady(llmProvider?)` and `ctx.web.fetchReady(llmProvider?)` resolve the provider with the same rules as `search()` and `fetch()` and return its answer. A provider without `ready()` counts as ready, and a selection failure answers true because the operation reports that failure as a structured `WebError`. -- **Service Provider.** Each DeepSeek provider checks its credentials in the order its operation resolves them. `dsh-web-search-deepseek` checks, on a route whose `ctx.llm.routeCredential()` publishes an account credential, whether that credential is configured for its Messages endpoint, and then its literal `apiKey` or its `apiKeyEnv` reference. The Search and Fetch API providers of `dsh-web-deepseek-api` resolve the same plan as the operation ([credential resolution](2026-10-29-web-provider-selection.md)): a capability with its own YAML fields checks only the key under its `*ApiKeyEnv`; otherwise, on the account route with the account model route mounted, that route's credential configured for its `/v1/tools` base counts, and then the key of the `deepseek-official` route, or `DEEPSEEK_API_KEY` without that route. A key counts when `ctx.credentials.describe()` reports its reference configured (without that service, when the launching environment carries it); the reference helpers of `dsh-credentials` and each route's own presence check perform these checks. A failed account-token or credential-store read answers false, because the operation fails on that read instead of trying the next credential. The providers name no tool or prompt section. +- **Service Provider.** Each DeepSeek provider checks its credentials in the order its operation resolves them. `dsh-web-search-deepseek` checks, on a route whose `ctx.llm.providerCredential()` publishes an account credential, whether that credential is configured for its Messages endpoint, and then its literal `apiKey` or its `apiKeyEnv` reference. The Search and Fetch API providers of `dsh-web-deepseek-api` resolve the same plan as the operation ([credential resolution](2026-10-29-web-provider-selection.md)): a capability with its own YAML fields checks only the key under its `*ApiKeyEnv`; otherwise, on the account route with the account model route mounted, that route's credential configured for its `/v1/tools` base counts, and then the key of the `deepseek-official` route, or `DEEPSEEK_API_KEY` without that route. A key counts when `ctx.credentials.describe()` reports its reference configured (without that service, when the launching environment carries it); the reference helpers of `dsh-credentials` and each route's own presence check perform these checks. A failed account-token or credential-store read answers false, because the operation fails on that read instead of trying the next credential. The providers name no tool or prompt section. - **Consumer.** `dsh-tool-web` registers `web_search` and `web_fetch` with [step activation conditions](../../../../packages/core/tools/README.md#conditional-tools) that ask `ctx.web.searchReady()` and `ctx.web.fetchReady()` about the route of the step's model selection. The agent loop resolves conditions before it assembles the step, so the declared tools, the `tool:web_search` and `tool:web_fetch` prompt sections, PTC program bindings, and dispatch all read the same admitted set. The route decides only whether the account token is checked before the API key, which happens on the `deepseek-account` route; an API key counts on every route, so a conversation on another provider's model is offered the DeepSeek web tools whenever a DeepSeek key is configured. A Search or Fetch API capability with its own YAML fields ignores the route and is ready exactly when its own key is configured. diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md index 96277e8532..0712cacc50 100644 --- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md @@ -13,7 +13,7 @@ Status: implemented web 能力 seam 的每个角色各负责逐步骤检查的一部分: - **Service Definition。** `WebSearchProvider` 与 `WebFetchProvider` 有一个可选的 `ready(llmProvider)`,回答为该对话路由上的模型请求发起的操作是否有可发送的凭据。它只检查配置,不发起网络调用。`ctx.web.searchReady(llmProvider?)` 与 `ctx.web.fetchReady(llmProvider?)` 按与 `search()`、`fetch()` 相同的规则解析提供方并返回其回答。没有 `ready()` 的提供方视为就绪;选择失败时回答 true,因为对应操作会把该失败报告为结构化 `WebError`。 -- **Service Provider。** 每个 DeepSeek 提供方都按其操作解析凭据的顺序检查凭据。`dsh-web-search-deepseek` 在 `ctx.llm.routeCredential()` 发布账号凭据的路由上检查该凭据是否已为其 Messages 端点配置,然后检查其字面 `apiKey` 或 `apiKeyEnv` 引用。`dsh-web-deepseek-api` 的 Search 与 Fetch API 提供方解析与操作相同的方案([凭据解析](2026-10-29-web-provider-selection.zh.md)):在 YAML 中设置了单独字段的能力只检查其 `*ApiKeyEnv` 下的密钥;否则,在账号路由上且账号模型路由已挂载时,该路由为其 `/v1/tools` 基础地址配置的凭据算数,然后是 `deepseek-official` 路由的密钥,没有该路由时为 `DEEPSEEK_API_KEY`。`ctx.credentials.describe()` 报告其引用已配置时(没有该服务时,启动环境中存在该变量),密钥即算存在;这些存在性检查由 `dsh-credentials` 的引用函数和各路由自身的存在性检查执行。读取账号 token 或凭据存储失败时回答 false,因为操作会在该次读取上失败,而不会尝试下一种凭据。提供方不点名任何工具或提示词段落。 +- **Service Provider。** 每个 DeepSeek 提供方都按其操作解析凭据的顺序检查凭据。`dsh-web-search-deepseek` 在 `ctx.llm.providerCredential()` 发布账号凭据的路由上检查该凭据是否已为其 Messages 端点配置,然后检查其字面 `apiKey` 或 `apiKeyEnv` 引用。`dsh-web-deepseek-api` 的 Search 与 Fetch API 提供方解析与操作相同的方案([凭据解析](2026-10-29-web-provider-selection.zh.md)):在 YAML 中设置了单独字段的能力只检查其 `*ApiKeyEnv` 下的密钥;否则,在账号路由上且账号模型路由已挂载时,该路由为其 `/v1/tools` 基础地址配置的凭据算数,然后是 `deepseek-official` 路由的密钥,没有该路由时为 `DEEPSEEK_API_KEY`。`ctx.credentials.describe()` 报告其引用已配置时(没有该服务时,启动环境中存在该变量),密钥即算存在;这些存在性检查由 `dsh-credentials` 的引用函数和各路由自身的存在性检查执行。读取账号 token 或凭据存储失败时回答 false,因为操作会在该次读取上失败,而不会尝试下一种凭据。提供方不点名任何工具或提示词段落。 - **Consumer。** `dsh-tool-web` 注册 `web_search` 与 `web_fetch` 时各带一个[步骤激活条件](../../../../packages/core/tools/README.zh.md#conditional-tools),以该步骤模型选择的路由询问 `ctx.web.searchReady()` 与 `ctx.web.fetchReady()`。agent loop 在组装该步骤之前解析各条件,因此声明的工具、`tool:web_search` 与 `tool:web_fetch` 提示词段落、PTC 程序绑定与派发都读取同一个准入集合。 路由只决定是否先检查账号 token 再检查 API 密钥,这发生在 `deepseek-account` 路由上;API 密钥在每条路由上都算数,因此只要配置了 DeepSeek 密钥,使用其他提供方模型的对话也会获得 DeepSeek Web 工具。在 YAML 中设置了单独字段的 Search 或 Fetch API 能力不看路由,恰在其自身密钥已配置时就绪。 diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml index 4c0e201093..9c22957426 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml @@ -18,8 +18,8 @@ en: 9d68ffca5c8be681 zh: 36bb661f98de0ebb /agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/credential-resolution: - en: 6650000bd819e2ce - zh: 9e141db8bc3f51f8 + en: aa5522b172d2c580 + zh: 04561ffe78d69ff4 /agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/defaults-and-stored-selections: en: 5fcd3319fbceed1d zh: 20771646b9c36fa6 diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md index 42aca3fdbc..3d11c29843 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md @@ -30,11 +30,11 @@ The Search and Fetch APIs read one `web-deepseek-api` namespace, and each resolv Each of Search and Fetch has a billing setting, `web-deepseek-api.searchBilling` or `fetchBilling`, which the settings page edits as a **Billing** menu under the selected API. The default, `auto`, follows the DeepSeek credential of the conversation; `account` sends only the signed-in account's token and `api-key` only the API key, without falling back to the other. The conversation's route is the `provider` of the initiating Session's latest request context, which account sign-out also reads; `ready()` uses the route of the model request being prepared, so readiness and execution resolve the same plan. -The account credential is the one `ctx.deepseekAccount` releases for the dispatch endpoint under the origin of the base URL the mounted `deepseek-account` route publishes through `ctx.llm.routeCredential()`, with `/v1/tools`; without that route, the origin `DEEPSEEK_BASE_URL` names is used. An HTTP 401 invalidates that credential. With `auto` billing on the `deepseek-account` route, the operation sends the account credential when that route is mounted and a credential is released. Every other `auto` operation, including one in an account conversation without a sign-in or a credential, sends the key the mounted `deepseek-official` route publishes, which the route resolves under its `apiKeyEnv` (its base URL includes `DEEPSEEK_BASE_URL`), to the origin of that route's base URL with `/v1/tools`; without that route, `DEEPSEEK_API_KEY` goes to `https://api.deepseek.com/v1/tools`. With `auto` billing on a route other than the two DeepSeek routes, or outside a Session, an operation without a configured key sends the account token instead, so a signed-in user without a key keeps web tools in conversations on other model providers; on the `deepseek-official` route it never sends the token, because that conversation bills the API key. Sending the API key in a signed-out account conversation keeps web tools available there. A user with only `DEEPSEEK_API_KEY`, including every headless, SDK, and ACP run, therefore searches and fetches by default, and a gateway or internal deployment set through the model provider's base URL serves web access at the same origin. A missing credential makes the capability not ready, and an operation fails with `WEB_PROVIDER_CREDENTIAL_MISSING` and guidance for its billing that names the account sign-in, the Models page and the reference, and the billing field. A mounted route whose configuration does not resolve is not treated as absent: an operation that needs that route is not ready and fails with `WEB_PROVIDER_MISCONFIGURED` before reading the credential that depends on that route, without trying later sources or sending the request, so a broken gateway setting never redirects requests to the official endpoint. +The account credential is the one `ctx.deepseekAccount` releases for the dispatch endpoint under the origin of the base URL the mounted `deepseek-account` route publishes through `ctx.llm.providerCredential()`, with `/v1/tools`; without that route, the origin `DEEPSEEK_BASE_URL` names is used. An HTTP 401 invalidates that credential. With `auto` billing on the `deepseek-account` route, the operation sends the account credential when that route is mounted and a credential is released. Every other `auto` operation, including one in an account conversation without a sign-in or a credential, sends the key the mounted `deepseek-official` route publishes, which the route resolves under its `apiKeyEnv` (its base URL includes `DEEPSEEK_BASE_URL`), to the origin of that route's base URL with `/v1/tools`; without that route, `DEEPSEEK_API_KEY` goes to `https://api.deepseek.com/v1/tools`. With `auto` billing on a route other than the two DeepSeek routes, or outside a Session, an operation without a configured key sends the account token instead, so a signed-in user without a key keeps web tools in conversations on other model providers; on the `deepseek-official` route it never sends the token, because that conversation bills the API key. Sending the API key in a signed-out account conversation keeps web tools available there. A user with only `DEEPSEEK_API_KEY`, including every headless, SDK, and ACP run, therefore searches and fetches by default, and a gateway or internal deployment set through the model provider's base URL serves web access at the same origin. A missing credential makes the capability not ready, and an operation fails with `WEB_PROVIDER_CREDENTIAL_MISSING` and guidance for its billing that names the account sign-in, the Models page and the reference, and the billing field. A mounted route whose configuration does not resolve is not treated as absent: an operation that needs that route is not ready and fails with `WEB_PROVIDER_MISCONFIGURED` before reading the credential that depends on that route, without trying later sources or sending the request, so a broken gateway setting never redirects requests to the official endpoint. A capability whose YAML sets a non-empty `searchBaseURL` or `searchApiKeyEnv` (`fetchBaseURL` or `fetchApiKeyEnv` for Fetch) instead, whatever its billing, always sends the key under its `*ApiKeyEnv` (`DEEPSEEK_API_KEY` when unset) to its `*BaseURL` (the official base when unset) and never the account token, so an intranet or third-party endpoint receives only the key chosen for it. Each capability has its own fields because a deployment can serve search and fetch from different gateways. These fields are YAML-only, and an empty value counts as unset. Stored values of fields outside the schema, including `baseURL`, `apiKeyEnv`, and `apiKey`, load without schema errors and have no effect. -The DeepSeek model routes publish the credential they send through `ctx.llm.routeCredential()` ([route credentials](2026-11-10-llm-route-credential-seam.md)): the API-key route its key under `apiKeyEnv`, the account route the credential `ctx.deepseekAccount` releases for a destination. Messages search and the Search and Fetch APIs read those publications instead of provider configuration, and read `DEEPSEEK_API_KEY` and own keys through the reference helpers of `dsh-credentials`, so every DeepSeek request reads the credential store the same way; a credential whose grant offers invalidation is invalidated after an HTTP 401. Shipped profiles need no per-profile credential override, because the API-key path works wherever `DEEPSEEK_API_KEY` or the DeepSeek API-key route has a key. +The DeepSeek model routes publish the credential they send through `ctx.llm.providerCredential()` ([route credentials](2026-11-10-llm-route-credential-seam.md)): the API-key route its key under `apiKeyEnv`, the account route the credential `ctx.deepseekAccount` releases for a destination. Messages search and the Search and Fetch APIs read those publications instead of provider configuration, and read `DEEPSEEK_API_KEY` and own keys through the reference helpers of `dsh-credentials`, so every DeepSeek request reads the credential store the same way; a credential whose grant offers invalidation is invalidated after an HTTP 401. Shipped profiles need no per-profile credential override, because the API-key path works wherever `DEEPSEEK_API_KEY` or the DeepSeek API-key route has a key. ### Defaults and stored selections diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md index 58bb904d33..cb3c0e67c0 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md @@ -30,11 +30,11 @@ Search 与 Fetch API 读取同一个 `web-deepseek-api` namespace,并各自解 Search 与 Fetch 各有一个计费方式设置 `web-deepseek-api.searchBilling` 或 `fetchBilling`,设置页在选中的 API 下方以**计费方式**下拉框编辑它。默认值 `auto` 跟随会话的 DeepSeek 凭据;`account` 只发送已登录账号的令牌,`api-key` 只发送 API 密钥,都不回退到另一种凭据。会话的路由是发起会话最近一次请求上下文的 `provider`,账号退出登录读取的也是它;`ready()` 使用正在准备的模型请求的路由,因此就绪判断与执行解析出相同的方案。 -账号凭据是 `ctx.deepseekAccount` 为请求端点释放的凭据,端点位于已挂载的 `deepseek-account` 路由通过 `ctx.llm.routeCredential()` 发布的基础地址的 origin 加 `/v1/tools` 下;没有该路由时使用 `DEEPSEEK_BASE_URL` 所指的 origin。HTTP 401 会作废该凭据。`auto` 计费在 `deepseek-account` 路由上,若该路由已挂载且释放出凭据,操作发送账号凭据。其他所有 `auto` 操作,包括账号会话中没有登录或没有凭据的操作,都把已挂载的 `deepseek-official` 路由发布的密钥(由该路由按其 `apiKeyEnv` 解析,其基础地址包含 `DEEPSEEK_BASE_URL`)发往该路由基础地址的 origin 加 `/v1/tools`;没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。`auto` 计费在两个 DeepSeek 路由之外的路由上或会话之外,没有配置密钥的操作改为发送账号令牌,因此已登录但没有密钥的用户在其他模型提供方的会话中仍可使用网页工具;在 `deepseek-official` 路由上从不发送令牌,因为该会话按 API 密钥计费。未登录的账号会话发送 API 密钥,网页工具因此在其中仍然可用。因此只有 `DEEPSEEK_API_KEY` 的用户(包括所有 headless、SDK 与 ACP 运行)默认即可搜索和抓取,通过模型提供方基础地址设置的网关或内部部署也在同一 origin 上提供 Web 访问。缺少凭据时,该能力未就绪,操作以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败,指引信息按计费方式点名账号登录、模型页面与该引用,以及计费方式字段。已挂载但配置无法解析的路由不视为不存在:需要该路由的操作未就绪,并在读取依赖该路由的凭据前以 `WEB_PROVIDER_MISCONFIGURED` 失败,不再尝试后续来源,也不发送请求,因此网关设置出错时请求不会被改发到官方端点。 +账号凭据是 `ctx.deepseekAccount` 为请求端点释放的凭据,端点位于已挂载的 `deepseek-account` 路由通过 `ctx.llm.providerCredential()` 发布的基础地址的 origin 加 `/v1/tools` 下;没有该路由时使用 `DEEPSEEK_BASE_URL` 所指的 origin。HTTP 401 会作废该凭据。`auto` 计费在 `deepseek-account` 路由上,若该路由已挂载且释放出凭据,操作发送账号凭据。其他所有 `auto` 操作,包括账号会话中没有登录或没有凭据的操作,都把已挂载的 `deepseek-official` 路由发布的密钥(由该路由按其 `apiKeyEnv` 解析,其基础地址包含 `DEEPSEEK_BASE_URL`)发往该路由基础地址的 origin 加 `/v1/tools`;没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。`auto` 计费在两个 DeepSeek 路由之外的路由上或会话之外,没有配置密钥的操作改为发送账号令牌,因此已登录但没有密钥的用户在其他模型提供方的会话中仍可使用网页工具;在 `deepseek-official` 路由上从不发送令牌,因为该会话按 API 密钥计费。未登录的账号会话发送 API 密钥,网页工具因此在其中仍然可用。因此只有 `DEEPSEEK_API_KEY` 的用户(包括所有 headless、SDK 与 ACP 运行)默认即可搜索和抓取,通过模型提供方基础地址设置的网关或内部部署也在同一 origin 上提供 Web 访问。缺少凭据时,该能力未就绪,操作以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败,指引信息按计费方式点名账号登录、模型页面与该引用,以及计费方式字段。已挂载但配置无法解析的路由不视为不存在:需要该路由的操作未就绪,并在读取依赖该路由的凭据前以 `WEB_PROVIDER_MISCONFIGURED` 失败,不再尝试后续来源,也不发送请求,因此网关设置出错时请求不会被改发到官方端点。 在 YAML 中设置了非空 `searchBaseURL` 或 `searchApiKeyEnv`(Fetch 为 `fetchBaseURL` 或 `fetchApiKeyEnv`)的能力,则无论计费方式如何,始终把其 `*ApiKeyEnv`(未设置时为 `DEEPSEEK_API_KEY`)下的密钥发往其 `*BaseURL`(未设置时为官方基础地址),从不发送账号令牌,因此内网或第三方端点只收到为它选择的密钥。每个能力有自己的字段,因为一个部署可以由不同网关提供搜索和抓取。这些字段只能在 YAML 中设置,空值视为未设置。schema 之外字段的已保存值,包括 `baseURL`、`apiKeyEnv` 和 `apiKey`,可以加载而不产生 schema 错误,且不生效。 -DeepSeek 模型路由通过 `ctx.llm.routeCredential()` 发布自己发送的凭据([路由凭据](2026-11-10-llm-route-credential-seam.zh.md)):API 密钥路由发布其 `apiKeyEnv` 下的密钥,账号路由发布 `ctx.deepseekAccount` 为目标地址释放的凭据。Messages 搜索以及 Search 与 Fetch API 读取这些发布的凭据而不读取提供方配置,并通过 `dsh-credentials` 的引用函数读取 `DEEPSEEK_API_KEY` 和单独配置的密钥,因此每个 DeepSeek 请求都以同一方式读取凭据库;授权提供失效操作的凭据会在 HTTP 401 后被作废。内置配置不需要按 profile 覆盖凭据,因为只要 `DEEPSEEK_API_KEY` 或 DeepSeek API 密钥路由有密钥,API 密钥路径就能工作。 +DeepSeek 模型路由通过 `ctx.llm.providerCredential()` 发布自己发送的凭据([路由凭据](2026-11-10-llm-route-credential-seam.zh.md)):API 密钥路由发布其 `apiKeyEnv` 下的密钥,账号路由发布 `ctx.deepseekAccount` 为目标地址释放的凭据。Messages 搜索以及 Search 与 Fetch API 读取这些发布的凭据而不读取提供方配置,并通过 `dsh-credentials` 的引用函数读取 `DEEPSEEK_API_KEY` 和单独配置的密钥,因此每个 DeepSeek 请求都以同一方式读取凭据库;授权提供失效操作的凭据会在 HTTP 401 后被作废。内置配置不需要按 profile 覆盖凭据,因为只要 `DEEPSEEK_API_KEY` 或 DeepSeek API 密钥路由有密钥,API 密钥路径就能工作。 ### 默认值与已保存的选择 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index c46edc0386..a5d7ec13b7 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -9,11 +9,11 @@ en: 9665e1879893fe76 zh: 9da30ad0be6fc38d /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision: - en: 339c58ce1afd8225 - zh: d82a5074d7849cc8 + en: aaa2d2c7202408d4 + zh: 134987da042fd07b /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered: en: d6b2de393add9887 zh: b5351f9a49387bd6 /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/consequences: - en: ff4e2a7346097e54 - zh: 7881f404099276b3 + en: df942606f0d31fa5 + zh: cb1f21dd7f60ab7f diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md index fc30a5a383..c0544bdcfb 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -10,7 +10,7 @@ Several packages shared one DeepSeek credential without an owner. `@deepseek-ai/ ## Decision -`@deepseek-ai/dsh-llm` owns the Service Definition. `LlmAdapter.routeCredential(provider)` publishes a `RouteCredential`: the route's `kind` (merge-extensible, with `api-key` and `account` declared), its resolved `baseURL`, an optional credential `reference` for diagnostics, `configured(endpoint)` for presence checks that neither validate the credential nor contact the destination, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with the protocol `headers`, the bare `value` for destinations that render it differently, an optional `reject()` for HTTP 401, and an optional `revoked` signal that aborts when the owner withdraws the credential while requests carry it. `LlmRuntime.routeCredential(provider)` forwards to the owning adapter; an unregistered route answers `undefined`, and a route whose configuration does not resolve propagates the adapter's failure. The adapter reads one configuration generation per call, as it does per model request. +`@deepseek-ai/dsh-llm` owns the Service Definition. `LlmAdapter.providerCredential(provider)` publishes a `ProviderCredential`: the route's `kind` (merge-extensible, with `api-key` and `account` declared), its resolved `baseURL`, an optional credential `reference` for diagnostics, `configured(endpoint)` for presence checks that neither validate the credential nor contact the destination, and `resolve(endpoint, signal)` returning a `ProviderCredentialGrant` with the protocol `headers`, the bare `value` for destinations that render it differently, an optional `reject()` for HTTP 401, and an optional `revoked` signal that aborts when the owner withdraws the credential while requests carry it. `LlmRuntime.providerCredential(provider)` forwards to the owning adapter; an unregistered route answers `undefined`, and a route whose configuration does not resolve propagates the adapter's failure. The adapter reads one configuration generation per call, as it does per model request. `@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the grant or `undefined`; `missingCredential(connection, provider)` names the failure of a request without one, `MISSING_CREDENTIAL` by default; `credential` declares the published kind, reference, and presence check. The transport runs each model request and its file operations under the grant's `revoked` signal and hands the resulting failure to the provider's failure callback, which names it. The listing cache scopes by endpoint and a hash of the credential headers. @@ -18,7 +18,7 @@ The route plugins own credentials. `llm-deepseek-api-key` reads its key through `@deepseek-ai/dsh-deepseek-account` releases request credentials. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, the bare token, a `reject()` that removes the grant while it still matches and contains storage failures, and a `revoked` signal the service aborts at each sign-out after the `deepseek-account/signed-out` listeners have returned; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The service inspects no Agents and depends on neither `dsh-agent` nor `dsh-llm`. The package lives in the `packages/account/` group under its unchanged name. -The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.routeCredential('deepseek-official')` and `routeCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Under each route id it accepts only the kind that route publishes, `api-key` as `deepseek-official` and `account` as `deepseek-account`, so billing by route id never sends the other kind. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account` and the search endpoint has the origin of the route's base URL, and the reference helpers otherwise; it does not request an account credential published for another origin. Both web consumers contain a failed `reject()`, so the HTTP rejection stays the reported error for every credential kind. Both run their request under the grant's `revoked` signal and report a request it ended as `WEB_PROVIDER_ERROR` with sign-in guidance, keeping `WEB_ABORTED` for the caller's cancellation. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. +The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.providerCredential('deepseek-official')` and `providerCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Under each route id it accepts only the kind that route publishes, `api-key` as `deepseek-official` and `account` as `deepseek-account`, so billing by route id never sends the other kind. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account` and the search endpoint has the origin of the route's base URL, and the reference helpers otherwise; it does not request an account credential published for another origin. Both web consumers contain a failed `reject()`, so the HTTP rejection stays the reported error for every credential kind. Both run their request under the grant's `revoked` signal and report a request it ended as `WEB_PROVIDER_ERROR` with sign-in guidance, keeping `WEB_ABORTED` for the caller's cancellation. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. ## Alternatives considered @@ -42,6 +42,6 @@ The web providers consume publications. `web-deepseek-api` builds each operation ## Consequences -Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `routeCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`. +Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `providerCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`. A sign-out ends the in-flight model, Files, Search, and Fetch requests that carry the account token, including requests no Agent turn owns, such as a model request outside a turn or an account-billed web search; the account listing request keeps its own deadline. The signal supplements the Agent cancellation of the [account sign-out decision](2026-09-17-account-provider-signout.md), which rejected a login-level signal as a duplicate of that chain: the chain reaches a request only through a mounted listener and a running Agent turn. While the account route is disabled, a task it started that still runs is not reported to the sign-out confirmation, and a sign-out ends it only through a model request in flight. A credential released by an account service that has since been replaced is not withdrawn by the replacement's sign-out; the route plugin's listener still cancels Agent turns. diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index b370391879..2282d44a68 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.routeCredential(provider)` 发布一个 `RouteCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不校验凭据、不联系目的地的存在性检查 `configured(endpoint)`,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`、可选的 HTTP 401 `reject()`,以及可选的 `revoked` 信号;所有者在请求仍携带凭据时撤回凭据,该信号即中止。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 +`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.providerCredential(provider)` 发布一个 `ProviderCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不校验凭据、不联系目的地的存在性检查 `configured(endpoint)`,以及返回 `ProviderCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`、可选的 HTTP 401 `reject()`,以及可选的 `revoked` 信号;所有者在请求仍携带凭据时撤回凭据,该信号即中止。`LlmRuntime.providerCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 `@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回授权或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`;`credential` 声明发布的种类、引用和存在性检查。传输层让每次模型请求及其文件操作受授权的 `revoked` 信号约束,并把由此产生的失败交给提供方的失败回调命名。列表缓存以端点和凭据请求头的哈希划分作用域。 @@ -18,7 +18,7 @@ Status: implemented `@deepseek-ai/dsh-deepseek-account` 释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、裸 token、`reject()` 和 `revoked` 信号;`reject()` 仅在授权仍一致时删除它并隔离存储失败,`revoked` 由服务在每次退登时、`deepseek-account/signed-out` 的监听器返回之后中止。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。该服务不检查任何 Agent,也不依赖 `dsh-agent` 或 `dsh-llm`。包以不变的名字位于 `packages/account/` 组。 -Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.routeCredential('deepseek-official')` 和 `routeCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。每个路由 id 下只接受该路由发布的种类(`deepseek-official` 下为 `api-key`,`deepseek-account` 下为 `account`),因此按路由 id 计费不会发出另一种凭据。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类且搜索端点与该路由的基础地址同源时使用其账号凭据,否则使用引用函数;为其他 origin 发布的账号凭据不会被索取。两个 Web 消费方都会隔离失败的 `reject()`,因此对任何凭据种类,报告的都是 HTTP 拒绝。二者都让请求受授权的 `revoked` 信号约束,把被它结束的请求报告为带登录指引的 `WEB_PROVIDER_ERROR`,`WEB_ABORTED` 仍只表示调用方取消。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 +Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.providerCredential('deepseek-official')` 和 `providerCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。每个路由 id 下只接受该路由发布的种类(`deepseek-official` 下为 `api-key`,`deepseek-account` 下为 `account`),因此按路由 id 计费不会发出另一种凭据。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类且搜索端点与该路由的基础地址同源时使用其账号凭据,否则使用引用函数;为其他 origin 发布的账号凭据不会被索取。两个 Web 消费方都会隔离失败的 `reject()`,因此对任何凭据种类,报告的都是 HTTP 拒绝。二者都让请求受授权的 `revoked` 信号约束,把被它结束的请求报告为带登录指引的 `WEB_PROVIDER_ERROR`,`WEB_ABORTED` 仍只表示调用方取消。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 ## 考虑过的替代方案 @@ -42,6 +42,6 @@ Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.route ## 后果 -新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `routeCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 +新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `providerCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 退登会结束携带账号 token 的在途模型、Files、Search 与 Fetch 请求,包括不属于任何 Agent 回合的请求,例如回合之外的模型请求或按账号计费的 Web 搜索;账号列表请求仍只受自身期限约束。该信号是对[账号退登决策](2026-09-17-account-provider-signout.zh.md)中 Agent 取消链路的补充;那份决策以重复该链路为由否决了登录级信号,而该链路只能经由已挂载的监听和运行中的 Agent 回合到达请求。账号路由被停用期间,它此前启动且仍在运行的任务不会报告给退登确认,退登也只能通过在途的模型请求结束它。已被替换的账号服务释放的凭据不会被替换后服务的退登撤回;路由插件的监听仍会取消 Agent 回合。 diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml index d683eb8924..4493a15e53 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml @@ -27,8 +27,8 @@ en: 0dcc97d8105fab60 zh: d80d40ae3a0c601d /agent-note-direct-deepseek-search-and-fetch-apis/alternatives-considered: - en: 88708dc170d3e77b - zh: e04536e494769d9c + en: 021a4b08ad534b36 + zh: e98e1f65e50a568b /agent-note-direct-deepseek-search-and-fetch-apis/consequences: en: 7ec21c5b1124e5f8 zh: af769dbdb4face9f diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md index 18c1946887..f6ed9ab69f 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md @@ -52,7 +52,7 @@ The independent `dsh-web-search-deepseek` provider sends Messages search request **Keep the APIs inside the Messages provider behind a provider-local switch.** A switch inside the Messages provider cannot change fetch routing, so `web_fetch` would stay on HTTP unless the user also edited `web.fetchProvider`; it also ties the APIs' lifecycle to Messages search. Separate registrations let the web service's existing selection choose each provider, without coupling either API to the Messages provider. -**Share one transport between Messages search and the new APIs.** A shared web transport would couple different request formats and failure mappings. Credential values instead come from the credentials the model routes publish through `ctx.llm.routeCredential()` and from the `dsh-credentials` reference helpers; Messages search and the Search/Fetch API transports remain independent. +**Share one transport between Messages search and the new APIs.** A shared web transport would couple different request formats and failure mappings. Credential values instead come from the credentials the model routes publish through `ctx.llm.providerCredential()` and from the `dsh-credentials` reference helpers; Messages search and the Search/Fetch API transports remain independent. **Split Search and Fetch into separate packages.** The guide serves both APIs from one base with one credential; separate packages would duplicate settings that address one deployment. Independent selection does not require separate packages, because each API registers its own provider id. Each operation lives in its own module, so either API can change without the other. diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md index 324fcd1d0c..fb88219a08 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md @@ -52,7 +52,7 @@ HTTP 提供方继续负责自身的 URL 校验和资源限制。选择 DeepSeek **把两个 API 放在 Messages 提供方内部,由提供方自己的开关切换。** Messages 提供方内的开关无法改变抓取路由,因此除非用户另外修改 `web.fetchProvider`,`web_fetch` 仍会走 HTTP;它还会把两个 API 的生命周期绑在 Messages 搜索上。独立注册让 Web 服务通过现有的提供方选择机制选择各个提供方,不会把任一 API 与 Messages 提供方绑定。 -**让 Messages 搜索与新 API 共用一套传输层。** 共享 Web 传输层会耦合不同的请求格式和失败映射。凭据值改为来自模型路由通过 `ctx.llm.routeCredential()` 发布的凭据以及 `dsh-credentials` 的引用函数;Messages 搜索与 Search/Fetch API 传输层保持独立。 +**让 Messages 搜索与新 API 共用一套传输层。** 共享 Web 传输层会耦合不同的请求格式和失败映射。凭据值改为来自模型路由通过 `ctx.llm.providerCredential()` 发布的凭据以及 `dsh-credentials` 的引用函数;Messages 搜索与 Search/Fetch API 传输层保持独立。 **把 Search 和 Fetch 拆成两个包。** 指南从同一基础地址、以同一份凭据提供两个 API;拆成两个包会让指向同一部署的设置重复出现。分别选择不需要拆包,因为每个 API 注册自己的提供方 id。每种操作位于独立模块,任一 API 都可以单独修改。 diff --git a/docs/subsystems/account.i18n.yaml b/docs/subsystems/account.i18n.yaml index d54fbdfdf8..665e916b45 100644 --- a/docs/subsystems/account.i18n.yaml +++ b/docs/subsystems/account.i18n.yaml @@ -6,8 +6,8 @@ en: 2302e2999588bac3 zh: 5e0ac058b50036dc /deepseek-account/request-credentials: - en: 8b2ab927576926cf - zh: a41a275c39103347 + en: c5fb32307f841c66 + zh: 8ed40c0c99884301 /deepseek-account/embedded-platform-credentials: en: 9a651d70acbe83a6 zh: 4624b0299f5fdd8e diff --git a/docs/subsystems/account.md b/docs/subsystems/account.md index a550fc9d13..d064016326 100644 --- a/docs/subsystems/account.md +++ b/docs/subsystems/account.md @@ -8,7 +8,7 @@ Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/accoun ## Request credentials -`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. Its `revoked` signal aborts when the account signs out of the sign-in that token belongs to, by the user or after a rejection, once the `deepseek-account/signed-out` listeners have returned; the account model route and the DeepSeek web providers run each model, Files, Search, and Fetch request that carries the token under it, so a sign-out ends those requests even after the plugin that sent them has unloaded. The `deepseek-account` model route publishes this credential through `ctx.llm.routeCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `reject()` runs on the account service mounted when it is called, so a reload between a request and the destination's answer still removes the grant; without a mounted service it leaves the grant for the next one to reject. A credential released by an account service that has since been replaced keeps an unaborted signal, because the replacement withdraws only the credentials it released. +`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. Its `revoked` signal aborts when the account signs out of the sign-in that token belongs to, by the user or after a rejection, once the `deepseek-account/signed-out` listeners have returned; the account model route and the DeepSeek web providers run each model, Files, Search, and Fetch request that carries the token under it, so a sign-out ends those requests even after the plugin that sent them has unloaded. The `deepseek-account` model route publishes this credential through `ctx.llm.providerCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `reject()` runs on the account service mounted when it is called, so a reload between a request and the destination's answer still removes the grant; without a mounted service it leaves the grant for the next one to reject. A credential released by an account service that has since been replaced keeps an unaborted signal, because the replacement withdraws only the credentials it released. Model routes that bill the account register a running-task report with `registerRunningTaskReport(report)` inside `ctx.effect()`; `hasRunningAccountTasks()` answers true while any report does, so the sign-out confirmation can warn about work the sign-out interrupts. The route plugin owns cancellation of that work after `deepseek-account/signed-out`; a request that outlives the plugin ends through its credential's `revoked` signal, and the plugin's failure callback for that request cancels the work. diff --git a/docs/subsystems/account.zh.md b/docs/subsystems/account.zh.md index ce7e1c5f31..ccbdbd0510 100644 --- a/docs/subsystems/account.zh.md +++ b/docs/subsystems/account.zh.md @@ -8,7 +8,7 @@ ## 请求凭据 -`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。其 `revoked` 信号在账号退出该 token 所属的登录时中止,无论退登由用户发起还是由拒绝触发,且在 `deepseek-account/signed-out` 的监听器返回之后;账号模型路由和 DeepSeek Web 提供方让携带该 token 的每个模型、Files、Search 与 Fetch 请求受它约束,因此即使发出请求的插件已卸载,退登仍会结束这些请求。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。已被替换的账号服务释放的凭据,其信号保持未中止,因为替换后的服务只撤回自己释放的凭据。 +`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。其 `revoked` 信号在账号退出该 token 所属的登录时中止,无论退登由用户发起还是由拒绝触发,且在 `deepseek-account/signed-out` 的监听器返回之后;账号模型路由和 DeepSeek Web 提供方让携带该 token 的每个模型、Files、Search 与 Fetch 请求受它约束,因此即使发出请求的插件已卸载,退登仍会结束这些请求。`deepseek-account` 模型路由通过 `ctx.llm.providerCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。已被替换的账号服务释放的凭据,其信号保持未中止,因为替换后的服务只撤回自己释放的凭据。 按账号计费的模型路由在 `ctx.effect()` 内用 `registerRunningTaskReport(report)` 注册运行中任务报告;只要有报告回答 true,`hasRunningAccountTasks()` 就回答 true,使退登确认能够提醒退登将打断的工作。`deepseek-account/signed-out` 之后取消这些工作由路由插件负责;比插件存活更久的请求通过其凭据的 `revoked` 信号结束,插件为该请求提供的失败回调随后取消这些工作。 diff --git a/docs/subsystems/llm-streaming.i18n.yaml b/docs/subsystems/llm-streaming.i18n.yaml index d432290702..dbb124b198 100644 --- a/docs/subsystems/llm-streaming.i18n.yaml +++ b/docs/subsystems/llm-streaming.i18n.yaml @@ -36,8 +36,8 @@ en: 58dec2259b0b1c6f zh: fc99fe965acaabf3 /llm-streaming/the-model-request: - en: a345a763b420ff1a - zh: c3e0adef1b1036ef + en: 61d4131601adbc32 + zh: b83156c875d29b89 /llm-streaming/the-model-request/the-request-envelope-llmcallconfig-and-the-logged-header: en: b0eb4620c6953646 zh: fabf51c7245a4855 @@ -48,5 +48,5 @@ en: 8c140f9c5a799f01 zh: f66b895594247e92 /llm-streaming/service-and-provider-contracts: - en: 4d210152ca139cb0 - zh: d131e11d95666342 + en: 81b4ede66c5e906d + zh: 2ad0ddb1a32e3167 diff --git a/docs/subsystems/llm-streaming.md b/docs/subsystems/llm-streaming.md index 2b0427644f..1e93b92f64 100644 --- a/docs/subsystems/llm-streaming.md +++ b/docs/subsystems/llm-streaming.md @@ -527,14 +527,14 @@ interface LlmNativeAuth { } ``` -A route's adapter can also publish the credential the route currently sends, so consumers that call the same deployment outside the model request path, such as the DeepSeek web providers, reuse it through `ctx.llm.routeCredential(provider)` instead of reading provider configuration or choosing header names. A grant is Host-only and is held for one operation; `kind` is merge-extensible through `LlmCredentialKindMap`, whose declared members are `api-key` and `account`. A grant whose owner can withdraw the credential while requests carry it, as an account sign-out does, has a `revoked` signal: the consumer runs each request it authenticates under that signal and reports a request the signal ended as its own failure, not as the caller's cancellation. +A route's adapter can also publish the credential the route currently sends, so consumers that call the same deployment outside the model request path, such as the DeepSeek web providers, reuse it through `ctx.llm.providerCredential(provider)` instead of reading provider configuration or choosing header names. A grant is Host-only and is held for one operation; `kind` is merge-extensible through `LlmCredentialKindMap`, whose declared members are `api-key` and `account`. A grant whose owner can withdraw the credential while requests carry it, as an account sign-out does, has a `revoked` signal: the consumer runs each request it authenticates under that signal and reports a request the signal ended as its own failure, not as the caller's cancellation. ```ts type-equiv /** * One credential released for one destination. Host-only: it carries the * secret, so it never crosses a Remote boundary and never enters a log. */ -interface RouteCredentialGrant { +interface ProviderCredentialGrant { /** * Request headers carrying the credential as the route's own protocol * expects it, such as `x-api-key` for an API key. Consumers speaking that @@ -568,11 +568,11 @@ interface RouteCredentialGrant { /** * The credential one registered provider route currently sends, answered by * the route's owning adapter so that consumers read no provider configuration - * and choose no header names. `ctx.llm.routeCredential()` resolves a new value + * and choose no header names. `ctx.llm.providerCredential()` resolves a new value * per call from one configuration generation; a caller keeps it for one * operation only. */ -interface RouteCredential { +interface ProviderCredential { /** Kind of credential the route sends. */ readonly kind: LlmCredentialKind /** @@ -603,7 +603,7 @@ interface RouteCredential { * @param signal - cancellation for the lookup. * @returns the released credential, or `undefined`. */ - resolve(endpoint: string, signal?: AbortSignal): Promise + resolve(endpoint: string, signal?: AbortSignal): Promise } ``` @@ -950,7 +950,7 @@ The [wire reference](../deepseek-llm-api-wire-extensions.md) defines the exact r `LlmAdapter` is the provider contract: subclass, implement `stream()`, and register one adapter instance with `ctx.llm.registerAdapter(providers, adapter)`. `GenerateOptions.provider` selects the registered adapter; `GenerateOptions.model` is passed to that adapter and need not be registered at lifecycle start. Duplicate provider routes fail atomically. Optional `providerRetryPolicy()` is captured per route with normal defaults, while `providerInfo()` and asynchronous `listModels()` feed `LlmRuntime.listProviders()` / `listModels()` with detached selector metadata. That catalog is advisory rather than a request whitelist: the adapter remains authoritative and may accept unlisted model ids. One asynchronous `resolveModel()` query returns exact model identity plus optional correctness-sensitive context capacity, an adapter-configured `defaultMaxTokens`, and ordered model-owned reasoning ids with an optional deployment default; absent fields mean unavailable metadata or provider-owned behavior, not invalid catalog membership. The resolver receives optional cancellation and must settle promptly after abort. `LlmRuntime.resolveModelInfo()` validates and detaches the aggregate. At the final adapter boundary, `resolveCallConfig()` materializes the output default only when `maxTokens` is absent and validates and materializes reasoning, so direct calls cannot bypass either configured behavior; direct dispatch captures one registration before awaiting that resolution. The agent loop instead uses `prepareCall()` to keep the same registration across model resolution, durable header logging, and dispatch, retain detached context metadata from that exact lookup, and report which config fields the adapter defaulted. Adapter lookup happens at the terminal continuation of the `llm/stream` waterfall, so a listener may short-circuit the call or route a mutable one-shot request before lookup. AgentLoop observes a request attempt once the outer waterfall returns a stream handle; that limited boundary does not prove a lazy terminal adapter was constructed or began provider I/O. The `block-start` / `block-end` `index` correlation and the assembler together mean an adapter only has to emit well-formed chunks — block reassembly is not each adapter's problem. [architecture.md](../architecture.md#turn-flow) shows where `ctx.llm.stream()` and the `llm/stream` waterfall sit in one turn. -Optional `routeCredential()` publishes the credential a route currently sends, with the route's base URL, its kind, and an optional credential reference. `LlmRuntime.routeCredential(provider)` forwards to the owning adapter: an unregistered route answers `undefined`, because callers ask about routes a conversation named earlier, and a registered route whose configuration does not resolve propagates the adapter's failure. The DeepSeek web providers read it to call the deployment of the conversation's route with that route's credential, so no consumer reads another plugin's configuration or chooses its header names. +Optional `providerCredential()` publishes the credential a route currently sends, with the route's base URL, its kind, and an optional credential reference. `LlmRuntime.providerCredential(provider)` forwards to the owning adapter: an unregistered route answers `undefined`, because callers ask about routes a conversation named earlier, and a registered route whose configuration does not resolve propagates the adapter's failure. The DeepSeek web providers read it to call the deployment of the conversation's route with that route's credential, so no consumer reads another plugin's configuration or chooses its header names. ```ts type-equiv /** One model call whose config and adapter registration were resolved together. */ @@ -1028,7 +1028,7 @@ declare abstract class LlmAdapter { * @param _provider - a route passed to `registerAdapter()` for this instance. * @returns the route's current credential, or `undefined` when the route publishes none. */ - routeCredential(_provider: string): RouteCredential | undefined; + providerCredential(_provider: string): ProviderCredential | undefined; /** * List models this adapter can currently advertise for one owned provider. * Core routing accepts unlisted model ids; catalog-driven entry points such @@ -1216,9 +1216,9 @@ imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): * which may no longer be mounted; a registered route whose configuration * does not resolve propagates the adapter's failure. * @param provider - provider route whose credential is wanted. - * @returns the route credential, or `undefined` when the route is unregistered or publishes none. + * @returns the route's credential, or `undefined` when the route is unregistered or publishes none. */ -routeCredential(provider: string): RouteCredential | undefined +providerCredential(provider: string): ProviderCredential | undefined /** * Resolve the exact text one durable file occurrence contributes to every diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index cd6ea6501b..2e8707f13a 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -533,14 +533,14 @@ interface LlmNativeAuth { } ``` -路由的适配器还可以发布该路由当前发送的凭据,使在模型请求路径之外调用同一部署的消费方(如 DeepSeek Web 提供方)通过 `ctx.llm.routeCredential(provider)` 复用它,而不读取提供方配置或自行选择请求头名称。授权仅限 Host,且只在一次操作内持有;`kind` 通过 `LlmCredentialKindMap` 可合并扩展,已声明的成员为 `api-key` 和 `account`。所有者可能在请求仍携带凭据时撤回它(例如账号退登),这类授权带有 `revoked` 信号:消费方让它鉴权的每个请求都受该信号约束,并把被该信号结束的请求报告为自身的失败,而不是调用方的取消。 +路由的适配器还可以发布该路由当前发送的凭据,使在模型请求路径之外调用同一部署的消费方(如 DeepSeek Web 提供方)通过 `ctx.llm.providerCredential(provider)` 复用它,而不读取提供方配置或自行选择请求头名称。授权仅限 Host,且只在一次操作内持有;`kind` 通过 `LlmCredentialKindMap` 可合并扩展,已声明的成员为 `api-key` 和 `account`。所有者可能在请求仍携带凭据时撤回它(例如账号退登),这类授权带有 `revoked` 信号:消费方让它鉴权的每个请求都受该信号约束,并把被该信号结束的请求报告为自身的失败,而不是调用方的取消。 ```ts type-equiv /** * One credential released for one destination. Host-only: it carries the * secret, so it never crosses a Remote boundary and never enters a log. */ -interface RouteCredentialGrant { +interface ProviderCredentialGrant { /** * Request headers carrying the credential as the route's own protocol * expects it, such as `x-api-key` for an API key. Consumers speaking that @@ -574,11 +574,11 @@ interface RouteCredentialGrant { /** * The credential one registered provider route currently sends, answered by * the route's owning adapter so that consumers read no provider configuration - * and choose no header names. `ctx.llm.routeCredential()` resolves a new value + * and choose no header names. `ctx.llm.providerCredential()` resolves a new value * per call from one configuration generation; a caller keeps it for one * operation only. */ -interface RouteCredential { +interface ProviderCredential { /** Kind of credential the route sends. */ readonly kind: LlmCredentialKind /** @@ -609,7 +609,7 @@ interface RouteCredential { * @param signal - cancellation for the lookup. * @returns the released credential, or `undefined`. */ - resolve(endpoint: string, signal?: AbortSignal): Promise + resolve(endpoint: string, signal?: AbortSignal): Promise } ``` @@ -956,7 +956,7 @@ interface LlmCallConfigAdapterDefaults { `LlmAdapter` 是提供方约定:创建子类、实现 `stream()`,再用 `ctx.llm.registerAdapter(providers, adapter)` 注册一个适配器实例。`GenerateOptions.provider` 选择已注册适配器;`GenerateOptions.model` 会传给该适配器,无需在生命周期启动时注册。重复提供方路由会原子失败。可选的 `providerRetryPolicy()` 会按路由捕获并填入 normal 默认值,`providerInfo()` 与异步 `listModels()` 方法则为 `LlmRuntime.listProviders()` / `listModels()` 提供分离的 selector 元数据。该目录仅供参考,不是请求白名单:适配器仍是权威,并可接受未列出的模型 id。单次异步 `resolveModel()` 查询返回确切模型身份,以及可选的对正确性敏感的上下文容量、适配器配置的 `defaultMaxTokens`、由模型持有的有序推理强度 ID 和可选的部署默认值;字段缺失表示元数据不可用或保留提供方持有的行为,而不表示目录成员关系无效。解析器会接收可选的取消信号,并且必须在信号中止后迅速完成结算。`LlmRuntime.resolveModelInfo()` 会校验聚合结果并返回分离值。在最终适配器边界,`resolveCallConfig()` 仅在 `maxTokens` 缺失时填入输出默认值,并校验和填入推理强度,因此直接调用也无法绕过任何一项已配置行为;直接分派会在等待解析前捕获一项适配器注册。agent loop 则使用 `prepareCall()`,使模型解析、请求头持久记录和分派全程使用同一项注册,保留来自同一次查询的分离上下文元数据,并报告适配器填入的配置字段。适配器查找发生在 `llm/stream` waterfall 的终端 continuation,因此 listener 可以在查找前短路调用,或路由一个可变的一次性请求。AgentLoop 在外层 waterfall 返回流句柄时观察到一次请求尝试;这个有限边界不能证明惰性终端适配器已构造完成或开始提供方 I/O。`block-start` / `block-end` 的 `index` 关联与 assembler 共同意味着适配器只需 emit 格式正确的分片——块重组不是每个适配器各自的问题。`ctx.llm.stream()` 与 `llm/stream` waterfall 在一个轮次中的位置见 [architecture.md](../architecture.zh.md#turn-flow)。 -可选的 `routeCredential()` 发布路由当前发送的凭据,连同路由的基础地址、凭据种类和可选的凭据引用。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器:未注册的路由回答 `undefined`,因为调用方询问的是会话早先命名的路由;已注册但配置无法解析的路由则传播适配器的失败。DeepSeek Web 提供方据此用会话路由的凭据调用同一部署,因此没有消费方需要读取其他插件的配置或自行选择请求头名称。 +可选的 `providerCredential()` 发布路由当前发送的凭据,连同路由的基础地址、凭据种类和可选的凭据引用。`LlmRuntime.providerCredential(provider)` 转发给拥有该路由的适配器:未注册的路由回答 `undefined`,因为调用方询问的是会话早先命名的路由;已注册但配置无法解析的路由则传播适配器的失败。DeepSeek Web 提供方据此用会话路由的凭据调用同一部署,因此没有消费方需要读取其他插件的配置或自行选择请求头名称。 ```ts type-equiv /** One model call whose config and adapter registration were resolved together. */ @@ -1034,7 +1034,7 @@ declare abstract class LlmAdapter { * @param _provider - a route passed to `registerAdapter()` for this instance. * @returns the route's current credential, or `undefined` when the route publishes none. */ - routeCredential(_provider: string): RouteCredential | undefined; + providerCredential(_provider: string): ProviderCredential | undefined; /** * List models this adapter can currently advertise for one owned provider. * Core routing accepts unlisted model ids; catalog-driven entry points such @@ -1222,9 +1222,9 @@ imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): * which may no longer be mounted; a registered route whose configuration * does not resolve propagates the adapter's failure. * @param provider - provider route whose credential is wanted. - * @returns the route credential, or `undefined` when the route is unregistered or publishes none. + * @returns the route's credential, or `undefined` when the route is unregistered or publishes none. */ -routeCredential(provider: string): RouteCredential | undefined +providerCredential(provider: string): ProviderCredential | undefined /** * Resolve the exact text one durable file occurrence contributes to every diff --git a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.i18n.yaml index 5a217379ea..ce61c10cdf 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.i18n.yaml @@ -3,14 +3,14 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md /: - en: f0cf30e5430471e8 - zh: 2e6e871797dfdd6b + en: 56fc7afd90f0fcde + zh: 0b441fc159f25bcf /deepseek-routes-publish-the-credential-web-consumers-reuse: en: b5392bcd81f69488 zh: 68cd945f2dde46af /deepseek-routes-publish-the-credential-web-consumers-reuse/change: - en: 4e77c6f6c622beb2 - zh: 2c119f567ff411ff + en: 7568433b72e2633b + zh: dcd4c6deb72da3a4 /deepseek-routes-publish-the-credential-web-consumers-reuse/migration: - en: 6d117f2dfd7593d0 - zh: 1c1579fc7d0ccad0 + en: 0632d7c9ffce1675 + zh: a8b4d67f469eaee7 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md index f8dcf10eec..7b4b539fb7 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md @@ -1,6 +1,6 @@ --- kind: upgrade-guide -description: "DeepSeek model routes publish their credential through ctx.llm.routeCredential(); the llm-deepseek credential helpers, the route plugins' config exports, and account Agent inspection are removed." +description: "DeepSeek model routes publish their credential through ctx.llm.providerCredential(); the llm-deepseek credential helpers, the route plugins' config exports, and account Agent inspection are removed." --- # DeepSeek routes publish the credential web consumers reuse @@ -9,7 +9,7 @@ English | [中文](guide.zh.md) ## Change -`LlmAdapter.routeCredential(provider)` and `LlmRuntime.routeCredential(provider)` publish a route's current credential as a `RouteCredential`: kind, resolved base URL, optional reference, a `configured(endpoint)` presence check, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with protocol headers, the bare value, an optional `reject()`, and an optional `revoked` withdrawal signal. +`LlmAdapter.providerCredential(provider)` and `LlmRuntime.providerCredential(provider)` publish a route's current credential as a `ProviderCredential`: kind, resolved base URL, optional reference, a `configured(endpoint)` presence check, and `resolve(endpoint, signal)` returning a `ProviderCredentialGrant` with protocol headers, the bare value, an optional `reject()`, and an optional `revoked` withdrawal signal. `@deepseek-ai/dsh-llm-deepseek` no longer exports `resolveDeepSeekApiKey`, `deepSeekApiKeyConfigured`, `resolveDeepSeekAccountToken`, or `rejectDeepSeekAccountToken`. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns `DeepSeekRequestAuth | undefined`, and `DeepSeekRequestAuth` requires `value` beside `headers`; the new `missingCredential` and `credential` options name the missing-credential failure and the published credential. `createModelListingCache` takes `credential(url)` returning request headers, and its `load` is optional. @@ -17,13 +17,13 @@ English | [中文](guide.zh.md) `@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)` and makes `resolveToken(url)` and `rejectToken(token)` private; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. A sign-out aborts released credentials' `revoked` signal, ending in-flight account requests: model requests outside a turn fail with `ACCOUNT_SIGN_IN_REQUIRED`, Search and Fetch with `WEB_PROVIDER_ERROR`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name. `@deepseek-ai/dsh-credentials` adds `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`. -`@deepseek-ai/dsh-web-deepseek-api` drops its peer dependencies on `dsh-llm-deepseek`, both route plugins, and `cordis-plugin-loader`; `@deepseek-ai/dsh-web-search-deepseek` drops `dsh-llm-deepseek` and `dsh-deepseek-account` and adds `dsh-llm`. Both read route credentials through `ctx.llm.routeCredential()`, so an adapter registered under a DeepSeek route id that publishes no credential, or a credential of the other kind, counts as no route. Without the account route, the Search and Fetch APIs send the account credential to the origin `DEEPSEEK_BASE_URL` names and reject a value that is not an HTTP(S) URL without embedded credentials. `DeepSeekSearchProviderOptions` replaces `resolveAccountToken` and `rejectAccountToken` with `resolveAccountCredential(endpoint)`. +`@deepseek-ai/dsh-web-deepseek-api` drops its peer dependencies on `dsh-llm-deepseek`, both route plugins, and `cordis-plugin-loader`; `@deepseek-ai/dsh-web-search-deepseek` drops `dsh-llm-deepseek` and `dsh-deepseek-account` and adds `dsh-llm`. Both read route credentials through `ctx.llm.providerCredential()`, so an adapter registered under a DeepSeek route id that publishes no credential, or a credential of the other kind, counts as no route. Without the account route, the Search and Fetch APIs send the account credential to the origin `DEEPSEEK_BASE_URL` names and reject a value that is not an HTTP(S) URL without embedded credentials. `DeepSeekSearchProviderOptions` replaces `resolveAccountToken` and `rejectAccountToken` with `resolveAccountCredential(endpoint)`. ## Migration -1. Replace the removed `llm-deepseek` helpers: read keys with `resolveCredentialRef` and `credentialRefConfigured` from `@deepseek-ai/dsh-credentials` and validate them with `assertUsableApiKey`; read account credentials with `ctx.deepseekAccount.resolveRequestCredential(url)` and invalidate through the returned `reject()`. To reuse a mounted route's credential and endpoint, call `ctx.llm.routeCredential(provider)`, and run each request under the grant's `revoked` signal. +1. Replace the removed `llm-deepseek` helpers: read keys with `resolveCredentialRef` and `credentialRefConfigured` from `@deepseek-ai/dsh-credentials` and validate them with `assertUsableApiKey`; read account credentials with `ctx.deepseekAccount.resolveRequestCredential(url)` and invalidate through the returned `reject()`. To reuse a mounted route's credential and endpoint, call `ctx.llm.providerCredential(provider)`, and run each request under the grant's `revoked` signal. 2. In custom `DeepSeekAdapter` or `registerDeepSeekProvider` consumers, return `undefined` from `resolveAuth` when no credential exists, add `value` to every `DeepSeekRequestAuth`, supply `missingCredential` for a route-specific failure, and declare `credential` to publish the route's credential. Pass credential headers, not a token, to `createModelListingCache`. 3. Replace imports of the route plugins' config exports with the plugins' own `Config`, and read a route's endpoint from its published credential instead of its resolver. 4. Make `deepseekAccount` stand-ins used by the account route or the web providers implement `resolveRequestCredential`, returning a `revoked` signal; stand-ins that supplied `ctx.agents` for `hasRunningAccountTasks()` register a report instead. 5. Update workspace references to `packages/account/deepseek-account`; the npm package name, Remote namespace, and configuration keys are unchanged. -6. Replace `resolveAccountToken` and `rejectAccountToken` in `DeepSeekSearchProviderOptions` with `resolveAccountCredential` returning a `RouteCredentialGrant`. +6. Replace `resolveAccountToken` and `rejectAccountToken` in `DeepSeekSearchProviderOptions` with `resolveAccountCredential` returning a `ProviderCredentialGrant`. diff --git a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md index 712e402000..6e6705bfeb 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md @@ -1,6 +1,6 @@ --- kind: upgrade-guide -description: "DeepSeek 模型路由通过 ctx.llm.routeCredential() 发布自己的凭据;移除 llm-deepseek 的凭据辅助函数、路由插件的配置导出和账号服务对 Agent 的检查。" +description: "DeepSeek 模型路由通过 ctx.llm.providerCredential() 发布自己的凭据;移除 llm-deepseek 的凭据辅助函数、路由插件的配置导出和账号服务对 Agent 的检查。" --- # DeepSeek 路由发布 Web 消费方复用的凭据 @@ -9,7 +9,7 @@ description: "DeepSeek 模型路由通过 ctx.llm.routeCredential() 发布自己 ## 变更 -`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、`configured(endpoint)` 存在性检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值、可选的 `reject()`,以及可选的 `revoked` 撤回信号。 +`LlmAdapter.providerCredential(provider)` 与 `LlmRuntime.providerCredential(provider)` 把路由当前的凭据发布为 `ProviderCredential`:种类、解析后的基础地址、可选引用、`configured(endpoint)` 存在性检查,以及返回 `ProviderCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值、可选的 `reject()`,以及可选的 `revoked` 撤回信号。 `@deepseek-ai/dsh-llm-deepseek` 不再导出 `resolveDeepSeekApiKey`、`deepSeekApiKeyConfigured`、`resolveDeepSeekAccountToken` 和 `rejectDeepSeekAccountToken`。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回 `DeepSeekRequestAuth | undefined`,且 `DeepSeekRequestAuth` 在 `headers` 之外要求 `value`;新增的 `missingCredential` 与 `credential` 选项分别命名凭据缺失的失败和发布的凭据。`createModelListingCache` 的 `credential(url)` 返回请求头,其 `load` 变为可选。 @@ -17,13 +17,13 @@ description: "DeepSeek 模型路由通过 ctx.llm.routeCredential() 发布自己 `@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`,并将 `resolveToken(url)` 与 `rejectToken(token)` 改为私有;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。退登会中止已释放凭据的 `revoked` 信号,从而结束在途的账号请求:回合之外的模型请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,Search 与 Fetch 以 `WEB_PROVIDER_ERROR` 失败。该包移除 `dsh-agent` 与 `dsh-llm` peer 依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。`@deepseek-ai/dsh-credentials` 新增 `resolveCredentialRef(ctx, ref)` 与 `credentialRefConfigured(ctx, ref)`。 -`@deepseek-ai/dsh-web-deepseek-api` 移除对 `dsh-llm-deepseek`、两个路由插件和 `cordis-plugin-loader` 的 peer 依赖;`@deepseek-ai/dsh-web-search-deepseek` 移除 `dsh-llm-deepseek` 与 `dsh-deepseek-account`,新增 `dsh-llm`。两者都通过 `ctx.llm.routeCredential()` 读取路由凭据,因此以 DeepSeek 路由 id 注册但不发布凭据、或发布另一种凭据的适配器视为没有路由。没有账号路由时,Search 与 Fetch API 把账号凭据发往 `DEEPSEEK_BASE_URL` 所指的 origin,并拒绝不是不含内嵌凭据的 HTTP(S) URL 的值。`DeepSeekSearchProviderOptions` 用 `resolveAccountCredential(endpoint)` 替换 `resolveAccountToken` 与 `rejectAccountToken`。 +`@deepseek-ai/dsh-web-deepseek-api` 移除对 `dsh-llm-deepseek`、两个路由插件和 `cordis-plugin-loader` 的 peer 依赖;`@deepseek-ai/dsh-web-search-deepseek` 移除 `dsh-llm-deepseek` 与 `dsh-deepseek-account`,新增 `dsh-llm`。两者都通过 `ctx.llm.providerCredential()` 读取路由凭据,因此以 DeepSeek 路由 id 注册但不发布凭据、或发布另一种凭据的适配器视为没有路由。没有账号路由时,Search 与 Fetch API 把账号凭据发往 `DEEPSEEK_BASE_URL` 所指的 origin,并拒绝不是不含内嵌凭据的 HTTP(S) URL 的值。`DeepSeekSearchProviderOptions` 用 `resolveAccountCredential(endpoint)` 替换 `resolveAccountToken` 与 `rejectAccountToken`。 ## 迁移 -1. 替换被移除的 `llm-deepseek` 辅助函数:用 `@deepseek-ai/dsh-credentials` 的 `resolveCredentialRef` 与 `credentialRefConfigured` 读取密钥并用 `assertUsableApiKey` 校验;用 `ctx.deepseekAccount.resolveRequestCredential(url)` 读取账号凭据并通过返回的 `reject()` 作废。要复用已挂载路由的凭据和端点,调用 `ctx.llm.routeCredential(provider)`,并让每个请求受授权的 `revoked` 信号约束。 +1. 替换被移除的 `llm-deepseek` 辅助函数:用 `@deepseek-ai/dsh-credentials` 的 `resolveCredentialRef` 与 `credentialRefConfigured` 读取密钥并用 `assertUsableApiKey` 校验;用 `ctx.deepseekAccount.resolveRequestCredential(url)` 读取账号凭据并通过返回的 `reject()` 作废。要复用已挂载路由的凭据和端点,调用 `ctx.llm.providerCredential(provider)`,并让每个请求受授权的 `revoked` 信号约束。 2. 在自定义的 `DeepSeekAdapter` 或 `registerDeepSeekProvider` 消费方中,没有凭据时让 `resolveAuth` 返回 `undefined`,为每个 `DeepSeekRequestAuth` 加上 `value`,为路由专属的失败提供 `missingCredential`,并声明 `credential` 以发布路由凭据。向 `createModelListingCache` 传递凭据请求头而不是 token。 3. 用路由插件自身的 `Config` 替换对其配置导出的导入,并从路由发布的凭据而非其解析函数读取端点。 4. 让账号路由或 Web 提供方使用的 `deepseekAccount` 替身实现 `resolveRequestCredential` 并返回 `revoked` 信号;为 `hasRunningAccountTasks()` 提供 `ctx.agents` 的替身改为注册报告。 5. 把工作区引用更新为 `packages/account/deepseek-account`;npm 包名、Remote 命名空间和配置键均不变。 -6. 把 `DeepSeekSearchProviderOptions` 中的 `resolveAccountToken` 与 `rejectAccountToken` 替换为返回 `RouteCredentialGrant` 的 `resolveAccountCredential`。 +6. 把 `DeepSeekSearchProviderOptions` 中的 `resolveAccountToken` 与 `rejectAccountToken` 替换为返回 `ProviderCredentialGrant` 的 `resolveAccountCredential`。 diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 45aa44dd40..bba09726ca 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -2229,10 +2229,10 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'dimensions and byte target used by the adapter\'s request serializer.', }, { - signature: 'routeCredential(provider: string): RouteCredential | undefined', + signature: 'providerCredential(provider: string): ProviderCredential | undefined', description: 'Resolve the credential one registered route currently sends, through its owning adapter. An unregistered route answers `undefined` rather than throwing because callers ask about routes a conversation named earlier, which may no longer be mounted; a registered route whose configuration does not resolve propagates the adapter\'s failure.', parameters: [{ name: 'provider', description: 'provider route whose credential is wanted.' }], - returns: 'the route credential, or `undefined` when the route is unregistered or publishes none.', + returns: 'the route\'s credential, or `undefined` when the route is unregistered or publishes none.', }, { signature: 'fileRequestText(ref: FileAttachmentRef): string', @@ -7599,7 +7599,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'LlmAdapter', - declaration: 'export abstract class LlmAdapter {\n providerInfo(provider: string): LlmProviderInfo;\n providerRetryPolicy(_provider: string): ResolvedRetryPolicy | undefined;\n imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget;\n routeCredential(_provider: string): RouteCredential | undefined;\n listModels(_provider: string): Promise;\n resolveModel(provider: string, model: string, _signal?: AbortSignal): Promise;\n async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise;\n abstract stream(options: GenerateOptions): AsyncIterable;\n}', + declaration: 'export abstract class LlmAdapter {\n providerInfo(provider: string): LlmProviderInfo;\n providerRetryPolicy(_provider: string): ResolvedRetryPolicy | undefined;\n imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget;\n providerCredential(_provider: string): ProviderCredential | undefined;\n listModels(_provider: string): Promise;\n resolveModel(provider: string, model: string, _signal?: AbortSignal): Promise;\n async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise;\n abstract stream(options: GenerateOptions): AsyncIterable;\n}', }, { name: 'LlmAttemptId', @@ -7695,7 +7695,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'LlmRuntime', - declaration: 'export class LlmRuntime extends TypertRemoteService {\n constructor(ctx: Context);\n registerAdapter(providers: string[], adapter: LlmAdapter): AdapterRegistrationHandle;\n @Remote\n listProviders(): LlmProviderInfo[];\n registerConfigurableProviders(entries: readonly LlmConfigurableProvider[]): DirectoryRegistrationHandle;\n @Remote\n listConfigurableProviders(): LlmConfigurableProvider[];\n registerModelDiscovery(settingsNs: string, discover: (request: LlmModelDiscoveryRequest, signal?: AbortSignal) => Promise): () => void;\n async discoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal?: AbortSignal): Promise;\n @Remote(\'discoverModels\')\n async remoteDiscoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal: AbortSignal): Promise;\n providerRetryPolicy(provider: string): ResolvedRetryPolicy;\n imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget;\n routeCredential(provider: string): RouteCredential | undefined;\n fileRequestText(ref: FileAttachmentRef): string;\n async listModels(provider: string): Promise;\n async resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise;\n async resolveCallConfig(config: LlmCallConfig, signa /* …truncated — full shape in source */', + declaration: 'export class LlmRuntime extends TypertRemoteService {\n constructor(ctx: Context);\n registerAdapter(providers: string[], adapter: LlmAdapter): AdapterRegistrationHandle;\n @Remote\n listProviders(): LlmProviderInfo[];\n registerConfigurableProviders(entries: readonly LlmConfigurableProvider[]): DirectoryRegistrationHandle;\n @Remote\n listConfigurableProviders(): LlmConfigurableProvider[];\n registerModelDiscovery(settingsNs: string, discover: (request: LlmModelDiscoveryRequest, signal?: AbortSignal) => Promise): () => void;\n async discoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal?: AbortSignal): Promise;\n @Remote(\'discoverModels\')\n async remoteDiscoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal: AbortSignal): Promise;\n providerRetryPolicy(provider: string): ResolvedRetryPolicy;\n imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget;\n providerCredential(provider: string): ProviderCredential | undefined;\n fileRequestText(ref: FileAttachmentRef): string;\n async listModels(provider: string): Promise;\n async resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise;\n async resolveCallConfig(config: LlmCallConfig, /* …truncated — full shape in source */', }, { name: 'LocalAtInput', @@ -8501,6 +8501,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'PromptSubmitResult', declaration: 'export type PromptSubmitResult = {\n text: string;\n context?: readonly string[];\n drop?: undefined;\n} | {\n drop: string;\n text?: undefined;\n context?: undefined;\n};', }, + { + name: 'ProviderCredential', + declaration: 'export interface ProviderCredential {\n readonly kind: LlmCredentialKind;\n readonly baseURL: string;\n readonly reference?: string;\n configured(endpoint: string): Promise;\n resolve(endpoint: string, signal?: AbortSignal): Promise;\n}', + }, + { + name: 'ProviderCredentialGrant', + declaration: 'export interface ProviderCredentialGrant {\n readonly headers: Readonly>;\n readonly value: string;\n reject?(): Promise;\n readonly revoked?: AbortSignal;\n}', + }, { name: 'ProviderRequestId', declaration: 'export type ProviderRequestId = Branded<\'ProviderRequestId\'>;', @@ -8789,14 +8797,6 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ReviewVerdict', declaration: 'export type ReviewVerdict = \'approved\' | \'changes-requested\' | \'commented\' | \'dismissed\';', }, - { - name: 'RouteCredential', - declaration: 'export interface RouteCredential {\n readonly kind: LlmCredentialKind;\n readonly baseURL: string;\n readonly reference?: string;\n configured(endpoint: string): Promise;\n resolve(endpoint: string, signal?: AbortSignal): Promise;\n}', - }, - { - name: 'RouteCredentialGrant', - declaration: 'export interface RouteCredentialGrant {\n readonly headers: Readonly>;\n readonly value: string;\n reject?(): Promise;\n readonly revoked?: AbortSignal;\n}', - }, { name: 'RpcId', declaration: 'export type RpcId = Branded<\'rpc-id\'>;', diff --git a/packages/llm/llm-deepseek-account/README.i18n.yaml b/packages/llm/llm-deepseek-account/README.i18n.yaml index 0b1592817f..ab9e5e1b82 100644 --- a/packages/llm/llm-deepseek-account/README.i18n.yaml +++ b/packages/llm/llm-deepseek-account/README.i18n.yaml @@ -9,8 +9,8 @@ en: 8fa1148e0ee9d351 zh: 634ec9d79d5ffbf0 /deepseek-ai-dsh-llm-deepseek-account/summary: - en: 90635454957391b0 - zh: 815bf79ba6056c3c + en: 47201804733ec769 + zh: 3c6751b16a45759f /deepseek-ai-dsh-llm-deepseek-account/table-of-contents: en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 diff --git a/packages/llm/llm-deepseek-account/README.md b/packages/llm/llm-deepseek-account/README.md index b534844f32..283b36d3eb 100644 --- a/packages/llm/llm-deepseek-account/README.md +++ b/packages/llm/llm-deepseek-account/README.md @@ -11,7 +11,7 @@ English | [中文](README.zh.md) Register authentication, the account model listing, and model gating for `deepseek-account`. This plugin shares the [Messages transport](../llm-deepseek/README.md) and owns credential resolution, the account catalog, and model admission. -Authentication resolution returns the request credential the account service releases for the destination, carrying `x-dsh-auth-token`, with a failure callback that invalidates that same credential. HTTP 401 classification stays in this provider; a rejected older request cannot clear a replacement login. The route publishes the account credential through `ctx.llm.routeCredential('deepseek-account')` with its base URL, so the DeepSeek web providers send it to the same deployment. +Authentication resolution returns the request credential the account service releases for the destination, carrying `x-dsh-auth-token`, with a failure callback that invalidates that same credential. HTTP 401 classification stays in this provider; a rejected older request cannot clear a replacement login. The route publishes the account credential through `ctx.llm.providerCredential('deepseek-account')` with its base URL, so the DeepSeek web providers send it to the same deployment. ## Table of Contents diff --git a/packages/llm/llm-deepseek-account/README.zh.md b/packages/llm/llm-deepseek-account/README.zh.md index c0614c8907..04b6256544 100644 --- a/packages/llm/llm-deepseek-account/README.zh.md +++ b/packages/llm/llm-deepseek-account/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" 为 `deepseek-account` 注册鉴权、账号模型列表和模型门控。通过 [llm-deepseek](../llm-deepseek/README.zh.md) 共用 Messages 请求实现;本包负责凭据解析、账号目录和模型准入。 -鉴权解析返回账号服务为目标地址释放的请求凭据,携带 `x-dsh-auth-token`,并附带使同一凭据失效的失败回调。HTTP 401 的分类由此提供方负责;被拒绝的旧请求不能清除替换后的登录。路由通过 `ctx.llm.routeCredential('deepseek-account')` 连同其基础地址发布账号凭据,使 DeepSeek Web 提供方把它发往同一部署。 +鉴权解析返回账号服务为目标地址释放的请求凭据,携带 `x-dsh-auth-token`,并附带使同一凭据失效的失败回调。HTTP 401 的分类由此提供方负责;被拒绝的旧请求不能清除替换后的登录。路由通过 `ctx.llm.providerCredential('deepseek-account')` 连同其基础地址发布账号凭据,使 DeepSeek Web 提供方把它发往同一部署。 ## 目录 diff --git a/packages/llm/llm-deepseek-account/tests/provider.spec.ts b/packages/llm/llm-deepseek-account/tests/provider.spec.ts index d47617c834..ac9ab397f4 100644 --- a/packages/llm/llm-deepseek-account/tests/provider.spec.ts +++ b/packages/llm/llm-deepseek-account/tests/provider.spec.ts @@ -215,7 +215,7 @@ it('publishes the account credential for its consumers, asking the account for e await ctx.plugin(LlmRuntime) ctx.provide('deepseekAccount', accountStub({ token: (url) => { asked.push(url); return token } })) await ctx.plugin(Account, { baseURL: 'https://account.deepseek.test/anthropic' }) - const credential = ctx.llm.routeCredential('deepseek-account') + const credential = ctx.llm.providerCredential('deepseek-account') expect(credential).toMatchObject({ kind: 'account', baseURL: 'https://account.deepseek.test/anthropic' }) expect(credential).not.toHaveProperty('reference') const endpoint = 'https://account.deepseek.test/v1/tools/search' @@ -225,7 +225,7 @@ it('publishes the account credential for its consumers, asking the account for e await expect(credential!.configured(endpoint)).resolves.toBe(false) await expect(credential!.resolve(endpoint)).resolves.toBeUndefined() expect(asked).toEqual([endpoint, endpoint, endpoint, endpoint]) - expect(ctx.llm.routeCredential('deepseek-official')).toBeUndefined() + expect(ctx.llm.providerCredential('deepseek-official')).toBeUndefined() }) it('publishes a credential nobody holds without the account service', async () => { @@ -233,7 +233,7 @@ it('publishes a credential nobody holds without the account service', async () = contexts.push(ctx) await ctx.plugin(LlmRuntime) await ctx.plugin(Account, { baseURL: 'https://account.deepseek.test/anthropic' }) - const credential = ctx.llm.routeCredential('deepseek-account')! + const credential = ctx.llm.providerCredential('deepseek-account')! await expect(credential.configured('https://account.deepseek.test/v1/tools/search')).resolves.toBe(false) await expect(credential.resolve('https://account.deepseek.test/v1/tools/search')).resolves.toBeUndefined() }) diff --git a/packages/llm/llm-deepseek-api-key/README.i18n.yaml b/packages/llm/llm-deepseek-api-key/README.i18n.yaml index b88b876c62..6b0f0744ae 100644 --- a/packages/llm/llm-deepseek-api-key/README.i18n.yaml +++ b/packages/llm/llm-deepseek-api-key/README.i18n.yaml @@ -9,8 +9,8 @@ en: b6871195e386cc64 zh: 742b05a3ca80883c /deepseek-ai-dsh-llm-deepseek-api-key/summary: - en: 735e39ebfef73dcb - zh: 42036db3ae53de0f + en: 25f6f430c8ce1a6b + zh: b221bef9390771e7 /deepseek-ai-dsh-llm-deepseek-api-key/table-of-contents: en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 diff --git a/packages/llm/llm-deepseek-api-key/README.md b/packages/llm/llm-deepseek-api-key/README.md index a4cb98c257..c0010921d9 100644 --- a/packages/llm/llm-deepseek-api-key/README.md +++ b/packages/llm/llm-deepseek-api-key/README.md @@ -11,7 +11,7 @@ English | [中文](README.zh.md) Register authentication, model discovery, and the official model listing for `deepseek-official`. This plugin shares the [Messages transport](../llm-deepseek/README.md) and owns credential resolution, catalog availability, and model admission. -Authentication resolution returns the validated API key in `x-api-key` for Messages, Files, and listing requests, and publishes the same key through `ctx.llm.routeCredential('deepseek-official')` with the route's base URL and `apiKeyEnv` reference, so the DeepSeek web providers send it as a bearer token to the same deployment. The published credential releases the key only for destinations under the origin of that base URL. +Authentication resolution returns the validated API key in `x-api-key` for Messages, Files, and listing requests, and publishes the same key through `ctx.llm.providerCredential('deepseek-official')` with the route's base URL and `apiKeyEnv` reference, so the DeepSeek web providers send it as a bearer token to the same deployment. The published credential releases the key only for destinations under the origin of that base URL. ## Table of Contents diff --git a/packages/llm/llm-deepseek-api-key/README.zh.md b/packages/llm/llm-deepseek-api-key/README.zh.md index f47bbed9cc..59b5229f04 100644 --- a/packages/llm/llm-deepseek-api-key/README.zh.md +++ b/packages/llm/llm-deepseek-api-key/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" 为 `deepseek-official` 注册鉴权、模型发现和官方模型列表。通过 [llm-deepseek](../llm-deepseek/README.zh.md) 共用 Messages 请求实现;本包拥有凭据解析、目录可用性判断和模型准入。 -鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages、Files 和列表请求使用,并通过 `ctx.llm.routeCredential('deepseek-official')` 连同路由的基础地址和 `apiKeyEnv` 引用发布同一密钥,使 DeepSeek Web 提供方以 Bearer 令牌把它发往同一部署。发布的凭据只对该基础地址所在 origin 下的目的地释放密钥。 +鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages、Files 和列表请求使用,并通过 `ctx.llm.providerCredential('deepseek-official')` 连同路由的基础地址和 `apiKeyEnv` 引用发布同一密钥,使 DeepSeek Web 提供方以 Bearer 令牌把它发往同一部署。发布的凭据只对该基础地址所在 origin 下的目的地释放密钥。 ## 目录 diff --git a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts index 976ce160ae..5f1cb8035f 100644 --- a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts +++ b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts @@ -78,7 +78,7 @@ it('publishes the route API key for its consumers from the credential planes it try { await ctx.plugin(LlmRuntime) await ctx.plugin(ApiKey, { baseURL: 'https://route.deepseek.test/anthropic' }) - const credential = ctx.llm.routeCredential('deepseek-official') + const credential = ctx.llm.providerCredential('deepseek-official') expect(credential).toMatchObject({ kind: 'api-key', baseURL: 'https://route.deepseek.test/anthropic', reference: 'DEEPSEEK_API_KEY' }) const endpoint = 'https://route.deepseek.test/v1/tools/search' await expect(credential!.configured(endpoint)).resolves.toBe(true) @@ -109,7 +109,7 @@ it.each([ ctx.provide('credentials', { resolve, describe } as never) await ctx.plugin(LlmRuntime) await ctx.plugin(ApiKey, { baseURL: 'https://route.deepseek.test/anthropic' }) - const credential = ctx.llm.routeCredential('deepseek-official') + const credential = ctx.llm.providerCredential('deepseek-official') await expect(credential!.configured(endpoint)).resolves.toBe(false) await expect(credential!.resolve(endpoint)).resolves.toBeUndefined() expect(resolve).not.toHaveBeenCalled() diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index cee7e7d9b6..c929a5cfcc 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -27,8 +27,8 @@ en: 2a634ead5b47fe97 zh: 46f199ee79a8c5dc /deepseek-ai-dsh-llm-deepseek/use-this-package/account-credentials: - en: bcb58fd33f59dbf2 - zh: ff512a17c15aeadf + en: 22d74c69c0aa9234 + zh: d70eaf90c93a76d1 /deepseek-ai-dsh-llm-deepseek/use-this-package/streaming-with-thinking-and-images: en: f20f2cfbb38e4ba9 zh: c527b91c8b747886 diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 7f6cc3edb6..96223b73bc 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -94,7 +94,7 @@ Messages sends text, thinking, tool calls, and tool results as content blocks, r Messages and Files requests send account tokens as `x-dsh-auth-token` without a Bearer prefix; API keys use `x-api-key`. Neither credential mode follows redirects. The account route owns HTTP 401 classification and the account service the credential invalidation; the transport passes failures to the credential's callback. -Provider plugins own credentials through three adapter hooks. `resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: the headers the Messages, Files, and listing requests send, the bare value, an optional failure callback, and an optional `revoked` signal, or `undefined` when none is configured. The signal ends the model request and its file operations when the credential's owner withdraws it, and the failure callback names that end. `missingCredential(connection, provider)` names the failure of a request without one; the default is `MISSING_CREDENTIAL`. `credential` publishes the route's credential kind, optional reference, and presence check through `ctx.llm.routeCredential(provider)` together with the route's base URL, so web providers call the same deployment with the same credential without reading provider configuration. The plugins read API keys through the [credential reference helpers](../../credentials/credentials/README.md) of `dsh-credentials` and account credentials through the [account service](../../account/deepseek-account/README.md); this transport reads neither. +Provider plugins own credentials through three adapter hooks. `resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: the headers the Messages, Files, and listing requests send, the bare value, an optional failure callback, and an optional `revoked` signal, or `undefined` when none is configured. The signal ends the model request and its file operations when the credential's owner withdraws it, and the failure callback names that end. `missingCredential(connection, provider)` names the failure of a request without one; the default is `MISSING_CREDENTIAL`. `credential` publishes the route's credential kind, optional reference, and presence check through `ctx.llm.providerCredential(provider)` together with the route's base URL, so web providers call the same deployment with the same credential without reading provider configuration. The plugins read API keys through the [credential reference helpers](../../credentials/credentials/README.md) of `dsh-credentials` and account credentials through the [account service](../../account/deepseek-account/README.md); this transport reads neither. ### Streaming with thinking and images diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index 22e8c4dfec..84772f3fcd 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -94,7 +94,7 @@ Messages 以内容块发送文本、思考、工具调用和工具结果,以 ` Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 Bearer 前缀;API Key 使用 `x-api-key`。两种凭据模式均拒绝重定向。账号路由负责 HTTP 401 分类,账号服务负责凭据失效处理;传输层将错误交给凭据的回调。 -提供方插件通过三个适配器钩子拥有凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、裸凭据值、可选的失败回调以及可选的 `revoked` 信号;未配置时返回 `undefined`。凭据的所有者撤回凭据时,该信号结束模型请求及其文件操作,失败回调为这次结束命名。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。`credential` 通过 `ctx.llm.routeCredential(provider)` 发布路由的凭据种类、可选引用和存在性检查,并附带路由的基础地址,使 Web 提供方无需读取提供方配置即可用同一凭据调用同一部署。插件通过 `dsh-credentials` 的[凭据引用函数](../../credentials/credentials/README.zh.md)读取 API Key,通过[账号服务](../../account/deepseek-account/README.zh.md)读取账号凭据;本传输层两者都不读取。 +提供方插件通过三个适配器钩子拥有凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、裸凭据值、可选的失败回调以及可选的 `revoked` 信号;未配置时返回 `undefined`。凭据的所有者撤回凭据时,该信号结束模型请求及其文件操作,失败回调为这次结束命名。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。`credential` 通过 `ctx.llm.providerCredential(provider)` 发布路由的凭据种类、可选引用和存在性检查,并附带路由的基础地址,使 Web 提供方无需读取提供方配置即可用同一凭据调用同一部署。插件通过 `dsh-credentials` 的[凭据引用函数](../../credentials/credentials/README.zh.md)读取 API Key,通过[账号服务](../../account/deepseek-account/README.zh.md)读取账号凭据;本传输层两者都不读取。 ### 带 thinking 与图片的流式调用 diff --git a/packages/llm/llm-deepseek/src/adapter.ts b/packages/llm/llm-deepseek/src/adapter.ts index 9bb7f1424c..5f625e687d 100644 --- a/packages/llm/llm-deepseek/src/adapter.ts +++ b/packages/llm/llm-deepseek/src/adapter.ts @@ -1,7 +1,7 @@ /** Direct Messages transport with one cancellable lifecycle per model request. */ import { attributionHeaders, LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm' -import type { GenerateOptions, ImageAttachmentAccessResolver, PreparedAdapterCall, RouteCredential, StreamChunk } from '@deepseek-ai/dsh-llm' +import type { GenerateOptions, ImageAttachmentAccessResolver, PreparedAdapterCall, ProviderCredential, StreamChunk } from '@deepseek-ai/dsh-llm' import type { DeepSeekLlmApiExtensionRequest, DeepSeekLlmApiJson } from '@deepseek-ai/dsh-deepseek-llm-api-extensions' import { idleWatchdog, timeoutOf } from '@deepseek-ai/dsh-timeout' import { modelInfo } from './model-info.ts' @@ -47,7 +47,7 @@ export class DeepSeekAdapter extends LlmAdapt if (entry === undefined) throw new LlmError(`DeepSeek model "${model}" has no declared image projection`, 'UNKNOWN_MODEL') return resolveRequestImageTarget(entry, image) } - override routeCredential(_provider: string): RouteCredential | undefined { + override providerCredential(_provider: string): ProviderCredential | undefined { const publication = this.dependencies.credential if (publication === undefined) return undefined // One configuration generation serves the whole published object, as it does one model request. diff --git a/packages/llm/llm-deepseek/src/index.ts b/packages/llm/llm-deepseek/src/index.ts index 0474969f60..8bd83450b4 100644 --- a/packages/llm/llm-deepseek/src/index.ts +++ b/packages/llm/llm-deepseek/src/index.ts @@ -15,7 +15,7 @@ export { DEFAULT_STREAM_IDLE_TIMEOUT_MS, } from './defaults.ts' export { DeepSeekAdapter } from './adapter.ts' -export type { DeepSeekRequestAuth, DeepSeekAdapterOptions, DeepSeekCatalogModel, DeepSeekConnectionOptions, DeepSeekRouteCredentialOptions } from './types.ts' +export type { DeepSeekRequestAuth, DeepSeekAdapterOptions, DeepSeekCatalogModel, DeepSeekConnectionOptions, DeepSeekProviderCredentialOptions } from './types.ts' export { DEFAULT_LOW_DETAIL_IMAGE_PIXEL_BUDGET, DEFAULT_MAX_IMAGES_PER_REQUEST, diff --git a/packages/llm/llm-deepseek/src/types.ts b/packages/llm/llm-deepseek/src/types.ts index 7b37ff1616..0e483b92a4 100644 --- a/packages/llm/llm-deepseek/src/types.ts +++ b/packages/llm/llm-deepseek/src/types.ts @@ -1,6 +1,6 @@ /** Model catalog and request-local dependencies for DeepSeek Messages. */ import type { - ImageAttachmentAccess, LlmCredentialKind, LlmError, LlmModelInfo, ModelModality, ResolvedRetryPolicy, RouteCredentialGrant, + ImageAttachmentAccess, LlmCredentialKind, LlmError, LlmModelInfo, ModelModality, ProviderCredentialGrant, ResolvedRetryPolicy, SystemPromptUpdate, ToolUpdate, } from '@deepseek-ai/dsh-llm' import type { AttachmentStore, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' @@ -90,7 +90,7 @@ export interface DeepSeekConnectionOptions { * classification bound to that credential. The grant's `revoked` signal ends * the request and its file operations as the caller's cancellation does. */ -export interface DeepSeekRequestAuth extends RouteCredentialGrant { +export interface DeepSeekRequestAuth extends ProviderCredentialGrant { /** * Classify a failure using the captured credential; callback failure preserves the original error. The end a * withdrawn credential causes arrives here too, for the provider plugin to name. @@ -99,11 +99,11 @@ export interface DeepSeekRequestAuth extends RouteCredentialGrant { } /** - * What `routeCredential()` publishes about the route's credential beside the + * What `providerCredential()` publishes about the route's credential beside the * request-path hooks, so consumers outside the model request path share the * route's credential without reading its configuration. */ -export interface DeepSeekRouteCredentialOptions { +export interface DeepSeekProviderCredentialOptions { /** Kind of credential the route sends. */ kind: LlmCredentialKind /** Credential reference the route resolves, named by diagnostics; omission publishes none. */ @@ -138,7 +138,7 @@ export interface DeepSeekAdapterOptions Promise /** @@ -147,10 +147,10 @@ export interface DeepSeekAdapterOptions LlmError /** - * Publish the route's credential through `routeCredential()`, whose `resolve` forwards the headers, value, + * Publish the route's credential through `providerCredential()`, whose `resolve` forwards the headers, value, * rejection, and withdrawal signal of {@link resolveAuth} without its failure classification; omission publishes none. */ - credential?: DeepSeekRouteCredentialOptions + credential?: DeepSeekProviderCredentialOptions /** Resolve the harness-home anonymous id shared with telemetry and feedback. */ resolveUserId: () => AnonymousUserId /** Resolve the current durable attachment service; absence rejects image input. */ diff --git a/packages/llm/llm-deepseek/tests/route-credential.spec.ts b/packages/llm/llm-deepseek/tests/route-credential.spec.ts index 3314455d4e..9c74f6ef14 100644 --- a/packages/llm/llm-deepseek/tests/route-credential.spec.ts +++ b/packages/llm/llm-deepseek/tests/route-credential.spec.ts @@ -48,7 +48,7 @@ function adapterWithout(missingCredential?: DeepSeekAdapterOptions['missingCrede it('publishes no credential for a provider that declares none', async () => { const ctx = await route({}) - expect(ctx.llm.routeCredential('fixture-route')).toBeUndefined() + expect(ctx.llm.providerCredential('fixture-route')).toBeUndefined() }) it('publishes the declared credential from one configuration generation and resolves it per endpoint', async () => { @@ -58,7 +58,7 @@ it('publishes the declared credential from one configuration generation and reso endpoint === ALLOWED ? { headers: { 'x-fixture': 'k' }, value: 'k', reject, revoked, onRequestError: error => Promise.resolve(error) } : undefined) const configured = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string) => endpoint === ALLOWED) const ctx = await route({ resolveAuth, credential: { kind: 'api-key', reference: () => 'FIXTURE_KEY', configured } }) - const credential = ctx.llm.routeCredential('fixture-route') + const credential = ctx.llm.providerCredential('fixture-route') expect(credential).toMatchObject({ kind: 'api-key', baseURL: BASE_URL, reference: 'FIXTURE_KEY' }) await expect(credential!.configured(ALLOWED)).resolves.toBe(true) await expect(credential!.configured(OTHER)).resolves.toBe(false) @@ -80,7 +80,7 @@ it('omits the reference of a credential kind without one and the rejection and w resolveAuth: () => Promise.resolve({ headers: { 'x-fixture': 'k' }, value: 'k' }), credential: { kind: 'account', configured: () => Promise.resolve(false) }, }) - const credential = ctx.llm.routeCredential('fixture-route') + const credential = ctx.llm.providerCredential('fixture-route') expect(credential).toMatchObject({ kind: 'account', baseURL: BASE_URL }) expect(credential).not.toHaveProperty('reference') await expect(credential!.resolve(ALLOWED)).resolves.toEqual({ headers: { 'x-fixture': 'k' }, value: 'k' }) diff --git a/packages/llm/llm/src/index.ts b/packages/llm/llm/src/index.ts index 1affba4950..bcc94686db 100644 --- a/packages/llm/llm/src/index.ts +++ b/packages/llm/llm/src/index.ts @@ -22,7 +22,7 @@ import type { LlmResolvedModelInfo, LlmProviderInfo, ModelModality, - RouteCredential, + ProviderCredential, StreamChunk, SystemPromptUpdate, ToolSchema, @@ -274,7 +274,7 @@ export abstract class LlmAdapter { * @param _provider - a route passed to `registerAdapter()` for this instance. * @returns the route's current credential, or `undefined` when the route publishes none. */ - routeCredential(_provider: string): RouteCredential | undefined { + providerCredential(_provider: string): ProviderCredential | undefined { return undefined } @@ -729,10 +729,10 @@ export class LlmRuntime extends TypertRemoteService { * which may no longer be mounted; a registered route whose configuration * does not resolve propagates the adapter's failure. * @param provider - provider route whose credential is wanted. - * @returns the route credential, or `undefined` when the route is unregistered or publishes none. + * @returns the route's credential, or `undefined` when the route is unregistered or publishes none. */ - routeCredential(provider: string): RouteCredential | undefined { - return this.adapters.get(provider)?.adapter.routeCredential(provider) + providerCredential(provider: string): ProviderCredential | undefined { + return this.adapters.get(provider)?.adapter.providerCredential(provider) } /** diff --git a/packages/llm/llm/src/types.ts b/packages/llm/llm/src/types.ts index 60b576c1aa..fdc7320c40 100644 --- a/packages/llm/llm/src/types.ts +++ b/packages/llm/llm/src/types.ts @@ -310,7 +310,7 @@ export type LlmCredentialKind = LlmCredentialKindMap[keyof LlmCredentialKindMap] * One credential released for one destination. Host-only: it carries the * secret, so it never crosses a Remote boundary and never enters a log. */ -export interface RouteCredentialGrant { +export interface ProviderCredentialGrant { /** * Request headers carrying the credential as the route's own protocol * expects it, such as `x-api-key` for an API key. Consumers speaking that @@ -342,11 +342,11 @@ export interface RouteCredentialGrant { /** * The credential one registered provider route currently sends, answered by * the route's owning adapter so that consumers read no provider configuration - * and choose no header names. `ctx.llm.routeCredential()` resolves a new value + * and choose no header names. `ctx.llm.providerCredential()` resolves a new value * per call from one configuration generation; a caller keeps it for one * operation only. */ -export interface RouteCredential { +export interface ProviderCredential { /** Kind of credential the route sends. */ readonly kind: LlmCredentialKind /** @@ -377,7 +377,7 @@ export interface RouteCredential { * @param signal - cancellation for the lookup. * @returns the released credential, or `undefined`. */ - resolve(endpoint: string, signal?: AbortSignal): Promise + resolve(endpoint: string, signal?: AbortSignal): Promise } /** diff --git a/packages/llm/llm/tests/topology.spec.ts b/packages/llm/llm/tests/topology.spec.ts index 7eddb69b35..3a9735fbef 100644 --- a/packages/llm/llm/tests/topology.spec.ts +++ b/packages/llm/llm/tests/topology.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import LlmRuntime, { LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm' -import type { GenerateOptions, LlmConfigurableProvider, RouteCredential, StreamChunk } from '@deepseek-ai/dsh-llm' +import type { GenerateOptions, LlmConfigurableProvider, ProviderCredential, StreamChunk } from '@deepseek-ai/dsh-llm' class NoopAdapter extends LlmAdapter { @@ -340,24 +340,24 @@ describe('imageRequestPricing resolution', () => { }) }) -describe('routeCredential resolution', () => { +describe('providerCredential resolution', () => { it('forwards to the owning adapter and answers undefined everywhere else', async () => { const ctx = await setup() - const credential: RouteCredential = { + const credential: ProviderCredential = { kind: 'api-key', baseURL: 'https://a.example/v1', configured: () => Promise.resolve(true), resolve: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }), } class CredentialAdapter extends NoopAdapter { - override routeCredential(provider: string) { return provider === 'a' ? credential : undefined } + override providerCredential(provider: string) { return provider === 'a' ? credential : undefined } } const dispose = ctx.llm.registerAdapter(['a', 'b'], new CredentialAdapter()) ctx.llm.registerAdapter(['plain'], new NoopAdapter()) - expect(ctx.llm.routeCredential('a')).toBe(credential) - expect(ctx.llm.routeCredential('b')).toBeUndefined() - expect(ctx.llm.routeCredential('plain')).toBeUndefined() - expect(ctx.llm.routeCredential('missing')).toBeUndefined() + expect(ctx.llm.providerCredential('a')).toBe(credential) + expect(ctx.llm.providerCredential('b')).toBeUndefined() + expect(ctx.llm.providerCredential('plain')).toBeUndefined() + expect(ctx.llm.providerCredential('missing')).toBeUndefined() dispose() - expect(ctx.llm.routeCredential('a')).toBeUndefined() + expect(ctx.llm.providerCredential('a')).toBeUndefined() }) }) diff --git a/packages/web/web-deepseek-api/README.i18n.yaml b/packages/web/web-deepseek-api/README.i18n.yaml index 6d2f73adfb..d2e5ca1950 100644 --- a/packages/web/web-deepseek-api/README.i18n.yaml +++ b/packages/web/web-deepseek-api/README.i18n.yaml @@ -18,14 +18,14 @@ en: 673ba23a4e608cf2 zh: 042afa607aaf4335 /deepseek-ai-dsh-web-deepseek-api/use-this-package/authentication: - en: 8923728d77eb1256 - zh: 85d1b8408cf1f325 + en: ba52a11cc1840ca6 + zh: d8f238abb1b309c8 /deepseek-ai-dsh-web-deepseek-api/use-this-package/results-and-failures: en: e7a5d332ebababe7 zh: 6ea098d53d4e9616 /deepseek-ai-dsh-web-deepseek-api/understand-the-implementation: - en: 597dab3fe52fa59d - zh: 4370d01d5a58f2f9 + en: ab3a0eaeee8747cf + zh: 449aeb4bce7d7707 /deepseek-ai-dsh-web-deepseek-api/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 @@ -54,8 +54,8 @@ en: 14f9af39f3be4fac zh: 3c7139fba0f17862 /deepseek-ai-dsh-web-deepseek-api/known-limitations-and-deferred-work: - en: c71abd58d3afbcfe - zh: d463321359b84e94 + en: c52fd4fda604976e + zh: 5cc3fad3d756362a /deepseek-ai-dsh-web-deepseek-api/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 zh: 9f56528562c7c914 diff --git a/packages/web/web-deepseek-api/README.md b/packages/web/web-deepseek-api/README.md index 80b0b68b57..bb141166c7 100644 --- a/packages/web/web-deepseek-api/README.md +++ b/packages/web/web-deepseek-api/README.md @@ -59,8 +59,8 @@ Run the real API tests with `DEEPSEEK_API_KEY` and `DEEPSEEK_SEARCH_API_TEST_BAS Search and Fetch each resolve their endpoint and credential from one settings snapshot per operation, so a saved setting, a model-provider change, a sign-in, or a stored key applies to the next operation. The conversation's route is the `provider` of the initiating Session's latest request context; `ready()` uses the route of the model request being prepared. - **Own settings.** A capability with a non-empty `*BaseURL` or `*ApiKeyEnv` sends only the key under its `*ApiKeyEnv` (`DEEPSEEK_API_KEY` when unset) as `Authorization: Bearer` to its `*BaseURL` (`https://api.deepseek.com/v1/tools` when unset) on every route, and never the account token. Without the key, the operation fails with a diagnostic that names the reference and the `*ApiKeyEnv` field. -- **Account credential.** The operation sends the credential `ctx.deepseekAccount` releases for the dispatch endpoint as `x-dsh-auth-token`; the public Search and Fetch routes accepted it on 2026-10-16. With the `deepseek-account` model route mounted, the endpoint is under the origin of the base URL that route publishes through `ctx.llm.routeCredential`; without that route, it is under the origin `DEEPSEEK_BASE_URL` names, `https://api.deepseek.com` by default. No sign-in or no account service means no credential. A failed credential read fails the operation without trying another credential. A mounted route whose settings do not resolve, or a `DEEPSEEK_BASE_URL` that is not an HTTP(S) URL without credentials, fails the operation before the credential is read when the operation reaches this source. -- **API key.** With the `deepseek-official` model route mounted, the operation sends the key that route publishes through `ctx.llm.routeCredential`, read under the route's `apiKeyEnv` (`DEEPSEEK_API_KEY` by default), as `Authorization: Bearer` to the origin of the route's base URL. Without that route, it sends `DEEPSEEK_API_KEY` to `https://api.deepseek.com/v1/tools`. A mounted route whose settings do not resolve fails each operation that needs the key, before the key is read; the operation never substitutes the official endpoint or `DEEPSEEK_API_KEY`. +- **Account credential.** The operation sends the credential `ctx.deepseekAccount` releases for the dispatch endpoint as `x-dsh-auth-token`; the public Search and Fetch routes accepted it on 2026-10-16. With the `deepseek-account` model route mounted, the endpoint is under the origin of the base URL that route publishes through `ctx.llm.providerCredential`; without that route, it is under the origin `DEEPSEEK_BASE_URL` names, `https://api.deepseek.com` by default. No sign-in or no account service means no credential. A failed credential read fails the operation without trying another credential. A mounted route whose settings do not resolve, or a `DEEPSEEK_BASE_URL` that is not an HTTP(S) URL without credentials, fails the operation before the credential is read when the operation reaches this source. +- **API key.** With the `deepseek-official` model route mounted, the operation sends the key that route publishes through `ctx.llm.providerCredential`, read under the route's `apiKeyEnv` (`DEEPSEEK_API_KEY` by default), as `Authorization: Bearer` to the origin of the route's base URL. Without that route, it sends `DEEPSEEK_API_KEY` to `https://api.deepseek.com/v1/tools`. A mounted route whose settings do not resolve fails each operation that needs the key, before the key is read; the operation never substitutes the official endpoint or `DEEPSEEK_API_KEY`. - **`auto` billing** follows the conversation. On the `deepseek-account` route it sends the account credential, and without one the API key; without the account route, only the API key. On the `deepseek-official` route it sends only the API key. On any other route or outside a Session it sends the API key, and without a key the account credential; without a key, a mounted account route whose settings do not resolve fails the operation. - **`account` billing** sends only the account credential on every route, and **`api-key` billing** only the API key; neither falls back to the other credential. @@ -84,7 +84,7 @@ An unparseable own base URL makes that capability's provider unavailable; and a
Implementation internals — click to expand -The [plugin](src/index.ts) reads its settings once per operation, registers both providers, and turns one capability's settings snapshot, the conversation's route, and the credentials the mounted DeepSeek model routes publish through `ctx.llm.routeCredential` into the operation's ordered credentials, each bound to the API base it is sent to. The [Search provider](src/search.ts) validates response JSON before returning service results; the [Fetch provider](src/fetch.ts) validates the Markdown body. The [transport](src/transport.ts) reads those credentials in order, sends one request with the first present one, and owns cancellation, redirect rejection, and failure guidance; a recording hook runs before dispatch and prevents it by throwing. Search and Fetch API calls emit no auxiliary request event. The [Messages search provider](../web-search-deepseek/README.md) owns its `web/deepseek-search-llm-request` Session event declaration and recording. Tool calls and results retain their normal Session logging. +The [plugin](src/index.ts) reads its settings once per operation, registers both providers, and turns one capability's settings snapshot, the conversation's route, and the credentials the mounted DeepSeek model routes publish through `ctx.llm.providerCredential` into the operation's ordered credentials, each bound to the API base it is sent to. The [Search provider](src/search.ts) validates response JSON before returning service results; the [Fetch provider](src/fetch.ts) validates the Markdown body. The [transport](src/transport.ts) reads those credentials in order, sends one request with the first present one, and owns cancellation, redirect rejection, and failure guidance; a recording hook runs before dispatch and prevents it by throwing. Search and Fetch API calls emit no auxiliary request event. The [Messages search provider](../web-search-deepseek/README.md) owns its `web/deepseek-search-llm-request` Session event declaration and recording. Tool calls and results retain their normal Session logging. See the [web subsystem](../../../docs/subsystems/web.md) for service types and [tool-web](../tool-web/README.md) for bounded model output. @@ -132,7 +132,7 @@ A returning or removed web tool changes the declared tools as [`dsh-tool-web`](. - API query and URL constraints are enforced by the remote service. An unresolvable Fetch target returned HTTP 500 rather than the documented 404 on 2026-10-16, and its failure carries the same endpoint guidance as an endpoint failure. Fetch exposes neither the target status nor the final redirect URL, so results report HTTP 200 and the requested URL; the provider discards the API's page title. - `available()` cannot query asynchronous credential stores; `ready()` does, so model steps withhold the tools when the store lacks the key. A direct `ctx.web.search()` or `ctx.web.fetch()` call can still fail with a missing-credential error. - Search pacing limits send times within one plugin instance. Other processes and clients on the same account share the account-wide 5 QPS limit without coordination, and network jitter can still bunch arrivals; an HTTP 429 fails that search, and `dsh-tool-web` then fails the whole multi-query call. Fetch is not paced, so parallel `web_fetch` calls can exceed the Fetch limit. -- Route endpoints and credentials follow what the adapter registered as `deepseek-official` or `deepseek-account` publishes through `ctx.llm.routeCredential`. An adapter that publishes no credential, such as a test replay adapter, or a credential of the other kind (an account credential as `deepseek-official`, an API key as `deepseek-account`) counts as no route: its conversations use `DEEPSEEK_API_KEY` and the official base, and `account` billing asks the account service as it does without the account route. +- Route endpoints and credentials follow what the adapter registered as `deepseek-official` or `deepseek-account` publishes through `ctx.llm.providerCredential`. An adapter that publishes no credential, such as a test replay adapter, or a credential of the other kind (an account credential as `deepseek-official`, an API key as `deepseek-account`) counts as no route: its conversations use `DEEPSEEK_API_KEY` and the official base, and `account` billing asks the account service as it does without the account route. ### Dev Note diff --git a/packages/web/web-deepseek-api/README.zh.md b/packages/web/web-deepseek-api/README.zh.md index 3dbe337001..bcc91f5444 100644 --- a/packages/web/web-deepseek-api/README.zh.md +++ b/packages/web/web-deepseek-api/README.zh.md @@ -59,8 +59,8 @@ kind: "package-reference" Search 与 Fetch 每次操作各自从同一份设置快照解析端点和凭据,因此保存的设置、模型提供方变更、登录或存入的密钥从下一次操作开始生效。会话的路由是发起会话最近一次请求上下文的 `provider`;`ready()` 使用正在准备的模型请求的路由。 - **单独配置。** 设置了非空 `*BaseURL` 或 `*ApiKeyEnv` 的能力在任何路由上都只以 `Authorization: Bearer` 把其 `*ApiKeyEnv`(未设置时为 `DEEPSEEK_API_KEY`)下的密钥发往其 `*BaseURL`(未设置时为 `https://api.deepseek.com/v1/tools`),从不发送账号令牌。没有该密钥时,操作失败,诊断信息点名该引用和 `*ApiKeyEnv` 字段。 -- **账号凭据。** 操作通过 `x-dsh-auth-token` 发送 `ctx.deepseekAccount` 为请求端点释放的凭据;2026-10-16 公网 Search 与 Fetch 路由已接受该凭据。挂载了 `deepseek-account` 模型路由时,端点位于该路由通过 `ctx.llm.routeCredential` 发布的基础地址的 origin 下;没有该路由时,位于 `DEEPSEEK_BASE_URL` 所指 origin 下,默认 `https://api.deepseek.com`。没有登录或没有账号服务都算没有凭据。凭据读取失败时操作失败,不再尝试其他凭据。已挂载路由的设置无法解析,或 `DEEPSEEK_BASE_URL` 不是不含凭据的 HTTP(S) URL 时,操作在轮到该来源时于读取凭据前失败。 -- **API 密钥。** 挂载了 `deepseek-official` 模型路由时,操作以 `Authorization: Bearer` 把该路由通过 `ctx.llm.routeCredential` 发布的密钥(按路由的 `apiKeyEnv` 读取,默认 `DEEPSEEK_API_KEY`)发往该路由基础地址的 origin。没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。已挂载路由的设置无法解析时,每个需要该密钥的操作都在读取密钥前失败,绝不改用官方端点或 `DEEPSEEK_API_KEY`。 +- **账号凭据。** 操作通过 `x-dsh-auth-token` 发送 `ctx.deepseekAccount` 为请求端点释放的凭据;2026-10-16 公网 Search 与 Fetch 路由已接受该凭据。挂载了 `deepseek-account` 模型路由时,端点位于该路由通过 `ctx.llm.providerCredential` 发布的基础地址的 origin 下;没有该路由时,位于 `DEEPSEEK_BASE_URL` 所指 origin 下,默认 `https://api.deepseek.com`。没有登录或没有账号服务都算没有凭据。凭据读取失败时操作失败,不再尝试其他凭据。已挂载路由的设置无法解析,或 `DEEPSEEK_BASE_URL` 不是不含凭据的 HTTP(S) URL 时,操作在轮到该来源时于读取凭据前失败。 +- **API 密钥。** 挂载了 `deepseek-official` 模型路由时,操作以 `Authorization: Bearer` 把该路由通过 `ctx.llm.providerCredential` 发布的密钥(按路由的 `apiKeyEnv` 读取,默认 `DEEPSEEK_API_KEY`)发往该路由基础地址的 origin。没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。已挂载路由的设置无法解析时,每个需要该密钥的操作都在读取密钥前失败,绝不改用官方端点或 `DEEPSEEK_API_KEY`。 - **`auto` 计费**跟随会话。在 `deepseek-account` 路由上先发送账号凭据,没有凭据时发送 API 密钥;没有账号路由时只发送 API 密钥。在 `deepseek-official` 路由上只发送 API 密钥。在其他路由上或会话之外先发送 API 密钥,没有密钥时发送账号凭据;没有密钥且已挂载的账号路由设置无法解析时,操作失败。 - **`account` 计费**在任何路由上只发送账号凭据,**`api-key` 计费**只发送 API 密钥;两者都不回退到另一种凭据。 @@ -84,7 +84,7 @@ Search API 接收 `query`、`count`(配置的结果数,或请求中更小的
实现细节 — 点击展开 -[插件](src/index.ts)在每次操作时读取一次设置,注册两个提供者,并把一个能力的设置快照、会话的路由,以及已挂载的 DeepSeek 模型路由通过 `ctx.llm.routeCredential` 发布的凭据转换为该操作的有序凭据,每个凭据都绑定其发往的 API 基础地址。[Search 提供者](src/search.ts)在返回服务结果前校验响应 JSON;[Fetch 提供者](src/fetch.ts)校验 Markdown 正文。[传输层](src/transport.ts)按顺序读取这些凭据,用第一个存在的凭据发送一次请求,并负责取消、重定向拒绝和失败指引;记录钩子在发送前运行,抛出异常即阻止发送。Search 与 Fetch API 调用不产生辅助请求事件。[Messages 搜索提供方](../web-search-deepseek/README.zh.md)负责声明和记录自身的 `web/deepseek-search-llm-request` 会话事件。工具调用和结果仍按常规记录到会话。 +[插件](src/index.ts)在每次操作时读取一次设置,注册两个提供者,并把一个能力的设置快照、会话的路由,以及已挂载的 DeepSeek 模型路由通过 `ctx.llm.providerCredential` 发布的凭据转换为该操作的有序凭据,每个凭据都绑定其发往的 API 基础地址。[Search 提供者](src/search.ts)在返回服务结果前校验响应 JSON;[Fetch 提供者](src/fetch.ts)校验 Markdown 正文。[传输层](src/transport.ts)按顺序读取这些凭据,用第一个存在的凭据发送一次请求,并负责取消、重定向拒绝和失败指引;记录钩子在发送前运行,抛出异常即阻止发送。Search 与 Fetch API 调用不产生辅助请求事件。[Messages 搜索提供方](../web-search-deepseek/README.zh.md)负责声明和记录自身的 `web/deepseek-search-llm-request` 会话事件。工具调用和结果仍按常规记录到会话。 服务类型见 [Web 子系统](../../../docs/subsystems/web.zh.md),受限的模型输出见 [tool-web](../tool-web/README.zh.md)。 @@ -132,7 +132,7 @@ Search API 接收 `query`、`count`(配置的结果数,或请求中更小的 - 查询和 URL 约束由远端服务执行。2026-10-16 抓取无法解析的目标域名时返回 HTTP 500,而非文档所述的 404,其失败信息与端点失败附带相同的端点指引。Fetch 既不暴露目标状态,也不暴露最终重定向 URL,因此结果报告 HTTP 200 和请求 URL;提供者丢弃 API 返回的页面标题。 - `available()` 无法查询异步凭据存储;`ready()` 可以,因此凭据存储缺少密钥时,模型步骤会撤下这两个工具。直接调用 `ctx.web.search()` 或 `ctx.web.fetch()` 仍可能因凭据缺失失败。 - Search 限速只约束单个插件实例内的发送时间。同一账号下的其他进程和客户端共享账号级 5 QPS 限制,彼此不协调,网络抖动也可能使请求集中到达;HTTP 429 会使该次搜索失败,随后 `dsh-tool-web` 会使整个多查询调用失败。Fetch 不限速,因此并行的 `web_fetch` 调用可能超过 Fetch 限制。 -- 路由端点与凭据只认以 `deepseek-official` 或 `deepseek-account` 注册的适配器通过 `ctx.llm.routeCredential` 发布的内容。不发布凭据的适配器(例如测试回放适配器),或发布另一种凭据的适配器(以 `deepseek-official` 发布账号凭据,或以 `deepseek-account` 发布 API 密钥),都视为没有路由:其会话使用 `DEEPSEEK_API_KEY` 与官方基础地址,`account` 计费则像没有账号路由时一样询问账号服务。 +- 路由端点与凭据只认以 `deepseek-official` 或 `deepseek-account` 注册的适配器通过 `ctx.llm.providerCredential` 发布的内容。不发布凭据的适配器(例如测试回放适配器),或发布另一种凭据的适配器(以 `deepseek-official` 发布账号凭据,或以 `deepseek-account` 发布 API 密钥),都视为没有路由:其会话使用 `DEEPSEEK_API_KEY` 与官方基础地址,`account` 计费则像没有账号路由时一样询问账号服务。 ### 开发备注 diff --git a/packages/web/web-deepseek-api/src/index.ts b/packages/web/web-deepseek-api/src/index.ts index aeebcdd51f..88f972c641 100644 --- a/packages/web/web-deepseek-api/src/index.ts +++ b/packages/web/web-deepseek-api/src/index.ts @@ -6,7 +6,7 @@ * otherwise the API key; one on the `deepseek-official` route sends the API key; any other operation sends the API key * and, without a key, the signed-in account's credential. `account` sends only the account credential and `api-key` * only the API key. Each mounted DeepSeek model route publishes its credential and base URL through - * `ctx.llm.routeCredential()`: the API key is that of the `deepseek-official` route, sent to its origin, or + * `ctx.llm.providerCredential()`: the API key is that of the `deepseek-official` route, sent to its origin, or * `DEEPSEEK_API_KEY` sent to the official base without that route; the account credential is that of the * `deepseek-account` route, sent to its origin, or outside an account conversation without that route the signed-in * account's credential sent to the origin `DEEPSEEK_BASE_URL` names, by default the official one. An operation that @@ -271,7 +271,7 @@ function ruleSources(ctx: Context, capability: Capability, rule: Rule): DeepSeek */ function routeSource(ctx: Context, capability: Capability, provider: RouteName): DeepSeekWebAuthSource | undefined { try { - const credential = ctx.get('llm')?.routeCredential(provider) + const credential = ctx.get('llm')?.providerCredential(provider) if (credential === undefined || credential.kind !== ROUTE_CREDENTIAL_KIND[provider]) return undefined return { kind: 'route', baseURL: toolsBase(credential.baseURL), credential } } catch (error: unknown) { diff --git a/packages/web/web-deepseek-api/src/transport.ts b/packages/web/web-deepseek-api/src/transport.ts index befc4d4b65..7405c1c0da 100644 --- a/packages/web/web-deepseek-api/src/transport.ts +++ b/packages/web/web-deepseek-api/src/transport.ts @@ -5,7 +5,7 @@ * @module @deepseek-ai/dsh-web-deepseek-api/transport */ import type { CredentialRef } from '@deepseek-ai/dsh-credentials' -import type { LlmCredentialKind, RouteCredential } from '@deepseek-ai/dsh-llm' +import type { LlmCredentialKind, ProviderCredential } from '@deepseek-ai/dsh-llm' import { WebError } from '@deepseek-ai/dsh-web' const USER_AGENT = 'deepseek-harness/0.0.1' @@ -34,7 +34,7 @@ export type DeepSeekWebAuthSource = /** API base the credential is sent to, including its path prefix. */ baseURL: string /** The credential's owner: it answers presence and releases a grant for an endpoint, and read failures reject. */ - credential: Omit + credential: Omit } /** An API key, sent as `Authorization: Bearer`. */ | { diff --git a/packages/web/web-deepseek-api/tests/routes.ts b/packages/web/web-deepseek-api/tests/routes.ts index 98b82fbf65..29f0f426c9 100644 --- a/packages/web/web-deepseek-api/tests/routes.ts +++ b/packages/web/web-deepseek-api/tests/routes.ts @@ -7,7 +7,7 @@ import type { Context } from '@deepseek-ai/cordis' import { credentialRefConfigured, resolveCredentialRef } from '@deepseek-ai/dsh-credentials' import type {} from '@deepseek-ai/dsh-deepseek-account' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' -import type { RouteCredential } from '@deepseek-ai/dsh-llm' +import type { ProviderCredential } from '@deepseek-ai/dsh-llm' import { Config as AccountConfig } from '@deepseek-ai/dsh-llm-deepseek-account' import { plainAccountOptions, resolveAccountOptions } from '@deepseek-ai/dsh-llm-deepseek-account/src/config.ts' import { Config as OfficialConfig } from '@deepseek-ai/dsh-llm-deepseek-api-key' @@ -21,7 +21,7 @@ export interface RouteRow { config?: Record /** Publish no credential, as an adapter another package registers under this id does. Defaults to false. */ withoutCredential?: boolean - /** Value `routeCredential()` throws instead of publishing. */ + /** Value `providerCredential()` throws instead of publishing. */ throws?: unknown /** Base URL published in place of the resolved one, as a route publishing an unparsable base would. */ publishedBaseURL?: string @@ -30,7 +30,7 @@ export interface RouteRow { } /** The credential `route` publishes, resolved from its config as the route plugin resolves it on each call. */ -function credentialOf(ctx: Context, route: RouteRow): RouteCredential { +function credentialOf(ctx: Context, route: RouteRow): ProviderCredential { const environment = launchEnvironmentOf(ctx) if ((route.publishes ?? (route.provider === 'deepseek-official' ? 'api-key' : 'account')) === 'api-key') { const resolved = resolveAdapterOptions(plainOptions(OfficialConfig(route.config ?? {})), environment) @@ -53,13 +53,13 @@ function credentialOf(ctx: Context, route: RouteRow): RouteCredential { } /** - * Provide an `llm` stand-in whose `routeCredential()` answers for `routes`. + * Provide an `llm` stand-in whose `providerCredential()` answers for `routes`. * @param ctx - the root context. * @param routes - route rows, one per provider id. */ export function provideRoutes(ctx: Context, routes: readonly RouteRow[]): void { ctx.provide('llm', { - routeCredential: (provider: string): RouteCredential | undefined => { + providerCredential: (provider: string): ProviderCredential | undefined => { const route = routes.find(row => row.provider === provider) if (route === undefined || route.withoutCredential === true) return undefined if (route.throws !== undefined) throw route.throws diff --git a/packages/web/web-search-deepseek/README.i18n.yaml b/packages/web/web-search-deepseek/README.i18n.yaml index 76e5c0a067..a9907cc6f9 100644 --- a/packages/web/web-search-deepseek/README.i18n.yaml +++ b/packages/web/web-search-deepseek/README.i18n.yaml @@ -24,8 +24,8 @@ en: 3ed88edabdf63c8d zh: c66176c8a7c9a434 /deepseek-ai-dsh-web-search-deepseek/use-this-package/authentication: - en: 5bd18e6e586eb4f0 - zh: 133927c4db79ac71 + en: bea7705262c58779 + zh: a8c166024477b311 /deepseek-ai-dsh-web-search-deepseek/use-this-package/what-a-search-returns: en: e30442c90365357b zh: 9c9e2f1182963a8a @@ -45,8 +45,8 @@ en: 6488e1c85646339f zh: 2b5ca1c6b5939a8c /deepseek-ai-dsh-web-search-deepseek/understand-the-implementation/request-flow: - en: ec407206b9f6371d - zh: a94d1e864102342b + en: f5f0e602ec250162 + zh: 5854cc89c0806644 /deepseek-ai-dsh-web-search-deepseek/further-exploration: en: 3a650478cf33d792 zh: ab4247c4c31f4a90 diff --git a/packages/web/web-search-deepseek/README.md b/packages/web/web-search-deepseek/README.md index 741d92499a..503822edf5 100644 --- a/packages/web/web-search-deepseek/README.md +++ b/packages/web/web-search-deepseek/README.md @@ -58,7 +58,7 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a ### Authentication -A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names a model route that publishes an account credential through `ctx.llm.routeCredential`, the `deepseek-account` route, the search endpoint has the origin of that route's base URL, and that credential resolves for the search endpoint. The provider asks a route for its credential only at that origin, so an account credential published for another deployment is never sent to the search endpoint. The account service releases one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only the credential's headers, `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the credential that search sent through the credential's own invalidation: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. An account-authenticated search in flight when the account signs out ends through the credential's `revoked` signal and fails as `WEB_PROVIDER_ERROR` with sign-in guidance. +A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names a model route that publishes an account credential through `ctx.llm.providerCredential`, the `deepseek-account` route, the search endpoint has the origin of that route's base URL, and that credential resolves for the search endpoint. The provider asks a route for its credential only at that origin, so an account credential published for another deployment is never sent to the search endpoint. The account service releases one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only the credential's headers, `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the credential that search sent through the credential's own invalidation: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. An account-authenticated search in flight when the account signs out ends through the credential's `revoked` signal and fails as `WEB_PROVIDER_ERROR` with sign-in guidance. The provider's `ready()` answers whether the search a model request would make has a credential, on any model route: the request's route publishes an account credential for the origin of the configured search endpoint that reports itself configured for that endpoint, or a literal `apiKey` is set or `ctx.credentials.describe` reports the `apiKeyEnv` reference configured (without that service, the process environment must carry it). It checks them in the order a search resolves them, and a route whose settings do not resolve or whose published base URL does not parse, or a failed account-credential or credential-store read, answers false, because the search fails there instead of trying the next credential. While this provider is the selected search provider, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and its prompt guidance from each request for which it answers false. Only presence is checked: a wrong key, or an endpoint that does not serve the native `web_search_20250305` server tool, counts as ready and fails each call. A call that still arrives resolves credentials when it runs. @@ -103,7 +103,7 @@ The provider is built on two commitments: ### Request flow -Each search captures the current Config values into provider options — endpoint, model, key reference, limits — then asks the initiating Session's model route for its account credential through `ctx.llm.routeCredential` when it publishes one for the search endpoint's origin, otherwise resolves the credential reference through `ctx.credentials` (or the environment), appends the log-only session event, and dispatches the Messages request with the native `web_search` server tool. The response's `web_search_tool_result` blocks become `sources[]`; `cited_text` entries from text blocks are joined to their URLs as snippets; results are deduplicated by URL; and the service enforces the requested source bound on the way back. +Each search captures the current Config values into provider options — endpoint, model, key reference, limits — then asks the initiating Session's model route for its account credential through `ctx.llm.providerCredential` when it publishes one for the search endpoint's origin, otherwise resolves the credential reference through `ctx.credentials` (or the environment), appends the log-only session event, and dispatches the Messages request with the native `web_search` server tool. The response's `web_search_tool_result` blocks become `sources[]`; `cited_text` entries from text blocks are joined to their URLs as snippets; results are deduplicated by URL; and the service enforces the requested source bound on the way back. Readiness captures the same options but reads no API key value: on a route publishing an account credential for the search endpoint's origin it first asks that credential whether it is configured for the search endpoint, then checks the literal key or asks `ctx.credentials.describe()` (or the environment) whether the key reference is configured. diff --git a/packages/web/web-search-deepseek/README.zh.md b/packages/web/web-search-deepseek/README.zh.md index 7b7c8ac43c..a8196222d3 100644 --- a/packages/web/web-search-deepseek/README.zh.md +++ b/packages/web/web-search-deepseek/README.zh.md @@ -58,7 +58,7 @@ kind: "package-reference" ### 鉴权 -当发起会话最近的 `request/context` 事件指明的模型路由通过 `ctx.llm.routeCredential` 发布账号凭据(即 `deepseek-account` 路由),搜索端点与该路由的基础地址同源,且该凭据为搜索端点解析成功时,搜索使用 DeepSeek 账号鉴权。提供方只在同源时向路由索取凭据,因此为其他部署发布的账号凭据不会发往搜索端点。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)释放凭据。这类搜索只发送该凭据的请求头 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并通过凭据自身的失效操作只作废该搜索实际发送的凭据:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。账号退登时仍在途的账号鉴权搜索会通过凭据的 `revoked` 信号结束,并以 `WEB_PROVIDER_ERROR` 失败,附带登录指引。 +当发起会话最近的 `request/context` 事件指明的模型路由通过 `ctx.llm.providerCredential` 发布账号凭据(即 `deepseek-account` 路由),搜索端点与该路由的基础地址同源,且该凭据为搜索端点解析成功时,搜索使用 DeepSeek 账号鉴权。提供方只在同源时向路由索取凭据,因此为其他部署发布的账号凭据不会发往搜索端点。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)释放凭据。这类搜索只发送该凭据的请求头 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并通过凭据自身的失效操作只作废该搜索实际发送的凭据:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。账号退登时仍在途的账号鉴权搜索会通过凭据的 `revoked` 信号结束,并以 `WEB_PROVIDER_ERROR` 失败,附带登录指引。 提供方的 `ready()` 回答模型请求将发起的搜索是否有凭据,不论模型路由:该请求的路由为配置的搜索端点所在 origin 发布了账号凭据且该凭据报告自身已为该端点配置,或者设置了字面 `apiKey`,或 `ctx.credentials.describe` 报告 `apiKeyEnv` 引用已配置(没有该服务时,进程环境中必须存在该变量)。它按搜索解析凭据的顺序检查;路由设置无法解析或其发布的基础地址无法解析,或读取账号凭据或凭据存储失败时回答 false,因为搜索会在那里失败,而不会尝试下一种凭据。本提供方是选中的搜索提供方时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它回答 false 的每个请求中撤下 `web_search` 及其提示词说明。这里只检查凭据是否存在:错误的密钥,或不提供原生 `web_search_20250305` 服务器工具的端点,都视为就绪并使每次调用失败。仍然到达的调用会在运行时解析凭据。 @@ -103,7 +103,7 @@ kind: "package-reference" ### 请求流程 -每次搜索先把当前 Config 段投影为提供方选项——端点、模型、密钥引用、上限——然后在发起会话的模型路由通过 `ctx.llm.routeCredential` 为搜索端点所在 origin 发布账号凭据时向其索取该凭据,否则通过 `ctx.credentials`(或环境)解析凭据引用,追加仅用于日志的会话事件,并以原生 `web_search` 服务器工具分发 Messages 请求。响应中的 `web_search_tool_result` 块变为 `sources[]`;文本块中的 `cited_text` 条目按其 URL 拼接为 snippet;结果按 URL 去重;服务在返回路径上强制执行请求的来源上限。 +每次搜索先把当前 Config 段投影为提供方选项——端点、模型、密钥引用、上限——然后在发起会话的模型路由通过 `ctx.llm.providerCredential` 为搜索端点所在 origin 发布账号凭据时向其索取该凭据,否则通过 `ctx.credentials`(或环境)解析凭据引用,追加仅用于日志的会话事件,并以原生 `web_search` 服务器工具分发 Messages 请求。响应中的 `web_search_tool_result` 块变为 `sources[]`;文本块中的 `cited_text` 条目按其 URL 拼接为 snippet;结果按 URL 去重;服务在返回路径上强制执行请求的来源上限。 就绪判断捕获相同的选项,但不读取 API 密钥的值:路由为搜索端点所在 origin 发布账号凭据时,先询问该凭据是否已为搜索端点配置,再检查字面密钥,或询问 `ctx.credentials.describe()`(或环境)密钥引用是否已配置。 diff --git a/packages/web/web-search-deepseek/src/index.ts b/packages/web/web-search-deepseek/src/index.ts index 006749c9d9..b63dd86263 100644 --- a/packages/web/web-search-deepseek/src/index.ts +++ b/packages/web/web-search-deepseek/src/index.ts @@ -1,7 +1,7 @@ /** * Register a DeepSeek-backed provider in `ctx.web`. It calls the Anthropic-compatible Messages API * with native `web_search_20250305`. A search initiated by a Session whose latest model request used - * a route that publishes an account credential through `ctx.llm.routeCredential()` authenticates with + * a route that publishes an account credential through `ctx.llm.providerCredential()` authenticates with * that credential when the search endpoint has the origin of that route's base URL and the * credential's owner allows the endpoint; every other search reuses `DEEPSEEK_API_KEY`. The provider * does not reuse `DEEPSEEK_BASE_URL`; auxiliary search has its own endpoint configuration. The @@ -17,7 +17,7 @@ import { credentialRef, credentialRefConfigured, resolveCredentialRef } from '@d import type { CredentialRef } from '@deepseek-ai/dsh-credentials' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' import { assertUsableApiKey } from '@deepseek-ai/dsh-llm' -import type { RouteCredential } from '@deepseek-ai/dsh-llm' +import type { ProviderCredential } from '@deepseek-ai/dsh-llm' import type {} from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-web' import { @@ -102,8 +102,8 @@ type SearchOptions = DeepSeekSearchProviderOptions & { readonly apiKeyEnv: Crede * @returns the route's account credential, or undefined for another kind, another origin, no credential, or no route. * @throws when the route's settings do not resolve, or its published base URL or `endpoint` does not parse. */ -function accountCredentialOf(ctx: Context, route: string | undefined, endpoint: string): RouteCredential | undefined { - const credential = route === undefined ? undefined : ctx.get('llm')?.routeCredential(route) +function accountCredentialOf(ctx: Context, route: string | undefined, endpoint: string): ProviderCredential | undefined { + const credential = route === undefined ? undefined : ctx.get('llm')?.providerCredential(route) if (credential?.kind !== 'account') return undefined return new URL(credential.baseURL).origin === new URL(endpoint).origin ? credential : undefined } @@ -170,7 +170,7 @@ async function searchConfigured( ctx: Context, options: SearchOptions, route: string | undefined, ): Promise { const endpoint = `${options.baseURL}/messages` - let account: RouteCredential | undefined + let account: ProviderCredential | undefined try { account = accountCredentialOf(ctx, route, endpoint) } catch (_unresolvedRoute) { return false /* The search fails on this route before it reads any credential. */ } if (account !== undefined) { diff --git a/packages/web/web-search-deepseek/src/provider.ts b/packages/web/web-search-deepseek/src/provider.ts index 5813d1f2d5..bff545d5cf 100644 --- a/packages/web/web-search-deepseek/src/provider.ts +++ b/packages/web/web-search-deepseek/src/provider.ts @@ -14,7 +14,7 @@ import type { WebSearchSource, } from '@deepseek-ai/dsh-web' import type { CredentialRef } from '@deepseek-ai/dsh-credentials' -import type { RouteCredentialGrant } from '@deepseek-ai/dsh-llm' +import type { ProviderCredentialGrant } from '@deepseek-ai/dsh-llm' import type {} from '@deepseek-ai/dsh-session' import type { AnthropicError, @@ -100,7 +100,7 @@ export interface DeepSeekSearchProviderOptions { * search reports the HTTP rejection. The grant's `revoked` signal ends the search when the * account signs out. `undefined` selects API-key authentication. */ - resolveAccountCredential?: (endpoint: string) => Promise + resolveAccountCredential?: (endpoint: string) => Promise /** Literal DeepSeek API key; when present it wins over {@link resolveApiKey}. */ apiKey?: string /** Resolve the current DeepSeek API key for one search operation. */ diff --git a/packages/web/web-search-deepseek/tests/deepseek.spec.ts b/packages/web/web-search-deepseek/tests/deepseek.spec.ts index 76c26394da..3af5b9666e 100644 --- a/packages/web/web-search-deepseek/tests/deepseek.spec.ts +++ b/packages/web/web-search-deepseek/tests/deepseek.spec.ts @@ -12,7 +12,7 @@ import LocalCredentialProvider from '@deepseek-ai/dsh-credentials-local' import { createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY } from '@deepseek-ai/dsh-launch-environment' import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' import LlmRuntime from '@deepseek-ai/dsh-llm' -import type { RouteCredential, RouteCredentialGrant } from '@deepseek-ai/dsh-llm' +import type { ProviderCredential, ProviderCredentialGrant } from '@deepseek-ai/dsh-llm' import * as AccountRoute from '@deepseek-ai/dsh-llm-deepseek-account' import SessionStore, { type SessionId } from '@deepseek-ai/dsh-session' import WebRuntime, { WebError, type WebSearchResult } from '@deepseek-ai/dsh-web' @@ -39,7 +39,7 @@ const searchProvider = (options: DeepSeekSearchProviderOptions): DeepSeekSearchP */ function accountCredential( token: (endpoint: string) => Promise, reject?: (token: string) => Promise, revoked?: AbortSignal, -): (endpoint: string) => Promise { +): (endpoint: string) => Promise { return async (endpoint) => { const value = await token(endpoint) if (value === undefined || value.length === 0) return undefined @@ -1070,19 +1070,19 @@ describe('web-search-deepseek search readiness', () => { } }) - it.each<[string, () => RouteCredential, string]>([ + it.each<[string, () => ProviderCredential, string]>([ ['settings do not resolve', () => { throw new Error('route settings do not resolve') }, 'route settings do not resolve'], ['published base URL does not parse', () => ({ kind: 'account', baseURL: 'not a url', configured: () => Promise.resolve(true), resolve: () => Promise.resolve({ headers: { 'x-dsh-auth-token': 'account-token' }, value: 'account-token' }), }), 'Invalid URL'], - ])('is not ready and fails the search when the initiating route\'s %s, despite a literal key', async (_fault, routeCredential, diagnostic) => { + ])('is not ready and fails the search when the initiating route\'s %s, despite a literal key', async (_fault, providerCredential, diagnostic) => { const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init: RequestInit = {}) => jsonResponse(searchResponse())) vi.stubGlobal('fetch', fetchMock) const ctx = new Context() mounted.push(ctx) await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) - ctx.provide('llm', { routeCredential } as never) + ctx.provide('llm', { providerCredential } as never) await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' }) expect(await ctx.web.searchReady('deepseek-account')).toBe(false) expect(await ctx.web.searchReady(undefined)).toBe(true) diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index a124eb82aa..01d4c94626 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -493,7 +493,7 @@ export const LINK_MAP: Readonly> = { LlmResolvedModelInfo: 'llm-streaming.md', LlmFailure: 'llm-streaming.md', LlmImageRequestPricing: 'llm-streaming.md', - RouteCredential: 'llm-streaming.md', + ProviderCredential: 'llm-streaming.md', LlmModelInfo: 'llm-streaming.md', LlmProviderInfo: 'llm-streaming.md', LlmConfigurableProvider: 'llm-streaming.md', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index d4dd42d7ae..08d8d22bb3 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -1844,12 +1844,12 @@ }, { "doc": "docs/subsystems/llm-streaming.md", - "symbol": "RouteCredentialGrant", + "symbol": "ProviderCredentialGrant", "source": "packages/llm/llm/src/types.ts" }, { "doc": "docs/subsystems/llm-streaming.md", - "symbol": "RouteCredential", + "symbol": "ProviderCredential", "source": "packages/llm/llm/src/types.ts" }, { From 9ab02fb88ae2d0b46aab818c7a58ad3dae8989d2 Mon Sep 17 00:00:00 2001 From: dsh-ci-bot Date: Fri, 13 Nov 2026 22:12:21 +0800 Subject: [PATCH 31/48] test(timeline): pin the locale of language-dependent assertions --- packages/experimental/timeline/tests/panel.client.spec.tsx | 5 ++++- packages/experimental/timeline/tests/reports.spec.ts | 2 +- packages/experimental/timeline/tests/tools.spec.ts | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/experimental/timeline/tests/panel.client.spec.tsx b/packages/experimental/timeline/tests/panel.client.spec.tsx index 119f00b44c..4ec0d4c0f7 100644 --- a/packages/experimental/timeline/tests/panel.client.spec.tsx +++ b/packages/experimental/timeline/tests/panel.client.spec.tsx @@ -632,10 +632,13 @@ describe('the Task Tree and Timeline tabs', () => { const titles = [...container.querySelectorAll('.timeline-annotation-target')].map( node => node.textContent, ) + // The panel renders dates with the locale the fixture supplies; format the expected text with + // the same locale instead of the host ICU locale, which differs across CI runners. + const shown = (at: number) => new Date(at).toLocaleString('en') expect(titles).toEqual([ 'Task Tree: Review release', 'Review release · Verify behavior', - `Level 1 · 1m: ${new Date(report.start).toLocaleString()} – ${new Date(report.end).toLocaleString()}`, + `Level 1 · 1m: ${shown(report.start)} – ${shown(report.end)}`, ]) expect(screen.getByText(en.controlWaiting)).toBeTruthy() expect(screen.getByText('The saved result is verified.')).toBeTruthy() diff --git a/packages/experimental/timeline/tests/reports.spec.ts b/packages/experimental/timeline/tests/reports.spec.ts index f7dd8bbfcd..d8a68e52fa 100644 --- a/packages/experimental/timeline/tests/reports.spec.ts +++ b/packages/experimental/timeline/tests/reports.spec.ts @@ -659,7 +659,7 @@ describe('background summaries through a real agent loop', () => { it('hard-codes no activity without calling the model, including later empty intervals', async () => { const adapter = new Adapter() adapter.calls = 0 - const f = await running({}, adapter) + const f = await running({ language: 'en' }, adapter) await vi.advanceTimersByTimeAsync(60000) await f.waitRecords('plugin:timeline/report') expect(f.reports()[0]).toMatchObject({ diff --git a/packages/experimental/timeline/tests/tools.spec.ts b/packages/experimental/timeline/tests/tools.spec.ts index 0f7bf4d099..7b7f766ec9 100644 --- a/packages/experimental/timeline/tests/tools.spec.ts +++ b/packages/experimental/timeline/tests/tools.spec.ts @@ -504,7 +504,7 @@ describe('agent tools in the production loop', () => { } }) it('updates the fixed language rule in the next prompt assembly', async () => { - const f = await setup() + const f = await setup({ language: 'en' }) try { const prompt = () => f.ctx.systemPrompt.assemble({ scope: f.agent }) expect( From 1791494137c174d9264f368f9bf82c1c6ff49906 Mon Sep 17 00:00:00 2001 From: dsh-ci-bot Date: Fri, 13 Nov 2026 22:23:14 +0800 Subject: [PATCH 32/48] test(timeline): pin the settings counter expectation to the fixture locale --- packages/experimental/timeline/tests/settings.client.spec.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/experimental/timeline/tests/settings.client.spec.tsx b/packages/experimental/timeline/tests/settings.client.spec.tsx index 425273a92c..715b7f19d1 100644 --- a/packages/experimental/timeline/tests/settings.client.spec.tsx +++ b/packages/experimental/timeline/tests/settings.client.spec.tsx @@ -154,7 +154,9 @@ describe('the Timeline Settings section', () => { expect(within(section).getByRole('heading', { level: 2 }).textContent).toBe('Task writing guidance') expect(section.previousElementSibling).toBe(screen.getByRole('region', { name: 'Timed reports' })) expect(taskPrompt.maxLength).toBe(32768) - const count = (length: number) => `${length.toLocaleString()} / ${taskPrompt.maxLength.toLocaleString()}` + // The counter renders with the locale the fixture supplies; do not follow the host ICU locale. + const count = (length: number) => + `${length.toLocaleString('en')} / ${taskPrompt.maxLength.toLocaleString('en')}` const prompt = 'Explain results and remaining evidence in task details.' expect(within(section).getByText(count(value.taskPrompt.length))).toBeTruthy() fireEvent.change(taskPrompt, { target: { value: prompt } }) From 79015b174c1413d755470a076c6861322eb07e08 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Mon, 16 Nov 2026 11:59:34 +0800 Subject: [PATCH 33/48] refactor(session): move list metadata to sessionQuery and query Workspace headers Address review on #8238: - Replace the Workspace.sessionHeaders property with getSessionHeaders(). The public contract states only membership and order; the in-memory header index is documented on the implementation. - SessionQueryEngine now injects sessionProjections, registers the sessionListMetadata projection in Service.init, and exposes getListMetadata(session). Disposing the service releases the registration. The Session API and list_session read metadata through ctx.sessionQuery; registerSessionListMetadata and the passed reader closure are removed. - SqliteSessionQueryEngine injects sessionProjections and chains Service.init. - Tests: a newly attached Session appears in a later getSessionHeaders() result; query-service disposal removes the projection; test query services run Service.init; projection-order expectations follow the new registration order. --- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/subsystems/session-query.md | 7 +++ docs/subsystems/session-query.zh.md | 7 +++ docs/subsystems/workspace.md | 7 +-- docs/subsystems/workspace.zh.md | 7 +-- .../api/session-controller/README.i18n.yaml | 4 +- packages/api/session-controller/README.md | 2 +- packages/api/session-controller/README.zh.md | 2 +- packages/api/session-controller/src/list.ts | 11 ++-- .../tests/agent.host.spec.ts | 2 +- .../tests/commands-create-fork.host.spec.ts | 2 +- .../commands-queue-attachment.host.spec.ts | 2 +- .../tests/controller.host.spec.ts | 2 +- .../tests/history-controller.host.spec.ts | 2 +- .../tests/list-scheduling.host.spec.ts | 3 +- .../tests/listeners.host.spec.ts | 2 +- .../tests/session-fork.host.spec.ts | 2 +- .../session-history-journal.host.spec.ts | 2 +- .../tests/session-projections.host.spec.ts | 6 +- .../tests/session-search.host.spec.ts | 60 ++++++++++--------- .../tests/state-controller.host.spec.ts | 2 +- .../tests/subagent-catalog.host.spec.ts | 4 +- .../session-controller/tests/test-remote.ts | 16 +++-- .../tests/transport.host.spec.ts | 7 +-- .../tests/session-reference.spec.ts | 5 ++ .../extensions/tool-cordis/src/api-catalog.ts | 12 +++- .../session-query-sqlite/src/index.ts | 5 +- .../session-query/README.i18n.yaml | 18 +++--- .../session-query/session-query/README.md | 9 +-- .../session-query/session-query/README.zh.md | 9 +-- .../session-query/session-query/package.json | 3 - .../session-query/session-query/src/index.ts | 21 ++++++- .../session-query/src/list-metadata.ts | 21 ++----- .../session-query/tests/list-metadata.spec.ts | 37 +++++------- .../tool-session-list/README.i18n.yaml | 4 +- .../session-query/tool-session-list/README.md | 2 +- .../tool-session-list/README.zh.md | 2 +- .../tool-session-list/src/index.ts | 7 +-- .../tool-session-list/src/list.ts | 13 ++-- packages/workspace/workspace/README.i18n.yaml | 4 +- packages/workspace/workspace/README.md | 2 +- packages/workspace/workspace/README.zh.md | 2 +- packages/workspace/workspace/src/entity.ts | 3 +- packages/workspace/workspace/src/types.ts | 7 +-- .../workspace/tests/workspace.spec.ts | 19 +++++- scripts/gen-cordis-catalog.ts | 1 + 47 files changed, 206 insertions(+), 165 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index b35e5aa168..3d1cf5eeab 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -3280,7 +3280,7 @@ export interface Config { ## `@deepseek-ai/dsh-session-query-sqlite` -- `inject`: `sessions` +- `inject`: `sessions` · `sessionProjections` - `refs`: [`SessionQueryConfig`](../packages/session-query/session-query/src/index.ts) - `source`: [`packages/session-query/session-query-sqlite/src/index.ts:92`](../packages/session-query/session-query-sqlite/src/index.ts) diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 908b3c708d..44a2550947 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -3282,7 +3282,7 @@ export interface Config { ## `@deepseek-ai/dsh-session-query-sqlite` -- `inject`: `sessions` +- `inject`: `sessions` · `sessionProjections` - `refs`: [`SessionQueryConfig`](../packages/session-query/session-query/src/index.ts) - `source`: [`packages/session-query/session-query-sqlite/src/index.ts:92`](../packages/session-query/session-query-sqlite/src/index.ts) diff --git a/docs/subsystems/session-query.md b/docs/subsystems/session-query.md index 94e7eae55b..5dca82b24c 100644 --- a/docs/subsystems/session-query.md +++ b/docs/subsystems/session-query.md @@ -381,6 +381,13 @@ Unified live-preferred session query service. Exact reads, filters, and traces are backend-independent concrete behavior. A backend implements full-text observation, reconciliation, ranking, cursor generations, and query execution on the same `ctx.sessionQuery` service. ```ts cordis-catalog +/** + * Read the metadata that summarizes one live or prepared Session in a Session list. + * @param session - live or prepared Session to summarize. + * @returns whether the Session has no turn, and its latest human-authored prompt time. + */ +getListMetadata(session: Session): SessionListMetadata + /** * Observe one exact live or prepared Session without a persistence listing preflight. * @param sessionId - logical Session identity. diff --git a/docs/subsystems/session-query.zh.md b/docs/subsystems/session-query.zh.md index 7d33c1946c..40605385c1 100644 --- a/docs/subsystems/session-query.zh.md +++ b/docs/subsystems/session-query.zh.md @@ -381,6 +381,13 @@ Unified live-preferred session query service. Exact reads, filters, and traces are backend-independent concrete behavior. A backend implements full-text observation, reconciliation, ranking, cursor generations, and query execution on the same `ctx.sessionQuery` service. ```ts cordis-catalog +/** + * Read the metadata that summarizes one live or prepared Session in a Session list. + * @param session - live or prepared Session to summarize. + * @returns whether the Session has no turn, and its latest human-authored prompt time. + */ +getListMetadata(session: Session): SessionListMetadata + /** * Observe one exact live or prepared Session without a persistence listing preflight. * @param sessionId - logical Session identity. diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index ba01258c94..c82ba0dbc9 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -64,11 +64,10 @@ interface Workspace { readonly sessionIds: readonly SessionId[] /** - * Stored headers of {@link sessionIds}, in the same order. Read from the - * registry's startup and attach-time header index without persistence I/O; - * headers are immutable, so an indexed header never goes stale. + * List the stored headers of the current members. + * @returns a new array with one header per entry of {@link sessionIds}, in the same order. */ - readonly sessionHeaders: readonly SessionHeader[] + getSessionHeaders(): readonly SessionHeader[] /** * Replace the display title durably. diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index 55b4bd531d..3504f9391e 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -64,11 +64,10 @@ interface Workspace { readonly sessionIds: readonly SessionId[] /** - * Stored headers of {@link sessionIds}, in the same order. Read from the - * registry's startup and attach-time header index without persistence I/O; - * headers are immutable, so an indexed header never goes stale. + * List the stored headers of the current members. + * @returns a new array with one header per entry of {@link sessionIds}, in the same order. */ - readonly sessionHeaders: readonly SessionHeader[] + getSessionHeaders(): readonly SessionHeader[] /** * Replace the display title durably. diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index d309647399..5f99650f2f 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1fdf707322fb6996 zh: 0204f7e9d4aa3cce /session-controller/use-this-package: - en: 179c281216ad0660 - zh: 81dbc1d8985ab21b + en: 15d6cb30e1e7f5e2 + zh: 21fe7028a4ed4aef /session-controller/client-references: en: e8979a803ec3e194 zh: c567efcd971728ba diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index 12e9c840a0..7c71dea39e 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -43,7 +43,7 @@ Every Remote endpoint is access-controlled: a Peer whose principal is not the ow List rows carry `formatStatus` when available, so Clients can identify migration-required Sessions without requesting their projections. -Host list generation yields between complete rows only when its configured work slice is exhausted; cheap remaining work returns without a forced yield. Request cancellation is checked per row and after each yield and rejects without partial results. Each row is synchronous; the list does not promise one cross-Session snapshot. A Session already queued as cold remains a cached row if it attaches during a yield: Client in-flight mutation replay corrects its availability, and sequenced projections supersede cached hints. An attached Session's summary reads its blankness and last-prompt recency through the [shared Session-list reader](../../session-query/session-query/README.md#shared-list-metadata), and its projection hints carry every summary key computed through `snapshot`. The first summary of an attached Session computes these projections over its whole in-memory log, and later summaries advance them incrementally; this computation runs inside one synchronous row, so `listWorkSliceMs` cannot split it. +Host list generation yields between complete rows only when its configured work slice is exhausted; cheap remaining work returns without a forced yield. Request cancellation is checked per row and after each yield and rejects without partial results. Each row is synchronous; the list does not promise one cross-Session snapshot. A Session already queued as cold remains a cached row if it attaches during a yield: Client in-flight mutation replay corrects its availability, and sequenced projections supersede cached hints. An attached Session's summary reads its blankness and last-prompt recency through [`sessionQuery.getListMetadata`](../../session-query/session-query/README.md#session-list-metadata), and its projection hints carry every summary key computed through `snapshot`. The first summary of an attached Session computes these projections over its whole in-memory log, and later summaries advance them incrementally; this computation runs inside one synchronous row, so `listWorkSliceMs` cannot split it. Client list rows and resident Sessions use the current `sessionListMetadata` projection to reject stale blank-session hints; recency is the later of the summary timestamp and the projected last user prompt. When SessionManager creates an instance before its list row arrives, it reconciles blankness with metadata already retained for that Session. An opened conversation is therefore not reused by New Session even when an older list response still marks it blank. diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index 1287e60744..1749a99c4a 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -43,7 +43,7 @@ Client journal 在发布 follow 快照、live entry 或历史页之前验证当 列表行在状态可用时携带 `formatStatus`,Client 无需请求其投影即可识别需要迁移的 Session。 -Host 仅在配置的工作时间片耗尽时,于完整条目之间让出事件循环;剩余工作较少时直接返回,不强制让出。每行及每次让出之后检查请求取消,取消时拒绝返回部分结果。每行同步计算;列表不承诺跨 Session 的统一快照。已经进入冷态队列的 Session 若在让出期间接入,仍返回缓存行:Client 对进行中请求的变更重放会纠正其可用性,带序号的投影会覆盖缓存提示。已接入 Session 的摘要通过[共享 Session 列表读取函数](../../session-query/session-query/README.zh.md#shared-list-metadata)读取是否为空和最后一次提示词的最近活动时间,其投影提示携带通过 `snapshot` 计算的每个摘要 key。已接入 Session 的首次摘要在其完整内存日志上计算这些投影,之后的摘要增量推进;这次计算在单行的同步工作内进行,`listWorkSliceMs` 无法切分它。 +Host 仅在配置的工作时间片耗尽时,于完整条目之间让出事件循环;剩余工作较少时直接返回,不强制让出。每行及每次让出之后检查请求取消,取消时拒绝返回部分结果。每行同步计算;列表不承诺跨 Session 的统一快照。已经进入冷态队列的 Session 若在让出期间接入,仍返回缓存行:Client 对进行中请求的变更重放会纠正其可用性,带序号的投影会覆盖缓存提示。已接入 Session 的摘要通过[`sessionQuery.getListMetadata`](../../session-query/session-query/README.zh.md#session-list-metadata)读取是否为空和最后一次提示词的最近活动时间,其投影提示携带通过 `snapshot` 计算的每个摘要 key。已接入 Session 的首次摘要在其完整内存日志上计算这些投影,之后的摘要增量推进;这次计算在单行的同步工作内进行,`listWorkSliceMs` 无法切分它。 Client 列表行和驻留 Session 使用当前 `sessionListMetadata` 投影纠正过期的空白会话提示;最近活动时间取摘要时间戳与投影中最后一次用户提示词时间的较晚值。当 SessionManager 在列表行到达前创建实例时,会使用已保留的该 Session 元数据对账空白状态。因此,即使旧列表响应仍将已有对话标为空白,新会话操作也不会复用已经打开过的对话。 diff --git a/packages/api/session-controller/src/list.ts b/packages/api/session-controller/src/list.ts index d2ff0d2a67..e49a59fcd5 100644 --- a/packages/api/session-controller/src/list.ts +++ b/packages/api/session-controller/src/list.ts @@ -8,7 +8,7 @@ import type { ImageAttachmentLimits } from '@deepseek-ai/dsh-attachment' import type { Session, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import type { ProjectionSnapshot } from '@deepseek-ai/dsh-session-projection' import type {} from '@deepseek-ai/dsh-session-projection-cache' -import { registerSessionListMetadata, SessionQueryError, type SessionRecord, type SessionSearchCursor } from '@deepseek-ai/dsh-session-query' +import { SessionQueryError, type SessionRecord, type SessionSearchCursor } from '@deepseek-ai/dsh-session-query' import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' import { z } from 'zod' import { @@ -52,8 +52,6 @@ export function truncateUnicodeCodePoints(value: string, maximum: number): strin /** Owns list projection registration, bounded cold summaries, and authorized search. */ export class ApiSessionList { - private listMetadata!: (session: Session) => SessionListMetadata - /** * @param ctx - Host context carrying Session, query, persistence, and projection services. * @param workSliceMs - Resolved positive integral list-work budget in milliseconds. @@ -65,7 +63,6 @@ export class ApiSessionList { * @returns when all required registrations are ready. */ async initialize(): Promise { - this.listMetadata = await registerSessionListMetadata(this.ctx) await this.ctx.sessionProjections.register<'imageLimits', null>({ key: 'imageLimits', stateSchema: z.null(), @@ -82,17 +79,17 @@ export class ApiSessionList { /** * Build one current attached-Session summary. - * Blankness and recency come from the shared `sessionListMetadata` reader; projection + * Blankness and recency come from `sessionQuery.getListMetadata`; projection * hints carry every summary key computed through `snapshot`. The first call * for a Session computes these projections over its whole in-memory log, and - * later calls advance them incrementally. The handle read and the hint with + * later calls advance them incrementally. The metadata read and the hint with * the same key come from one cell; the metadata read does not depend on any * other unit's view. * @param session - attached Session to summarize. * @returns current list metadata and available projections. */ summaryFor(session: Session): SessionSummary { - const metadata = this.listMetadata(session) + const metadata = this.ctx.sessionQuery.getListMetadata(session) const projections = this.projectionsFor(session.header, session) return { sessionId: session.id, diff --git a/packages/api/session-controller/tests/agent.host.spec.ts b/packages/api/session-controller/tests/agent.host.spec.ts index aea96d5e04..9f73c9230f 100644 --- a/packages/api/session-controller/tests/agent.host.spec.ts +++ b/packages/api/session-controller/tests/agent.host.spec.ts @@ -35,7 +35,7 @@ async function harness(): Promise<{ ctx: Context; agents: ApiSessionAgentControl await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) await ctx.sessionProjections.register(agentPresetProjectionDefinition) ctx.provide('agentDefaultModel', { currentSelection: () => ({ provider: 'fixture', model: 'fixture-model' }), diff --git a/packages/api/session-controller/tests/commands-create-fork.host.spec.ts b/packages/api/session-controller/tests/commands-create-fork.host.spec.ts index eb2093ea18..68eee9071f 100644 --- a/packages/api/session-controller/tests/commands-create-fork.host.spec.ts +++ b/packages/api/session-controller/tests/commands-create-fork.host.spec.ts @@ -50,7 +50,7 @@ async function baseContext(): Promise { await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) ctx.provide('agentDefaultModel', { currentSelection: () => ({ provider: 'fixture', model: 'fixture-model' }), saveSelection: () => Promise.resolve(), diff --git a/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts b/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts index f575583063..74c9cf2f9b 100644 --- a/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts +++ b/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts @@ -42,7 +42,7 @@ async function commandHarness( await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) await ctx.plugin(TypertRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) await ctx.sessionProjections.register(subagentIdentityProjectionDefinition) const sessionId = SessionId('commands-session') const ancestor = Session.create(SessionId('ancestor')) diff --git a/packages/api/session-controller/tests/controller.host.spec.ts b/packages/api/session-controller/tests/controller.host.spec.ts index 664c4f9244..6822dc89e7 100644 --- a/packages/api/session-controller/tests/controller.host.spec.ts +++ b/packages/api/session-controller/tests/controller.host.spec.ts @@ -38,7 +38,7 @@ describe('SessionController facade', () => { const original = ctx.sessionProjections.register.bind(ctx.sessionProjections) let first = true vi.spyOn(ctx.sessionProjections, 'register').mockImplementation(async (...args: Parameters) => { - if (first) { + if (first && args[0].key === 'imageLimits') { first = false entered.resolve(undefined) await gate.promise diff --git a/packages/api/session-controller/tests/history-controller.host.spec.ts b/packages/api/session-controller/tests/history-controller.host.spec.ts index 1f71f48e5e..4a6925feb6 100644 --- a/packages/api/session-controller/tests/history-controller.host.spec.ts +++ b/packages/api/session-controller/tests/history-controller.host.spec.ts @@ -17,7 +17,7 @@ async function fixture() { const ctx = new Context() roots.push(ctx) await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) const history = new HistoryController(ctx) const web = new WebController(ctx, history, (observation) => { observation[Symbol.dispose]() }) const session = ctx.sessions.create(SessionId('history-target'), { meta: { cwd: '/history-test' } }) diff --git a/packages/api/session-controller/tests/list-scheduling.host.spec.ts b/packages/api/session-controller/tests/list-scheduling.host.spec.ts index 0cba6939d7..3d5c326fd5 100644 --- a/packages/api/session-controller/tests/list-scheduling.host.spec.ts +++ b/packages/api/session-controller/tests/list-scheduling.host.spec.ts @@ -84,7 +84,8 @@ async function harness(rows: readonly Row[], summaryMs = 8, workSliceMs = 8) { return { header: session.header, live: row.phase === 'live', persisted: true } }) const listSessions = vi.fn(async (_signal?: AbortSignal) => records) - ctx.provide('sessionQuery', { listSessions } as never) + const getListMetadata = () => ({ blank: true, lastPromptAt: null }) + ctx.provide('sessionQuery', { listSessions, getListMetadata } as never) ctx.provide('sessionProjectionCache', { cachedSnapshot: (header: SessionRecord['header']) => { recordSummary('cold', header.id) diff --git a/packages/api/session-controller/tests/listeners.host.spec.ts b/packages/api/session-controller/tests/listeners.host.spec.ts index d8f97b9244..bf28c37402 100644 --- a/packages/api/session-controller/tests/listeners.host.spec.ts +++ b/packages/api/session-controller/tests/listeners.host.spec.ts @@ -24,7 +24,7 @@ async function fixture() { const ctx = new Context() roots.push(ctx) await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) const session = ctx.sessions.create(SessionId('listener-target'), { meta: { cwd: '/listeners' } }) const abort = cancellation() const partial: Partial = { id: session.id, session } diff --git a/packages/api/session-controller/tests/session-fork.host.spec.ts b/packages/api/session-controller/tests/session-fork.host.spec.ts index 72b21aa31e..91ad497289 100644 --- a/packages/api/session-controller/tests/session-fork.host.spec.ts +++ b/packages/api/session-controller/tests/session-fork.host.spec.ts @@ -34,7 +34,7 @@ async function composed(workspaces: readonly Workspace[] = []): Promise await ctx.plugin(SystemPrompt, { personaPrefix: '' }) await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) ctx.provide('workspaceRegistry', { list: () => workspaces, archivedSessionIds: [] } as never) ctx.agents.setFactory({ createAgent: async (ownerCtx: Context, options: CreateAgentOptions): Promise => { diff --git a/packages/api/session-controller/tests/session-history-journal.host.spec.ts b/packages/api/session-controller/tests/session-history-journal.host.spec.ts index 328e797677..9f55fb0e16 100644 --- a/packages/api/session-controller/tests/session-history-journal.host.spec.ts +++ b/packages/api/session-controller/tests/session-history-journal.host.spec.ts @@ -54,7 +54,7 @@ async function harness(): Promise<{ ctx: Context }> { await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) return { ctx } } diff --git a/packages/api/session-controller/tests/session-projections.host.spec.ts b/packages/api/session-controller/tests/session-projections.host.spec.ts index aa4ae6a702..a57622e3a5 100644 --- a/packages/api/session-controller/tests/session-projections.host.spec.ts +++ b/packages/api/session-controller/tests/session-projections.host.spec.ts @@ -540,7 +540,7 @@ describe('session.list projections column', () => { const row = response.value.items.find(item => item.sessionId === session.id) expect(row?.projections?.kind).toBe('sequenced') expect(Object.keys(row?.projections?.values ?? {})).toEqual([...ctx.sessionProjections.summaryKeys()]) - expect(Object.keys(row?.projections?.values ?? {})).toEqual(['conversationContinuation', 'sessionListMetadata']) + expect(Object.keys(row?.projections?.values ?? {})).toEqual(['sessionListMetadata', 'conversationContinuation']) expect(row?.projections?.values.conversationContinuation).toBeNull() }) @@ -796,8 +796,8 @@ describe('Session control projection frames', () => { { type: 'projection', sessionId: session.id, seq: 0, changes: [ { key: 'test/last-user', val: { text: 'm0' } }, - { key: 'conversationContinuation', val: null }, { key: 'sessionListMetadata', val: { blank: true, lastPromptAt: 100 } }, + { key: 'conversationContinuation', val: null }, ], }, { @@ -837,8 +837,8 @@ describe('Session control projection frames', () => { value: { type: 'projection', seq: 0, changes: [ { key: 'test/last-user', val: { text: 'm0' } }, - { key: 'conversationContinuation', val: null }, { key: 'sessionListMetadata', val: { blank: true, lastPromptAt: 100 } }, + { key: 'conversationContinuation', val: null }, ], }, }) diff --git a/packages/api/session-controller/tests/session-search.host.spec.ts b/packages/api/session-controller/tests/session-search.host.spec.ts index 9b14011fbe..2d7c944867 100644 --- a/packages/api/session-controller/tests/session-search.host.spec.ts +++ b/packages/api/session-controller/tests/session-search.host.spec.ts @@ -5,7 +5,7 @@ */ import { describe, expect, it, vi } from 'vitest' -import { Context } from '@deepseek-ai/cordis' +import { Context, Service } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { SESSION_FORMAT_VERSION, SessionSeq } from '@deepseek-ai/dsh-session' @@ -73,6 +73,10 @@ class SearchSessionQuery extends SessionQueryEngine { super(ctx) } + initialize(): Promise { + return this[Service.init]() + } + override searchSessions( ...args: Parameters ): ReturnType { @@ -89,8 +93,8 @@ function installSearchQuery( searchSessions: ( ...args: Parameters ) => Promise, -): void { - new SearchSessionQuery(ctx, searchSessions) +): Promise { + return new SearchSessionQuery(ctx, searchSessions).initialize() } describe('session.search', () => { @@ -152,7 +156,7 @@ describe('session.search', () => { }, ], })) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const remote = await createSessionTestRemote(ctx, defaults) const signal = new AbortController().signal @@ -188,7 +192,7 @@ describe('session.search', () => { const ctx = await baseContext() ctx.sessions.create(sid('visible'), { meta: header('visible') }) const searchSessions = vi.fn() - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const remote = await createSessionTestRemote(ctx, defaults) for (const query of ['', ' ', 'contains\0nul', 'x'.repeat(501)]) { @@ -202,7 +206,7 @@ describe('session.search', () => { it('returns an empty page without invoking the index when no session is visible', async () => { const ctx = await baseContext() const searchSessions = vi.fn() - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const remote = await createSessionTestRemote(ctx, defaults) const response = await remote.search( @@ -228,7 +232,7 @@ describe('session.search', () => { const base = hit('visible', index) return { ...base, bestMatch: { ...base.bestMatch, ...bestMatch } } } - installSearchQuery(ctx, () => Promise.resolve({ + await installSearchQuery(ctx, () => Promise.resolve({ items: [ withBestMatch(0, { sessionId: sid('hidden') }), withBestMatch(1, { surface: 'shadowed' }), @@ -263,7 +267,7 @@ describe('session.search', () => { nextCursor: 'page-2', }) .mockResolvedValueOnce({ items: items.slice(19) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('match'), new AbortController().signal, @@ -303,7 +307,7 @@ describe('session.search', () => { ...end < items.length ? { nextCursor: `offset-${end}` } : {}, }) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('adaptive-page-limit'), @@ -346,7 +350,7 @@ describe('session.search', () => { nextCursor: `page-${searchSessions.mock.calls.length}`, }) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('endless-pages'), @@ -411,7 +415,7 @@ describe('session.search', () => { return Promise.reject(new Error('unexpected provider call')) } }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('stale-restart'), @@ -450,7 +454,7 @@ describe('session.search', () => { nextCursor: `cursor-${searchSessions.mock.calls.length}`, }) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('stale-churn'), @@ -479,7 +483,7 @@ describe('session.search', () => { controller.abort() return Promise.reject(stale) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('abort-stale'), @@ -500,7 +504,7 @@ describe('session.search', () => { 'provider generation changed before paging', 'SESSION_QUERY_STALE_CURSOR', ))) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('first-page-stale'), @@ -524,7 +528,7 @@ describe('session.search', () => { 'continuation limit is invalid', 'SESSION_QUERY_INVALID_LIMIT', )) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('continuation-invalid-limit'), @@ -551,7 +555,7 @@ describe('session.search', () => { 'SESSION_QUERY_INVALID_LIMIT', ), )) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('minimum-page-limit'), @@ -577,7 +581,7 @@ describe('session.search', () => { 'SESSION_QUERY_INVALID_LIMIT', )) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('abort-invalid-limit'), @@ -596,7 +600,7 @@ describe('session.search', () => { ctx.sessions.create(sid('visible'), { meta: header('visible') }) const oversized = Array.from({ length: 21 }, (_, index) => hit(`oversized-${index}`)) const searchSessions = vi.fn(() => Promise.resolve({ items: oversized })) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('oversized-page'), @@ -622,7 +626,7 @@ describe('session.search', () => { } return Promise.resolve({ items: oversized }) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('adapted-oversized-page'), @@ -648,7 +652,7 @@ describe('session.search', () => { snippet: `${expected}${'y'.repeat(10_000)}`, }, } - installSearchQuery(ctx, () => Promise.resolve({ items: [overlong] })) + await installSearchQuery(ctx, () => Promise.resolve({ items: [overlong] })) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('bounded-snippet'), @@ -670,7 +674,7 @@ describe('session.search', () => { const searchSessions = vi.fn() .mockResolvedValueOnce({ items: [], nextCursor: 'repeated' }) .mockResolvedValueOnce({ items: [], nextCursor: 'repeated' }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('repeated-cursor'), @@ -693,7 +697,7 @@ describe('session.search', () => { const searchSessions = vi.fn() .mockResolvedValueOnce({ items: items.slice(0, 20), nextCursor: 'repeated' }) .mockResolvedValueOnce({ items: items.slice(20), nextCursor: 'repeated' }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('repeated-lookahead-cursor'), @@ -720,7 +724,7 @@ describe('session.search', () => { .mockResolvedValueOnce({ items: items.slice(0, 20), nextCursor: 'page-2' }) .mockResolvedValueOnce({ items: items.slice(0, 20), nextCursor: 'page-3' }) .mockResolvedValueOnce({ items: items.slice(20) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('duplicate-pages'), @@ -748,7 +752,7 @@ describe('session.search', () => { controller.abort() return Promise.resolve({ items: [] }) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('cancel-continuation'), @@ -777,7 +781,7 @@ describe('session.search', () => { const searchSessions = vi.fn((_request: SessionSearchRequest) => Promise.resolve({ items: [hit('cold-32750')], })) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('large corpus'), @@ -813,7 +817,7 @@ describe('session.search', () => { }, }) as never) const searchSessions = vi.fn() - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('cancel-during-visibility'), @@ -840,7 +844,7 @@ describe('session.search', () => { inspect, }) as never) const searchSessions = vi.fn(() => Promise.resolve({ items: [] })) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('header-only-visibility'), @@ -876,7 +880,7 @@ describe('session.search', () => { const searchSessions = vi.fn() .mockRejectedValueOnce(aborted) .mockRejectedValueOnce(new Error('database unavailable')) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const remote = await createSessionTestRemote(ctx, defaults) const cancelled = await remote.search( diff --git a/packages/api/session-controller/tests/state-controller.host.spec.ts b/packages/api/session-controller/tests/state-controller.host.spec.ts index 5fc74006ff..5b634aaa88 100644 --- a/packages/api/session-controller/tests/state-controller.host.spec.ts +++ b/packages/api/session-controller/tests/state-controller.host.spec.ts @@ -47,7 +47,7 @@ async function fixture() { const ctx = new Context() roots.push(ctx) await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) const session = ctx.sessions.create(SessionId('state-target'), { meta: { cwd: '/state-test' } }) let agent: Agent | undefined const get = vi.fn(() => agent) diff --git a/packages/api/session-controller/tests/subagent-catalog.host.spec.ts b/packages/api/session-controller/tests/subagent-catalog.host.spec.ts index 0f834506d9..98d523ae0b 100644 --- a/packages/api/session-controller/tests/subagent-catalog.host.spec.ts +++ b/packages/api/session-controller/tests/subagent-catalog.host.spec.ts @@ -58,7 +58,7 @@ async function bench() { sessionId === PARENT ? { meta: header, events } : undefined, ), }) as never) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) provideWorkingDirectoryFixture(ctx) await ctx.plugin(SubagentRuntime) const controller = await createSessionTestController(ctx, defaults) @@ -200,7 +200,7 @@ describe('SessionController subagent catalog', () => { await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) const controller = await createSessionTestController(ctx, defaults) const session = ctx.sessions.create(PARENT, { meta: { cwd: '/workspace' } }) const expected = ctx.sessionProjections.snapshot(session) diff --git a/packages/api/session-controller/tests/test-remote.ts b/packages/api/session-controller/tests/test-remote.ts index 04ed6788cf..cb6e5ef89f 100644 --- a/packages/api/session-controller/tests/test-remote.ts +++ b/packages/api/session-controller/tests/test-remote.ts @@ -221,6 +221,10 @@ export function testSessionPersistence( /** Concrete point-read query used by Session Controller tests that do not exercise search. */ class TestSessionQuery extends SessionQueryEngine { + initialize(): Promise { + return this[Service.init]() + } + override searchSessions(): Promise { return Promise.reject(new Error('session search is not configured in this test')) } @@ -230,10 +234,14 @@ class TestSessionQuery extends SessionQueryEngine { } } -/** Install the required projection and point-query services for direct controller tests. */ -export function installSessionReadTestServices(ctx: Context): void { +/** + * Install the required projection and point-query services for direct controller tests. + * @param ctx - test context that receives missing services. + * @returns when the installed query service has registered its projections. + */ +export async function installSessionReadTestServices(ctx: Context): Promise { if (ctx.get('sessionProjections') === undefined) new SessionProjectionRegistry(ctx) - if (ctx.get('sessionQuery') === undefined) new TestSessionQuery(ctx) + if (ctx.get('sessionQuery') === undefined) await new TestSessionQuery(ctx).initialize() } async function installControllers( @@ -294,7 +302,7 @@ async function installControllers( retirePrompt: () => {}, } as never) } - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) if (ctx.get('remoteAccess') === undefined) new RemoteAccessService(ctx) const cwd = vi.spyOn(process, 'cwd').mockReturnValue(defaults.cwd) class TestController extends SessionController { diff --git a/packages/api/session-controller/tests/transport.host.spec.ts b/packages/api/session-controller/tests/transport.host.spec.ts index 8a3df2ae43..461972eb8d 100644 --- a/packages/api/session-controller/tests/transport.host.spec.ts +++ b/packages/api/session-controller/tests/transport.host.spec.ts @@ -86,7 +86,6 @@ function controllers( web: WebController } { roots.add(ctx.root) - installSessionReadTestServices(ctx) const history = new HistoryController(ctx) return { history, web: new WebController(ctx, history, promote) } } @@ -94,7 +93,7 @@ function controllers( async function setup(): Promise<{ ctx: Context; history: HistoryController; web: WebController }> { const ctx = new Context() await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) await ctx.sessionProjections.register(subagentIdentityProjectionDefinition) return { ctx, ...controllers(ctx) } } @@ -130,7 +129,7 @@ describe('Session history and Web follow', () => { it('ends active followers when the owning Controller unloads', async () => { const ctx = new Context() await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) let web!: WebController const owner = ctx.plugin(Object.assign( (inner: Context) => { @@ -273,7 +272,7 @@ describe('Session history and Web follow', () => { it('bridges the unpublished end-seed boundary when a cold source attaches', async () => { const ctx = new Context() await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) let web!: WebController let agentCtx!: Context await ctx.plugin(Object.assign( diff --git a/packages/context/session-reference/tests/session-reference.spec.ts b/packages/context/session-reference/tests/session-reference.spec.ts index e4a6885f8b..cae6553148 100644 --- a/packages/context/session-reference/tests/session-reference.spec.ts +++ b/packages/context/session-reference/tests/session-reference.spec.ts @@ -491,6 +491,7 @@ describe('model-relative reference budgets', () => { const ctx = new Context() contexts.push(ctx) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(TestSessionQueryEngine) const resolverFiber = ctx.plugin(SessionReferenceResolver, config) await resolverFiber @@ -810,6 +811,7 @@ describe('session reference discovery and preparation', () => { it('labels every session by id when no projection face is composed', async () => { const ctx = new Context() await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(TestSessionQueryEngine) await ctx.plugin(SessionReferenceResolver) const target = ctx.sessions.create(SessionId('target'), { meta: { cwd: '/same' } }) @@ -1304,18 +1306,21 @@ describe('session reference discovery and preparation', () => { it('rejects direct invalid configuration before service publication', async () => { const ctx = new Context() await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(TestSessionQueryEngine) expect(() => new SessionReferenceResolver(ctx, { maxReferences: 0 })) .toThrow(expectCode('SESSION_REFERENCE_INVALID_CONFIG')) const oversizedCtx = new Context() await oversizedCtx.plugin(SessionStore) + await oversizedCtx.plugin(SessionProjectionRegistry) await oversizedCtx.plugin(TestSessionQueryEngine) expect(() => new SessionReferenceResolver(oversizedCtx, { maxReferences: 4 })) .toThrow(expectCode('SESSION_REFERENCE_INVALID_CONFIG')) const defaultCtx = new Context() await defaultCtx.plugin(SessionStore) + await defaultCtx.plugin(SessionProjectionRegistry) await defaultCtx.plugin(TestSessionQueryEngine) expect(() => new SessionReferenceResolver(defaultCtx)).not.toThrow() }) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 6d21ec6d7b..94e821f2c3 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -3280,6 +3280,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ summary: 'Unified live-preferred session query service.', description: 'Unified live-preferred session query service.\n\nExact reads, filters, and traces are backend-independent concrete behavior. A backend implements full-text observation, reconciliation, ranking, cursor generations, and query execution on the same `ctx.sessionQuery` service.', methods: [ + { + signature: 'getListMetadata(session: Session): SessionListMetadata', + description: 'Read the metadata that summarizes one live or prepared Session in a Session list.', + parameters: [{ name: 'session', description: 'live or prepared Session to summarize.' }], + returns: 'whether the Session has no turn, and its latest human-authored prompt time.', + }, { signature: 'observeSession( sessionId: SessionId, options: SessionObservationOptions = {}, ): Promise', description: 'Observe one exact live or prepared Session without a persistence listing preflight.', @@ -9100,6 +9106,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SessionLineageTrace', declaration: 'export type SessionLineageTrace = {\n target: SessionRecord;\n ancestors: SessionRecord[];\n descendants: SessionLineageNode[];\n} & ({\n complete: true;\n root: SessionRecord;\n} | {\n complete: false;\n unresolvedParentId: SessionId;\n});', }, + { + name: 'SessionListMetadata', + declaration: 'export interface SessionListMetadata {\n readonly blank: boolean;\n readonly lastPromptAt: number | null;\n}', + }, { name: 'SessionListRequest', declaration: 'export interface SessionListRequest {\n readonly cursor?: string;\n}', @@ -10774,7 +10784,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'Workspace', - declaration: 'export interface Workspace {\n readonly id: WorkspaceId;\n readonly path: string;\n readonly title: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n readonly sessionIds: readonly SessionId[];\n readonly sessionHeaders: readonly SessionHeader[];\n setTitle(title: string): Promise;\n attachSession(sessionId: SessionId): Promise;\n insertSessionBefore(sessionId: SessionId, beforeSessionId?: SessionId): Promise;\n detachSession(sessionId: SessionId): Promise;\n status(): Promise<\'ok\' | \'missing-dir\'>;\n}', + declaration: 'export interface Workspace {\n readonly id: WorkspaceId;\n readonly path: string;\n readonly title: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n readonly sessionIds: readonly SessionId[];\n getSessionHeaders(): readonly SessionHeader[];\n setTitle(title: string): Promise;\n attachSession(sessionId: SessionId): Promise;\n insertSessionBefore(sessionId: SessionId, beforeSessionId?: SessionId): Promise;\n detachSession(sessionId: SessionId): Promise;\n status(): Promise<\'ok\' | \'missing-dir\'>;\n}', }, { name: 'WorkspaceArchiveSessionRequest', diff --git a/packages/session-query/session-query-sqlite/src/index.ts b/packages/session-query/session-query-sqlite/src/index.ts index 7c95afa28d..48494ebc1d 100644 --- a/packages/session-query/session-query-sqlite/src/index.ts +++ b/packages/session-query/session-query-sqlite/src/index.ts @@ -201,7 +201,7 @@ interface CursorPayload { /** Concrete SQLite owner of the combined `ctx.sessionQuery` service. */ export class SqliteSessionQueryEngine extends SessionQueryEngine { - static override inject = ['sessions'] + static override inject = ['sessions', 'sessionProjections'] static Config: z = z.object({ path: z.string().required(), @@ -261,7 +261,8 @@ export class SqliteSessionQueryEngine extends SessionQueryEngine { } /** Open eagerly only when activation owns the configured readiness boundary. */ - protected async [Service.init](): Promise { + protected override async [Service.init](): Promise { + await super[Service.init]() if (this.config.openAt === 'startup') await this._ensureReady(undefined) } diff --git a/packages/session-query/session-query/README.i18n.yaml b/packages/session-query/session-query/README.i18n.yaml index 8e8ae5bcfd..48d79d6d6a 100644 --- a/packages/session-query/session-query/README.i18n.yaml +++ b/packages/session-query/session-query/README.i18n.yaml @@ -18,8 +18,8 @@ en: dfc90afac9ef47be zh: 0a5aa60a34f24e61 /deepseek-ai-dsh-session-query/use-this-package/what-you-can-do: - en: 608cd6d4c5cf2c35 - zh: 23d3c5a7374b5283 + en: f0baf912893e2edd + zh: b71f2d1df02a8d2a /deepseek-ai-dsh-session-query/use-this-package/filters: en: 1b95403461947ca1 zh: cffa21b03df9f0ad @@ -36,14 +36,14 @@ en: b34fb0d209192ff4 zh: 455bdb024d04f16a /deepseek-ai-dsh-session-query/understand-the-implementation/source-map: - en: 58964ca2cde96c32 - zh: 9699c328cefc9f09 + en: fa54846e5df84028 + zh: de31ff744819413e /deepseek-ai-dsh-session-query/understand-the-implementation/corpus-resolution: - en: 4dde9107d05de6ee - zh: 8c775eb7630e659a -/deepseek-ai-dsh-session-query/understand-the-implementation/shared-list-metadata: - en: 30d9af561283c382 - zh: bc8ceabe718239bf + en: 3254f25af5734621 + zh: 3f8e8e0bbb83095e +/deepseek-ai-dsh-session-query/understand-the-implementation/session-list-metadata: + en: a46a831dce49d0ba + zh: 840d4982f059b41b /deepseek-ai-dsh-session-query/understand-the-implementation/observation-cache: en: 16d4a29af5b2ac07 zh: 7ec4a91f97697d2e diff --git a/packages/session-query/session-query/README.md b/packages/session-query/session-query/README.md index af901c891d..6321321296 100644 --- a/packages/session-query/session-query/README.md +++ b/packages/session-query/session-query/README.md @@ -32,6 +32,7 @@ Use `ctx.sessionQuery` from application code when you need to read or search ses | Operation | What you get | |---|---| | `listSessions()` | Every logical session, newest first, with `live` and `persisted` availability flags and optional `formatStatus` | +| `getListMetadata(session)` | Whether a live or prepared Session has no turn, and its latest human-authored prompt time | | `readSession(id)` | The complete replay-validated raw event log, without making the session live | | `filterSessions(filters)` | Sessions matching ANDed metadata and availability predicates | | `filterEvents(id, filters)` | Semantic event documents matching metadata and literal-text predicates | @@ -92,7 +93,7 @@ The decision history lives in the [unified service decision](../../../.agents/no | [`src/index.ts`](src/index.ts) | Service definition: the abstract `SessionQueryEngine`, concrete reads, config validation | | [`src/corpus.ts`](src/corpus.ts) | Live-preferred corpus resolution, optional persistence binding, batch projections | | [`src/observation.ts`](src/observation.ts) | Live-preferred point observations with a bounded revision-keyed prepared-Session cache | -| [`src/list-metadata.ts`](src/list-metadata.ts) | Shared blankness and human-prompt recency projection registration | +| [`src/list-metadata.ts`](src/list-metadata.ts) | Session-list blankness and human-prompt recency projection definition | | [`src/cold-read.ts`](src/cold-read.ts) | Handle-based cold log read with in-memory interrupted-turn closers | | [`src/types.ts`](src/types.ts) | Public records, filters, requests, and page types | | [`src/config.ts`](src/config.ts) | Inherited config and the closed `SessionQueryError` taxonomy | @@ -106,10 +107,10 @@ The decision history lives in the [unified service decision](../../../.agents/no `SessionCorpus` binds optional `ctx.sessionPersistence` through a fiber and resolves each read live-first: a known live target is snapshotted without consulting persistence; otherwise the session is listed, read completely through a short-lived read handle, and re-checked for a live attachment before cloning. A cold log whose writer crashed mid-turn is balanced in memory with `interruptedTurnClosers` — persistence is never mutated by a read. Header compatibility is asserted between listed and loaded observations. Batch title reads run one metadata listing and bounded-concurrency reads, isolating per-session failures while cancellation rejects the whole batch. - -### Shared list metadata + +### Session-list metadata -`registerSessionListMetadata(ctx)` acquires the shared projection for Session blankness and the latest human-authored prompt time, and returns a synchronous reader for prepared live Sessions. The Session API and optional [listing tools](../tool-session-list/README.md) share one projection unit; disposing a consumer releases only its own reference. Registration requires `sessionProjections`, independently of the query service's header-only `listSessions()` operation. +The service registers the `sessionListMetadata` projection for Session blankness and the latest human-authored prompt time when it starts, and its disposal releases that registration; it therefore requires `sessionProjections`. `getListMetadata(session)` reads the projection synchronously for a live or prepared Session. The Session API and optional [listing tools](../tool-session-list/README.md) read it through `ctx.sessionQuery`. ### Observation cache diff --git a/packages/session-query/session-query/README.zh.md b/packages/session-query/session-query/README.zh.md index c65fc09154..550c62d349 100644 --- a/packages/session-query/session-query/README.zh.md +++ b/packages/session-query/session-query/README.zh.md @@ -32,6 +32,7 @@ kind: "package-reference" | 操作 | 你得到什么 | |---|---| | `listSessions()` | 每个逻辑会话,最新的在前,带 `live` 与 `persisted` 可用性标志及可选 `formatStatus` | +| `getListMetadata(session)` | 实时或已准备的 Session 是否还没有 turn,及其最近一条人工提示词的时间 | | `readSession(id)` | 经过回放校验的完整原始事件日志,且不会让该会话变为实时 | | `filterSessions(filters)` | 匹配 AND 连接的元数据与可用性谓词的会话 | | `filterEvents(id, filters)` | 匹配元数据与字面文本谓词的语义事件文档 | @@ -92,7 +93,7 @@ kind: "package-reference" | [`src/index.ts`](src/index.ts) | 服务定义:抽象 `SessionQueryEngine`、具体读取、配置校验 | | [`src/corpus.ts`](src/corpus.ts) | 实时优先的语料库解析、可选持久化绑定、批量投影 | | [`src/observation.ts`](src/observation.ts) | 实时优先的定点观察,带按修订键控的有界 prepared-Session 缓存 | -| [`src/list-metadata.ts`](src/list-metadata.ts) | 共享的空白状态与人工提示词活动时间投影注册 | +| [`src/list-metadata.ts`](src/list-metadata.ts) | Session 列表空白状态与人工提示词活动时间投影定义 | | [`src/cold-read.ts`](src/cold-read.ts) | 基于句柄的冷日志读取,附内存中的中断轮次闭合事件 | | [`src/types.ts`](src/types.ts) | 公共记录、过滤器、请求与分页类型 | | [`src/config.ts`](src/config.ts) | 继承配置与封闭的 `SessionQueryError` 分类体系 | @@ -106,10 +107,10 @@ kind: "package-reference" `SessionCorpus` 通过 fiber 绑定可选的 `ctx.sessionPersistence`,并实时优先解析每次读取:已知实时目标直接快照,不查询持久化;否则先列出会话,再通过短生命周期的读取句柄完整读出日志,并在克隆前重新检查是否出现实时挂载。写入者在轮次中途崩溃的冷日志用 `interruptedTurnClosers` 在内存中补齐——读取从不修改持久化。列表与加载观察之间会断言 header 兼容性。批量标题读取执行一次元数据列表与有界并发读取,把逐会话失败隔离,而取消会拒绝整个批次。 - -### 共享列表元数据 + +### Session 列表元数据 -`registerSessionListMetadata(ctx)` 获取 Session 空白状态与最近人工提示词时间的共享投影,并返回准备就绪的实时 Session 的同步读取函数。Session API 与可选的[列表工具](../tool-session-list/README.zh.md)共享同一个投影单元;释放消费方时只移除它自己的引用。注册需要 `sessionProjections`,独立于查询服务仅读取 header 的 `listSessions()` 操作。 +服务启动时注册记录 Session 空白状态与最近人工提示词时间的 `sessionListMetadata` 投影,释放服务时移除该注册;因此服务依赖 `sessionProjections`。`getListMetadata(session)` 同步读取实时或已准备 Session 的该投影。Session API 与可选的[列表工具](../tool-session-list/README.zh.md)通过 `ctx.sessionQuery` 读取。 ### 观察缓存 diff --git a/packages/session-query/session-query/package.json b/packages/session-query/session-query/package.json index 0bf1278c42..5d3340a20e 100644 --- a/packages/session-query/session-query/package.json +++ b/packages/session-query/session-query/package.json @@ -49,9 +49,6 @@ "@deepseek-ai/dsh-session-persistence": { "optional": true }, - "@deepseek-ai/dsh-session-projection": { - "optional": true - }, "@deepseek-ai/dsh-session-projection-cache": { "optional": true } diff --git a/packages/session-query/session-query/src/index.ts b/packages/session-query/session-query/src/index.ts index 62dcbcc337..21d924f971 100644 --- a/packages/session-query/session-query/src/index.ts +++ b/packages/session-query/session-query/src/index.ts @@ -13,6 +13,7 @@ import { type SessionId, type SessionSeq as SessionSeqType, } from '@deepseek-ai/dsh-session' +import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import { foldSessionTitle } from '@deepseek-ai/dsh-session-title' import type { SessionTitleSnapshot } from '@deepseek-ai/dsh-session-title' import type { @@ -32,6 +33,7 @@ import type { SessionSearchExecContext, SessionSearchHit, SessionSearchPage, + SessionListMetadata, SessionSearchRequest, SessionSurfaceSnapshot, SessionTitleObservation, @@ -45,6 +47,7 @@ import { type Config, } from './config.ts' import { SessionCorpus } from './corpus.ts' +import { sessionListMetadataDefinition } from './list-metadata.ts' import { SessionObservationReader, type SessionObservation, @@ -60,7 +63,6 @@ import { import * as tracing from './tracing.ts' export type * from './types.ts' -export { registerSessionListMetadata } from './list-metadata.ts' export { SessionSearchCursor } from './cursor.ts' export type { Config, SessionQueryErrorCode } from './config.ts' export { @@ -97,9 +99,10 @@ declare module '@deepseek-ai/cordis' { * generations, and query execution on the same `ctx.sessionQuery` service. */ export abstract class SessionQueryEngine extends Service { - static inject = ['sessions'] + static inject = ['sessions', 'sessionProjections'] private readonly _readWindowMax: number + private _listMetadata!: ProjectionHandle private readonly _corpus: SessionCorpus private readonly _observations: SessionObservationReader @@ -132,6 +135,20 @@ export abstract class SessionQueryEngine extends Service { this._observations = new SessionObservationReader(ctx, preparedSessionCacheSize) } + /** Register the Session-list metadata projection for this service's lifetime. */ + protected async [Service.init](): Promise { + this._listMetadata = await this.ctx.sessionProjections.register(sessionListMetadataDefinition) + } + + /** + * Read the metadata that summarizes one live or prepared Session in a Session list. + * @param session - live or prepared Session to summarize. + * @returns whether the Session has no turn, and its latest human-authored prompt time. + */ + getListMetadata(session: Session): SessionListMetadata { + return this._listMetadata.stateOf(session) + } + /** * Observe one exact live or prepared Session without a persistence listing preflight. * @param sessionId - logical Session identity. diff --git a/packages/session-query/session-query/src/list-metadata.ts b/packages/session-query/session-query/src/list-metadata.ts index 46d77244fe..2a4c3fce71 100644 --- a/packages/session-query/session-query/src/list-metadata.ts +++ b/packages/session-query/session-query/src/list-metadata.ts @@ -1,7 +1,6 @@ -/** Shared Session-list projection ownership for API and model-tool readers. */ +/** Session-list metadata projection definition registered by `SessionQueryEngine`. */ -import type { Context } from '@deepseek-ai/cordis' -import type { Session, SessionEvent } from '@deepseek-ai/dsh-session' +import type { SessionEvent } from '@deepseek-ai/dsh-session' import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' import { z } from 'zod' import type { SessionListMetadata } from './types.ts' @@ -25,7 +24,8 @@ function applySessionListMetadata( : { blank, lastPromptAt } } -const sessionListMetadataDefinition = { +/** Blankness and latest human-prompt time folded per Session; persisted at state version 1. */ +export const sessionListMetadataDefinition = { key: 'sessionListMetadata', stateSchema: sessionListMetadataSchema, init: () => ({ blank: true, lastPromptAt: null }), @@ -33,16 +33,3 @@ const sessionListMetadataDefinition = { wire: { viewSchema: sessionListMetadataSchema, view: state => state }, stateVersion: 1, } satisfies ProjectionDefinition<'sessionListMetadata', SessionListMetadata> - -/** - * Acquire the shared Session-list unit on the caller's fiber. - * Concurrent callers share one projection; disposal releases only the caller's reference. - * @param ctx - owner context with the required projection registry. - * @returns a synchronous domain reader ready for prepared live Sessions. - */ -export async function registerSessionListMetadata( - ctx: Context, -): Promise<(session: Session) => SessionListMetadata> { - const handle = await ctx.sessionProjections.register(sessionListMetadataDefinition) - return session => handle.stateOf(session) -} diff --git a/packages/session-query/session-query/tests/list-metadata.spec.ts b/packages/session-query/session-query/tests/list-metadata.spec.ts index 96fd8bf536..14b75460d9 100644 --- a/packages/session-query/session-query/tests/list-metadata.spec.ts +++ b/packages/session-query/session-query/tests/list-metadata.spec.ts @@ -1,12 +1,12 @@ -/** Shared list metadata keeps its values and lifetime across independent consumers. */ +/** Session-list metadata is registered and read through the query service lifecycle. */ import { Context } from '@deepseek-ai/cordis' import { createUserMessage } from '@deepseek-ai/dsh-llm' import SessionStore from '@deepseek-ai/dsh-session' import type { Session } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' -import { describe, expect, it, onTestFinished, vi } from 'vitest' -import { registerSessionListMetadata } from '../src/list-metadata.ts' +import { describe, expect, it, onTestFinished } from 'vitest' +import { TestSessionQueryEngine } from './test-service.ts' async function setup() { const ctx = new Context() @@ -23,10 +23,11 @@ function prompt(session: Session) { }), { surfaceOp: 'append' }) } -describe('shared Session-list metadata', () => { +describe('Session-list metadata', () => { it('tracks human prompts and turns while preserving unchanged state references', async () => { const ctx = await setup() - const read = await registerSessionListMetadata(ctx) + await ctx.plugin(TestSessionQueryEngine) + const read = (session: Session) => ctx.sessionQuery.getListMetadata(session) const session = ctx.sessions.create() const initial = read(session) expect(initial).toEqual({ blank: true, lastPromptAt: null }) @@ -51,34 +52,24 @@ describe('shared Session-list metadata', () => { expect(ctx.sessionProjections.checkpoint(session).sessionListMetadata?.ver).toBe(1) }) - it('shares one cell and notification across owners until the last owner unloads', async () => { + it('releases the projection registration when the query service is disposed', async () => { const ctx = await setup() - const first = await ctx.plugin(Object.assign(function firstOwner() {}, { inject: ['sessionProjections'] })) - const second = await ctx.plugin(Object.assign(function secondOwner() {}, { inject: ['sessionProjections'] })) - const firstRead = await registerSessionListMetadata(first.ctx) - const secondRead = await registerSessionListMetadata(second.ctx) + const fiber = await ctx.plugin(TestSessionQueryEngine) const session = ctx.sessions.create() - expect(firstRead(session)).toBe(secondRead(session)) - const changed = vi.fn() - ctx.sessionProjections.onChanged(changed) session.append('turn/start', { turn: 1 }) - expect(changed).toHaveBeenCalledOnce() - expect(firstRead(session)).toBe(secondRead(session)) + expect(ctx.sessionProjections.snapshot(session).values.sessionListMetadata) + .toEqual({ blank: false, lastPromptAt: null }) - await first.dispose() - const event = prompt(session) - expect(secondRead(session)).toEqual({ blank: false, lastPromptAt: event.time }) - expect(ctx.sessionProjections.snapshot(session).values.sessionListMetadata).toEqual(secondRead(session)) - await second.dispose() + await fiber.dispose() expect(ctx.sessionProjections.snapshot(session).values).not.toHaveProperty('sessionListMetadata') }) - it('folds existing live history when the first consumer registers', async () => { + it('folds existing live history when the query service starts', async () => { const ctx = await setup() const session = ctx.sessions.create() session.append('turn/start', { turn: 1 }) const event = prompt(session) - const read = await registerSessionListMetadata(ctx) - expect(read(session)).toEqual({ blank: false, lastPromptAt: event.time }) + await ctx.plugin(TestSessionQueryEngine) + expect(ctx.sessionQuery.getListMetadata(session)).toEqual({ blank: false, lastPromptAt: event.time }) }) }) diff --git a/packages/session-query/tool-session-list/README.i18n.yaml b/packages/session-query/tool-session-list/README.i18n.yaml index 362ea0c6c0..d5264c53d9 100644 --- a/packages/session-query/tool-session-list/README.i18n.yaml +++ b/packages/session-query/tool-session-list/README.i18n.yaml @@ -27,8 +27,8 @@ en: 95ee3e3c0ecedadd zh: 933d267402ceec74 /deepseek-ai-dsh-tool-session-list/understand-the-implementation: - en: 730fef413ce5a404 - zh: 325a5700a9edbda1 + en: ac9f08e72d3f7e64 + zh: 231196ddbb82b779 /deepseek-ai-dsh-tool-session-list/further-exploration: en: 06d8fa5cb2d63b6b zh: 2635b93fccf3dbc9 diff --git a/packages/session-query/tool-session-list/README.md b/packages/session-query/tool-session-list/README.md index 3a17a6f125..3d9cab0fd4 100644 --- a/packages/session-query/tool-session-list/README.md +++ b/packages/session-query/tool-session-list/README.md @@ -65,7 +65,7 @@ Invalid pagination and an unknown `workspace_id` fail with `ToolArgsError` (`INV
Implementation internals — click to expand -A Workspace selection reads `Workspace.sessionHeaders`; an unscoped call uses the existing header-only query listing. Both combine headers with projected metadata. The shared `registerSessionListMetadata` helper acquires the same projection unit used by the Session API; each consumer releases its own registration when disposed. The title projection remains owned by `dsh-session-title`. Cold rows read the projection cache without opening the underlying log, including on a cache miss. No Session Controller or Agent activation is required. +A Workspace selection reads `Workspace.getSessionHeaders()`; an unscoped call uses the existing header-only query listing. Both combine headers with projected metadata. Live rows read blankness and prompt recency through `ctx.sessionQuery.getListMetadata`, the same projection the Session API reads. The title projection remains owned by `dsh-session-title`. Cold rows read the projection cache without opening the underlying log, including on a cache miss. No Session Controller or Agent activation is required. | File | Role | |---|---| diff --git a/packages/session-query/tool-session-list/README.zh.md b/packages/session-query/tool-session-list/README.zh.md index a6dbcf8786..023374121b 100644 --- a/packages/session-query/tool-session-list/README.zh.md +++ b/packages/session-query/tool-session-list/README.zh.md @@ -65,7 +65,7 @@ kind: "package-reference"
实现细节——点击展开 -选定 Workspace 时读取 `Workspace.sessionHeaders`;不指定范围时使用现有的仅 header 查询列表。两者都把 header 与投影元数据结合。共享的 `registerSessionListMetadata` 辅助函数获取 Session API 使用的同一个投影单元;每个消费方在释放时只移除自己的注册。标题投影仍由 `dsh-session-title` 拥有。冷条目读取投影缓存,不打开底层日志,缓存未命中时也一样。不需要 Session 控制器,也不会激活 agent。 +选定 Workspace 时读取 `Workspace.getSessionHeaders()`;不指定范围时使用现有的仅 header 查询列表。两者都把 header 与投影元数据结合。实时条目通过 `ctx.sessionQuery.getListMetadata` 读取空白状态与提示词活动时间,与 Session API 读取同一个投影。标题投影仍由 `dsh-session-title` 拥有。冷条目读取投影缓存,不打开底层日志,缓存未命中时也一样。不需要 Session 控制器,也不会激活 agent。 | 文件 | 职责 | |---|---| diff --git a/packages/session-query/tool-session-list/src/index.ts b/packages/session-query/tool-session-list/src/index.ts index a7d17b0bab..1ec7e96f4b 100644 --- a/packages/session-query/tool-session-list/src/index.ts +++ b/packages/session-query/tool-session-list/src/index.ts @@ -4,7 +4,6 @@ */ import type { Context } from '@deepseek-ai/cordis' -import { registerSessionListMetadata } from '@deepseek-ai/dsh-session-query' import { defineTool } from '@deepseek-ai/dsh-tools' import { listSessions, listWorkspaces } from './list.ts' @@ -21,10 +20,8 @@ const pagination = { /** * Grant tools access to all Workspace and Session metadata in this runtime. * @param ctx - scoped context granting these tools to its callers. - * @returns when the shared list metadata projection and tools are registered. */ -export async function apply(ctx: Context): Promise { - const readMetadata = await registerSessionListMetadata(ctx) +export function apply(ctx: Context): void { ctx.tools.register(defineTool({ name: 'list_workspace', description: 'List workspaces in registry order, including empty workspaces. Returns IDs, titles, paths, and creation and update times.', @@ -75,7 +72,7 @@ export async function apply(ctx: Context): Promise { render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], }, isConcurrencySafe: () => true, - execute: (args, exec) => listSessions(ctx, readMetadata, args, exec.signal), + execute: (args, exec) => listSessions(ctx, args, exec.signal), presentCall: args => ({ card: 'generic', title: 'List sessions', kind: 'read', rawInput: args.workspace_id }), })) } diff --git a/packages/session-query/tool-session-list/src/list.ts b/packages/session-query/tool-session-list/src/list.ts index 2de007a6eb..a21e68e7b5 100644 --- a/packages/session-query/tool-session-list/src/list.ts +++ b/packages/session-query/tool-session-list/src/list.ts @@ -1,8 +1,8 @@ /** Header-only selection and cached metadata for the read-only listing tools. */ import type { Context } from '@deepseek-ai/cordis' -import type { Session, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' -import type { SessionListMetadata } from '@deepseek-ai/dsh-session-query' +import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-session-query' import type {} from '@deepseek-ai/dsh-session-projection-cache' import type {} from '@deepseek-ai/dsh-session-title' import { ToolArgsError } from '@deepseek-ai/dsh-tools' @@ -76,14 +76,12 @@ export function listWorkspaces(ctx: Context, input: PageInput, signal: AbortSign * A Workspace selection reads only its members' indexed headers; an unscoped call enumerates * the corpus headers. Subagent Sessions are excluded. * @param ctx - context providing query, Workspace, and projection services. - * @param readLiveMetadata - ready reader owned by this plugin's registration. * @param input - filters and pagination arguments. * @param signal - caller cancellation, forwarded to the corpus listing. * @returns filtered Session metadata ordered by activity, then identity. */ export async function listSessions( ctx: Context, - readLiveMetadata: (session: Session) => SessionListMetadata, input: SessionListInput, signal: AbortSignal, ): Promise { @@ -98,14 +96,14 @@ export async function listSessions( if (workspace === undefined) { throw new ToolArgsError([`workspace_id ${JSON.stringify(input.workspace_id)} is not registered; use list_workspace to find a workspace`]) } - headers = workspace.sessionHeaders + headers = workspace.getSessionHeaders() } const archived = new Set(ctx.workspaceRegistry.archivedSessionIds) const items = [] for (const header of headers) { if (header.origin === 'subagent') continue if (archived.has(header.id) !== (input.archived ?? false)) continue - const metadata = readListMetadata(ctx, header, readLiveMetadata) + const metadata = readListMetadata(ctx, header) items.push({ session_id: header.id, title: metadata.title, @@ -124,13 +122,12 @@ export async function listSessions( function readListMetadata( ctx: Context, header: SessionHeader, - readLiveMetadata: (session: Session) => SessionListMetadata, ): { title: string | null; lastPromptAt: number | null } { const live = ctx.sessions.get(header.id) if (live !== undefined) { return { title: ctx.sessionProjections.snapshot(live, ['title']).values.title ?? null, - lastPromptAt: readLiveMetadata(live).lastPromptAt, + lastPromptAt: ctx.sessionQuery.getListMetadata(live).lastPromptAt, } } const cache = ctx.get('sessionProjectionCache') diff --git a/packages/workspace/workspace/README.i18n.yaml b/packages/workspace/workspace/README.i18n.yaml index 56af9d261a..cd426494c8 100644 --- a/packages/workspace/workspace/README.i18n.yaml +++ b/packages/workspace/workspace/README.i18n.yaml @@ -39,8 +39,8 @@ en: 447ced401b3b14a8 zh: 3ce2105605223945 /deepseek-ai-dsh-workspace/understand-the-implementation/design-philosophy: - en: 512431b309ba0051 - zh: 206c77de2022a541 + en: 9e06dc2424613790 + zh: 806bf45f13ebcc72 /deepseek-ai-dsh-workspace/understand-the-implementation/api-behavior: en: 8fcd81ee32f3c01e zh: 08ac92d085bb8147 diff --git a/packages/workspace/workspace/README.md b/packages/workspace/workspace/README.md index 23d8e88804..a3abb7fbca 100644 --- a/packages/workspace/workspace/README.md +++ b/packages/workspace/workspace/README.md @@ -91,7 +91,7 @@ This section explains the design decisions behind the feature and points at the ### Design philosophy - **One record per canonical path.** `fs.realpath` is the single uniqueness canon: paths are stored canonicalized, so a symlink to an owned directory collides, and uniqueness is string equality of canonical paths. -- **Membership starts from the recorded account.** The header index validates ordered `sessionIds`; missing-directory candidates retain their account, while other invalid candidates are filtered on read and pruned by the next mutation. `sessionHeaders` returns the indexed headers of `sessionIds` in the same order without persistence I/O. The strict canonical-path index used for history bootstrap includes existing directories only. +- **Membership starts from the recorded account.** The header index validates ordered `sessionIds`; missing-directory candidates retain their account, while other invalid candidates are filtered on read and pruned by the next mutation. `getSessionHeaders()` returns the indexed headers of `sessionIds` in the same order without persistence I/O. The strict canonical-path index used for history bootstrap includes existing directories only. - **Header-only reads.** Bootstrap and attach validation read `SessionHeader` fields only; event bodies are never loaded. - **Two-write mutations with an explicit marker.** Create and delete persist a `pendingMutation` marker before the record/order pair can diverge, so startup completes exactly the interrupted operation and unmarked divergence fails loud as corruption. - **Serialized writes.** Registry operations run on one operation chain; entity mutations go through `table.update` on the domain write chain, stamping `updatedAt` and deciding membership at their chain slot. diff --git a/packages/workspace/workspace/README.zh.md b/packages/workspace/workspace/README.zh.md index 02bf670648..6990a70857 100644 --- a/packages/workspace/workspace/README.zh.md +++ b/packages/workspace/workspace/README.zh.md @@ -91,7 +91,7 @@ Workspace 注册不意味着拥有其目录。未来的破坏性文件系统操 ### 设计理念 - **每个规范路径一条记录。** `fs.realpath` 是唯一的一套唯一性规范:路径以规范化形式存储,因此指向已有记录目录的符号链接会与之冲突,唯一性即规范路径的字符串相等。 -- **成员资格以已记录的归属为起点。** 头部索引校验有序的 `sessionIds`;目录缺失的候选保留归属,其他无效候选在读取时过滤,并在下一次变更时剪除。`sessionHeaders` 按相同顺序返回 `sessionIds` 的已索引 header,不做持久化 I/O。历史引导使用的严格规范路径索引只包含现存目录。 +- **成员资格以已记录的归属为起点。** 头部索引校验有序的 `sessionIds`;目录缺失的候选保留归属,其他无效候选在读取时过滤,并在下一次变更时剪除。`getSessionHeaders()` 按相同顺序返回 `sessionIds` 的已索引 header,不做持久化 I/O。历史引导使用的严格规范路径索引只包含现存目录。 - **仅读取头部。** 引导与 attach 校验只读取 `SessionHeader` 字段;事件正文绝不加载。 - **两次写入的变更带显式标记。** 创建与删除在记录/顺序对可能分叉之前先持久化 `pendingMutation` 标记,因此启动只补全被中断的操作,未标记的分叉作为损坏明确报错。 - **串行化写入。** 注册表操作跑在同一条操作链上;实体变更通过领域写链上的 `table.update` 执行,写入 `updatedAt`,并在其所在的链位置决定成员资格。 diff --git a/packages/workspace/workspace/src/entity.ts b/packages/workspace/workspace/src/entity.ts index cecd435181..7bf2ea5727 100644 --- a/packages/workspace/workspace/src/entity.ts +++ b/packages/workspace/workspace/src/entity.ts @@ -111,7 +111,8 @@ export class WorkspaceEntity implements Workspace { return this.record.sessionIds.filter(id => this.host.candidateMatches(id, this.record.path)) } - get sessionHeaders(): readonly SessionHeader[] { + /** Reads the registry's startup and attach-time header index without persistence I/O. */ + getSessionHeaders(): readonly SessionHeader[] { return this.sessionIds.map(id => this.host.sessionHeader(id)) } diff --git a/packages/workspace/workspace/src/types.ts b/packages/workspace/workspace/src/types.ts index bd3ae0a3e4..aa47a38627 100644 --- a/packages/workspace/workspace/src/types.ts +++ b/packages/workspace/workspace/src/types.ts @@ -100,11 +100,10 @@ export interface Workspace { readonly sessionIds: readonly SessionId[] /** - * Stored headers of {@link sessionIds}, in the same order. Read from the - * registry's startup and attach-time header index without persistence I/O; - * headers are immutable, so an indexed header never goes stale. + * List the stored headers of the current members. + * @returns a new array with one header per entry of {@link sessionIds}, in the same order. */ - readonly sessionHeaders: readonly SessionHeader[] + getSessionHeaders(): readonly SessionHeader[] /** * Replace the display title durably. diff --git a/packages/workspace/workspace/tests/workspace.spec.ts b/packages/workspace/workspace/tests/workspace.spec.ts index ddba94bb49..45373bce19 100644 --- a/packages/workspace/workspace/tests/workspace.spec.ts +++ b/packages/workspace/workspace/tests/workspace.spec.ts @@ -667,10 +667,25 @@ describe('Workspace session ordering', () => { expect(workspace.sessionIds).toEqual(['s2', 's1']) await workspace.attachSession(SessionId('s1')) expect(workspace.sessionIds).toEqual(['s2', 's1']) - expect(workspace.sessionHeaders).toEqual([header('s2', dir, 2), header('s1', dir, 1)]) + expect(workspace.getSessionHeaders()).toEqual([header('s2', dir, 2), header('s1', dir, 1)]) expect(storedRecord(result.pool, workspace.id).sessionIds).toEqual(['s2', 's1']) }) + it('includes a newly created and attached Session in later header lists', async () => { + const dir = await makeDir('attach-headers') + const result = await harness() + result.setSessions([header('s1', dir, 1)]) + const workspace = await result.registry.create(dir) + await workspace.attachSession(SessionId('s1')) + const before = workspace.getSessionHeaders() + expect(before).toEqual([header('s1', dir, 1)]) + + result.setSessions([header('s1', dir, 1), header('s2', dir, 2)]) + await workspace.attachSession(SessionId('s2')) + expect(workspace.getSessionHeaders()).toEqual([header('s2', dir, 2), header('s1', dir, 1)]) + expect(before).toEqual([header('s1', dir, 1)]) + }) + it('moves one id before an anchor or to the end, durably', async () => { const dir = await makeDir('insert-before') const result = await harness() @@ -891,7 +906,7 @@ describe('header-validated membership projection', () => { onTestFinished(() => result.ctx.fiber.dispose()) const workspace = result.registry.get(id)! expect(workspace.sessionIds).toEqual(['missing-dir']) - expect(workspace.sessionHeaders).toEqual([header('missing-dir', missing)]) + expect(workspace.getSessionHeaders()).toEqual([header('missing-dir', missing)]) await workspace.setTitle('Validated') expect(storedRecord(pool, id).sessionIds).toEqual(['missing-dir']) }) diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 12950471bb..f7cf70bae4 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -744,6 +744,7 @@ export const LINK_MAP: Readonly> = { SessionEventTraceRequest: 'session-query.md', SessionEventWindow: 'session-query.md', SessionLineageTrace: 'session-query.md', + SessionListMetadata: 'session-query.md', SessionObservation: 'session-query.md', SessionObservationOptions: 'session-query.md', SessionRecord: 'session-query.md', From 1851e875f429d5049525df9370891204d905404c Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Mon, 16 Nov 2026 13:07:46 +0800 Subject: [PATCH 34/48] feat(tool-session-list): show complete call arguments on tool cards list_session showed only workspace_id and list_workspace showed no input, so calls that differ in archived, limit, or offset rendered identical cards. --- packages/session-query/tool-session-list/src/index.ts | 4 ++-- .../tool-session-list/tests/tool-session-list.spec.ts | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/session-query/tool-session-list/src/index.ts b/packages/session-query/tool-session-list/src/index.ts index 1ec7e96f4b..139b50a023 100644 --- a/packages/session-query/tool-session-list/src/index.ts +++ b/packages/session-query/tool-session-list/src/index.ts @@ -45,7 +45,7 @@ export function apply(ctx: Context): void { }, isConcurrencySafe: () => true, execute: (args, exec) => Promise.resolve(listWorkspaces(ctx, args, exec.signal)), - presentCall: () => ({ card: 'generic', title: 'List workspaces', kind: 'read' }), + presentCall: args => ({ card: 'generic', title: 'List workspaces', kind: 'read', rawInput: args }), })) ctx.tools.register(defineTool({ name: 'list_session', @@ -73,6 +73,6 @@ export function apply(ctx: Context): void { }, isConcurrencySafe: () => true, execute: (args, exec) => listSessions(ctx, args, exec.signal), - presentCall: args => ({ card: 'generic', title: 'List sessions', kind: 'read', rawInput: args.workspace_id }), + presentCall: args => ({ card: 'generic', title: 'List sessions', kind: 'read', rawInput: args }), })) } diff --git a/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts index 6777822aef..b9d54912f0 100644 --- a/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts +++ b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts @@ -325,6 +325,10 @@ describe('read-only Session list tools', () => { expect(tool?.isConcurrencySafe?.({})).toBe(true) expect(tool?.presentCall?.({})).toMatchObject({ card: 'generic', kind: 'read' }) } + const page = { limit: 5, offset: 10 } + expect(mounted.ctx.tools.get('list_workspace')?.presentCall?.(page)).toMatchObject({ rawInput: page }) + const filters = { workspace_id: 'w1', archived: true, limit: 5, offset: 10 } + expect(mounted.ctx.tools.get('list_session')?.presentCall?.(filters)).toMatchObject({ rawInput: filters }) await mounted.fiber.dispose() expect(mounted.ctx.tools.get('list_workspace')).toBeUndefined() expect(mounted.ctx.tools.get('list_session')).toBeUndefined() From a65aacaa6ac02529717496fd4d6a2014115f45fa Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Mon, 16 Nov 2026 13:21:21 +0800 Subject: [PATCH 35/48] fix(session): follow sessionQuery's projection dependency and rc.3 version - SessionReferenceResolver injects sessions and sessionProjections, which sessionQuery now requires; its absent-registry label branch is unreachable and is removed. - The translator paid fixture mounts the projection registry beside its SQLite query service. - dsh-tool-session-list follows the master release version 0.2.2-rc.3. --- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- packages/context/session-reference/src/index.ts | 12 ++++-------- .../tests/session-reference.spec.ts | 2 +- packages/experimental/translator/package.json | 1 + .../experimental/translator/tests/paid-fixture.ts | 3 +++ .../session-query/tool-session-list/package.json | 2 +- pnpm-lock.yaml | 3 +++ 8 files changed, 15 insertions(+), 12 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 3806d9008f..21746e40ec 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -3375,7 +3375,7 @@ export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist' ## `@deepseek-ai/dsh-session-reference` -- `inject`: `sessionQuery` +- `inject`: `sessionQuery` · `sessions` · `sessionProjections` - `source`: [`packages/context/session-reference/src/config.ts:11`](../packages/context/session-reference/src/config.ts) ```ts config-catalog diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 24edf6e1f6..6c6b2d8b93 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -3377,7 +3377,7 @@ export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist' ## `@deepseek-ai/dsh-session-reference` -- `inject`: `sessionQuery` +- `inject`: `sessionQuery` · `sessions` · `sessionProjections` - `source`: [`packages/context/session-reference/src/config.ts:11`](../packages/context/session-reference/src/config.ts) ```ts config-catalog diff --git a/packages/context/session-reference/src/index.ts b/packages/context/session-reference/src/index.ts index b9f83f8140..4864b7d1c1 100644 --- a/packages/context/session-reference/src/index.ts +++ b/packages/context/session-reference/src/index.ts @@ -105,7 +105,7 @@ function candidateKeys({ record, label, displayTitle }: LabelledCandidate): Sear /** Exact-read consumer that prepares immutable cross-session message context. */ export class SessionReferenceResolver extends TypertRemoteService { - static inject = ['sessionQuery'] + static inject = ['sessionQuery', 'sessions', 'sessionProjections'] static Config: z = z.object({ maxReferences: z.number().step(1).min(1).max(MAX_REFERENCES).default(MAX_REFERENCES), candidateLimit: z.number().step(1).min(1).default(DEFAULT_CANDIDATE_LIMIT), @@ -272,17 +272,13 @@ export class SessionReferenceResolver extends TypertRemoteService { private projectedLabels( items: readonly T[], ): Array { - const projections = this.ctx.get('sessionProjections') - const sessions = this.ctx.get('sessions') - // An attached session answers from its live cut only while the registry is mounted. - const attached = new Map(sessions === undefined || projections === undefined - ? undefined - : sessions.list().map(session => [session.id, session])) + const projections = this.ctx.sessionProjections + const attached = new Map(this.ctx.sessions.list().map(session => [session.id, session])) const cache = this.ctx.get('sessionProjectionCache') const cachedSnapshot = cache?.cachedSnapshot.bind(cache) return items.map((item) => { const session = attached.get(item.record.header.id) - const snapshot = session !== undefined && projections !== undefined + const snapshot = session !== undefined ? projections.snapshot(session, LABEL_KEYS) : cachedSnapshot?.(item.record.header, LABEL_KEYS) const label = titleOf(snapshot) ?? item.record.header.id diff --git a/packages/context/session-reference/tests/session-reference.spec.ts b/packages/context/session-reference/tests/session-reference.spec.ts index e4768fd0af..db9fc4e870 100644 --- a/packages/context/session-reference/tests/session-reference.spec.ts +++ b/packages/context/session-reference/tests/session-reference.spec.ts @@ -821,7 +821,7 @@ describe('session reference discovery and preparation', () => { vi.restoreAllMocks() }) - it('labels every session by id when no projection face is composed', async () => { + it('labels every session by id when no title projection is registered', async () => { const ctx = new Context() await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) diff --git a/packages/experimental/translator/package.json b/packages/experimental/translator/package.json index a8b5ac641f..b30925db07 100644 --- a/packages/experimental/translator/package.json +++ b/packages/experimental/translator/package.json @@ -69,6 +69,7 @@ "@deepseek-ai/dsh-deepseek-account": "workspace:*", "@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:*", "@deepseek-ai/dsh-session-log-deepseek": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", "@deepseek-ai/dsh-session-query-sqlite": "workspace:*" } } diff --git a/packages/experimental/translator/tests/paid-fixture.ts b/packages/experimental/translator/tests/paid-fixture.ts index 70ee57f4bc..3435e9becd 100644 --- a/packages/experimental/translator/tests/paid-fixture.ts +++ b/packages/experimental/translator/tests/paid-fixture.ts @@ -4,6 +4,7 @@ import { boot } from '@deepseek-ai/dsh-app-boot' import LlmRuntime from '@deepseek-ai/dsh-llm' import SessionStore, { SESSION_FORMAT_VERSION, type SessionId, SessionSeq, type Session, type SessionEvent, type SessionHeader } from '@deepseek-ai/dsh-session' import * as JsonlPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SqliteSessionQuery from '@deepseek-ai/dsh-session-query-sqlite' import * as Official from '@deepseek-ai/dsh-llm-deepseek-api-key' import * as Account from '@deepseek-ai/dsh-llm-deepseek-account' @@ -136,6 +137,7 @@ export async function paidFixture(cleanups: Array<() => Promise>, options: { id: 'account-custom-id', name: '@deepseek-ai/dsh-llm-deepseek-account', disabled: !withNativeOwners, config: { baseURL } }, { id: 'translator', name: '@deepseek-ai/dsh-experimental-translator', config: translator }, ...options.withSessionQuery === true ? [ + { id: 'projections', name: '@deepseek-ai/dsh-session-projection' }, { id: 'query', name: '@deepseek-ai/dsh-session-query-sqlite', config: { path: join(root, 'query.sqlite'), openAt: 'never' } }, ] : [], ...options.withSessionLog === true ? [ @@ -147,6 +149,7 @@ export async function paidFixture(cleanups: Array<() => Promise>, options: const modules = new Map([ ['@deepseek-ai/dsh-llm', LlmRuntime], ['@deepseek-ai/dsh-session', SessionStore], ['@deepseek-ai/dsh-session-persistence-jsonl', JsonlPersistence], ['@deepseek-ai/dsh-session-query-sqlite', SqliteSessionQuery], + ['@deepseek-ai/dsh-session-projection', SessionProjectionRegistry], [options.officialName ?? '@deepseek-ai/dsh-llm-deepseek-api-key', Official], ['@deepseek-ai/dsh-llm-deepseek-account', Account], ['@deepseek-ai/dsh-experimental-translator', Translator], ['@deepseek-ai/dsh-deepseek-llm-api-extensions', DeepSeekLlmApiExtensionRegistry], diff --git a/packages/session-query/tool-session-list/package.json b/packages/session-query/tool-session-list/package.json index 0c24c7fcae..392a8f22ac 100644 --- a/packages/session-query/tool-session-list/package.json +++ b/packages/session-query/tool-session-list/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tool-session-list", "description": "Read-only paginated Workspace and Session metadata tools", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.3", "publishConfig": { "access": "public" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1d0bd1bd5d..be787bcb59 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -12600,6 +12600,9 @@ importers: '@deepseek-ai/dsh-session-persistence-jsonl': specifier: workspace:* version: link:../../session/session-persistence-jsonl + '@deepseek-ai/dsh-session-projection': + specifier: workspace:* + version: link:../../session/session-projection '@deepseek-ai/dsh-session-query-sqlite': specifier: workspace:* version: link:../../session-query/session-query-sqlite From 01aafcb4e9c6fa054fc515819e33b39054d324e6 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Mon, 16 Nov 2026 13:25:42 +0800 Subject: [PATCH 36/48] docs(session): address remaining list tool review notes - Name the model-visible page limits once and derive the schema text from them. - Type the intermediate Session rows and make list_workspace's execute async. - Document that blank Sessions are listed and that unscoped listing has unit coverage only. - State that the Workspace registry adds no model-visible surface of its own while the optional listing tools expose its metadata. --- docs/subsystems/workspace.i18n.yaml | 4 ++-- docs/subsystems/workspace.md | 2 +- docs/subsystems/workspace.zh.md | 2 +- .../tool-session-list/README.i18n.yaml | 4 ++-- packages/session-query/tool-session-list/README.md | 2 ++ .../session-query/tool-session-list/README.zh.md | 2 ++ .../session-query/tool-session-list/src/index.ts | 6 +++--- .../session-query/tool-session-list/src/list.ts | 13 +++++++++---- packages/workspace/workspace/README.i18n.yaml | 4 ++-- packages/workspace/workspace/README.md | 2 +- packages/workspace/workspace/README.zh.md | 2 +- 11 files changed, 26 insertions(+), 17 deletions(-) diff --git a/docs/subsystems/workspace.i18n.yaml b/docs/subsystems/workspace.i18n.yaml index bf01196282..86c2f01cb1 100644 --- a/docs/subsystems/workspace.i18n.yaml +++ b/docs/subsystems/workspace.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/workspace.md /workspaces: - en: 183fd2f466e3279c - zh: 6e79009b7294c240 + en: 70865308120d0b14 + zh: fe5d7406141657e1 /workspaces/identity: en: d61a7e78bbc1fb56 zh: 8397869f70cd5b28 diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index c82ba0dbc9..eda76426f7 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -2,7 +2,7 @@ English | [中文](workspace.zh.md) -A workspace is the persistent record of a directory the user works in: a stable id over a canonical path, a display title, and the ordered account of sessions that belong to it. The subsystem is one package ([dsh-workspace](../../packages/workspace/workspace), `ctx.workspaceRegistry`) — an optional host-side capability, not part of the agent-loop spine, and invisible to models (no tools, no prompt text, no session events). It stores its records through the [storage domain form](storage.md) and validates session membership against [`SessionHeader.cwd`](persistence.md#sessionheader--metadata-beside-the-log), so `storageDomain` and `sessionPersistence` are mandatory startup dependencies: an unavailable persistence peer leaves the plugin pending rather than being mistaken for an empty history. Design record: [domain KV storage Agent Note](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md); bootstrap and GUI ordering: [Workspace UI product-flow Agent Note](../../.agents/notes/archived/feature/2026-07-25-workspace-ui-product-flow.md). +A workspace is the persistent record of a directory the user works in: a stable id over a canonical path, a display title, and the ordered account of sessions that belong to it. The subsystem is one package ([dsh-workspace](../../packages/workspace/workspace), `ctx.workspaceRegistry`) — an optional host-side capability, not part of the agent-loop spine, and adds no model-visible surface of its own (no tools, no prompt text, no session events); the optional [listing tools](../../packages/session-query/tool-session-list) expose Workspace IDs, titles, and paths to models that are granted them. It stores its records through the [storage domain form](storage.md) and validates session membership against [`SessionHeader.cwd`](persistence.md#sessionheader--metadata-beside-the-log), so `storageDomain` and `sessionPersistence` are mandatory startup dependencies: an unavailable persistence peer leaves the plugin pending rather than being mistaken for an empty history. Design record: [domain KV storage Agent Note](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md); bootstrap and GUI ordering: [Workspace UI product-flow Agent Note](../../.agents/notes/archived/feature/2026-07-25-workspace-ui-product-flow.md). Source: [`packages/workspace/workspace/src/types.ts`](../../packages/workspace/workspace/src/types.ts) diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index 3504f9391e..e800d15107 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -2,7 +2,7 @@ [English](workspace.md) | 中文 -工作区(workspace)是用户工作目录的持久记录:一个建立在规范路径之上的稳定 id、一个显示标题,以及归属于它的会话的有序账本。该子系统是单个包(package)([dsh-workspace](../../packages/workspace/workspace),`ctx.workspaceRegistry`)——一项宿主侧可选能力,不属于 agent loop(智能体循环)主干,并且对模型不可见(没有工具、没有提示词文本、没有会话事件)。它通过[存储领域数据形式](storage.zh.md)存储自己的记录,并对照 [`SessionHeader.cwd`](persistence.zh.md#sessionheader--metadata-beside-the-log) 校验会话成员资格,因此 `storageDomain` 与 `sessionPersistence` 是必需的启动依赖:持久化这一依赖不可用时,插件保持 pending,而不是把这种不可用误当作空历史。设计记录:[领域 KV 存储 Agent Note(agent 决策记录)](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md);引导与 GUI 顺序:[Workspace UI 产品流程 Agent Note](../../.agents/notes/archived/feature/2026-07-25-workspace-ui-product-flow.md)。 +工作区(workspace)是用户工作目录的持久记录:一个建立在规范路径之上的稳定 id、一个显示标题,以及归属于它的会话的有序账本。该子系统是单个包(package)([dsh-workspace](../../packages/workspace/workspace),`ctx.workspaceRegistry`)——一项宿主侧可选能力,不属于 agent loop(智能体循环)主干,并且自身不增加模型可见内容(没有工具、没有提示词文本、没有会话事件);可选的[列表工具](../../packages/session-query/tool-session-list)会把 Workspace ID、标题与路径提供给获准使用它们的模型。它通过[存储领域数据形式](storage.zh.md)存储自己的记录,并对照 [`SessionHeader.cwd`](persistence.zh.md#sessionheader--metadata-beside-the-log) 校验会话成员资格,因此 `storageDomain` 与 `sessionPersistence` 是必需的启动依赖:持久化这一依赖不可用时,插件保持 pending,而不是把这种不可用误当作空历史。设计记录:[领域 KV 存储 Agent Note(agent 决策记录)](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md);引导与 GUI 顺序:[Workspace UI 产品流程 Agent Note](../../.agents/notes/archived/feature/2026-07-25-workspace-ui-product-flow.md)。 源码:[`packages/workspace/workspace/src/types.ts`](../../packages/workspace/workspace/src/types.ts) diff --git a/packages/session-query/tool-session-list/README.i18n.yaml b/packages/session-query/tool-session-list/README.i18n.yaml index d5264c53d9..2c3d1b503c 100644 --- a/packages/session-query/tool-session-list/README.i18n.yaml +++ b/packages/session-query/tool-session-list/README.i18n.yaml @@ -48,8 +48,8 @@ en: 0e201fbbe37798d8 zh: fd4bd41e7393c234 /deepseek-ai-dsh-tool-session-list/known-limitations-and-deferred-work: - en: f0b57c2f2e7a0984 - zh: ed80800cb0d021c8 + en: 2c53c1fc603e0ff2 + zh: 99a58f1e0e3c27fc /deepseek-ai-dsh-tool-session-list/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/session-query/tool-session-list/README.md b/packages/session-query/tool-session-list/README.md index 3d9cab0fd4..f487684915 100644 --- a/packages/session-query/tool-session-list/README.md +++ b/packages/session-query/tool-session-list/README.md @@ -111,6 +111,8 @@ These constraints affect consumers of the lists. - **Cold metadata can be missing or stale** — listing never rebuilds it by reading the full log. A `null` title can mean either no title or unavailable title metadata. - **Pagination is not a stable snapshot** — concurrent registry or Session changes can move entries between calls. Session listing reads every candidate before selecting a page, so the page size does not bound total work; an unscoped call scales with the Session count. +- **Blank sessions are listed** — a Session without a turn, such as a Workspace's unused new Session, is a regular result; its `updated_at` equals `created_at` and its title is usually `null`. +- **Unscoped listing has unit coverage only** — the recorded headless replay passes `workspace_id` on every `list_session` call, so enumeration without a Workspace runs only in unit tests. - **Metadata access is runtime-wide** — callers needing per-agent Workspace authorization require a separately defined access policy before these tools are enabled for them. diff --git a/packages/session-query/tool-session-list/README.zh.md b/packages/session-query/tool-session-list/README.zh.md index 023374121b..e11f949f77 100644 --- a/packages/session-query/tool-session-list/README.zh.md +++ b/packages/session-query/tool-session-list/README.zh.md @@ -111,6 +111,8 @@ kind: "package-reference" - **冷元数据可能缺失或过期**——列表不会通过读取完整日志重建它。标题为 `null` 可能表示没有标题,也可能表示标题元数据不可用。 - **分页不是稳定快照**——并发的注册表或 Session 变化可能让条目在多次调用间移动。会话列表先读取全部候选项,再选取一页,因此每页大小不限制总工作量;不指定范围的调用随 Session 总数增长。 +- **空白会话也会列出**——还没有 turn 的 Session(例如 Workspace 中未使用的新 Session)是普通结果;它的 `updated_at` 等于 `created_at`,标题通常为 `null`。 +- **不指定范围的列表只有单测覆盖**——录制的 headless 回放中每次 `list_session` 调用都带 `workspace_id`,因此不指定 Workspace 的枚举只在单元测试中运行。 - **元数据访问覆盖整个运行时**——需要逐 agent Workspace 授权的调用者,必须先定义独立的访问策略,再为其启用这些工具。 diff --git a/packages/session-query/tool-session-list/src/index.ts b/packages/session-query/tool-session-list/src/index.ts index 139b50a023..f0c2f84b8d 100644 --- a/packages/session-query/tool-session-list/src/index.ts +++ b/packages/session-query/tool-session-list/src/index.ts @@ -5,7 +5,7 @@ import type { Context } from '@deepseek-ai/cordis' import { defineTool } from '@deepseek-ai/dsh-tools' -import { listSessions, listWorkspaces } from './list.ts' +import { DEFAULT_PAGE_LIMIT, listSessions, listWorkspaces, MAX_PAGE_LIMIT } from './list.ts' /** Cordis plugin identity. */ export const name = 'tool-session-list' @@ -13,7 +13,7 @@ export const name = 'tool-session-list' export const inject = ['tools', 'sessions', 'sessionQuery', 'workspaceRegistry', 'sessionProjections'] const pagination = { - limit: { type: 'integer', description: 'Maximum entries to return, from 1 to 100. Defaults to 20.' }, + limit: { type: 'integer', description: `Maximum entries to return, from 1 to ${String(MAX_PAGE_LIMIT)}. Defaults to ${String(DEFAULT_PAGE_LIMIT)}.` }, offset: { type: 'integer', description: 'Number of matching entries to skip. Defaults to 0.' }, } as const @@ -44,7 +44,7 @@ export function apply(ctx: Context): void { render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], }, isConcurrencySafe: () => true, - execute: (args, exec) => Promise.resolve(listWorkspaces(ctx, args, exec.signal)), + execute: async (args, exec) => listWorkspaces(ctx, args, exec.signal), presentCall: args => ({ card: 'generic', title: 'List workspaces', kind: 'read', rawInput: args }), })) ctx.tools.register(defineTool({ diff --git a/packages/session-query/tool-session-list/src/list.ts b/packages/session-query/tool-session-list/src/list.ts index a21e68e7b5..6f8e9b3175 100644 --- a/packages/session-query/tool-session-list/src/list.ts +++ b/packages/session-query/tool-session-list/src/list.ts @@ -35,16 +35,21 @@ interface SessionListItem { updated_at: string } +/** Entries per page when the model passes no `limit`; part of the model-visible schema. */ +export const DEFAULT_PAGE_LIMIT = 20 +/** Largest accepted `limit`; part of the model-visible schema. */ +export const MAX_PAGE_LIMIT = 100 + /** * Resolve pagination before reading any registry or persistence data. * @param input - model pagination arguments. * @returns the validated count and starting index. */ export function resolvePage(input: PageInput): { limit: number; offset: number } { - const limit = input.limit ?? 20 + const limit = input.limit ?? DEFAULT_PAGE_LIMIT const offset = input.offset ?? 0 - if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) { - throw new ToolArgsError(['limit must be an integer from 1 to 100']) + if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_PAGE_LIMIT) { + throw new ToolArgsError([`limit must be an integer from 1 to ${String(MAX_PAGE_LIMIT)}`]) } if (!Number.isSafeInteger(offset) || offset < 0) { throw new ToolArgsError(['offset must be a non-negative safe integer']) @@ -99,7 +104,7 @@ export async function listSessions( headers = workspace.getSessionHeaders() } const archived = new Set(ctx.workspaceRegistry.archivedSessionIds) - const items = [] + const items: Array & { updatedAt: number }> = [] for (const header of headers) { if (header.origin === 'subagent') continue if (archived.has(header.id) !== (input.archived ?? false)) continue diff --git a/packages/workspace/workspace/README.i18n.yaml b/packages/workspace/workspace/README.i18n.yaml index cd426494c8..1f922bc5f3 100644 --- a/packages/workspace/workspace/README.i18n.yaml +++ b/packages/workspace/workspace/README.i18n.yaml @@ -9,8 +9,8 @@ en: 7a12adba4e7766e3 zh: f6d5c8374f4512c8 /deepseek-ai-dsh-workspace/summary: - en: 30aea62cabd8e8a8 - zh: b22b30ef08fd4713 + en: 587ea2786e0c12a6 + zh: 6bb61ba4379886b4 /deepseek-ai-dsh-workspace/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb diff --git a/packages/workspace/workspace/README.md b/packages/workspace/workspace/README.md index a3abb7fbca..2237c64c31 100644 --- a/packages/workspace/workspace/README.md +++ b/packages/workspace/workspace/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Use this package to keep an ordered, persistent list of project directories and the sessions run in each directory. Hosts can build project sidebars, hide sessions from grouping without deleting their histories, and remove projects without deleting folders, files, or sessions. Re-adding a removed directory creates a fresh project; an existing project's sessions stay grouped when its directory disappears. Choose it for GUI or host workflows that need durable project grouping; it is invisible to models and adds no prompt or request-context cost, but requires session persistence and storage backends. +Use this package to keep an ordered, persistent list of project directories and the sessions run in each directory. Hosts can build project sidebars, hide sessions from grouping without deleting their histories, and remove projects without deleting folders, files, or sessions. Re-adding a removed directory creates a fresh project; an existing project's sessions stay grouped when its directory disappears. Choose it for GUI or host workflows that need durable project grouping; it adds no model-visible surface or prompt or request-context cost of its own (the optional [listing tools](../../session-query/tool-session-list/README.md) expose Workspace metadata to models), but requires session persistence and storage backends. ## Table of Contents diff --git a/packages/workspace/workspace/README.zh.md b/packages/workspace/workspace/README.zh.md index 6990a70857..9bbff74562 100644 --- a/packages/workspace/workspace/README.zh.md +++ b/packages/workspace/workspace/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -使用此包可以维护一个有序、持久的项目目录列表,以及在每个目录中运行的会话。宿主可以构建项目侧边栏、在不删除历史的情况下把会话从分组中隐藏,并在不删除文件夹、文件或会话的情况下移除项目。重新添加已移除的目录会创建一个全新项目;已有项目的目录消失时,其会话仍保持原分组。需要持久项目分组的 GUI 或宿主工作流适合使用它;它对模型不可见,不增加提示词或请求上下文成本,但需要会话持久化与存储后端。 +使用此包可以维护一个有序、持久的项目目录列表,以及在每个目录中运行的会话。宿主可以构建项目侧边栏、在不删除历史的情况下把会话从分组中隐藏,并在不删除文件夹、文件或会话的情况下移除项目。重新添加已移除的目录会创建一个全新项目;已有项目的目录消失时,其会话仍保持原分组。需要持久项目分组的 GUI 或宿主工作流适合使用它;它自身不增加模型可见内容,也不增加提示词或请求上下文成本(可选的[列表工具](../../session-query/tool-session-list/README.zh.md)会向模型提供 Workspace 元数据),但需要会话持久化与存储后端。 ## 目录 From 3e42e0f61716b8da672b71b73b0ec1bdfa697906 Mon Sep 17 00:00:00 2001 From: ZiyaZhang <199893125+ZiyaZhang@users.noreply.github.com> Date: Sun, 15 Nov 2026 23:26:13 -0800 Subject: [PATCH 37/48] feat(ui-schedule): recommend a weekly review task The empty automation page lists an eighth built-in recommendation, Weekly review, after Daily brief. Its request asks for a Friday 16:00 task that reviews the week's changes in the current workspace, lists unfinished work and what to do first next week, covers commits and pull requests when the workspace is a code repository, and summarizes in the conversation without changing workspace files. Its tile draws a calendar with a check in the style of the other glyphs, and the copy covers all eight UI languages. --- .../schedule-recommendations-en.expected.md | 2 ++ .../schedule-recommendations-zh.expected.md | 2 ++ apps/web/tests/schedule-manual.e2e.ts | 2 +- packages/client/ui-schedule/README.i18n.yaml | 4 +-- packages/client/ui-schedule/README.md | 2 +- packages/client/ui-schedule/README.zh.md | 2 +- .../src/client/RecommendationArtwork.tsx | 17 ++++++++++ .../src/client/ScheduleRecommendations.tsx | 3 +- .../src/client/recommendation-locales.ts | 32 +++++++++++++++++++ .../tests/browser-plugin.client.spec.ts | 6 ++-- .../tests/task-manager-page.client.spec.tsx | 4 +-- 11 files changed, 65 insertions(+), 11 deletions(-) diff --git a/apps/web/tests/expected/schedule-recommendations-en.expected.md b/apps/web/tests/expected/schedule-recommendations-en.expected.md index 57a00d021e..b11eeadea2 100644 --- a/apps/web/tests/expected/schedule-recommendations-en.expected.md +++ b/apps/web/tests/expected/schedule-recommendations-en.expected.md @@ -3,6 +3,8 @@ - list: - listitem: - button "Daily brief": Daily brief Recent changes in the workspace and what needs follow-up, with what to do first today. Weekdays at 9:00 + - listitem: + - button "Weekly review": Weekly review This week's changes in the workspace, with loose ends and what to do first next week. Fridays at {{clock}} - listitem: - button "Issue scan": Issue scan Sort new issues into bugs, requests, and questions, and flag duplicates and ones that need a reply. Weekdays at {{clock}} - listitem: diff --git a/apps/web/tests/expected/schedule-recommendations-zh.expected.md b/apps/web/tests/expected/schedule-recommendations-zh.expected.md index 68c90f0426..f4d7e76203 100644 --- a/apps/web/tests/expected/schedule-recommendations-zh.expected.md +++ b/apps/web/tests/expected/schedule-recommendations-zh.expected.md @@ -3,6 +3,8 @@ - list: - listitem: - button "每日简报": 每日简报 汇总工作区最近的变化和待跟进的事,列出今天先做什么。 工作日 9:00 + - listitem: + - button "每周回顾": 每周回顾 回顾这周工作区的变化,列出没收尾的事和下周先做什么。 周五 {{clock}} - listitem: - button "Issue 扫描": Issue 扫描 把新开的 issue 分成 bug、需求、提问,标出重复的和需要回复的。 工作日 {{clock}} - listitem: diff --git a/apps/web/tests/schedule-manual.e2e.ts b/apps/web/tests/schedule-manual.e2e.ts index abf438f7e8..46b52df29f 100644 --- a/apps/web/tests/schedule-manual.e2e.ts +++ b/apps/web/tests/schedule-manual.e2e.ts @@ -71,7 +71,7 @@ it.each([ const recommendations = manager.getByRole('region', { name: copy.heading, exact: true }) const recommendation = recommendations.getByRole('button', { name: copy.title, exact: true }) await recommendation.waitFor() - expect(await recommendations.getByRole('button').count()).toBe(7) + expect(await recommendations.getByRole('button').count()).toBe(8) if (draft === '') { expect(await recommendationColumns(recommendations)).toBe(2) await compareOrRefreshGolden( diff --git a/packages/client/ui-schedule/README.i18n.yaml b/packages/client/ui-schedule/README.i18n.yaml index 3745e445aa..e851c470e1 100644 --- a/packages/client/ui-schedule/README.i18n.yaml +++ b/packages/client/ui-schedule/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 405b30feaf48c087 /deepseek-ai-dsh-client-ui-schedule/use-this-package: - en: ff9e353f9330cf8d - zh: 61b0656261a69d4d + en: ac56ad367cd6624f + zh: 47642dc177dd0b58 /deepseek-ai-dsh-client-ui-schedule/use-this-package/time-zone-data-source: en: 4005b800e930f581 zh: ccb9318dad7f7e8f diff --git a/packages/client/ui-schedule/README.md b/packages/client/ui-schedule/README.md index b313e1e810..0776f904f4 100644 --- a/packages/client/ui-schedule/README.md +++ b/packages/client/ui-schedule/README.md @@ -27,7 +27,7 @@ The Automation tasks page and right Sidebar task tab use the same editor for tas Below 768px, the task list uses 20px horizontal insets, matching the Plugins page. -The shipped Web composition mounts `ui-schedule` with Host Schedule. The Automation tasks sidebar entry opens the task list without selecting or activating a Session. New and the adjacent menu's Create in a session action both open a new conversation with a short task-creation prompt in the current UI language, ready for the user to complete and send. When a blank conversation is reused, the prompt is appended on a new line, preserving its text, inline references, and attachments. The same menu offers Create manually. Manual creation opens the same editor as an existing task, validates required fields, and saves a task without starting an Agent or sending the instruction. A failed request leaves the form and its values visible. The empty state shows a decorative document-and-clock illustration whose colors follow the theme. Below the empty Enabled and All views, seven built-in recommended tasks appear in two columns, each with a glyph, title, description, and default run time. Choosing one opens a new conversation with that task's request prefilled in the same way. Each glyph tile takes the empty-state artwork's background color, and its glyph is drawn in blue with a light blue fill. +The shipped Web composition mounts `ui-schedule` with Host Schedule. The Automation tasks sidebar entry opens the task list without selecting or activating a Session. New and the adjacent menu's Create in a session action both open a new conversation with a short task-creation prompt in the current UI language, ready for the user to complete and send. When a blank conversation is reused, the prompt is appended on a new line, preserving its text, inline references, and attachments. The same menu offers Create manually. Manual creation opens the same editor as an existing task, validates required fields, and saves a task without starting an Agent or sending the instruction. A failed request leaves the form and its values visible. The empty state shows a decorative document-and-clock illustration whose colors follow the theme. Below the empty Enabled and All views, eight built-in recommended tasks appear in two columns, each with a glyph, title, description, and default run time. Choosing one opens a new conversation with that task's request prefilled in the same way. Each glyph tile takes the empty-state artwork's background color, and its glyph is drawn in blue with a light blue fill. Enabled, Paused, Ended, and All filters combine with text search over the title, prompt, and linked Session id; the page starts on Enabled. The search-row menu clears all ended tasks after confirmation, preserving active and paused tasks. Selecting a task opens its editable Rules / Records page. Save is enabled only for valid, meaningful changes and sends only changed fields with `expectedUpdatedAt`, or `null` when no stored revision exists. The fields stay editable after saving. Unsaved drafts survive navigation between tasks and away from the page. A conflict retains the whole draft and disables Save. Review with my edits reapplies the changed field groups to the latest values for review before saving; Discard replaces the draft with the latest stored values. For a new task, Discard closes the editor. Late responses cannot change another task's detail. Coarse-pointer search, instruction, and timing fields use 16px text to prevent focus zoom on iOS Safari. diff --git a/packages/client/ui-schedule/README.zh.md b/packages/client/ui-schedule/README.zh.md index 3e108eb805..775887d4e7 100644 --- a/packages/client/ui-schedule/README.zh.md +++ b/packages/client/ui-schedule/README.zh.md @@ -27,7 +27,7 @@ kind: "package-reference" 宽度小于 768px 时,任务列表使用 20px 的左右内边距,与插件页一致。 -发布的 Web 组合将 `ui-schedule` 与宿主 Schedule 一起挂载。自动化任务侧栏入口打开任务列表,不选择或激活会话。“新建”和相邻菜单的“在会话中创建”都会进入新会话,按当前界面语言预填简短的任务创建提示,供用户补充并发送。若复用空白会话,提示会另起一行追加,保留原有文本、行内引用和附件。该菜单还提供“手动创建”。手动创建与已有任务打开同一编辑页,校验必填项并保存任务,不启动 Agent 或发送指令。请求失败时保留表单和已填内容。空态显示装饰性的文档与时钟插图,其颜色随主题变化。“已开启”和“全部”的空态下方以两列列出七个内置推荐任务,每项显示图标、标题、说明和默认运行时间。点击其中一项会同样进入新会话,并预填该任务的请求。推荐图标块使用空态插图的背景色,图标为蓝色线条加浅蓝填充。 +发布的 Web 组合将 `ui-schedule` 与宿主 Schedule 一起挂载。自动化任务侧栏入口打开任务列表,不选择或激活会话。“新建”和相邻菜单的“在会话中创建”都会进入新会话,按当前界面语言预填简短的任务创建提示,供用户补充并发送。若复用空白会话,提示会另起一行追加,保留原有文本、行内引用和附件。该菜单还提供“手动创建”。手动创建与已有任务打开同一编辑页,校验必填项并保存任务,不启动 Agent 或发送指令。请求失败时保留表单和已填内容。空态显示装饰性的文档与时钟插图,其颜色随主题变化。“已开启”和“全部”的空态下方以两列列出八个内置推荐任务,每项显示图标、标题、说明和默认运行时间。点击其中一项会同样进入新会话,并预填该任务的请求。推荐图标块使用空态插图的背景色,图标为蓝色线条加浅蓝填充。 “已开启”“已暂停”“已结束”“全部”筛选结合标题、指令和关联会话 id 搜索,默认显示已开启任务。搜索行菜单在确认后清除全部已结束任务,保留已开启和已暂停任务。选择任务直接打开可编辑的“规则 / 任务运行记录”页面。只有字段有效且有实际修改时才能保存;保存只发送变更字段及 `expectedUpdatedAt`,存储版本缺失时发送 `null`。保存后字段保持可编辑。切换任务或离开页面时保留未保存的草稿。冲突保留整份草稿并禁用保存。“保留修改并复核”将改过的字段组应用到最新值,供保存前复核;“放弃”用最新存储值替换草稿。对于新任务,“放弃”关闭编辑页。迟到响应不会改变其他任务详情。粗指针设备的搜索、指令和时间字段使用 16px 字号,避免 iOS Safari 聚焦时缩放。 diff --git a/packages/client/ui-schedule/src/client/RecommendationArtwork.tsx b/packages/client/ui-schedule/src/client/RecommendationArtwork.tsx index 909ec2f016..0c5ad0ebde 100644 --- a/packages/client/ui-schedule/src/client/RecommendationArtwork.tsx +++ b/packages/client/ui-schedule/src/client/RecommendationArtwork.tsx @@ -38,6 +38,23 @@ export function SunriseGlyph(props: TileGlyphProps): ReactNode { ) } +/** + * Calendar page with a check: a week in review. + * @param props - class of the root SVG. + * @returns the glyph. + */ +export function CalendarCheckGlyph(props: TileGlyphProps): ReactNode { + return ( + + + + + + + + ) +} + /** * Open-issue mark: a ring with a center dot. * @param props - class of the root SVG. diff --git a/packages/client/ui-schedule/src/client/ScheduleRecommendations.tsx b/packages/client/ui-schedule/src/client/ScheduleRecommendations.tsx index b130a538a4..8f3accdd29 100644 --- a/packages/client/ui-schedule/src/client/ScheduleRecommendations.tsx +++ b/packages/client/ui-schedule/src/client/ScheduleRecommendations.tsx @@ -3,13 +3,14 @@ import { useId, type ReactNode } from 'react' import { Button, IconClockOutlineRegular, IconPlusOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { TaskManagerKey } from './task-manager-locales.ts' import { - BranchGlyph, CloudSunGlyph, DumbbellGlyph, IssueGlyph, NewspaperGlyph, PluginCheckGlyph, + BranchGlyph, CalendarCheckGlyph, CloudSunGlyph, DumbbellGlyph, IssueGlyph, NewspaperGlyph, PluginCheckGlyph, SunriseGlyph, type TileGlyphProps, } from './RecommendationArtwork.tsx' import css from './TaskManagerPage.module.css' const RECOMMENDATIONS = [ { id: 'dailyBrief', Glyph: SunriseGlyph }, + { id: 'weeklyReview', Glyph: CalendarCheckGlyph }, { id: 'issueScan', Glyph: IssueGlyph }, { id: 'pluginCompat', Glyph: PluginCheckGlyph }, { id: 'topicTracking', Glyph: NewspaperGlyph }, diff --git a/packages/client/ui-schedule/src/client/recommendation-locales.ts b/packages/client/ui-schedule/src/client/recommendation-locales.ts index ec965a647a..ab52e0392c 100644 --- a/packages/client/ui-schedule/src/client/recommendation-locales.ts +++ b/packages/client/ui-schedule/src/client/recommendation-locales.ts @@ -7,6 +7,10 @@ export const recommendationEn = { 'recommend.dailyBrief.description': 'Recent changes in the workspace and what needs follow-up, with what to do first today.', 'recommend.dailyBrief.schedule': 'Weekdays at 9:00', 'recommend.dailyBrief.prompt': 'Create an automation task named "Daily brief": every weekday at 9:00, review the last 24 hours of changes in the current workspace and list what needs my follow-up and what to do first today; when the workspace is a code repository, also cover new commits, pull requests awaiting my review, and failing CI.', + 'recommend.weeklyReview.title': 'Weekly review', + 'recommend.weeklyReview.description': 'This week\'s changes in the workspace, with loose ends and what to do first next week.', + 'recommend.weeklyReview.schedule': 'Fridays at 16:00', + 'recommend.weeklyReview.prompt': 'Create an automation task named "Weekly review": every Friday at 16:00, review this week\'s changes in the current workspace, summarize what got done, and list what is still unfinished and what to do first next week; when the workspace is a code repository, also cover this week\'s commits, merged pull requests, and pull requests still open. Summarize here only; do not change files in the workspace.', 'recommend.issueScan.title': 'Issue scan', 'recommend.issueScan.description': 'Sort new issues into bugs, requests, and questions, and flag duplicates and ones that need a reply.', 'recommend.issueScan.schedule': 'Weekdays at 10:00', @@ -40,6 +44,10 @@ export const recommendationZh: Record = { 'recommend.dailyBrief.description': '汇总工作区最近的变化和待跟进的事,列出今天先做什么。', 'recommend.dailyBrief.schedule': '工作日 9:00', 'recommend.dailyBrief.prompt': '创建一个名为「每日简报」的自动化任务:每个工作日 9:00 查看当前工作区过去 24 小时的变化,列出需要我跟进的事和今天先做的事;工作区是代码仓库时,也看新提交、待我评审的 PR 和失败的 CI。', + 'recommend.weeklyReview.title': '每周回顾', + 'recommend.weeklyReview.description': '回顾这周工作区的变化,列出没收尾的事和下周先做什么。', + 'recommend.weeklyReview.schedule': '周五 16:00', + 'recommend.weeklyReview.prompt': '创建一个名为「每周回顾」的自动化任务:每周五 16:00 回顾当前工作区这一周的变化,总结这周做了什么,列出还没收尾的事和下周先做的事;工作区是代码仓库时,也看这周的提交、合入的 PR 和还开着的 PR。只在这里汇总,不改工作区里的文件。', 'recommend.issueScan.title': 'Issue 扫描', 'recommend.issueScan.description': '把新开的 issue 分成 bug、需求、提问,标出重复的和需要回复的。', 'recommend.issueScan.schedule': '工作日 10:00', @@ -73,6 +81,10 @@ export const recommendationJa: Record = { 'recommend.dailyBrief.description': 'ワークスペースの最近の変化とフォローが必要なことをまとめ、今日最初にやることを挙げます。', 'recommend.dailyBrief.schedule': '平日 9:00', 'recommend.dailyBrief.prompt': '「デイリーブリーフィング」という名前の自動化タスクを作成してください。平日は毎日 9:00 に、現在のワークスペースの過去24時間の変化を確認し、私がフォローすべきことと今日最初にやることを挙げてください。ワークスペースがコードリポジトリの場合は、新しいコミット、私のレビュー待ちのプルリクエスト、失敗した CI も確認してください。', + 'recommend.weeklyReview.title': '週次レビュー', + 'recommend.weeklyReview.description': '今週のワークスペースの変化を振り返り、やり残したことと来週最初にやることを挙げます。', + 'recommend.weeklyReview.schedule': '毎週金曜日 16:00', + 'recommend.weeklyReview.prompt': '「週次レビュー」という名前の自動化タスクを作成してください。毎週金曜日の 16:00 に、現在のワークスペースの今週の変化を振り返り、今週やったことをまとめて、まだ終わっていないことと来週最初にやることを挙げてください。ワークスペースがコードリポジトリの場合は、今週のコミット、マージされたプルリクエスト、まだオープンのプルリクエストも確認してください。まとめはここでだけ行い、ワークスペースのファイルは変更しないでください。', 'recommend.issueScan.title': 'Issue スキャン', 'recommend.issueScan.description': '新しい Issue をバグ・要望・質問に分類し、重複しているものと返信が必要なものを指摘します。', 'recommend.issueScan.schedule': '平日 10:00', @@ -106,6 +118,10 @@ export const recommendationEs: Record = { 'recommend.dailyBrief.description': 'Cambios recientes en el espacio de trabajo y pendientes de seguimiento, con lo primero que hacer hoy.', 'recommend.dailyBrief.schedule': 'De lunes a viernes a las 9:00', 'recommend.dailyBrief.prompt': 'Crea una tarea de automatización llamada «Resumen diario»: de lunes a viernes a las 9:00, revisa los cambios de las últimas 24 horas en el espacio de trabajo actual y enumera lo que requiere mi seguimiento y lo primero que debo hacer hoy; si el espacio de trabajo es un repositorio de código, incluye también los commits nuevos, los pull requests pendientes de mi revisión y los fallos de CI.', + 'recommend.weeklyReview.title': 'Revisión semanal', + 'recommend.weeklyReview.description': 'Cambios de la semana en el espacio de trabajo, con lo pendiente y lo primero que hacer la próxima semana.', + 'recommend.weeklyReview.schedule': 'Los viernes a las 16:00', + 'recommend.weeklyReview.prompt': 'Crea una tarea de automatización llamada «Revisión semanal»: todos los viernes a las 16:00, repasa los cambios de esta semana en el espacio de trabajo actual, resume lo que se hizo y enumera lo que queda pendiente y lo primero que debo hacer la próxima semana; si el espacio de trabajo es un repositorio de código, incluye también los commits de la semana, los pull requests fusionados y los que siguen abiertos. Haz el resumen solo aquí; no modifiques archivos del espacio de trabajo.', 'recommend.issueScan.title': 'Revisión de issues', 'recommend.issueScan.description': 'Clasifica los issues nuevos en bugs, solicitudes y preguntas, y señala los duplicados y los que necesitan respuesta.', 'recommend.issueScan.schedule': 'De lunes a viernes a las 10:00', @@ -139,6 +155,10 @@ export const recommendationFr: Record = { 'recommend.dailyBrief.description': 'Changements récents dans l\'espace de travail et points à suivre, avec les priorités du jour.', 'recommend.dailyBrief.schedule': 'Du lundi au vendredi à 9:00', 'recommend.dailyBrief.prompt': 'Crée une tâche d\'automatisation nommée « Résumé quotidien » : du lundi au vendredi à 9:00, passe en revue les changements des dernières 24 heures dans l\'espace de travail actuel et liste ce qui demande mon suivi et ce que je dois faire en premier aujourd\'hui ; si l\'espace de travail est un dépôt de code, couvre aussi les nouveaux commits, les pull requests en attente de ma revue et les échecs de CI.', + 'recommend.weeklyReview.title': 'Bilan hebdomadaire', + 'recommend.weeklyReview.description': 'Changements de la semaine dans l\'espace de travail, avec ce qui reste à terminer et les priorités de la semaine prochaine.', + 'recommend.weeklyReview.schedule': 'Le vendredi à 16:00', + 'recommend.weeklyReview.prompt': 'Crée une tâche d\'automatisation nommée « Bilan hebdomadaire » : tous les vendredis à 16:00, passe en revue les changements de la semaine dans l\'espace de travail actuel, résume ce qui a été fait et liste ce qui reste à terminer et ce que je dois faire en premier la semaine prochaine ; si l\'espace de travail est un dépôt de code, couvre aussi les commits de la semaine, les pull requests fusionnées et celles encore ouvertes. Fais le résumé ici uniquement ; ne modifie pas les fichiers de l\'espace de travail.', 'recommend.issueScan.title': 'Analyse des issues', 'recommend.issueScan.description': 'Trie les nouvelles issues en bugs, demandes et questions, et signale les doublons et celles qui nécessitent une réponse.', 'recommend.issueScan.schedule': 'Du lundi au vendredi à 10:00', @@ -172,6 +192,10 @@ export const recommendationDe: Record = { 'recommend.dailyBrief.description': 'Aktuelle Änderungen im Arbeitsbereich und offene Punkte, dazu, was heute zuerst ansteht.', 'recommend.dailyBrief.schedule': 'Mo–Fr um 9:00', 'recommend.dailyBrief.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Tagesüberblick“: Prüfe montags bis freitags um 9:00 Uhr die Änderungen der letzten 24 Stunden im aktuellen Arbeitsbereich und liste auf, was ich nachverfolgen muss und was heute zuerst ansteht; ist der Arbeitsbereich ein Code-Repository, berücksichtige auch neue Commits, auf mein Review wartende Pull Requests und fehlgeschlagene CI-Läufe.', + 'recommend.weeklyReview.title': 'Wochenrückblick', + 'recommend.weeklyReview.description': 'Änderungen der Woche im Arbeitsbereich, dazu offene Punkte und was nächste Woche zuerst ansteht.', + 'recommend.weeklyReview.schedule': 'Freitags um 16:00', + 'recommend.weeklyReview.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Wochenrückblick“: Blicke freitags um 16:00 Uhr auf die Änderungen dieser Woche im aktuellen Arbeitsbereich zurück, fasse zusammen, was erledigt wurde, und liste auf, was noch offen ist und was nächste Woche zuerst ansteht; ist der Arbeitsbereich ein Code-Repository, berücksichtige auch die Commits dieser Woche sowie gemergte und noch offene Pull Requests. Fasse alles nur hier zusammen; ändere keine Dateien im Arbeitsbereich.', 'recommend.issueScan.title': 'Issue-Sichtung', 'recommend.issueScan.description': 'Sortiert neue Issues in Bugs, Feature-Wünsche und Fragen und hebt Duplikate sowie Issues hervor, die eine Antwort brauchen.', 'recommend.issueScan.schedule': 'Mo–Fr um 10:00', @@ -205,6 +229,10 @@ export const recommendationRu: Record = { 'recommend.dailyBrief.description': 'Недавние изменения в рабочей области и то, что требует внимания, а также первоочередные дела на сегодня.', 'recommend.dailyBrief.schedule': 'По будням в 9:00', 'recommend.dailyBrief.prompt': 'Создай задачу автоматизации под названием «Ежедневная сводка»: по будням в 9:00 просматривай изменения в текущей рабочей области за последние 24 часа и перечисляй, что требует моего внимания и с чего начать сегодня; если рабочая область — репозиторий кода, учитывай также новые коммиты, пул-реквесты, ожидающие моего ревью, и сбои CI.', + 'recommend.weeklyReview.title': 'Еженедельный обзор', + 'recommend.weeklyReview.description': 'Изменения за неделю в рабочем пространстве, незавершённые дела и первоочередные задачи на следующую неделю.', + 'recommend.weeklyReview.schedule': 'По пятницам в 16:00', + 'recommend.weeklyReview.prompt': 'Создай задачу автоматизации под названием «Еженедельный обзор»: по пятницам в 16:00 просматривай изменения за эту неделю в текущем рабочем пространстве, подводи итог сделанного и перечисляй, что ещё не завершено и с чего начать на следующей неделе; если рабочее пространство — репозиторий кода, учитывай также коммиты за неделю, слитые и ещё открытые пул-реквесты. Сводку пиши только здесь; файлы в рабочем пространстве не меняй.', 'recommend.issueScan.title': 'Обзор issues', 'recommend.issueScan.description': 'Делит новые issues на баги, пожелания и вопросы и выделяет дубликаты и те, на которые нужно ответить.', 'recommend.issueScan.schedule': 'По будням в 10:00', @@ -238,6 +266,10 @@ export const recommendationPt: Record = { 'recommend.dailyBrief.description': 'Mudanças recentes no espaço de trabalho e o que precisa de acompanhamento, com o que fazer primeiro hoje.', 'recommend.dailyBrief.schedule': 'Segunda a sexta às 9:00', 'recommend.dailyBrief.prompt': 'Crie uma tarefa de automação chamada “Resumo diário”: de segunda a sexta às 9:00, revise as mudanças das últimas 24 horas no espaço de trabalho atual e liste o que precisa do meu acompanhamento e o que fazer primeiro hoje; se o espaço de trabalho for um repositório de código, inclua também os novos commits, os pull requests aguardando minha revisão e as falhas de CI.', + 'recommend.weeklyReview.title': 'Revisão semanal', + 'recommend.weeklyReview.description': 'Mudanças da semana no espaço de trabalho, com o que ficou pendente e o que fazer primeiro na próxima semana.', + 'recommend.weeklyReview.schedule': 'Sextas às 16:00', + 'recommend.weeklyReview.prompt': 'Crie uma tarefa de automação chamada “Revisão semanal”: toda sexta-feira às 16:00, revise as mudanças desta semana no espaço de trabalho atual, resuma o que foi feito e liste o que ainda está pendente e o que fazer primeiro na próxima semana; se o espaço de trabalho for um repositório de código, inclua também os commits da semana, os pull requests mesclados e os que continuam abertos. Faça o resumo só aqui; não altere arquivos do espaço de trabalho.', 'recommend.issueScan.title': 'Varredura de issues', 'recommend.issueScan.description': 'Classifica as novas issues em bugs, solicitações e perguntas e destaca as duplicadas e as que precisam de resposta.', 'recommend.issueScan.schedule': 'Segunda a sexta às 10:00', diff --git a/packages/client/ui-schedule/tests/browser-plugin.client.spec.ts b/packages/client/ui-schedule/tests/browser-plugin.client.spec.ts index b3a9ef6d76..acc5f78520 100644 --- a/packages/client/ui-schedule/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-schedule/tests/browser-plugin.client.spec.ts @@ -461,14 +461,14 @@ describe('ui-schedule browser half', () => { const panel = injectedFace(ctx.slots.entries('main')[0]!, undefined as never) as TaskManagerInjected for (const dictionary of Object.values(managerLocales)) { const prompts = Object.entries(dictionary).filter(([key]) => key.startsWith('recommend.') && key.endsWith('.prompt')) - expect(prompts).toHaveLength(7) + expect(prompts).toHaveLength(8) for (const [, prompt] of prompts) { expect(prompt).not.toContain('\n') panel.onUseRecommendation(prompt) expect(startSession).toHaveBeenLastCalledWith(undefined, { prompt, whenDraftExists: 'append' }) } } - expect(startSession).toHaveBeenCalledTimes(56) + expect(startSession).toHaveBeenCalledTimes(64) } finally { await fiber.dispose() owner() @@ -479,7 +479,7 @@ describe('ui-schedule browser half', () => { it('states each recommendation\'s shown run time in its request in every language', () => { for (const dictionary of Object.values(managerLocales)) { const schedules = Object.entries(dictionary).filter(([key]) => key.startsWith('recommend.') && key.endsWith('.schedule')) - expect(schedules).toHaveLength(7) + expect(schedules).toHaveLength(8) for (const [key, schedule] of schedules) { const times = schedule.match(/\d{1,2}:\d{2}/g) expect(times).toHaveLength(1) diff --git a/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx b/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx index 33eb9e2628..cc26dccb0d 100644 --- a/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx +++ b/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx @@ -840,8 +840,8 @@ describe('Task manager catalog', () => { expect(emptyNewTaskButton().textContent).toBe(en['empty.action']) }) - const RECOMMENDATION_IDS = ['dailyBrief', 'issueScan', 'pluginCompat', 'topicTracking', 'branchCleanup', - 'weather', 'workout'] as const + const RECOMMENDATION_IDS = ['dailyBrief', 'weeklyReview', 'issueScan', 'pluginCompat', 'topicTracking', + 'branchCleanup', 'weather', 'workout'] as const function recommendations(dictionary: Dictionary = en): HTMLElement | null { return screen.queryByRole('region', { name: dictionary['recommend.heading'] }) From a85b27fdd4398441d6c50a7b89da0dff307e3062 Mon Sep 17 00:00:00 2001 From: Shigma Date: Mon, 16 Nov 2026 15:46:58 +0800 Subject: [PATCH 38/48] fix(cordis): address loader rc.9 review and CI findings --- apps/web/vite.config.ts | 2 + .../guide.i18n.yaml | 14 ++-- .../cordis-loader-entry-validation/guide.md | 4 +- .../guide.zh.md | 4 +- .../app-boot/src/config-schema/collect.ts | 2 +- packages/boot/app-boot/src/index.ts | 13 ++-- .../boot/app-boot/tests/config-dump.spec.ts | 14 ++++ .../boot/app-boot/tests/config-schema.spec.ts | 8 +++ pnpm-lock.yaml | 69 ++----------------- scripts/cordis-entry-yaml.spec.ts | 7 ++ scripts/cordis-loader-rc9.spec.ts | 55 ++++++++++----- vendor/README.md | 5 +- vendor/include/README.md | 2 +- vendor/include/package.json | 2 +- vendor/include/src/index.ts | 27 ++++++-- vendor/loader/README.md | 2 +- 16 files changed, 123 insertions(+), 107 deletions(-) rename docs/upgrade-guide/{v0.2.2-rc.2 => v0.2.2-rc.3}/cordis-loader-entry-validation/guide.i18n.yaml (74%) rename docs/upgrade-guide/{v0.2.2-rc.2 => v0.2.2-rc.3}/cordis-loader-entry-validation/guide.md (77%) rename docs/upgrade-guide/{v0.2.2-rc.2 => v0.2.2-rc.3}/cordis-loader-entry-validation/guide.zh.md (77%) diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 372059dcc9..7aa6d3ab55 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -259,6 +259,8 @@ export default defineConfig({ // internal slot the shell boot fills with the client module loader). 'process.versions.node': '"0.0.0"', 'process.execArgv': '[]', + // vendored loader tree.ts: import() converts drive-letter names only on win32. + 'process.platform': '"browser"', // vendored loader index.ts: envData falls to its default branch. 'process.env.CORDIS_SHARED': 'undefined', }, diff --git a/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.i18n.yaml similarity index 74% rename from docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.i18n.yaml rename to docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.i18n.yaml index 2d20fa39db..491b537557 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.i18n.yaml @@ -1,16 +1,16 @@ # Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading # section, a hash of its English and Chinese blocks outside code blocks and generated regions. # After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.md +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.md /: en: b414093b29c38765 zh: 2a69f37a40e35a99 /loader-validates-entry-options-and-include-parses-yaml-1-2: - en: 0ba0b666924ce1f0 - zh: 0c5668ee67163d00 + en: cf5dc11adadfd1e1 + zh: 4656ed9a0d4e9087 /loader-validates-entry-options-and-include-parses-yaml-1-2/change: - en: b0d2ae6a748cab50 - zh: a2521c4dc48e4d3d + en: b345762ab470b57b + zh: 0f931faf28da0d27 /loader-validates-entry-options-and-include-parses-yaml-1-2/migration: - en: 2c167e1042c952a5 - zh: aec49a7754befae0 + en: ff01b0eddb91d5b1 + zh: 81478d5e1594db65 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.md similarity index 77% rename from docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.md rename to docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.md index 336418a559..cc4ef09ede 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.md @@ -12,7 +12,7 @@ English | [中文](guide.zh.md) `@deepseek-ai/cordis-plugin-loader` now carries upstream Loader 1.0.0-rc.9, and `@deepseek-ai/cordis-plugin-include` carries Include 1.2.0. Hand-written `cordis.yml`, `cordis.patch.yml` and overlay files, and code that calls the Include or Loader exports, are affected: - Include and `parseEntryYaml` parse YAML 1.2 under the core schema instead of the js-yaml JSON schema. A binary integer such as `0b101` now reads as the string `'0b101'`. An empty `!!js` scalar now reads as an empty expression, which evaluates to `undefined`, instead of failing to parse. -- Entry options are validated before an entry is created or updated. `name` must be a string; `group` a boolean; `disabled` a boolean or `!!js` expression; a group's `config` a list; `inject` a string list or a mapping; `isolate` a mapping whose values are `true` or a string. An entry that loaded before with such a value is now rejected and logged, and its siblings still start. An Include file with an entry that is not a mapping is rejected as a whole. Ids containing `:` remain accepted. +- Entry options are validated before an entry is created or updated. `name` must be a string; `group` a boolean; `disabled` a boolean or `!!js` expression; an entry with `group: true` must have a `config` list, even an empty one; `inject` a string list or a mapping; `isolate` a mapping whose values are `true` or a string. An entry that loaded before with such a value is now rejected and logged, and its siblings still start. An Include file with an entry that is not a mapping is rejected as a whole. Ids containing `:` remain accepted. - Parse, entry option and config validation errors name the file position as `file:line:column`. When an entry's own module cannot be found, the error is a `ModuleNotFoundError` without Node's `imported from` part; its `code` is still `ERR_MODULE_NOT_FOUND`. - A patch that replaces a group's `config` brings child entries that later patches can address, and the children it replaces can no longer be patched. - `applyEntryPatches(data, patches, warn)` returns `{ data, index }` instead of the entry list, and writes generated ids into the anonymous entries of a replaced group `config` in `patches`. `parseEntryYaml` throws the `YAMLError` of the `yaml` package instead of a js-yaml `YAMLException`. @@ -21,7 +21,7 @@ English | [中文](guide.zh.md) 1. Write binary integers that must stay numbers in decimal or hexadecimal. 2. Run `dsh --dump-config` for each profile. A parse error now names its line and column; fix the reported value. -3. Start the profile and check the log for `invalid entry options` and `invalid config`. Correct each listed path at the position shown. +3. Add `config: []` to every `group: true` entry without `config`, such as a group whose children all come from patch `insert`. Start the profile and check the log for `invalid entry options` and `invalid config`. Correct each listed path at the position shown. 4. Where a later patch addressed a child of a group whose `config` an earlier patch replaced, check that the child now receives the patch. 5. In code, read `applyEntryPatches(...).data`, and pass `structuredClone(patches)` where the patch list must stay unchanged. Catch parse errors without depending on js-yaml types; `entryYamlErrorPosition(error)` still returns the position. 6. Confirm that `dsh --dump-config` prints the expected entries and that the profile starts without those diagnostics. diff --git a/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.zh.md similarity index 77% rename from docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.zh.md rename to docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.zh.md index d1e3170659..c2e67208c5 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.zh.md @@ -12,7 +12,7 @@ description: "Cordis Loader 1.0.0-rc.9 与 Include 1.2.0 按 YAML 1.2 解析、 `@deepseek-ai/cordis-plugin-loader` 现在包含上游 Loader 1.0.0-rc.9,`@deepseek-ai/cordis-plugin-include` 包含 Include 1.2.0。受影响的是手写的 `cordis.yml`、`cordis.patch.yml` 与 overlay 文件,以及调用 Include 或 Loader 导出的代码: - Include 和 `parseEntryYaml` 按 YAML 1.2 core schema 解析,不再使用 js-yaml 的 JSON schema。`0b101` 这样的二进制整数现在读作字符串 `'0b101'`。空的 `!!js` 标量现在读作空表达式,求值结果为 `undefined`,不再解析失败。 -- 创建或更新条目前会校验条目选项。`name` 必须是字符串;`group` 必须是布尔值;`disabled` 必须是布尔值或 `!!js` 表达式;group 的 `config` 必须是列表;`inject` 必须是字符串列表或映射;`isolate` 必须是映射,其值为 `true` 或字符串。此前能加载但含有这类值的条目现在会被拒绝并记录日志,同级条目仍会启动。Include 文件中只要有一个条目不是映射,整个文件都会被拒绝。含 `:` 的 id 仍然可以使用。 +- 创建或更新条目前会校验条目选项。`name` 必须是字符串;`group` 必须是布尔值;`disabled` 必须是布尔值或 `!!js` 表达式;`group: true` 的条目必须带有 `config` 列表,空列表也要写出;`inject` 必须是字符串列表或映射;`isolate` 必须是映射,其值为 `true` 或字符串。此前能加载但含有这类值的条目现在会被拒绝并记录日志,同级条目仍会启动。Include 文件中只要有一个条目不是映射,整个文件都会被拒绝。含 `:` 的 id 仍然可以使用。 - 解析错误、条目选项错误和配置校验错误都会以 `file:line:column` 指出文件位置。条目自身的模块找不到时,错误为 `ModuleNotFoundError`,不含 Node 的 `imported from` 部分;其 `code` 仍为 `ERR_MODULE_NOT_FOUND`。 - 替换 group `config` 的 patch 带来的子条目可以被后续 patch 定位,被替换掉的子条目则不能再被 patch。 - `applyEntryPatches(data, patches, warn)` 返回 `{ data, index }`,不再直接返回条目列表;它会把生成的 id 写入 `patches` 中被替换的 group `config` 里的匿名条目。`parseEntryYaml` 抛出 `yaml` 包的 `YAMLError`,不再抛出 js-yaml 的 `YAMLException`。 @@ -21,7 +21,7 @@ description: "Cordis Loader 1.0.0-rc.9 与 Include 1.2.0 按 YAML 1.2 解析、 1. 必须保持为数字的二进制整数改写为十进制或十六进制。 2. 对每个 profile 运行 `dsh --dump-config`。解析错误现在会给出行号和列号;按提示修正对应的值。 -3. 启动 profile,检查日志中的 `invalid entry options` 和 `invalid config`,在给出的位置修正列出的每个路径。 +3. 给每个缺少 `config` 的 `group: true` 条目加上 `config: []`,例如子条目全部来自 patch `insert` 的 group。启动 profile,检查日志中的 `invalid entry options` 和 `invalid config`,在给出的位置修正列出的每个路径。 4. 如果后续 patch 针对的是某个 group 的子条目,而该 group 的 `config` 已被前面的 patch 替换,确认该子条目现在会应用这个 patch。 5. 在代码中读取 `applyEntryPatches(...).data`;如果 patch 列表必须保持不变,传入 `structuredClone(patches)`。捕获解析错误时不要依赖 js-yaml 的类型;`entryYamlErrorPosition(error)` 仍会返回错误位置。 6. 确认 `dsh --dump-config` 输出预期的条目,且 profile 启动时不再出现上述诊断。 diff --git a/packages/boot/app-boot/src/config-schema/collect.ts b/packages/boot/app-boot/src/config-schema/collect.ts index dead6f222f..ef57de682e 100644 --- a/packages/boot/app-boot/src/config-schema/collect.ts +++ b/packages/boot/app-boot/src/config-schema/collect.ts @@ -165,7 +165,7 @@ export async function collectConfigSchemas( if (hasNonRecordEntry(rows)) throw new Error(`include ${filename} has an entry that is not a mapping; child declarations are unavailable`) let children: EntryOptions[] try { - children = applyEntryPatches(rows as EntryOptions[], patches, warn(path)).data + children = applyEntryPatches(rows as EntryOptions[], structuredClone(patches), warn(path)).data } catch (error) { throw new Error(`include patches could not be composed for ${filename}; child declarations are unavailable`, { cause: error }) } diff --git a/packages/boot/app-boot/src/index.ts b/packages/boot/app-boot/src/index.ts index 57f6d1584c..3e2fd76cbf 100644 --- a/packages/boot/app-boot/src/index.ts +++ b/packages/boot/app-boot/src/index.ts @@ -670,12 +670,15 @@ export function renderConfigDump( const base = parsed as Parameters[0] // snapshot_k = ONE application of layers 1..k flattened, using the exact // arguments boot passes for that prefix. snapshot_N is the mounted composition. - // The patches are cloned per call: applyEntryPatches clones entries and - // inserted rows but assigns override values such as `config` by reference, - // so each snapshot keeps its own copies of those values. + // Every snapshot reads one clone of the patches: applyEntryPatches writes the + // ids it generates for anonymous children of a replaced group config into + // that clone, so each prefix assigns them the same ids. The snapshots share + // override values by reference and only read them. + const patches = structuredClone(layers.flatMap(layer => layer.patches)) + const ends: number[] = [] + for (const layer of layers) ends.push((ends.at(-1) ?? 0) + layer.patches.length) const snapshot = (count: number, warnings: string[]): ReturnType['data'] => { - const flattened = structuredClone(layers.slice(0, count).flatMap(layer => layer.patches)) - return applyEntryPatches(base, flattened, (message: string, ...args: unknown[]) => { + return applyEntryPatches(base, patches.slice(0, ends[count - 1]), (message: string, ...args: unknown[]) => { // The include logs through cordis's printf-style logger (`%C` = code); a // dump has no logger, so substitute inline for a plain line. let index = 0 diff --git a/packages/boot/app-boot/tests/config-dump.spec.ts b/packages/boot/app-boot/tests/config-dump.spec.ts index c3bc3bf88a..5451edfddf 100644 --- a/packages/boot/app-boot/tests/config-dump.spec.ts +++ b/packages/boot/app-boot/tests/config-dump.spec.ts @@ -143,6 +143,20 @@ describe('renderConfigDump', () => { expect(dump).toContain('# == base.yml, patched by a.yml, b.yml\n- id: g') }) + it('keeps generated ids of anonymous replaced group children across layers', () => { + const dir = tmp() + const base = join(dir, 'base.yml') + writeFileSync(base, '- id: g\n name: ./group.mjs\n group: true\n config: []\n- id: other\n name: ./noop.mjs\n') + const patches = [{ id: 'g', config: [{ name: './noop.mjs' }] }] + const dump = renderConfigDump(NAME, base, [ + { label: 'a.yml', patches }, + { label: 'b.yml', patches: [{ id: 'other', disabled: true }] }, + ], () => {}) + expect(dump).toContain('# == base.yml, patched by a.yml\n- id: g') + expect(dump).toContain('# == base.yml, patched by b.yml\n- id: other') + expect(patches).toEqual([{ id: 'g', config: [{ name: './noop.mjs' }] }]) + }) + it('drops the children of a replaced group config from the patch index', () => { const dir = tmp() const base = join(dir, 'base.yml') diff --git a/packages/boot/app-boot/tests/config-schema.spec.ts b/packages/boot/app-boot/tests/config-schema.spec.ts index 04ae5a3e9c..ca8e52f654 100644 --- a/packages/boot/app-boot/tests/config-schema.spec.ts +++ b/packages/boot/app-boot/tests/config-schema.spec.ts @@ -445,6 +445,14 @@ describe('collectConfigSchemas', () => { expect(result['x-cordis'].complete).toBe(false) }) + it('leaves the caller\'s include patches unchanged when a patch replaces a group config', async () => { + const patches = [{ id: 'group', config: [{ name: 'noop' }] }] + await collectConfigSchemas(profile, [row('cordis:include', { + path: './missing.yml', initial: [{ ...row('cordis:group', []), id: 'group', group: true }], patches, + })], resolution) + expect(patches).toEqual([{ id: 'group', config: [{ name: 'noop' }] }]) + }) + it('does not validate contents of an insertion that Loader skips', async () => { const result = await collectConfigSchemas(profile, [row('cordis:include', { path: './missing.yml', initial: [row('noop')], patches: [{ id: 'missing', insert: [null] }, { config: {} }], diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8371aa7689..4844e76ce9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -18627,7 +18627,7 @@ importers: version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) vitest: specifier: ^4.1.11 - version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.1)(@vitest/coverage-v8@4.1.11)(happy-dom@20.11.6)(jsdom@29.1.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1)) + version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.1)(@vitest/coverage-v8@4.1.11)(happy-dom@20.11.6)(jsdom@29.1.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.0)) devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ @@ -18847,7 +18847,7 @@ importers: version: 4.3.2 vitest: specifier: ^4.1.11 - version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.1)(@vitest/coverage-v8@4.1.11)(happy-dom@20.11.6)(jsdom@29.1.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1)) + version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.1)(@vitest/coverage-v8@4.1.11)(happy-dom@20.11.6)(jsdom@29.1.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.0)) devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ @@ -20212,8 +20212,8 @@ importers: specifier: link:../cosmokit version: link:../cosmokit yaml: - specifier: ^2.9.1 - version: 2.9.1 + specifier: ^2.9.0 + version: 2.9.0 vendor/loader: dependencies: @@ -27960,11 +27960,6 @@ packages: engines: {node: '>= 14.6'} hasBin: true - yaml@2.9.1: - resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} - engines: {node: '>= 14.6'} - hasBin: true - yargs-parser@20.2.9: resolution: {integrity: sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==} engines: {node: '>=10'} @@ -30970,14 +30965,6 @@ snapshots: optionalDependencies: vite: 8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.0) - '@vitest/mocker@4.1.11(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1))': - dependencies: - '@vitest/spy': 4.1.11 - estree-walker: 3.0.3 - magic-string: 0.30.21 - optionalDependencies: - vite: 8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1) - '@vitest/pretty-format@4.1.11': dependencies: tinyrainbow: 3.1.0 @@ -35729,21 +35716,6 @@ snapshots: tsx: 4.23.13 yaml: 2.9.0 - vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1): - dependencies: - lightningcss: 1.33.0 - picomatch: 4.0.7 - postcss: 8.5.28 - rolldown: 1.2.7 - tinyglobby: 0.2.17 - optionalDependencies: - '@types/node': 22.20.1 - esbuild: 0.28.2 - fsevents: 2.3.3 - jiti: 2.7.0 - tsx: 4.23.13 - yaml: 2.9.1 - vitepress-plugin-mermaid@2.0.17(mermaid@11.17.2)(vitepress@1.6.4(@algolia/client-search@5.55.2)(@types/node@22.20.1)(@types/react@18.3.31)(lightningcss@1.33.0)(postcss@8.5.28)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(search-insights@2.17.3)(typescript@6.0.3)): dependencies: mermaid: 11.17.2 @@ -35863,37 +35835,6 @@ snapshots: transitivePeerDependencies: - msw - vitest@4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.1)(@vitest/coverage-v8@4.1.11)(happy-dom@20.11.6)(jsdom@29.1.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1)): - dependencies: - '@vitest/expect': 4.1.11 - '@vitest/mocker': 4.1.11(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1)) - '@vitest/pretty-format': 4.1.11 - '@vitest/runner': 4.1.11 - '@vitest/snapshot': 4.1.11 - '@vitest/spy': 4.1.11 - '@vitest/utils': 4.1.11 - es-module-lexer: 2.1.0 - expect-type: 1.3.0 - magic-string: 0.30.21 - obug: 2.1.3 - pathe: 2.0.3 - picomatch: 4.0.7 - std-env: 4.1.0 - tinybench: 2.9.0 - tinyexec: 1.2.4 - tinyglobby: 0.2.17 - tinyrainbow: 3.1.0 - vite: 8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1) - why-is-node-running: 2.3.0 - optionalDependencies: - '@opentelemetry/api': 1.9.1 - '@types/node': 22.20.1 - '@vitest/coverage-v8': 4.1.11(vitest@4.1.11) - happy-dom: 20.11.6 - jsdom: 29.1.1(@noble/hashes@2.4.0) - transitivePeerDependencies: - - msw - vscode-jsonrpc@5.0.1: {} vscode-jsonrpc@9.0.1: {} @@ -36022,8 +35963,6 @@ snapshots: yaml@2.9.0: {} - yaml@2.9.1: {} - yargs-parser@20.2.9: {} yargs-parser@21.1.1: {} diff --git a/scripts/cordis-entry-yaml.spec.ts b/scripts/cordis-entry-yaml.spec.ts index 13f670487f..d2426d8b49 100644 --- a/scripts/cordis-entry-yaml.spec.ts +++ b/scripts/cordis-entry-yaml.spec.ts @@ -39,5 +39,12 @@ describe('Include YAML dialect', () => { } expect(entryYamlErrorPosition(error)).toEqual({ line: 3, column: 1 }) expect(entryYamlErrorPosition(new Error('other'))).toBeUndefined() + let alias: unknown + try { + parseEntryYaml('- id: a\n config: *missing\n') + } catch (caught) { + alias = caught + } + expect(entryYamlErrorPosition(alias)).toEqual({ line: 2, column: 11 }) }) }) diff --git a/scripts/cordis-loader-rc9.spec.ts b/scripts/cordis-loader-rc9.spec.ts index 8c5fa3eb80..0a48a324b7 100644 --- a/scripts/cordis-loader-rc9.spec.ts +++ b/scripts/cordis-loader-rc9.spec.ts @@ -13,21 +13,16 @@ const Typed = Object.assign((_ctx: Context, _config: { value: number }) => {}, { Config: Schema.object({ value: Schema.number().required() }), }) -async function fixture(filename: string, content: string) { +// `rows.yml` is the file the root Include reads; other files are reachable through nested includes. +async function fixture(files: Record) { const dir = await mkdtemp(join(tmpdir(), 'dsh-loader-rc9-')) + const pathOf = (name: string) => join(dir, name) + for (const [name, content] of Object.entries(files)) await writeFile(pathOf(name), content) const ctx = new Context() onTestFinished(async () => { await ctx.fiber.dispose() await rm(dir, { recursive: true, force: true, maxRetries: 3 }) }) - ctx.baseUrl = pathToFileURL(dir).href + '/' - await ctx.plugin(Loader) - ctx.loader.builtins.include = Include - ctx.loader.builtins.group = Group - ctx.loader.builtins.example = () => {} - ctx.loader.builtins.typed = Typed - const path = join(dir, filename) - await writeFile(path, content) const errors: unknown[] = [] const warnings: unknown[] = [] ctx.logger.exporter({ @@ -36,10 +31,13 @@ async function fixture(filename: string, content: string) { if (type === 'warn') warnings.push(...args) }, }) - const id = await ctx.loader.create({ name: 'cordis:include', config: { path: `./${filename}` } }) + ctx.baseUrl = pathToFileURL(dir).href + '/' + await ctx.plugin(Loader) + Object.assign(ctx.loader.builtins, { include: Include, group: Group, example: () => {}, typed: Typed }) + const id = await ctx.loader.create({ name: 'cordis:include', config: { path: './rows.yml' } }) await ctx.loader.await() const entry = ctx.loader.resolve(id) - return { ctx, path, entry, include: entry.subtree as Include | undefined, errors, warnings } + return { ctx, path: pathOf('rows.yml'), pathOf, entry, include: entry.subtree as Include | undefined, errors, warnings } } describe('Loader 1.0.0-rc.9 entry options', () => { @@ -63,14 +61,14 @@ describe('Loader 1.0.0-rc.9 entry options', () => { }) it('accepts explicit ids containing the separator from a file', async () => { - const app = await fixture('rows.yml', '- id: pkg:row\n name: cordis:example\n') + const app = await fixture({ 'rows.yml': '- id: pkg:row\n name: cordis:example\n' }) expect(app.include!.store['pkg:row']!.fiber!.state).toBe(FiberState.ACTIVE) }) }) describe('Include 1.2.0 config files', () => { it('reports invalid entries and config values at their file positions', async () => { - const app = await fixture('rows.yml', [ + const app = await fixture({ 'rows.yml': [ '- id: bad', ' name: cordis:example', ' disabled: 1', @@ -79,7 +77,7 @@ describe('Include 1.2.0 config files', () => { ' config:', ' value: text', '', - ].join('\n')) + ].join('\n') }) const messages = app.errors.map(String).join('\n') expect(messages).toContain(`disabled must be a boolean (at disabled, ${app.path}:3:13)`) expect(messages).toContain(`${app.path}:7:12`) @@ -88,14 +86,14 @@ describe('Include 1.2.0 config files', () => { }) it('reports an unknown plugin module at its name position', async () => { - const app = await fixture('rows.yml', '- id: missing\n name: ./missing-plugin.js\n') + const app = await fixture({ 'rows.yml': '- id: missing\n name: ./missing-plugin.js\n' }) const error = app.errors.find(error => error instanceof ModuleNotFoundError) expect(error?.specifier).toBe('./missing-plugin.js') expect(error?.message).toContain(`(at name, ${app.path}:2:9)`) }) it('parses YAML 1.2 core scalars and locates syntax errors', async () => { - const app = await fixture('rows.yml', '- id: typed\n name: cordis:typed\n config:\n value: 0x10\n') + const app = await fixture({ 'rows.yml': '- id: typed\n name: cordis:typed\n config:\n value: 0x10\n' }) expect(app.include!.store['typed']!.fiber!.effectiveConfig).toEqual({ value: 16 }) await writeFile(app.path, '- id: typed\n name: [\n') await app.include!.refresh() @@ -103,4 +101,29 @@ describe('Include 1.2.0 config files', () => { expect(error).toBeInstanceOf(ConfigFileError) expect((error as ConfigFileError).issues[0]!.location).toMatchObject({ filename: app.path, line: 3 }) }) + + it('rejects a file with a non-mapping entry at its position', async () => { + const app = await fixture({ 'rows.yml': '- id: ok\n name: cordis:example\n- id: g\n name: cordis:group\n group: true\n config:\n - plain\n' }) + const error = app.errors.find(error => error instanceof ConfigFileError) + expect(error?.issues).toEqual([{ message: 'entry must be an object', location: { filename: app.path, line: 7, column: 7 } }]) + expect(app.entry.fiber!.state).not.toBe(FiberState.ACTIVE) + }) + + it('locates an unresolved alias as a parse error', async () => { + const app = await fixture({ 'rows.yml': '- id: typed\n name: cordis:typed\n config: *missing\n' }) + const error = app.errors.find(error => error instanceof ConfigFileError) + expect(error?.stage).toBe('parse') + expect(error?.issues[0]!.location).toEqual({ filename: app.path, line: 3, column: 11 }) + }) + + it.each([ + ['an override', ' patches:\n - id: typed\n config:\n value: text\n', '- id: typed\n name: cordis:typed\n config:\n value: 1\n', 8], + ['an inserted entry', ' patches:\n - insert:\n - id: typed\n name: cordis:typed\n config:\n value: text\n', '[]\n', 10], + ])('locates a config value supplied by %s in the parent file', async (_kind, patches, inner, line) => { + const app = await fixture({ + 'rows.yml': `- id: inner\n name: cordis:include\n config:\n path: ./inner.yml\n${patches}`, + 'inner.yml': inner, + }) + expect(app.errors.map(String).join('\n')).toContain(`(at value, ${app.path}:${String(line)}:`) + }) }) diff --git a/vendor/README.md b/vendor/README.md index 06f3affe18..a0e73b7813 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -26,10 +26,10 @@ Intentionally **not** vendored (verified unused by this set): `reggol`, `@cordis ## Local modifications -Keep this log exhaustive — every divergence from upstream must be listed. Each entry has a stable ID: remove an entry when its divergence no longer exists, and never renumber or reuse IDs. The next new entry is V29. +Keep this log exhaustive — every divergence from upstream must be listed. Each entry has a stable ID: remove an entry when its divergence no longer exists, and never renumber or reuse IDs. The next new entry is V30. - **V1 · `hmr/src/index.ts`**: removed the `./locales/en-US.yml` / `./locales/zh-CN.yml` imports, the `.i18n({...})` call on the `Config` schema, and the `src/locales/` directory. Rationale: those imports require a runtime YAML loader hook (`@cordisjs/unyaml`) that we do not vendor; the i18n texts only localize config descriptions. -- **V2 · All `package.json` files**: regenerated for Harness releases with scoped names, release versions, publication metadata, precise bundled-runtime and `lib/types/**/*.d.ts` / `.d.ts.map` file entries, source exports where applicable, and declaration metadata pointing at `lib/types`. References within the vendored set use `workspace:~`. HMR declares `esbuild` as a direct dev dependency for its imported `BuildFailure` type, and Loader requires `node-addon-require-builtin@^0.1.4` to match published app runtimes. +- **V2 · All `package.json` files**: regenerated for Harness releases with scoped names, release versions, publication metadata, precise bundled-runtime and `lib/types/**/*.d.ts` / `.d.ts.map` file entries, source exports where applicable, and declaration metadata pointing at `lib/types`. References within the vendored set use `workspace:~`. HMR declares `esbuild` as a direct dev dependency for its imported `BuildFailure` type, Loader requires `node-addon-require-builtin@^0.1.4` to match published app runtimes, and Include declares `yaml@^2.9.0` instead of upstream's `^2.9.1` so the workspace installs one copy of `yaml`. - **V3 · All `tsconfig.json` files**: regenerated to extend the repo-root `tsconfig.base.json`, emit TypeScript intermediates to `lib/types`, and declare project references. - **V4 · Vendored TypeScript source internal specifiers**: changed local relative imports/exports from upstream's specifier shape to explicit `.ts` specifiers so TypeScript rewrites emitted JS to `.js` while declarations keep explicit, NodeNext-safe `.ts` specifiers. This includes `loader/src/config/isolate.ts` using `declare module './entry.ts'`. Core's upstream source already uses explicit `.ts` specifiers. Type-only dependencies use `import type` or inline `type` modifiers so ESM output does not retain erased interfaces. - **V5 · `schemastery/tsdown.config.ts` and `logger-console/tsdown.config.ts`**: ours, not upstream files — per-package build-shape overrides (dual ESM+CJS output; separate node/browser entries) for the repo-root tsdown build. They read the JS emitted under `lib/types` and then write the publish runtime entries under `lib/`. Like the regenerated tsconfigs, they are not part of the upstream sync surface. @@ -48,6 +48,7 @@ Keep this log exhaustive — every divergence from upstream must be listed. Each - **V25 · Loader lifecycle adaptations**: before a combined context/config update, Loader refreshes dependencies locally, which prevents activation against stale isolation bindings; disabled-entry updates await disposal. Failed fibers require an explicit update after correcting their input or dependencies. Core retains the effect hardening in V6; rc.11 owns dependency teardown ordering and superseded-activation handling. - **V26 · `loader/src/config/tree.ts` cross-tree moves**: backports [cordiverse/cordis#271](https://github.com/cordiverse/cordis/pull/271), merged after `v4.0.0-rc.12`. When `EntryTree.update()` moves an entry into a group of another tree, the entry and the same-tree members of its group move their store registrations to the target tree, and the move is rejected before either tree changes when the target tree already holds one of their ids. The source tree receives a removal and the target tree a creation, without `legacy` or `from`. Upstream at `v4.0.0-rc.12` keeps the entry registered in the source tree and the target receives an update with `legacy`, so the Include journal writes a partial row and reconciling the target file creates a second Entry. Retire this entry when the vendored Loader includes the upstream fix. Covered by `scripts/cordis-include-journal.spec.ts`. - **V27 · `loader/src/config/utils.ts` explicit ids with `:`**: `validateOptions()` accepts ids containing `EntryTree.sep`, so `EntryTree.create()`, `EntryTree.update()` and group reconciliation admit them; upstream rejects them with an `id must not contain` issue. `validateOptions()` keeps its upstream `sep` parameter. Generated bundles from `@deepseek-ai/dsh-creation-recommendations` prefix their row ids with `:`, and installed profiles already contain such rows. `resolve()` still splits ids on `:`, so these entries cannot be addressed by nested path. Covered by `scripts/cordis-entry-commit.spec.ts`, `scripts/cordis-loader-rc9.spec.ts` and `packages/experimental/creation-recommendations/tests/loader-composition.spec.ts`. +- **V29 · `include/src/index.ts` unresolved aliases**: `_read()` and `parseEntryYaml()` report each alias without a preceding anchor as a `YAMLParseError` with code `BAD_ALIAS` and its position. Upstream leaves these to `document.toJS()`, which throws an unlocated `ReferenceError` outside `ConfigFileError`. Retire this entry when upstream reports them. Covered by `scripts/cordis-loader-rc9.spec.ts` and `scripts/cordis-entry-yaml.spec.ts`. ### Resolver adaptations diff --git a/vendor/include/README.md b/vendor/include/README.md index 997f1857df..3fb6dcf605 100644 --- a/vendor/include/README.md +++ b/vendor/include/README.md @@ -44,7 +44,7 @@ Patches can insert entries or override fields on entries with a matching `id`. A ## File format and errors -YAML files are parsed as YAML 1.2 under the core schema with the `yaml` package, plus the `!!js` tag for Loader expressions. Unknown tags are rejected. The file must be a top-level array whose entries, including the entries of each group, are mappings. A file that cannot be read, parsed or validated rejects with `ConfigFileError`; parse and validation errors carry `issues`, each with a message and a `file:line:column` location, and JSON files report the position of their syntax error. Include implements `getLocation(id, path)` for its entries: values written in the file resolve to the file, values supplied by a patch resolve through the parent entry to that patch, and values changed at runtime but not yet written resolve to nothing. +YAML files are parsed as YAML 1.2 under the core schema with the `yaml` package, plus the `!!js` tag for Loader expressions. Unknown tags and aliases without a preceding anchor are rejected. The file must be a top-level array whose entries, including the entries of each group, are mappings. A file that cannot be read, parsed or validated rejects with `ConfigFileError`; parse and validation errors carry `issues`, each with a message and a `file:line:column` location, and JSON files report the position of their syntax error. Include implements `getLocation(id, path)` for its entries: values written in the file resolve to the file, values supplied by a patch resolve through the parent entry to that patch, and values changed at runtime but not yet written resolve to nothing. Anonymous entries receive ids before the Loader sees them. An anonymous entry identical to one named on the previous read, under the same parent, keeps that id unless the file or an inserted patch row now uses it explicitly. diff --git a/vendor/include/package.json b/vendor/include/package.json index 37afb43bb3..08058216af 100644 --- a/vendor/include/package.json +++ b/vendor/include/package.json @@ -35,6 +35,6 @@ }, "dependencies": { "@deepseek-ai/cosmokit": "workspace:~", - "yaml": "^2.9.1" + "yaml": "^2.9.0" } } diff --git a/vendor/include/src/index.ts b/vendor/include/src/index.ts index 8e9add4f8b..2fe77103f0 100644 --- a/vendor/include/src/index.ts +++ b/vendor/include/src/index.ts @@ -6,7 +6,7 @@ import { access, constants, readFile, rename, rm, writeFile } from 'node:fs/prom import { setTimeout as sleep } from 'node:timers/promises' import { fileURLToPath, pathToFileURL } from 'node:url' import { - isAlias, isMap, isNode, isScalar, isSeq, LineCounter, parseDocument, Scalar, stringify, YAMLError, + isAlias, isMap, isNode, isScalar, isSeq, LineCounter, parseDocument, Scalar, stringify, visit, YAMLError, YAMLParseError, type Document, type Range, type ScalarTag, type SchemaOptions, } from 'yaml' import { stringifyString } from 'yaml/util' @@ -51,12 +51,31 @@ export interface EntryYamlStringifyOptions { * @throws the first parse error, or the first warning such as an unknown tag; {@link entryYamlErrorPosition} reads its location. */ export function parseEntryYaml(content: string): unknown { - const document = parseDocument(content, yamlOptions) - const [error] = [...document.errors, ...document.warnings] + const lines = new LineCounter() + const document = parseDocument(content, { ...yamlOptions, lineCounter: lines }) + const [error] = [...document.errors, ...document.warnings, ...unresolvedAliases(document, lines)] if (error) throw error return document.contents === null ? undefined : document.toJS() } +/** + * The parser reports an alias without a preceding anchor only when `toJS()` throws an unlocated `ReferenceError`; + * report each one as a located parse error instead. + */ +function unresolvedAliases(document: Document, lines: LineCounter): YAMLParseError[] { + const errors: YAMLParseError[] = [] + visit(document, { + Alias(_, node) { + if (node.resolve(document) || !node.range) return + const [start, end] = node.range + const error = new YAMLParseError([start, end], 'BAD_ALIAS', `Unresolved alias (the anchor must be set before the alias): ${node.source}`) + error.linePos = [lines.linePos(start), lines.linePos(end)] + errors.push(error) + }, + }) + return errors +} + /** * Serialize a value in Include's YAML dialect. JavaScript expression nodes are written as `!!js` scalars. The output * never contains anchors or aliases: repeated object references are written out in full, and no option changes this. @@ -386,7 +405,7 @@ export class Include extends EntryTree { syntax = parseSyntax(content) const { document, lines } = syntax // unknown tags are only warnings to the parser, but leave the data incomplete - const errors: YAMLError[] = [...document.errors, ...document.warnings] + const errors: YAMLError[] = [...document.errors, ...document.warnings, ...unresolvedAliases(document, lines)] if (errors.length) { const issues = errors.map(error => ({ message: error.message, location: this._locate(lines, error.pos[0]) })) throw new ConfigFileError('parse', this.filename, undefined, issues) diff --git a/vendor/loader/README.md b/vendor/loader/README.md index f745df38bb..f5bc608113 100644 --- a/vendor/loader/README.md +++ b/vendor/loader/README.md @@ -50,7 +50,7 @@ For file-backed trees, use `@cordisjs/plugin-include`. ## Entry validation and source positions -`create()` and `update()` check the resulting options with `validateOptions()` before the tree changes and reject with `EntryValidationError`, whose `issues` list each rejected path. `id` and `name` must be strings, and `name` is required; `group` must be a boolean; `disabled` a boolean or `!!js` expression; a group's `config` an array; `inject` a string array or a mapping; `intercept` and `isolate` mappings, with each `isolate` value `true` or a string. `create()` and `update()` also check the entries of a group's `config`. A group checks each entry again as it creates it; an invalid entry is logged, any running entry with its id is disposed, and its siblings still start. Explicit ids may contain `:`. +`create()` and `update()` check the resulting options with `validateOptions()` before the tree changes and reject with `EntryValidationError`, whose `issues` list each rejected path. `id` and `name` must be strings, and `name` is required; `group` must be a boolean; `disabled` a boolean or `!!js` expression; an entry with `group: true` requires a `config` array, which may be empty; `inject` a string array or a mapping; `intercept` and `isolate` mappings, with each `isolate` value `true` or a string. `create()` and `update()` also check the entries of a group's `config`. A group checks each entry again as it creates it; an invalid entry is logged, any running entry with its id is disposed, and its siblings still start. Explicit ids may contain `:`. `EntryTree.getLocation(id, path)` returns where an entry option is written; the base tree returns `undefined`, and Include implements it. Config validation errors and entry option errors of an entry with a source list each issue with its `file:line:column`, and their stack frames name the entry ids from the innermost tree outward. A config passed at runtime has no source position, so its validation errors keep their original message. From 0204d50e3774244efadcba12a1d07f0b9a821d02 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Mon, 16 Nov 2026 16:57:00 +0800 Subject: [PATCH 39/48] fix(tool-session-list): keep list_workspace execute synchronous An async arrow without await fails the type-aware require-await lint rule. --- packages/session-query/tool-session-list/src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/session-query/tool-session-list/src/index.ts b/packages/session-query/tool-session-list/src/index.ts index f0c2f84b8d..96d2c315f7 100644 --- a/packages/session-query/tool-session-list/src/index.ts +++ b/packages/session-query/tool-session-list/src/index.ts @@ -44,7 +44,7 @@ export function apply(ctx: Context): void { render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], }, isConcurrencySafe: () => true, - execute: async (args, exec) => listWorkspaces(ctx, args, exec.signal), + execute: (args, exec) => Promise.resolve(listWorkspaces(ctx, args, exec.signal)), presentCall: args => ({ card: 'generic', title: 'List workspaces', kind: 'read', rawInput: args }), })) ctx.tools.register(defineTool({ From 897de8769b4279a69bf53dc48082eae6dffb9c36 Mon Sep 17 00:00:00 2001 From: Shigma Date: Mon, 16 Nov 2026 17:11:48 +0800 Subject: [PATCH 40/48] fix(app-boot): audit rejected entry options and isolate dump snapshots --- .../tests/expected/dump-config-schema.json | 24 +++- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- .../guide.i18n.yaml | 4 +- .../cordis-loader-entry-validation/guide.md | 2 +- .../guide.zh.md | 2 +- packages/boot/app-boot/README.i18n.yaml | 4 +- packages/boot/app-boot/README.md | 2 +- packages/boot/app-boot/README.zh.md | 2 +- .../app-boot/src/config-schema/document.ts | 9 +- packages/boot/app-boot/src/index.ts | 129 ++++++++++++------ packages/boot/app-boot/tests/app-boot.spec.ts | 38 +++++- .../boot/app-boot/tests/config-dump.spec.ts | 13 ++ .../boot/app-boot/tests/config-schema.spec.ts | 10 ++ .../boot/app-boot/tests/user-patches.spec.ts | 20 +++ .../bundle/web-app/tests/startup.host.spec.ts | 2 +- 16 files changed, 208 insertions(+), 57 deletions(-) diff --git a/apps/cli/tests/expected/dump-config-schema.json b/apps/cli/tests/expected/dump-config-schema.json index ce57b82073..6a5fb77153 100644 --- a/apps/cli/tests/expected/dump-config-schema.json +++ b/apps/cli/tests/expected/dump-config-schema.json @@ -37,7 +37,7 @@ "boolean", "null" ], - "description": "Allows patch indexing and insertion into an entry-list config; does not select the plugin implementation." + "description": "Allows patch indexing and insertion into an entry-list config, which a group: true entry requires; does not select the plugin implementation." }, "disabled": { "anyOf": [ @@ -249,6 +249,28 @@ { "$ref": "#/$defs/entryMetadata" }, + { + "if": { + "properties": { + "group": { + "const": true + } + }, + "required": [ + "group" + ] + }, + "then": { + "properties": { + "config": { + "$ref": "#/$defs/entryList" + } + }, + "required": [ + "config" + ] + } + }, { "if": { "properties": { diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index d40db8f32e..37f4330d46 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -28,7 +28,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:691`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:698`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:56`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | +| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:58`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | | `commands/change` | `emit` | [`packages/interaction/commands/src/types.ts:89`](../packages/interaction/commands/src/types.ts) | [`commands`](../packages/interaction/commands) (`events.dispatch`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index f2f10522f7..6d5cf1cc38 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -30,7 +30,7 @@ | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:691`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:698`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:56`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | +| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:58`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | | `commands/change` | `emit` | [`packages/interaction/commands/src/types.ts:89`](../packages/interaction/commands/src/types.ts) | [`commands`](../packages/interaction/commands) (`events.dispatch`) | `remotes` | diff --git a/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.i18n.yaml index 491b537557..0e1837282e 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.i18n.yaml @@ -9,8 +9,8 @@ en: cf5dc11adadfd1e1 zh: 4656ed9a0d4e9087 /loader-validates-entry-options-and-include-parses-yaml-1-2/change: - en: b345762ab470b57b - zh: 0f931faf28da0d27 + en: 3a403b763d8059c8 + zh: cbbdd8c71474130e /loader-validates-entry-options-and-include-parses-yaml-1-2/migration: en: ff01b0eddb91d5b1 zh: 81478d5e1594db65 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.md index cc4ef09ede..5582acb747 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.md @@ -12,7 +12,7 @@ English | [中文](guide.zh.md) `@deepseek-ai/cordis-plugin-loader` now carries upstream Loader 1.0.0-rc.9, and `@deepseek-ai/cordis-plugin-include` carries Include 1.2.0. Hand-written `cordis.yml`, `cordis.patch.yml` and overlay files, and code that calls the Include or Loader exports, are affected: - Include and `parseEntryYaml` parse YAML 1.2 under the core schema instead of the js-yaml JSON schema. A binary integer such as `0b101` now reads as the string `'0b101'`. An empty `!!js` scalar now reads as an empty expression, which evaluates to `undefined`, instead of failing to parse. -- Entry options are validated before an entry is created or updated. `name` must be a string; `group` a boolean; `disabled` a boolean or `!!js` expression; an entry with `group: true` must have a `config` list, even an empty one; `inject` a string list or a mapping; `isolate` a mapping whose values are `true` or a string. An entry that loaded before with such a value is now rejected and logged, and its siblings still start. An Include file with an entry that is not a mapping is rejected as a whole. Ids containing `:` remain accepted. +- Entry options are validated before an entry is created or updated. `name` must be a string; `group` a boolean; `disabled` a boolean or `!!js` expression; an entry with `group: true` must have a `config` list, even an empty one; `inject` a string list or a mapping; `isolate` a mapping whose values are `true` or a string. An entry that loaded before with such a value is now rejected and its siblings still start; `dsh` stops startup when the rejected entry is required, such as `webserver`, and warns otherwise. An Include file with an entry that is not a mapping is rejected as a whole. Ids containing `:` remain accepted. - Parse, entry option and config validation errors name the file position as `file:line:column`. When an entry's own module cannot be found, the error is a `ModuleNotFoundError` without Node's `imported from` part; its `code` is still `ERR_MODULE_NOT_FOUND`. - A patch that replaces a group's `config` brings child entries that later patches can address, and the children it replaces can no longer be patched. - `applyEntryPatches(data, patches, warn)` returns `{ data, index }` instead of the entry list, and writes generated ids into the anonymous entries of a replaced group `config` in `patches`. `parseEntryYaml` throws the `YAMLError` of the `yaml` package instead of a js-yaml `YAMLException`. diff --git a/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.zh.md index c2e67208c5..f6ae418353 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.zh.md @@ -12,7 +12,7 @@ description: "Cordis Loader 1.0.0-rc.9 与 Include 1.2.0 按 YAML 1.2 解析、 `@deepseek-ai/cordis-plugin-loader` 现在包含上游 Loader 1.0.0-rc.9,`@deepseek-ai/cordis-plugin-include` 包含 Include 1.2.0。受影响的是手写的 `cordis.yml`、`cordis.patch.yml` 与 overlay 文件,以及调用 Include 或 Loader 导出的代码: - Include 和 `parseEntryYaml` 按 YAML 1.2 core schema 解析,不再使用 js-yaml 的 JSON schema。`0b101` 这样的二进制整数现在读作字符串 `'0b101'`。空的 `!!js` 标量现在读作空表达式,求值结果为 `undefined`,不再解析失败。 -- 创建或更新条目前会校验条目选项。`name` 必须是字符串;`group` 必须是布尔值;`disabled` 必须是布尔值或 `!!js` 表达式;`group: true` 的条目必须带有 `config` 列表,空列表也要写出;`inject` 必须是字符串列表或映射;`isolate` 必须是映射,其值为 `true` 或字符串。此前能加载但含有这类值的条目现在会被拒绝并记录日志,同级条目仍会启动。Include 文件中只要有一个条目不是映射,整个文件都会被拒绝。含 `:` 的 id 仍然可以使用。 +- 创建或更新条目前会校验条目选项。`name` 必须是字符串;`group` 必须是布尔值;`disabled` 必须是布尔值或 `!!js` 表达式;`group: true` 的条目必须带有 `config` 列表,空列表也要写出;`inject` 必须是字符串列表或映射;`isolate` 必须是映射,其值为 `true` 或字符串。此前能加载但含有这类值的条目现在会被拒绝,同级条目仍会启动;被拒绝的条目若是 `webserver` 等必需条目,`dsh` 会终止启动,否则输出警告。Include 文件中只要有一个条目不是映射,整个文件都会被拒绝。含 `:` 的 id 仍然可以使用。 - 解析错误、条目选项错误和配置校验错误都会以 `file:line:column` 指出文件位置。条目自身的模块找不到时,错误为 `ModuleNotFoundError`,不含 Node 的 `imported from` 部分;其 `code` 仍为 `ERR_MODULE_NOT_FOUND`。 - 替换 group `config` 的 patch 带来的子条目可以被后续 patch 定位,被替换掉的子条目则不能再被 patch。 - `applyEntryPatches(data, patches, warn)` 返回 `{ data, index }`,不再直接返回条目列表;它会把生成的 id 写入 `patches` 中被替换的 group `config` 里的匿名条目。`parseEntryYaml` 抛出 `yaml` 包的 `YAMLError`,不再抛出 js-yaml 的 `YAMLException`。 diff --git a/packages/boot/app-boot/README.i18n.yaml b/packages/boot/app-boot/README.i18n.yaml index 24c97f03cc..91ea331f7a 100644 --- a/packages/boot/app-boot/README.i18n.yaml +++ b/packages/boot/app-boot/README.i18n.yaml @@ -36,8 +36,8 @@ en: 91d80c444ac0cfe5 zh: e7db496043528ffb /deepseek-ai-dsh-app-boot/use-this-package/startup-and-reload-failures: - en: 9b9e08c8638a975b - zh: 8a3f906c4d98cb89 + en: 53a9bfee48468abe + zh: 34d36ae0e46d8e49 /deepseek-ai-dsh-app-boot/understand-the-implementation: en: f4a2695cb4c8a570 zh: 89837235d2f376cf diff --git a/packages/boot/app-boot/README.md b/packages/boot/app-boot/README.md index 2425e7aabf..89647f5227 100644 --- a/packages/boot/app-boot/README.md +++ b/packages/boot/app-boot/README.md @@ -97,7 +97,7 @@ The profile templates, installation-owned profile tuples, and retired bundle lis Profile reconciliation returns diagnostics for unchanged inactive entries without failing an unrelated mutation. A new inactive entry, a changed configuration or fiber, or a changed diagnostic fails reconciliation; removed fibers must still finish disposal. Explicit enablement targets must activate even when their failure predates the operation. `recomposeProfile(ctx, patches, binName, { requiredIds, running })` runs one recomposition together with the runtime resolution: it removes the rows the generation no longer lists and waits for their disposal while their packages are still mapped, publishes the latest generation of a recomputable resolution, runs the compatibility preflight against the published packages, applies the generation, starts the `running` entries and entries whose import failed that the update left without a running fiber, and judges activation. `running` lists the entries that ran before the caller stopped some of them; each that failed afterwards counts as a new failure. A failure before the generation applies puts the removed rows back at their places, which starts them again, and starts the `running` entries again. An entry waiting for a service is reported as a warning unless it is required, so it starts once a provider appears; `reconcileProfilePatches()` judges it the same way. A publication the resolution rejects is such a failure and reports `package-moved`. `reconcileProfilePatches()`, which the Config Editor uses, applies and judges the patches without publishing the resolution or retrying failed imports. An entry whose import failed is reported with the error Loader's import returns again, so judging it evaluates the module when the import now succeeds; the state recorded before the change imports nothing, so an entry whose import failed before counts as the same failure whatever its error now is. Successful reconciliation emits `app-boot/config-reload` after lifecycle settlement and diagnostic checks, including programmatic updates without HMR. The event carries no diff or parsed config. Successful reconciliation returns after lifecycle settlement and diagnostic checks; volatile-only entry changes are committed by Loader during the update. -After the Loader settles, app-boot warns when only optional entries are inactive. If an enabled required entry cannot activate, `boot()` rejects with `StartupError` after disposal. An independently owned logger exporter retains warning and error records through asynchronous disposal and is released before `boot()` settles. Its message groups all failed plugins and pending services, marks required entries, and retains original stacks, nested causes, and aggregate members. The CLI prints that message once and saves [full startup diagnostics](../../../apps/cli/reference/README.md#startup-diagnostics) before exiting with code 1; unrelated exceptions retain their normal stack output. In the table, stopping startup means disposing any mounted plugins and exiting nonzero without reporting readiness; continuing keeps successful plugins running. Later configuration HMR does not repeat the required-startup audit and does not roll back the whole update. +After the Loader settles, app-boot warns when only optional entries are inactive. If an enabled required entry cannot activate, `boot()` rejects with `StartupError` after disposal. Entry options that their group rejects count as an entry that could not activate, with the Loader's validation issues and source positions as its error. An independently owned logger exporter retains warning and error records through asynchronous disposal and is released before `boot()` settles. Its message groups all failed plugins and pending services, marks required entries, and retains original stacks, nested causes, and aggregate members. The CLI prints that message once and saves [full startup diagnostics](../../../apps/cli/reference/README.md#startup-diagnostics) before exiting with code 1; unrelated exceptions retain their normal stack output. In the table, stopping startup means disposing any mounted plugins and exiting nonzero without reporting readiness; continuing keeps successful plugins running. Later configuration HMR does not repeat the required-startup audit and does not roll back the whole update. | Failure pattern | Optional entry at startup | Required entry at startup | Later configuration HMR | |---|---|---|---| diff --git a/packages/boot/app-boot/README.zh.md b/packages/boot/app-boot/README.zh.md index 8d2d4adf5b..f0f5c699b1 100644 --- a/packages/boot/app-boot/README.zh.md +++ b/packages/boot/app-boot/README.zh.md @@ -97,7 +97,7 @@ app-boot 应用的 profile 模板、安装方拥有的 profile 组合包元组 profile 重载返回未变化的已有故障诊断,不让无关修改因此失败。新增未激活条目、配置或 fiber 变化、诊断变化都会使重载失败;被移除的 fiber 仍须完成释放。显式启用的目标必须成功激活,即使它的故障早于本次操作。`recomposeProfile(ctx, patches, binName, { requiredIds, running })` 与 runtime resolution 一起执行一次重新组合:它移除新一代组合不再列出的行,并在其包仍有映射时等待这些行释放完成,发布可重新计算的 resolution 的最新一代,使兼容性预检读取已发布的包,应用新一代组合,启动更新后没有运行中 fiber 的 `running` 条目和导入失败的条目,然后判定激活结果。`running` 列出调用方停止其中部分条目之前正在运行的条目;之后每个失败的条目都计为新的故障。新一代组合应用之前的失败会把移除的行放回原位置,从而重新启动它们,并重新启动 `running` 条目。等待服务的条目报告为警告(required 条目除外),因此出现提供方后它即启动;`reconcileProfilePatches()` 以同样方式判定它。resolution 拒绝的发布属于这种失败,并报告 `package-moved`。Config Editor 使用的 `reconcileProfilePatches()` 应用并判定 patch,不发布 resolution,也不重试失败的导入。导入失败的条目以 Loader 再次导入时返回的错误报告,因此若导入现在成功,判定该条目时会对模块求值;变更前记录的激活状态不执行任何导入,因此之前导入失败的条目无论现在的错误是什么,都计为同一个故障。成功重载在生命周期结束及诊断检查通过后发出 `app-boot/config-reload`,包括未启用 HMR 时的程序化更新。事件不携带 diff 或解析后的配置。成功重载在生命周期结束及诊断检查通过后返回;仅 volatile 的条目变化由 Loader 在更新过程中提交。 -Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如果已启用的 required 条目无法激活,`boot()` 会在释放资源后以 `StartupError` 拒绝。独立管理生命周期的 logger exporter 会保留异步资源释放期间的警告和错误记录,并在 `boot()` 结算前释放。其消息分组列出所有失败插件和等待的服务,标记 required 条目,并保留原始堆栈、嵌套原因和聚合错误成员。CLI 仅输出该消息一次,并在保存[完整启动诊断](../../../apps/cli/reference/README.zh.md#startup-diagnostics)后以退出码 1 结束;其他异常保留正常堆栈输出。表中的“终止启动”指释放已挂载插件并以非零码退出,不报告就绪;“继续”指保留成功运行的插件。后续配置 HMR 不会再次执行 required 启动审计,也不会回滚整个更新。 +Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如果已启用的 required 条目无法激活,`boot()` 会在释放资源后以 `StartupError` 拒绝。被所在 group 拒绝的条目选项也视为无法激活的条目,其错误是 Loader 的校验问题及源码位置。独立管理生命周期的 logger exporter 会保留异步资源释放期间的警告和错误记录,并在 `boot()` 结算前释放。其消息分组列出所有失败插件和等待的服务,标记 required 条目,并保留原始堆栈、嵌套原因和聚合错误成员。CLI 仅输出该消息一次,并在保存[完整启动诊断](../../../apps/cli/reference/README.zh.md#startup-diagnostics)后以退出码 1 结束;其他异常保留正常堆栈输出。表中的“终止启动”指释放已挂载插件并以非零码退出,不报告就绪;“继续”指保留成功运行的插件。后续配置 HMR 不会再次执行 required 启动审计,也不会回滚整个更新。 | 失败模式 | Optional 条目启动时 | Required 条目启动时 | 后续配置 HMR | |---|---|---|---| diff --git a/packages/boot/app-boot/src/config-schema/document.ts b/packages/boot/app-boot/src/config-schema/document.ts index 70428c6671..e765d40923 100644 --- a/packages/boot/app-boot/src/config-schema/document.ts +++ b/packages/boot/app-boot/src/config-schema/document.ts @@ -13,7 +13,7 @@ function metadata(): Record { id: { type: 'string', description: 'Entry id. Loader generates an id when an entry omits it; patches use the configured id.' }, name: { type: 'string', description: 'Plugin module specifier. Inserted relative plugin paths are anchored beside their patch file.' }, config: {}, - group: { type: ['boolean', 'null'], description: 'Allows patch indexing and insertion into an entry-list config; does not select the plugin implementation.' }, + group: { type: ['boolean', 'null'], description: 'Allows patch indexing and insertion into an entry-list config, which a group: true entry requires; does not select the plugin implementation.' }, disabled: { anyOf: [{ type: ['boolean', 'null'] }, ref('loaderExpression')], description: 'Boolean or !!js expression. The Loader coerces other truthy values as disabled; this schema rejects them.' }, inject: { anyOf: [{ type: 'array', items: { type: 'string' } }, { type: 'object' }, { type: 'null' }] }, intercept: { type: ['object', 'null'] }, @@ -129,8 +129,13 @@ export async function buildConfigSchemaDocument( diagnostics.push({ level: 'warning', message: `Plugin ${JSON.stringify(name)} has multiple collected schemas; entry validation accepts their union because module resolution depends on the owning tree.` }) } } + // The Loader rejects a group entry without an entry-list config, disabled or not. + const groupRule: ConfigJsonSchema = { + if: { properties: { group: { const: true } }, required: ['group'] }, + then: { properties: { config: ref('entryList') }, required: ['config'] }, + } definitions.entry = { - type: 'object', required: ['name'], allOf: [ref('entryMetadata'), ...entryRules], + type: 'object', required: ['name'], allOf: [ref('entryMetadata'), groupRule, ...entryRules], description: 'Loader entry. Unknown metadata and plugin names are accepted; plugin-specific validation is available only for the names collected in this profile. Distinct resolutions of one name use a union of their schemas.', } diff --git a/packages/boot/app-boot/src/index.ts b/packages/boot/app-boot/src/index.ts index 3e2fd76cbf..99dc05701b 100644 --- a/packages/boot/app-boot/src/index.ts +++ b/packages/boot/app-boot/src/index.ts @@ -13,7 +13,9 @@ import { captureStartupComposition, type StartupCompositionDiagnostic } from './ export type { StartupCompositionDiagnostic, StartupPluginState, StartupServiceState } from './startup-diagnostics.ts' import { basename, dirname, isAbsolute, resolve } from 'node:path' import { Context, type Fiber, type FiberState } from '@deepseek-ai/cordis' -import Loader, { type Entry, type EntryGroup, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader' +import Loader, { + EntryTree, EntryValidationError, formatIssues, relocate, validateOptions, type Entry, type EntryGroup, type EntryOptions, +} from '@deepseek-ai/cordis-plugin-loader' import Include, { applyEntryPatches, parseEntryYaml, stringifyEntryYaml, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' import Group from '@deepseek-ai/cordis-plugin-group' import { dshHomePath, dshPath, resolveDshHome } from '@deepseek-ai/dsh-home-paths' @@ -349,9 +351,10 @@ async function recompose( if (entry === undefined) throw new Error(`${binName}: profile reload requires the root Include entry`) // Reading the prior state imports nothing, so plugin code does not run before the next resolution publishes. const previousFailures = (await inactiveEntries(ctx, false)).map((failure): RecordedFailure => ({ - entry: failure.entry, fiber: failure.entry.fiber, options: JSON.stringify(failure.entry.options), + entry: failure.entry, fiber: failure.entry?.fiber, options: JSON.stringify(failure.options), // An entry without a running fiber has no import error yet; the judgment after the update reads it. - diagnostic: failure.entry.fiber?.uid ? reloadDiagnostic(failure) : undefined, + // Rejected options have no entry, and their diagnostic depends only on the options. + diagnostic: failure.entry === undefined || failure.entry.fiber?.uid ? reloadDiagnostic(failure) : undefined, })) // Removed entries leave the Loader store before their async disposers finish. const previousFibers = [...ctx.loader.entries()].flatMap(row => row.fiber === undefined ? [] : [row.fiber]) @@ -410,11 +413,11 @@ async function recompose( await ctx.loader.await() const failures = await inactiveEntries(ctx) const introduced = failures.filter((failure) => { - if (requiredIds.includes(failure.entry.options.id)) return true + if (requiredIds.includes(failure.id)) return true // An entry waiting for a service starts once a provider appears. if (failure.outcome.kind === 'pending') return false // An entry that ran before the caller stopped it is a new failure even when it failed the same way before. - if (running.includes(failure.entry)) return true + if (failure.entry !== undefined && running.includes(failure.entry)) return true return !previousFailures.some(previous => sameFailure(previous, failure)) }) if (introduced.length > 0) throw new Error(activationDiagnostic(binName, introduced, false).trimEnd()) @@ -435,7 +438,7 @@ async function recompose( // A restored row is a new Loader entry with the id of the one that ran. const ran = new Set(running.map(row => row.options.id)) for (const failure of await inactiveEntries(ctx)) { - if (ran.has(failure.entry.options.id)) ctx.logger.warn(`${binName}: ${reloadDiagnostic(failure)}`) + if (ran.has(failure.id)) ctx.logger.warn(`${binName}: ${reloadDiagnostic(failure)}`) } } catch (error) { // The recomposition's own failure is the outcome. @@ -447,7 +450,7 @@ async function recompose( /** An inactive entry as a recomposition found it before changing anything. */ interface RecordedFailure { - entry: Entry + entry: Entry | undefined fiber: Fiber | undefined /** The entry's options as JSON. */ options: string @@ -457,8 +460,8 @@ interface RecordedFailure { /** Whether an inactive entry is the failure recorded before: the same entry, fiber and options, and a matching diagnostic. */ function sameFailure(previous: RecordedFailure, failure: InactiveEntry): boolean { - return previous.entry === failure.entry && previous.fiber === failure.entry.fiber - && previous.options === JSON.stringify(failure.entry.options) + return previous.entry === failure.entry && previous.fiber === failure.entry?.fiber + && previous.options === JSON.stringify(failure.options) && (previous.diagnostic === undefined || previous.diagnostic === reloadDiagnostic(failure)) } @@ -670,15 +673,17 @@ export function renderConfigDump( const base = parsed as Parameters[0] // snapshot_k = ONE application of layers 1..k flattened, using the exact // arguments boot passes for that prefix. snapshot_N is the mounted composition. - // Every snapshot reads one clone of the patches: applyEntryPatches writes the - // ids it generates for anonymous children of a replaced group config into - // that clone, so each prefix assigns them the same ids. The snapshots share - // override values by reference and only read them. + // applyEntryPatches writes the ids it generates for anonymous children of a + // replaced group config onto those patch entries, so one full composition + // assigns them first and every prefix reuses them. Composition holds a + // supplied `config` array by reference and appends later inserts to it, so + // that run reads copies of the arrays, and each snapshot composes its own clone. const patches = structuredClone(layers.flatMap(layer => layer.patches)) + applyEntryPatches(base, patches.map(patch => Array.isArray(patch.config) ? { ...patch, config: patch.config.slice() } : patch)) const ends: number[] = [] for (const layer of layers) ends.push((ends.at(-1) ?? 0) + layer.patches.length) const snapshot = (count: number, warnings: string[]): ReturnType['data'] => { - return applyEntryPatches(base, patches.slice(0, ends[count - 1]), (message: string, ...args: unknown[]) => { + return applyEntryPatches(base, structuredClone(patches.slice(0, ends[count - 1])), (message: string, ...args: unknown[]) => { // The include logs through cordis's printf-style logger (`%C` = code); a // dump has no logger, so substitute inline for a plain line. let index = 0 @@ -993,8 +998,14 @@ function formatActivationError(error: unknown, stacks = true): string { } interface InactiveEntry { - /** Loader entry used to identify the bootstrap Include and required ids. */ - entry: Entry + /** Loader entry used to identify the bootstrap Include; absent for options their group rejected before creating one. */ + entry: Entry | undefined + /** Entry id used for required ids, or `(no id)` for rejected options without a string id. */ + id: string + /** Module specifier; for rejected options, a non-string `name` rendered as JSON. */ + name: string + /** The options the group lists for this entry. */ + options: unknown /** Activation errors and missing services remain distinct for presentation. */ outcome: { kind: 'failed'; error: unknown; phase?: string } | { kind: 'pending'; missing: string[] } @@ -1049,8 +1060,45 @@ async function importFailure(entry: Entry): Promise { } } +/** Identity fields of an inactive Loader entry. */ +function identify(entry: Entry): Pick { + return { entry, id: entry.options.id, name: entry.options.name, options: entry.options } +} + +/** Groups whose option lists the Loader reconciled: the root group and those of active group and Include entries. */ +function activeGroups(ctx: Context): EntryGroup[] { + const groups = [ctx.loader.root] + for (const entry of ctx.loader.entries()) { + if (entry.subgroup !== undefined && entry.fiber?.state === FIBER_ACTIVE) groups.push(entry.subgroup) + } + return groups +} + /** - * Collect Loader activation failures and disabled-expression errors. Failed + * Options that a group lists but rejected before creating an entry, checked with the Loader's own rule. + * The group only logs such a rejection, so each one is reported here with its source position when its tree has one. + */ +function rejectedOptions(ctx: Context): InactiveEntry[] { + return activeGroups(ctx).flatMap(group => group.data.flatMap((options: unknown): InactiveEntry[] => { + const issues = validateOptions(options, EntryTree.sep) + if (issues.length === 0) return [] + const row: { id?: unknown; name?: unknown } = typeof options === 'object' && options !== null ? options : {} + const id = typeof row.id === 'string' ? row.id : undefined + const error = new EntryValidationError(issues) + // Source positions are found by id, so options without one keep the plain message. + if (id !== undefined) { + const frames = group.getOuterStack(id) + if (frames.length > 0) relocate(error, formatIssues('invalid entry options', issues, path => group.tree.getLocation(id, path)), frames) + } + return [{ + entry: undefined, id: id ?? '(no id)', name: typeof row.name === 'string' ? row.name : row.name === undefined ? 'undefined' : JSON.stringify(row.name), + options, outcome: { kind: 'failed', error, phase: 'invalid entry options' }, + }] + })) +} + +/** + * Collect Loader activation failures, disabled-expression errors and options their group rejected. Failed * fibers are awaited to recover their recorded rejection reason and coalesce * duplicate Loader notifications through the next process rejection checkpoint. * An entry whose import failed reports the error importing it raises now; without @@ -1063,14 +1111,14 @@ async function inactiveEntries(ctx: Context, importNow = true): Promise fiber.ctx.get(service) === undefined) failures.push({ - entry, + ...identify(entry), outcome: { kind: 'pending', missing }, }) } else { - failures.push({ entry, outcome: { kind: 'failed', error: `fiber state ${String(state)}` } }) + failures.push({ ...identify(entry), outcome: { kind: 'failed', error: `fiber state ${String(state)}` } }) } } + failures.push(...rejectedOptions(ctx)) if (rejectionReasons.length > 0) await observeLoaderRejectionCheckpoint(rejectionReasons) return failures } @@ -1121,31 +1170,31 @@ function reloadDiagnostic(failure: InactiveEntry): string { } /** Stable per-entry text for reload comparisons and optional warnings. */ -function inactiveDiagnostic({ entry, outcome }: InactiveEntry, stacks = true): string { +function inactiveDiagnostic({ id, name, outcome }: InactiveEntry, stacks = true): string { const detail = outcome.kind === 'failed' ? failureDetail(outcome, stacks) : `pending (waiting for ${outcome.missing.length === 1 ? 'service' : 'services'}: ${outcome.missing.join(', ') || 'unknown'})` - return `${entry.options.id} (${entry.options.name}): ${detail}` + return `${id} (${name}): ${detail}` } /** Group startup failures and pending services, marking every required entry. */ -function startupDiagnostic(binName: string, failures: readonly InactiveEntry[], required: ReadonlySet): string { +function startupDiagnostic(binName: string, failures: readonly InactiveEntry[], required: ReadonlySet): string { const lines = [`${binName}: startup failed: ${String(required.size)} required ${required.size === 1 ? 'plugin' : 'plugins'} did not activate`] - const failed = failures.flatMap(({ entry, outcome }) => outcome.kind === 'failed' ? [{ entry, outcome }] : []) - const pending = failures.flatMap(({ entry, outcome }) => outcome.kind === 'pending' ? [{ entry, outcome }] : []) - pending.sort((left, right) => Number(required.has(right.entry)) - Number(required.has(left.entry))) - const label = (entry: Entry): string => `${entry.options.id}${required.has(entry) ? ' (required)' : ''}` + const failed = failures.flatMap(failure => failure.outcome.kind === 'failed' ? [{ failure, outcome: failure.outcome }] : []) + const pending = failures.flatMap(failure => failure.outcome.kind === 'pending' ? [{ failure, outcome: failure.outcome }] : []) + pending.sort((left, right) => Number(required.has(right.failure)) - Number(required.has(left.failure))) + const label = (failure: InactiveEntry): string => `${failure.id}${required.has(failure) ? ' (required)' : ''}` if (failed.length > 0) { lines.push('', `Failed plugins (${String(failed.length)}):`) - for (const { entry, outcome } of failed) { - lines.push(` ${label(entry)}`, ` Package: ${entry.options.name}`) + for (const { failure, outcome } of failed) { + lines.push(` ${label(failure)}`, ` Package: ${failure.name}`) lines.push(...failureDetail(outcome).split('\n').map(line => ` ${line}`)) } } if (pending.length > 0) { - const width = Math.max('Plugin'.length, ...pending.map(({ entry }) => label(entry).length)) + 2 + const width = Math.max('Plugin'.length, ...pending.map(({ failure }) => label(failure).length)) + 2 lines.push('', `Plugins waiting for services (${String(pending.length)}):`, ` ${'Plugin'.padEnd(width)}Missing services`) - for (const { entry, outcome } of pending) { - lines.push(` ${label(entry).padEnd(width)}${outcome.missing.join(', ') || 'unknown'}`) + for (const { failure, outcome } of pending) { + lines.push(` ${label(failure).padEnd(width)}${outcome.missing.join(', ') || 'unknown'}`) } } return lines.join('\n') @@ -1154,7 +1203,8 @@ function startupDiagnostic(binName: string, failures: readonly InactiveEntry[], /** * Apply DSH startup policy to a settled Loader tree. * - * Inactive entries from the global required list reject startup. Other + * Inactive entries from the global required list reject startup, including + * options that their group rejected before creating an entry. Other * inactive entries join that failure diagnostic, or produce one warning when * no required entry failed and leave successful siblings running. * Required ids absent from the tree, and disabled required entries, are ignored. @@ -1173,11 +1223,12 @@ export async function auditStartupEntries( warn: (line: string) => void = line => void process.stderr.write(line), ): Promise { const failures = await inactiveEntries(ctx) - const required = new Set(failures.filter(({ entry }) => entry === bootstrapIncludes.get(ctx) - || requiredStartupEntryIds.has(entry.options.id)).map(({ entry }) => entry)) + const required = new Set(failures.filter(failure => (failure.entry !== undefined && failure.entry === bootstrapIncludes.get(ctx)) + || requiredStartupEntryIds.has(failure.id))) if (required.size > 0) { - throw new StartupError(startupDiagnostic(binName, failures, required), failures.map(({ entry, outcome }) => ({ - id: entry.options.id, module: entry.options.name, required: required.has(entry), fiberState: entry.fiber?.state, outcome, + throw new StartupError(startupDiagnostic(binName, failures, required), failures.map(failure => ({ + id: failure.id, module: failure.name, required: required.has(failure), + fiberState: failure.entry?.fiber?.state, outcome: failure.outcome, }))) } if (failures.length > 0) warn(activationDiagnostic(binName, failures)) diff --git a/packages/boot/app-boot/tests/app-boot.spec.ts b/packages/boot/app-boot/tests/app-boot.spec.ts index b4eded6e9c..dc4764aef3 100644 --- a/packages/boot/app-boot/tests/app-boot.spec.ts +++ b/packages/boot/app-boot/tests/app-boot.spec.ts @@ -25,6 +25,13 @@ const tmp = (): string => { return dir } + +/** Give a fake Loader the root group that the startup audit reads for rejected options. */ +function withRoot(ctx: Context, rows: unknown[] = []): Context { + const root = { data: rows, getOuterStack: () => [] } + Object.assign(ctx.loader, { root }) + return ctx +} describe('resolveConfigPath', () => { it('resolves relative to the given cwd outside replay mode', () => { expect(resolveConfigPath('./cordis.yml', undefined, `${sep}base`)).toBe(resolve(`${sep}base`, 'cordis.yml')) @@ -484,7 +491,7 @@ describe('installFailLoud', () => { installFailLoud(NAME, proc) const error = new Error('assembled activation failure') const warn = vi.fn() - const audit = auditStartupEntries({ + const audit = auditStartupEntries(withRoot({ loader: { entries: () => ['broken-a', 'broken-b'].map(name => ({ options: { id: name, name }, @@ -496,7 +503,7 @@ describe('installFailLoud', () => { }, })), }, - } as unknown as Context, NAME, warn) + } as unknown as Context), NAME, warn) await Promise.resolve() await Promise.resolve() proc.rejection(error) @@ -631,9 +638,9 @@ describe('auditStartupEntries', () => { parent?: { tree: { import(name: string): Promise } } } - const ctxWith = (entries: FakeEntry[]): Context => ({ + const ctxWith = (entries: FakeEntry[], rows: unknown[] = []): Context => withRoot(({ loader: { entries: () => entries.values() }, - }) as unknown as Context + }) as unknown as Context, rows) const fiber = ( state: number, @@ -792,6 +799,29 @@ describe('auditStartupEntries', () => { expect(warn).not.toHaveBeenCalled() }) + it('fails startup for required options their group rejected and lists optional ones', async () => { + const error = await auditStartupEntries(ctxWith([], [ + { id: 'webserver', name: './webserver.mjs', disabled: 'yes' }, + { id: 'tool-todo', name: 7 }, + { id: 'valid', name: './valid.mjs' }, + ]), NAME, vi.fn()).catch((error: unknown) => error) + expect(error).toBeInstanceOf(StartupError) + const message = (error as Error).message + expect(message).toContain(`${NAME}: startup failed: 1 required plugin did not activate`) + expect(message).toContain(' webserver (required)\n Package: ./webserver.mjs\n invalid entry options: EntryValidationError: invalid entry options:\n - disabled must be a boolean (at disabled)') + expect(message).toContain(' tool-todo\n Package: 7\n') + expect(message).not.toContain('valid.mjs') + expect((error as StartupError).entries.map(entry => [entry.id, entry.required, entry.fiberState])).toEqual([ + ['webserver', true, undefined], ['tool-todo', false, undefined], + ]) + }) + + it('warns about rejected options without an id', async () => { + const warn = vi.fn() + await auditStartupEntries(ctxWith([], [null]), NAME, warn) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('(no id) (undefined): invalid entry options:')) + }) + it('omits an error cause when required plugins are only waiting for services', async () => { const error = await auditStartupEntries(ctxWith([ { fiber: fiber(0, undefined, { webStartup: {} }), options: { id: 'connection', name: './connection.mjs' } }, diff --git a/packages/boot/app-boot/tests/config-dump.spec.ts b/packages/boot/app-boot/tests/config-dump.spec.ts index 5451edfddf..ccb49298b5 100644 --- a/packages/boot/app-boot/tests/config-dump.spec.ts +++ b/packages/boot/app-boot/tests/config-dump.spec.ts @@ -157,6 +157,19 @@ describe('renderConfigDump', () => { expect(patches).toEqual([{ id: 'g', config: [{ name: './noop.mjs' }] }]) }) + it('keeps each layer\'s snapshot when a later layer inserts into a config array an earlier layer supplied', () => { + const dir = tmp() + const base = join(dir, 'base.yml') + writeFileSync(base, '- id: x\n name: ./group.mjs\n') + const dump = renderConfigDump(NAME, base, [ + { label: 'a.yml', patches: [{ id: 'x', config: [] }] }, + { label: 'b.yml', patches: [{ id: 'x', group: true }] }, + { label: 'c.yml', patches: [{ id: 'x', insert: [{ id: 'child', name: './noop.mjs' }] }] }, + ], () => {}) + expect((parseEntryYaml(dump) as { config: unknown[] }[])[0]!.config).toEqual([{ id: 'child', name: './noop.mjs' }]) + expect(dump).toContain('# == base.yml, patched by a.yml, b.yml, c.yml\n- id: x') + }) + it('drops the children of a replaced group config from the patch index', () => { const dir = tmp() const base = join(dir, 'base.yml') diff --git a/packages/boot/app-boot/tests/config-schema.spec.ts b/packages/boot/app-boot/tests/config-schema.spec.ts index ca8e52f654..e63a12cfab 100644 --- a/packages/boot/app-boot/tests/config-schema.spec.ts +++ b/packages/boot/app-boot/tests/config-schema.spec.ts @@ -467,6 +467,16 @@ describe('collectConfigSchemas', () => { } }) + it('requires an entry-list config on every group: true entry, as the Loader does', async () => { + const result = await collectConfigSchemas(profile, [row('noop')], resolution) + expect(validates(result, [{ name: 'noop', group: true, config: [] }])).toBe(true) + expect(validates(result, [{ name: 'noop', group: false }])).toBe(true) + for (const value of [{ name: 'noop', group: true }, { name: 'noop', group: true, config: {} }, { name: 'noop', group: true, disabled: true }]) { + expect(validates(result, [value])).toBe(false) + } + expect(validates(result, [{ id: 'g', config: [] }], 'patchList')).toBe(true) + }) + it('allows disabled config omission without disabling group:true or supplied-config validation', async () => { modules.set('required', { Config: Schema.string().required() }) const result = await collectConfigSchemas(profile, [row('required')], resolution) diff --git a/packages/boot/app-boot/tests/user-patches.spec.ts b/packages/boot/app-boot/tests/user-patches.spec.ts index a974eaddec..68a887ddc6 100644 --- a/packages/boot/app-boot/tests/user-patches.spec.ts +++ b/packages/boot/app-boot/tests/user-patches.spec.ts @@ -18,6 +18,7 @@ import { loadOverlayPatches, PROFILE_PATCH_FILENAME, reconcileProfilePatches, + StartupError, } from '../src/index.ts' const NAME = 'dsh-test-bin' @@ -348,6 +349,25 @@ describe('profile reconciliation settlement', () => { expect(await reconcileProfilePatches(ctx, patches, NAME)).toEqual([expect.stringMatching(diagnostic)]) }) + it('fails startup for a required row whose options the Loader rejects, at its source position', async () => { + const dir = tmp() + writeFileSync(join(dir, 'cordis.yml'), '- id: webserver\n name: ./webserver.mjs\n disabled: maybe\n') + const error = await boot(NAME, join(dir, 'cordis.yml')).catch((caught: unknown) => caught) + expect(error).toBeInstanceOf(StartupError) + expect((error as Error).message).toContain(' webserver (required)\n Package: ./webserver.mjs') + expect((error as Error).message).toContain(`disabled must be a boolean (at disabled, ${join(dir, 'cordis.yml')}:3:13)`) + }) + + it('rejects a recomposition that introduces rows the Loader rejects', async () => { + const dir = tmp() + writeFileSync(join(dir, 'cordis.yml'), '[]\n') + const ctx = await boot(NAME, join(dir, 'cordis.yml')) + onTestFinished(() => ctx.fiber.dispose()) + const patches = [{ insert: [{ id: 'bad-group', name: 'cordis:group', group: true }] }] + await expect(reconcileProfilePatches(ctx, patches, NAME)).rejects + .toThrow('bad-group (cordis:group): invalid entry options: EntryValidationError: invalid entry options:\n - config is required (at config)') + }) + it('rejects a context without the launcher root Include', async () => { const ctx = new Context() onTestFinished(() => ctx.fiber.dispose()) diff --git a/packages/bundle/web-app/tests/startup.host.spec.ts b/packages/bundle/web-app/tests/startup.host.spec.ts index e162f9d30e..3e1c1ccba0 100644 --- a/packages/bundle/web-app/tests/startup.host.spec.ts +++ b/packages/bundle/web-app/tests/startup.host.spec.ts @@ -17,7 +17,7 @@ async function setup(options: { origin?: string; ssh?: 'SSH_CONNECTION' | 'SSH_T { source: 'process', values: options.ssh === undefined ? {} : { [options.ssh]: 'remote-launch' } }, { source: 'project-env', path: '/project/.env', values: { SSH_TTY: 'project-setting' } }, ])) - if (options.settle !== undefined) ctx.provide('loader', { await: options.settle, entries: () => [] } as never) + if (options.settle !== undefined) ctx.provide('loader', { await: options.settle, entries: () => [], root: { data: [] } } as never) const server: Pick = { host: '127.0.0.1', protocol: 'http:', registerFallback: () => () => {}, } From f70ec1ac463eef42b890ab085d441ca648bd6983 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Mon, 16 Nov 2026 17:35:17 +0800 Subject: [PATCH 41/48] Merge pull request #8348 from deepseek-harness/feat/subagent-report-guidance feat(subagent): tell delegated agents to report results with send_message --- .../subagent-inheritance/child.expected.jsonl | 2 +- .../subagent-settlement/child.expected.jsonl | 2 +- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/module-graph.md | 15 ++++++------ docs/module-graph.zh.md | 15 ++++++------ docs/tool-catalog.i18n.yaml | 8 +++---- docs/tool-catalog.md | 4 ++-- docs/tool-catalog.zh.md | 4 ++-- .../tool-subagent-control/README.i18n.yaml | 8 +++---- .../subagent/tool-subagent-control/README.md | 5 ++-- .../tool-subagent-control/README.zh.md | 5 ++-- .../tool-subagent-control/package.json | 9 ++++++- .../tool-subagent-control/src/index.ts | 6 +++++ .../tests/tool-subagent-control.spec.ts | 24 ++++++++++++++++++- .../tool-subagent-control/tsconfig.json | 3 +++ .../team/tool-agent-team/README.i18n.yaml | 4 ++-- packages/team/tool-agent-team/README.md | 2 +- packages/team/tool-agent-team/README.zh.md | 2 +- pnpm-lock.yaml | 3 +++ scripts/gen-tool-catalog.ts | 2 +- .../session.1.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../subagent-continuable/session.1.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../subagent-list-agents/session.1.v4.jsonl | 2 +- .../sdk/subagent-mixed/session.1.v4.jsonl | 2 +- .../sdk/subagent-mixed/session.2.v4.jsonl | 2 +- .../subagent-send-message/session.1.v4.jsonl | 2 +- .../notifications.expected.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../session.2.v4.jsonl | 2 +- .../advanced-toolchain/session.1.v4.jsonl | 2 +- .../advanced-toolchain/session.2.v4.jsonl | 2 +- .../session/ralph-loop/session.1.v4.jsonl | 2 +- .../session/ralph-loop/session.2.v4.jsonl | 2 +- .../subagent-agent-preset/session.1.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../session.2.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../session.2.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../subagent-multi/writer.1.expected.jsonl | 2 +- .../subagent-multi/writer.2.expected.jsonl | 2 +- .../subagent-parallel/session.1.v4.jsonl | 2 +- .../subagent-parallel/session.2.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../subagent-tool-filter/session.1.v4.jsonl | 2 +- .../session/workflow-run/session.1.v4.jsonl | 2 +- .../subagent-fork-schedule/session.1.v4.jsonl | 2 +- 53 files changed, 118 insertions(+), 73 deletions(-) diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl index 23df1c78fb..9e3ec3e15c 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl @@ -8,7 +8,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Use the write tool exactly","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl index 7fd42a7bc1..498fb3440a 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl @@ -8,7 +8,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly CHILD_RESULT and","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 39d7646afb..8e63f67fe5 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -4774,7 +4774,7 @@ export interface PresetSelectionConfig { ## `@deepseek-ai/dsh-tool-subagent-control` - `inject`: `tools` · `subagents` · `agents` · `systemPrompt` -- `source`: [`packages/subagent/tool-subagent-control/src/index.ts:24`](../packages/subagent/tool-subagent-control/src/index.ts) +- `source`: [`packages/subagent/tool-subagent-control/src/index.ts:25`](../packages/subagent/tool-subagent-control/src/index.ts) ```ts config-catalog /** Optional subagent control tools. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index d1576a36bb..96fd2f6bb3 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -4776,7 +4776,7 @@ export interface PresetSelectionConfig { ## `@deepseek-ai/dsh-tool-subagent-control` - `inject`: `tools` · `subagents` · `agents` · `systemPrompt` -- `source`: [`packages/subagent/tool-subagent-control/src/index.ts:24`](../packages/subagent/tool-subagent-control/src/index.ts) +- `source`: [`packages/subagent/tool-subagent-control/src/index.ts:25`](../packages/subagent/tool-subagent-control/src/index.ts) ```ts config-catalog /** Optional subagent control tools. */ diff --git a/docs/module-graph.md b/docs/module-graph.md index bb9b68cb44..a91a8808e7 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -1376,12 +1376,6 @@ flowchart TD pkg_tool_subagent --> pkg_subagent pkg_tool_subagent --> pkg_system_prompt pkg_tool_subagent --> pkg_tools - pkg_tool_subagent_control --> pkg_agent - pkg_tool_subagent_control --> pkg_llm - pkg_tool_subagent_control --> pkg_session - pkg_tool_subagent_control --> pkg_subagent - pkg_tool_subagent_control --> pkg_system_prompt - pkg_tool_subagent_control --> pkg_tools pkg_api_session_controller --> pkg_agent pkg_api_session_controller --> pkg_agent_default_model pkg_api_session_controller --> pkg_agent_preset_registry @@ -1509,6 +1503,13 @@ flowchart TD pkg_workflow_ptc --> pkg_tools pkg_workflow_ptc --> pkg_workflow pkg_workflow_ptc --> pkg_working_directory + pkg_tool_subagent_control --> pkg_agent + pkg_tool_subagent_control --> pkg_agent_team + pkg_tool_subagent_control --> pkg_llm + pkg_tool_subagent_control --> pkg_session + pkg_tool_subagent_control --> pkg_subagent + pkg_tool_subagent_control --> pkg_system_prompt + pkg_tool_subagent_control --> pkg_tools pkg_schedule --> pkg_agent pkg_schedule --> pkg_api_session_controller pkg_schedule --> pkg_llm @@ -1942,7 +1943,6 @@ flowchart TD | [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process) | `subagent` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process) | `subagent` | [`subagent`](../packages/subagent/subagent) | | [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`api-session-controller`](../packages/api/session-controller) | `api` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`api-gateway`](../packages/api/gateway), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-file-upload`](../packages/client/file-upload), [`commands`](../packages/interaction/commands), [`credentials`](../packages/credentials/credentials), [`file-reference`](../packages/context/file-reference), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`native-command`](../packages/util/native-command), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`settings`](../packages/settings/settings), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol), [`typert-registry`](../packages/typert/registry), [`util-time`](../packages/util/time), [`util-values`](../packages/util/values), [`util-workspace-path`](../packages/util/workspace-path), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`plugin-market`](../packages/boot/plugin-market) | `boot` | [`error`](../packages/util/error), [`plugin-manager`](../packages/boot/plugin-manager), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval) | @@ -1958,6 +1958,7 @@ flowchart TD | [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | [`agent-team`](../packages/team/agent-team) | `team` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`workflow-ptc`](../packages/workflow/workflow-ptc) | `workflow` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow), [`working-directory`](../packages/session/working-directory) | +| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`agent-team`](../packages/team/agent-team), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`schedule`](../packages/schedule/schedule) | `schedule` | [`agent`](../packages/core/agent), [`api-session-controller`](../packages/api/session-controller), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-time`](../packages/util/time), [`workspace`](../packages/workspace/workspace) | | [`sdk-client`](../packages/sdk/client) | `sdk` | [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session) | | [`tool-agent-team`](../packages/team/tool-agent-team) | `team` | [`agent`](../packages/core/agent), [`agent-team`](../packages/team/agent-team), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index fa21f68cba..9863a414d8 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -1378,12 +1378,6 @@ flowchart TD pkg_tool_subagent --> pkg_subagent pkg_tool_subagent --> pkg_system_prompt pkg_tool_subagent --> pkg_tools - pkg_tool_subagent_control --> pkg_agent - pkg_tool_subagent_control --> pkg_llm - pkg_tool_subagent_control --> pkg_session - pkg_tool_subagent_control --> pkg_subagent - pkg_tool_subagent_control --> pkg_system_prompt - pkg_tool_subagent_control --> pkg_tools pkg_api_session_controller --> pkg_agent pkg_api_session_controller --> pkg_agent_default_model pkg_api_session_controller --> pkg_agent_preset_registry @@ -1511,6 +1505,13 @@ flowchart TD pkg_workflow_ptc --> pkg_tools pkg_workflow_ptc --> pkg_workflow pkg_workflow_ptc --> pkg_working_directory + pkg_tool_subagent_control --> pkg_agent + pkg_tool_subagent_control --> pkg_agent_team + pkg_tool_subagent_control --> pkg_llm + pkg_tool_subagent_control --> pkg_session + pkg_tool_subagent_control --> pkg_subagent + pkg_tool_subagent_control --> pkg_system_prompt + pkg_tool_subagent_control --> pkg_tools pkg_schedule --> pkg_agent pkg_schedule --> pkg_api_session_controller pkg_schedule --> pkg_llm @@ -1944,7 +1945,6 @@ flowchart TD | [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process) | `subagent` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process) | `subagent` | [`subagent`](../packages/subagent/subagent) | | [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`api-session-controller`](../packages/api/session-controller) | `api` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`api-gateway`](../packages/api/gateway), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-file-upload`](../packages/client/file-upload), [`commands`](../packages/interaction/commands), [`credentials`](../packages/credentials/credentials), [`file-reference`](../packages/context/file-reference), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`native-command`](../packages/util/native-command), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`settings`](../packages/settings/settings), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol), [`typert-registry`](../packages/typert/registry), [`util-time`](../packages/util/time), [`util-values`](../packages/util/values), [`util-workspace-path`](../packages/util/workspace-path), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`plugin-market`](../packages/boot/plugin-market) | `boot` | [`error`](../packages/util/error), [`plugin-manager`](../packages/boot/plugin-manager), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval) | @@ -1960,6 +1960,7 @@ flowchart TD | [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | [`agent-team`](../packages/team/agent-team) | `team` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`workflow-ptc`](../packages/workflow/workflow-ptc) | `workflow` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow), [`working-directory`](../packages/session/working-directory) | +| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`agent-team`](../packages/team/agent-team), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`schedule`](../packages/schedule/schedule) | `schedule` | [`agent`](../packages/core/agent), [`api-session-controller`](../packages/api/session-controller), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-time`](../packages/util/time), [`workspace`](../packages/workspace/workspace) | | [`sdk-client`](../packages/sdk/client) | `sdk` | [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session) | | [`tool-agent-team`](../packages/team/tool-agent-team) | `team` | [`agent`](../packages/core/agent), [`agent-team`](../packages/team/agent-team), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index 2f947d20f8..c3173a7283 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -9,8 +9,8 @@ en: 6cc2cd9ced70bb09 zh: 1c0e6cb4ba2ed637 /tool-schema-catalog/tool-package-map: - en: 789c9c7932024257 - zh: 6d0465e0463b321c + en: a0118885d7ac9d96 + zh: d6031ede88059ea1 /tool-schema-catalog/deepseek-ai-dsh-plugin-manager: en: e0143916bb634762 zh: e0143916bb634762 @@ -309,8 +309,8 @@ en: 8001eda7e9ff6a25 zh: 2414761029f21404 /tool-schema-catalog/deepseek-ai-dsh-tool-agent-team/team-task-update: - en: 9acd1c5b2fac9853 - zh: 3bd81e9cd1f1c28d + en: 3c25013abbe19446 + zh: 9552eaab1a25adb2 /tool-schema-catalog/deepseek-ai-dsh-tool-todo: en: dea62d26fb18ff68 zh: dea62d26fb18ff68 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index dd30a3d823..500ee97fba 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -45,7 +45,7 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tool-subagent` | `list_subagent_models`, `subagent` | `ctx.tools`, `ctx.subagents`, `ctx.systemPrompt`, `ctx.sessionProjections`, `ctx.llm for model discovery and selected-route validation` | `tool/call`, `tool/result`, `child session events through the chosen provider` | `subagent`, `subagent_fork` | The load-time `toolName` selects the delegation name (default `subagent`); `modelSelection` adds optional route fields. `modelDiscovery` defaults off and registers shared discovery on one instance per scope. Web and Desktop presets enable spawn discovery and route fields and leave `subagent_fork` route fields disabled. The Host settings service records authorization for each new top-level Session; child Sessions inherit it. Without a recorded policy, discovery and explicit selection permit only the current parent route. Every delegation returns the child's name promptly; local children accept follow-ups, while external backends report their single execution automatically. | | `@deepseek-ai/dsh-tool-subagent-control` | `interrupt_agent`, `list_agents`, `send_message`, `wait_agent` | `ctx.tools`, `ctx.subagents`, `ctx.agents` | `tool/call`, `tool/result`, `child session events through ctx.subagents` | - | The shared control tools discover and contact agents in the subagent tree, interrupt owned descendants, and wait for input in the caller’s inbox. Provider-bound `tool-subagent` instances supply delegation tools. | | `@deepseek-ai/dsh-tool-jobs` | `job_kill`, `job_list`, `job_output` | `ctx.tools`, `ctx.jobs`, `ctx.systemPrompt` | `tool/call`, `tool/result`, `user/message via agent.inject() for background completion notices` | - | The kind-agnostic background-job controller: background bash commands and PTY sends are read, listed, and killed through the same three tools. Loading the plugin attaches the controller that arms producers' `ctx.jobs.start()`. | -| `@deepseek-ai/dsh-tool-agent-team` | `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `ctx.subagents`, `an exact live Team member Agent` | `tool/call`, `team/task`, `tool/result` | - | Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode. | +| `@deepseek-ai/dsh-tool-agent-team` | `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `ctx.subagents`, `an exact live Team member Agent` | `tool/call`, `team/task`, `tool/result` | - | Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode; their result report instruction appears only while Team mode is off. | | `@deepseek-ai/dsh-tool-todo` | `todo_write` | `ctx.tools`, `owning Agent session` | `tool/call`, `todo/write`, `tool/result` | - | todo_write is session-owned state; UIs render the latest todo/write event as a checklist. `allowParallelInProgress` is required with no default, so the catalog states its choice: `true`, whose description invites several `in_progress` items. A deployment choosing `false` receives the same tool with a description asking for exactly one active task. | | `@deepseek-ai/dsh-tool-working-directory` | `working_directory` | `ctx.tools`, `ctx.workingDirectory` | `tool/call`, `working-directory/change`, `user context for directory changes`, `tool/result` | - | Reads or changes the calling Session directory. Existing shells and processes retain their own directories; origin metadata and permission roots stay fixed. | | `@deepseek-ai/dsh-experimental-tool-worktree` | `create_worktree` | `ctx.tools`, `ctx.worktrees`, `a calling Agent` | `tool/call`, `Git branch and checkout`, `working-directory/change`, `tool/result` | - | Enabled through the Change requests & worktrees bundle on Web and Desktop; other profiles can select the standalone bundle. Creates a new branch and checkout from a pinned local commit under existing write permissions, then changes the Session directory. Leaving retains the branch and checkout. | @@ -2587,7 +2587,7 @@ Compare-and-set a shared task action using the latest revision from team_task_ge Source: [`packages/team/tool-agent-team/src/index.ts`](../packages/team/tool-agent-team/src/index.ts) -Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode. +Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode; their result report instruction appears only while Team mode is off. diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index 80929e113d..f6c004a58a 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -49,7 +49,7 @@ | `@deepseek-ai/dsh-tool-subagent` | `list_subagent_models`、`subagent` | `ctx.tools`、`ctx.subagents`、`ctx.systemPrompt`、`ctx.sessionProjections`、`用于模型发现和所选路由校验的 ctx.llm` | `tool/call`、`tool/result`、`child session events through the chosen provider` | `subagent`、`subagent_fork` | 加载时的 `toolName` 选择委派名称(默认为 `subagent`);`modelSelection` 增加可选路由字段。`modelDiscovery` 默认关闭,每个作用域由一个实例注册共享发现工具。Web 与 Desktop preset 启用 spawn 发现和路由字段,并为 `subagent_fork` 保持路由字段关闭。Host 设置服务为每个新顶层 Session 记录授权;子 Session 继承该授权。没有已记录策略时,发现和显式选择只允许当前父级路由。每次委派都会立即返回子代理的名称;本地子代理接受后续消息,外部后端自动汇报单次执行结果。 | | `@deepseek-ai/dsh-tool-subagent-control` | `interrupt_agent`、`list_agents`、`send_message`、`wait_agent` | `ctx.tools`、`ctx.subagents`、`ctx.agents` | `tool/call`、`tool/result`、`child session events through ctx.subagents` | - | 共享控制工具发现并联系 subagent 树中的 Agent,中断有权控制的后代,并等待调用者收件箱中的输入。绑定提供方的 `tool-subagent` 实例提供委派工具。 | | `@deepseek-ai/dsh-tool-jobs` | `job_kill`、`job_list`、`job_output` | `ctx.tools`、`ctx.jobs`、`ctx.systemPrompt` | `tool/call`、`tool/result`、`user/message via agent.inject() for background completion notices` | - | 与任务种类无关的后台任务控制器:后台 bash 命令与 PTY 发送 都通过相同的 3 个工具读取、列出和终止。加载该插件会挂接控制器,从而启用生产方的 `ctx.jobs.start()`。 | -| `@deepseek-ai/dsh-tool-agent-team` | `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `ctx.subagents`, `an exact live Team member Agent` | `tool/call`, `team/task`, `tool/result` | - | 四个任务板工具共享 subagent 树的根 Session。在根 Session 开启 Team 模式,会在标准 subagent 委派和控制工具之外增加任务板指导。标准 subagent 控制工具提供必需身份,不受 Team 模式影响。 | +| `@deepseek-ai/dsh-tool-agent-team` | `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `ctx.subagents`, `an exact live Team member Agent` | `tool/call`, `team/task`, `tool/result` | - | 四个任务板工具共享 subagent 树的根 Session。在根 Session 开启 Team 模式,会在标准 subagent 委派和控制工具之外增加任务板指导。标准 subagent 控制工具提供必需身份,不受 Team 模式影响;其结果汇报要求仅在 Team 模式关闭时出现。 | | `@deepseek-ai/dsh-tool-todo` | `todo_write` | `ctx.tools`、`owning Agent session` | `tool/call`、`todo/write`、`tool/result` | - | todo_write 是会话所有的状态;UI 将最新的 todo/write 事件渲染为检查清单。`allowParallelInProgress` 是没有默认值的必填项,因此本目录明确选择 `true`,对应描述允许同时存在多个 `in_progress` 项。选择 `false` 的部署会获得同一工具,但描述会要求只能有 1 个活动任务。 | | `@deepseek-ai/dsh-tool-working-directory` | `working_directory` | `ctx.tools`, `ctx.workingDirectory` | `tool/call`, `working-directory/change`, `user context for directory changes`, `tool/result` | - | 读取或改变调用方 Session 的目录。已有 shell 和进程保留自己的目录;原始元数据和权限根目录保持不变。 | | `@deepseek-ai/dsh-experimental-tool-worktree` | `create_worktree` | `ctx.tools`, `ctx.worktrees`, `a calling Agent` | `tool/call`, `Git branch and checkout`, `working-directory/change`, `tool/result` | - | 在 Web 和 Desktop 上通过变更请求与工作树组合包启用;其他 profile 可以选择独立组合包。在现有写权限下从固定的本地提交创建新分支与检出目录,再改变 Session 工作目录。离开时保留分支与检出目录。 | @@ -2593,7 +2593,7 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录 来源:[`packages/team/tool-agent-team/src/index.ts`](../packages/team/tool-agent-team/src/index.ts) -四个任务板工具共享 subagent 树的根 Session。在根 Session 开启 Team 模式,会在标准子代理委派和控制工具之外增加任务板指导。标准子代理控制工具提供必需身份,不受 Team 模式影响。 +四个任务板工具共享 subagent 树的根 Session。在根 Session 开启 Team 模式,会在标准子代理委派和控制工具之外增加任务板指导。标准子代理控制工具提供必需身份,不受 Team 模式影响;其结果汇报要求仅在 Team 模式关闭时出现。 diff --git a/packages/subagent/tool-subagent-control/README.i18n.yaml b/packages/subagent/tool-subagent-control/README.i18n.yaml index 36dc72bfa8..49fcadff0b 100644 --- a/packages/subagent/tool-subagent-control/README.i18n.yaml +++ b/packages/subagent/tool-subagent-control/README.i18n.yaml @@ -69,8 +69,8 @@ en: fc88c8ffb8ebc083 zh: 0baf2e5df37d813e /deepseek-ai-dsh-tool-subagent-control/model-experience/identity-and-communication-context/what-the-model-sees: - en: 3f59216388405b66 - zh: 70672463706bc5c5 + en: 2398af9e6e80f928 + zh: 4585ff2e63441896 /deepseek-ai-dsh-tool-subagent-control/model-experience/identity-and-communication-context/what-the-model-sees/subagent-identity: en: fc2b3383d52ded16 zh: d5074e59b79c7afd @@ -78,8 +78,8 @@ en: 37a7eed766856ea0 zh: 4a564f74e08a3252 /deepseek-ai-dsh-tool-subagent-control/model-experience/identity-and-communication-context/kv-cache-effect: - en: 49dc6a07ae9640e3 - zh: 465fcd7cfe452ad2 + en: 8879c43a533f66da + zh: 75f30ae42ea19311 /deepseek-ai-dsh-tool-subagent-control/model-experience/interrupt-result: en: d64e936e83e89a2b zh: b9905c33af6cca45 diff --git a/packages/subagent/tool-subagent-control/README.md b/packages/subagent/tool-subagent-control/README.md index a66d8ce145..6b3bde77fb 100644 --- a/packages/subagent/tool-subagent-control/README.md +++ b/packages/subagent/tool-subagent-control/README.md @@ -125,7 +125,7 @@ Prefix-stable; the schemas do not change at runtime, and a parent and its contin #### What the model sees -Required `subagent:identity` runtime context identifies each agent by name. It is independent of Team mode and tool filtering. When the live root is available, identity context includes messaging and discovery instructions independently for each admitted standard tool. The root sees `You are the root agent. Your name is "lead".` followed by the same guidance. A missing live root is reported with the agent's Session id, without preventing independent work. Automatic result delivery remains owned by the subagent service. A child of the root named `reviewer`, with both tools admitted, sees: +Required `subagent:identity` runtime context identifies each agent by name. Its identity lines are independent of Team mode and tool filtering. When the live root is available, identity context includes messaging and discovery instructions independently for each admitted standard tool. While Team mode is off, a subagent with `send_message` is also told to send a self-contained result to the agent that delegated it when it finishes, and to message any agent as soon as a finding changes what that agent should do next. The root sees `You are the root agent. Your name is "lead".` followed by the same messaging and discovery guidance. A missing live root is reported with the agent's Session id, without preventing independent work. Automatic result delivery remains owned by the subagent service. A child of the root named `reviewer`, with both tools admitted, sees: ##### Subagent identity @@ -135,6 +135,7 @@ Your name is "reviewer". The root agent of your collaboration tree is "lead". To message other agents, use send_message({ agent: "", message: "..." }). +When you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn. Use list_agents({}) to find your collaborator agents and their names. ``` @@ -144,7 +145,7 @@ One short context entry per agent, independent of tree size; full names lengthen #### KV Cache effect -Identity and communication guidance follow inherited history as logged runtime context, leaving the shared system prompt and tool definitions unchanged. When a retained snapshot's identity text differs from the current text, one current runtime-context snapshot is appended. This required context remains available with `includeRuntimeContext: false` and is restored after compaction. Team mode does not change it. +Identity and communication guidance follow inherited history as logged runtime context, leaving the shared system prompt and tool definitions unchanged. When a retained snapshot's identity text differs from the current text, one current runtime-context snapshot is appended. This required context remains available with `includeRuntimeContext: false` and is restored after compaction. Switching Team mode adds or removes the report instruction for delegated children, which appends one runtime-context snapshot on the next request. ### Interrupt result diff --git a/packages/subagent/tool-subagent-control/README.zh.md b/packages/subagent/tool-subagent-control/README.zh.md index 2b5a505be5..7dfcd3fda6 100644 --- a/packages/subagent/tool-subagent-control/README.zh.md +++ b/packages/subagent/tool-subagent-control/README.zh.md @@ -125,7 +125,7 @@ kind: "package-reference" #### 模型看到什么 -必需的 `subagent:identity` 运行时上下文按名称标识每个 agent。该上下文独立于 Team 模式和工具过滤。活动根可用时,身份上下文会分别根据标准工具的获准情况提供通信与发现指引。根看到 `You are the root agent. Your name is "lead".`,后接相同指引。活动根缺失时,上下文使用该 agent 的 Session id 明确报告,但不阻止独立工作。自动结果交付仍由 subagent 服务负责。根的子级名为 `reviewer`、两个工具均获准时,它看到: +必需的 `subagent:identity` 运行时上下文按名称标识每个 agent。其中的身份行独立于 Team 模式和工具过滤。活动根可用时,身份上下文会分别根据标准工具的获准情况提供通信与发现指引。Team 模式关闭时,获准 `send_message` 的 subagent 还会被要求在完成时把自包含结果发送给委派它的 agent,并在某项发现改变任一 agent 的下一步行动时立即通知该 agent。根看到 `You are the root agent. Your name is "lead".`,后接相同的通信与发现指引。活动根缺失时,上下文使用该 agent 的 Session id 明确报告,但不阻止独立工作。自动结果交付仍由 subagent 服务负责。根的子级名为 `reviewer`、两个工具均获准时,它看到: ##### Subagent 身份 @@ -135,6 +135,7 @@ Your name is "reviewer". The root agent of your collaboration tree is "lead". To message other agents, use send_message({ agent: "", message: "..." }). +When you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn. Use list_agents({}) to find your collaborator agents and their names. ``` @@ -144,7 +145,7 @@ Use list_agents({}) to find your collaborator agents and their names. #### KV Cache 影响 -身份与通信指引作为持久记录的运行时上下文位于继承历史之后,共享系统提示词和工具定义不变。保留快照中的身份文本与当前文本不同时,会追加一份当前运行时上下文快照。设置 `includeRuntimeContext: false` 后,该必需上下文仍会提供,并会在压缩后恢复。Team 模式不会改变它。 +身份与通信指引作为持久记录的运行时上下文位于继承历史之后,共享系统提示词和工具定义不变。保留快照中的身份文本与当前文本不同时,会追加一份当前运行时上下文快照。设置 `includeRuntimeContext: false` 后,该必需上下文仍会提供,并会在压缩后恢复。切换 Team 模式会为委派子级增删汇报要求,并在下一次请求时追加一份运行时上下文快照。 ### 中断结果 diff --git a/packages/subagent/tool-subagent-control/package.json b/packages/subagent/tool-subagent-control/package.json index d5aaeebdb1..190f43675d 100644 --- a/packages/subagent/tool-subagent-control/package.json +++ b/packages/subagent/tool-subagent-control/package.json @@ -38,9 +38,16 @@ "@deepseek-ai/dsh-subagent": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-agent": "workspace:*", - "@deepseek-ai/dsh-system-prompt": "workspace:*" + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-agent-team": "workspace:*" + }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-agent-team": { + "optional": true + } }, "devDependencies": { + "@deepseek-ai/dsh-agent-team": "workspace:*", "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", diff --git a/packages/subagent/tool-subagent-control/src/index.ts b/packages/subagent/tool-subagent-control/src/index.ts index 8f9ecc95ba..4e59ff8e28 100644 --- a/packages/subagent/tool-subagent-control/src/index.ts +++ b/packages/subagent/tool-subagent-control/src/index.ts @@ -14,6 +14,7 @@ import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import { ROOT_AGENT_NAME } from '@deepseek-ai/dsh-subagent' import type {} from '@deepseek-ai/dsh-system-prompt' +import type {} from '@deepseek-ai/dsh-agent-team' import { registerListAgents } from './list-agents.ts' import { registerWaitAgent } from './wait-agent.ts' @@ -99,6 +100,11 @@ export function apply(ctx: Context, config: Config = {}): void { const guidance: string[] = [] if (ctx.tools.get(sendMessage.name, scope, toolSet) === sendMessage) { guidance.push('To message other agents, use send_message({ agent: "", message: "..." }).') + // Team mode coordinates results through shared tasks, so only plain delegation asks for a report. + if (names.parent !== undefined && ctx.get('agentTeams')?.isEnabled(agent) !== true) { + guidance.push('When you finish, use send_message to send a self-contained result to the agent that delegated you. ' + + 'Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.') + } } if (ctx.tools.get(listAgents.name, scope, toolSet) === listAgents) { guidance.push('Use list_agents({}) to find your collaborator agents and their names.') diff --git a/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts b/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts index a6b5b08860..868aec9da5 100644 --- a/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts +++ b/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts @@ -16,6 +16,7 @@ import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-test import type { SessionId } from '@deepseek-ai/dsh-session' import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import SubagentRuntime, { SubagentError } from '@deepseek-ai/dsh-subagent' +import TeamService from '@deepseek-ai/dsh-agent-team' import * as SubagentFork from '@deepseek-ai/dsh-subagent-fork-in-process' import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm' @@ -203,9 +204,10 @@ describe('dsh-tool-subagent-control', () => { }) it.each([ + { name: 'send_message', instruction: 'use send_message to send a self-contained result to the agent that delegated you', other: 'Use list_agents' }, { name: 'send_message', instruction: 'To message other agents', other: 'Use list_agents' }, { name: 'list_agents', instruction: 'Use list_agents', other: 'To message other agents' }, - ])('gates $name guidance independently in an agent scope', async ({ name, instruction, other }) => { + ])('gates $name guidance "$instruction" independently in an agent scope', async ({ name, instruction, other }) => { const { ctx, parent } = await setup([]) const { agent: child } = await ctx.agents.create({ sessionId: brandString('communication-child'), @@ -233,6 +235,26 @@ describe('dsh-tool-subagent-control', () => { toolSet.dispose() }) + it('asks a delegated agent to report with send_message only while Team mode is off', async () => { + const { ctx, parent } = await setup([]) + await ctx.plugin(TeamService) + const { agent: child } = await ctx.agents.create({ + sessionId: brandString('team-child'), + meta: { origin: 'subagent', parentSession: parent.id }, + setup: (_ctx, agent) => { bindSubagentActivation(ctx, agent, parent) }, + }) + const report = 'When you finish, use send_message to send a self-contained result to the agent that delegated you.' + const communication = async () => renderContextSnapshot(await ctx.systemPrompt.assemble({ agent: child, scope: child })) + await ctx.agentTeams.setEnabled(parent, false) + expect(await communication()).toContain(report) + await ctx.agentTeams.setEnabled(parent, true) + const team = await communication() + expect(team).not.toContain(report) + expect(team).toContain('To message other agents') + await ctx.agentTeams.setEnabled(parent, false) + expect(await communication()).toContain(report) + }) + it('keeps collaboration instructions when controls are mounted in an agent scope', async () => { const { ctx, parent, controlFiber } = await setup([]) await controlFiber.dispose() diff --git a/packages/subagent/tool-subagent-control/tsconfig.json b/packages/subagent/tool-subagent-control/tsconfig.json index 78c8a11d76..34b7189834 100644 --- a/packages/subagent/tool-subagent-control/tsconfig.json +++ b/packages/subagent/tool-subagent-control/tsconfig.json @@ -34,6 +34,9 @@ }, { "path": "../../core/system-prompt" + }, + { + "path": "../../team/agent-team" } ] } diff --git a/packages/team/tool-agent-team/README.i18n.yaml b/packages/team/tool-agent-team/README.i18n.yaml index 02c1529c0b..fa9b648aeb 100644 --- a/packages/team/tool-agent-team/README.i18n.yaml +++ b/packages/team/tool-agent-team/README.i18n.yaml @@ -39,8 +39,8 @@ en: 3b906bae9ec19393 zh: 42c8dd145c704cb3 /deepseek-ai-dsh-tool-agent-team/understand-the-implementation/policy-and-tools: - en: 79c000a90c6c05a4 - zh: 610e2cebc2431674 + en: c251c8ea9e0eb835 + zh: fe99017a1714ac16 /deepseek-ai-dsh-tool-agent-team/understand-the-implementation/scoped-registration-and-teardown: en: ee8db166c0bc8a9b zh: 6bfe192220e931a6 diff --git a/packages/team/tool-agent-team/README.md b/packages/team/tool-agent-team/README.md index a4d69ef4b3..be1ffa05fa 100644 --- a/packages/team/tool-agent-team/README.md +++ b/packages/team/tool-agent-team/README.md @@ -89,7 +89,7 @@ The [subagent teammates Agent Note](../../../.agents/notes/implemented/architect ### Policy and tools -One plugin registration provides a dynamic `team:policy` section and four conditional task tools. Each provider reads the caller’s root Session selection, including fork children. An unavailable root disables Team tools and guidance. Tree authority comes from `ctx.subagents.rootOf(agent)`; task owners remain Session ids in `ctx.agentTeams`. Owner arguments resolve through `ctx.subagents.resolveName()`, which grants no authority. Results replace the saved `ownerId` and `ownerName` fields with `owner: ownerName ?? ownerId`. Displaying a task or editing its content requires no descendant catalog reads. Identity, discovery, communication, and waiting belong to [subagent controls](../../subagent/tool-subagent-control/README.md) and remain unchanged when Team mode switches. The subagent runtime delivers final results. +One plugin registration provides a dynamic `team:policy` section and four conditional task tools. Each provider reads the caller’s root Session selection, including fork children. An unavailable root disables Team tools and guidance. Tree authority comes from `ctx.subagents.rootOf(agent)`; task owners remain Session ids in `ctx.agentTeams`. Owner arguments resolve through `ctx.subagents.resolveName()`, which grants no authority. Results replace the saved `ownerId` and `ownerName` fields with `owner: ownerName ?? ownerId`. Displaying a task or editing its content requires no descendant catalog reads. Identity, discovery, communication, and waiting belong to [subagent controls](../../subagent/tool-subagent-control/README.md) and keep that ownership when Team mode switches; enabling Team mode removes only their result report instruction. The subagent runtime delivers final results. ### Scoped registration and teardown diff --git a/packages/team/tool-agent-team/README.zh.md b/packages/team/tool-agent-team/README.zh.md index 063fbcbd26..f8fe783cbc 100644 --- a/packages/team/tool-agent-team/README.zh.md +++ b/packages/team/tool-agent-team/README.zh.md @@ -89,7 +89,7 @@ kind: "package-reference" ### 策略与工具 -一次插件注册提供动态的 `team:policy` 段落和四个条件任务工具。各提供方读取调用者根 Session 的选择,包括 fork 子级。根不可用时禁用 Team 工具与指导。树权限从 `ctx.subagents.rootOf(agent)` 派生;在 `ctx.agentTeams` 中任务负责人保留为 Session id。所有者参数通过 `ctx.subagents.resolveName()` 解析,解析不授予权限。结果以 `owner: ownerName ?? ownerId` 取代保存的 `ownerId` 和 `ownerName` 字段。展示任务或编辑其内容无需读取后代目录。身份、发现、通信和等待属于 [subagent 控制工具](../../subagent/tool-subagent-control/README.zh.md),在切换 Team 模式时保持不变。subagent 运行时负责投递最终结果。 +一次插件注册提供动态的 `team:policy` 段落和四个条件任务工具。各提供方读取调用者根 Session 的选择,包括 fork 子级。根不可用时禁用 Team 工具与指导。树权限从 `ctx.subagents.rootOf(agent)` 派生;在 `ctx.agentTeams` 中任务负责人保留为 Session id。所有者参数通过 `ctx.subagents.resolveName()` 解析,解析不授予权限。结果以 `owner: ownerName ?? ownerId` 取代保存的 `ownerId` 和 `ownerName` 字段。展示任务或编辑其内容无需读取后代目录。身份、发现、通信和等待属于 [subagent 控制工具](../../subagent/tool-subagent-control/README.zh.md),切换 Team 模式时归属不变;开启 Team 模式只会去掉其中的结果汇报要求。subagent 运行时负责投递最终结果。 ### 按作用域注册与拆除 diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 206c69c0fe..14b99cef0a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -18303,6 +18303,9 @@ importers: '@deepseek-ai/dsh-agent-loop-testkit': specifier: workspace:* version: link:../../test-support/agent-loop-testkit + '@deepseek-ai/dsh-agent-team': + specifier: workspace:* + version: link:../../team/agent-team '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index fda6ce6d8e..02e6084ed4 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -683,7 +683,7 @@ const TOOL_PACKAGES: ToolPackage[] = [ }, scope: ctx => catalogChildScopes.get(ctx) as Agent, note: - 'Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode.', + 'Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode; their result report instruction appears only while Team mode is off.', }, { pkg: '@deepseek-ai/dsh-tool-todo', diff --git a/snapshots/sdk/subagent-activation-limit/session.1.v4.jsonl b/snapshots/sdk/subagent-activation-limit/session.1.v4.jsonl index c3cc7b9594..7268d60b9b 100644 --- a/snapshots/sdk/subagent-activation-limit/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-activation-limit/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:13}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly CHILD_OK."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} diff --git a/snapshots/sdk/subagent-continuable-inheritance/session.1.v4.jsonl b/snapshots/sdk/subagent-continuable-inheritance/session.1.v4.jsonl index b3cd7ec92c..29891b60f4 100644 --- a/snapshots/sdk/subagent-continuable-inheritance/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-continuable-inheritance/session.1.v4.jsonl @@ -8,7 +8,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} diff --git a/snapshots/sdk/subagent-continuable/session.1.v4.jsonl b/snapshots/sdk/subagent-continuable/session.1.v4.jsonl index 96eeb690e2..49eb1a6479 100644 --- a/snapshots/sdk/subagent-continuable/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-continuable/session.1.v4.jsonl @@ -12,7 +12,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:20}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:16}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:21}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:21}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:22}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} diff --git a/snapshots/sdk/subagent-fork-in-process/session.1.v4.jsonl b/snapshots/sdk/subagent-fork-in-process/session.1.v4.jsonl index 19d523aa3a..a4f658304c 100644 --- a/snapshots/sdk/subagent-fork-in-process/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-fork-in-process/session.1.v4.jsonl @@ -26,7 +26,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":2,"step":1}} {"type":"user/message","data":{"content":[{"type":"text","text":"What is the project codeword mentioned earlier in this conversation? Reply with exactly that one word and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"resume"}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user asked me to remember the project codeword \"MARMALADE\" and now they're asking what it is. I should just reply with that word."},{"type":"text","text":"MARMALADE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:13}}"},"usage":{"inputTokens":97,"outputTokens":39,"cacheReadTokens":2816,"reasoningTokens":34},"stream":[{"type":"chunk","time":1793796126253,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793796126253,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," asked"," me"," to"," remember"," the"," project"," cod","ew","ord"," \"","M","ARM","AL","ADE","\""," and"," now"," they","'re"," asking"," what"," it"," is","."," I"," should"," just"," reply"," with"," that"," word","."]},{"type":"chunk","time":1793796126253,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1793796126253,"index":1,"dt":[0,0,0],"texts":["M","ARM","AL","ADE"]},{"type":"chunk","time":1793796126253,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user asked me to remember the project codeword \"MARMALADE\" and now they're asking what it is. I should just reply with that word."}}},{"type":"chunk","time":1793796126253,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"MARMALADE"}}},{"type":"chunk","time":1793796126253,"chunk":{"type":"usage","usage":{"inputTokens":97,"outputTokens":39,"cacheReadTokens":2816,"reasoningTokens":34}}},{"type":"chunk","time":1793796126253,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":1}} diff --git a/snapshots/sdk/subagent-list-agents/session.1.v4.jsonl b/snapshots/sdk/subagent-list-agents/session.1.v4.jsonl index c2ddc6ba54..3f07ed2107 100644 --- a/snapshots/sdk/subagent-list-agents/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-list-agents/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:15}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:16}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:16}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} diff --git a/snapshots/sdk/subagent-mixed/session.1.v4.jsonl b/snapshots/sdk/subagent-mixed/session.1.v4.jsonl index d2a0c54601..70de7c510f 100644 --- a/snapshots/sdk/subagent-mixed/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-mixed/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:15}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:16}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:16}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} diff --git a/snapshots/sdk/subagent-mixed/session.2.v4.jsonl b/snapshots/sdk/subagent-mixed/session.2.v4.jsonl index 38cea8dd55..a88ecf5174 100644 --- a/snapshots/sdk/subagent-mixed/session.2.v4.jsonl +++ b/snapshots/sdk/subagent-mixed/session.2.v4.jsonl @@ -26,7 +26,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":2,"step":1}} {"type":"user/message","data":{"content":[{"type":"text","text":"What is the project codeword mentioned earlier in this conversation? Reply with exactly that one word and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:19}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:20}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:20}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"resume"}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user is asking me to recall the project codeword that was mentioned earlier in the conversation. I was told to remember it: SAFFRON."},{"type":"text","text":"SAFFRON"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:21}}"},"usage":{"inputTokens":95,"outputTokens":35,"cacheReadTokens":2816,"reasoningTokens":31},"stream":[{"type":"chunk","time":1793796127698,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793796127698,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," is"," asking"," me"," to"," recall"," the"," project"," cod","ew","ord"," that"," was"," mentioned"," earlier"," in"," the"," conversation","."," I"," was"," told"," to"," remember"," it",":"," SA","FF","RON","."]},{"type":"chunk","time":1793796127698,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1793796127698,"index":1,"dt":[0,0],"texts":["SA","FF","RON"]},{"type":"chunk","time":1793796127698,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user is asking me to recall the project codeword that was mentioned earlier in the conversation. I was told to remember it: SAFFRON."}}},{"type":"chunk","time":1793796127698,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"SAFFRON"}}},{"type":"chunk","time":1793796127698,"chunk":{"type":"usage","usage":{"inputTokens":95,"outputTokens":35,"cacheReadTokens":2816,"reasoningTokens":31}}},{"type":"chunk","time":1793796127698,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":1}} diff --git a/snapshots/sdk/subagent-send-message/session.1.v4.jsonl b/snapshots/sdk/subagent-send-message/session.1.v4.jsonl index d2decca80d..5c9f47fad3 100644 --- a/snapshots/sdk/subagent-send-message/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-send-message/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:14}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Send exactly CHILD_MESSAGE_OK to your parent with send_message, then stop."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:16}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} diff --git a/snapshots/sdk/subagent-spawn-in-process/notifications.expected.jsonl b/snapshots/sdk/subagent-spawn-in-process/notifications.expected.jsonl index 5feb3241f3..d9b754e40a 100644 --- a/snapshots/sdk/subagent-spawn-in-process/notifications.expected.jsonl +++ b/snapshots/sdk/subagent-spawn-in-process/notifications.expected.jsonl @@ -24,7 +24,7 @@ {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"Reply with exactly: child answer 42."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":10,"time":0,"data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":11,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/context","seq":12,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}}} diff --git a/snapshots/sdk/subagent-spawn-in-process/session.1.v4.jsonl b/snapshots/sdk/subagent-spawn-in-process/session.1.v4.jsonl index 42a8cca90a..3a765d41c2 100644 --- a/snapshots/sdk/subagent-spawn-in-process/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-spawn-in-process/session.1.v4.jsonl @@ -8,7 +8,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly: child answer 42."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} diff --git a/snapshots/session/advanced-toolchain-runtime/session.1.v4.jsonl b/snapshots/session/advanced-toolchain-runtime/session.1.v4.jsonl index 0459818119..a2fdb349d2 100644 --- a/snapshots/session/advanced-toolchain-runtime/session.1.v4.jsonl +++ b/snapshots/session/advanced-toolchain-runtime/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:15}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:16}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:16}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly DIRECT_CHILD_OK and","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/advanced-toolchain-runtime/session.2.v4.jsonl b/snapshots/session/advanced-toolchain-runtime/session.2.v4.jsonl index 5f04bbd358..b324dd8ca4 100644 --- a/snapshots/session/advanced-toolchain-runtime/session.2.v4.jsonl +++ b/snapshots/session/advanced-toolchain-runtime/session.2.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:19}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{message:18}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:20}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:20}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly WORKFLOW_CHILD_OK and","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/advanced-toolchain/session.1.v4.jsonl b/snapshots/session/advanced-toolchain/session.1.v4.jsonl index c76902452a..5448dc8976 100644 --- a/snapshots/session/advanced-toolchain/session.1.v4.jsonl +++ b/snapshots/session/advanced-toolchain/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:21}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:20}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:22}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:22}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly DIRECT_CHILD_OK and","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/advanced-toolchain/session.2.v4.jsonl b/snapshots/session/advanced-toolchain/session.2.v4.jsonl index c023e2862b..4aeef9e8c1 100644 --- a/snapshots/session/advanced-toolchain/session.2.v4.jsonl +++ b/snapshots/session/advanced-toolchain/session.2.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:25}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{message:24}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:26}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:26}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly WORKFLOW_CHILD_OK and","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/ralph-loop/session.1.v4.jsonl b/snapshots/session/ralph-loop/session.1.v4.jsonl index 1fc1bef3f1..82a097c2e3 100644 --- a/snapshots/session/ralph-loop/session.1.v4.jsonl +++ b/snapshots/session/ralph-loop/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:8}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"You are one fresh worker in a foreground Ralph loop. You receive no parent conversation and no prior child session. Do not call the ralph tool: this round already is its worker.\n\nImmutable objective:\nProve two fresh Ralph rounds through the shipped headless app.\n\nRalph round: 1 of 2.\n\nThe shared workspace and its current working tree are the long-term memory and source of truth. Inspect them before acting, preserve existing work, perform concrete in-scope work, and verify what you change. Treat the previous report only as a bounded handoff; confirm it against the workspace.\n\nPrevious structured handoff:\n(none — this is the first round)\n\nReturn one report with exact normalized strings. Use status continue with at least one nextSteps entry while useful work remains; complete only with concrete evidence and no nextSteps; blocked only when no meaningful progress is possible without human input or an external-state change. blocker must be empty unless blocked."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"You are one fresh worker","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/ralph-loop/session.2.v4.jsonl b/snapshots/session/ralph-loop/session.2.v4.jsonl index 8bcd71e4f5..c73c2a1649 100644 --- a/snapshots/session/ralph-loop/session.2.v4.jsonl +++ b/snapshots/session/ralph-loop/session.2.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:13}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"You are one fresh worker in a foreground Ralph loop. You receive no parent conversation and no prior child session. Do not call the ralph tool: this round already is its worker.\n\nImmutable objective:\nProve two fresh Ralph rounds through the shipped headless app.\n\nRalph round: 2 of 2.\n\nThe shared workspace and its current working tree are the long-term memory and source of truth. Inspect them before acting, preserve existing work, perform concrete in-scope work, and verify what you change. Treat the previous report only as a bounded handoff; confirm it against the workspace.\n\nPrevious structured handoff:\n{\"status\":\"continue\",\"summary\":\"ROUND_ONE_HANDOFF\",\"evidence\":[\"Round one inspected the workspace.\"],\"nextSteps\":[\"Finish the snapshot objective.\"],\"blocker\":\"\"}\n\nReturn one report with exact normalized strings. Use status continue with at least one nextSteps entry while useful work remains; complete only with concrete evidence and no nextSteps; blocked only when no meaningful progress is possible without human input or an external-state change. blocker must be empty unless blocked."}],"source":{"kind":"user"},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"You are one fresh worker","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-agent-preset/session.1.v4.jsonl b/snapshots/session/subagent-agent-preset/session.1.v4.jsonl index b23559714e..62bf1c479e 100644 --- a/snapshots/session/subagent-agent-preset/session.1.v4.jsonl +++ b/snapshots/session/subagent-agent-preset/session.1.v4.jsonl @@ -10,7 +10,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nDelegation depth for `reviewer_delegate`: current 1, maximum 1, remaining levels 0. Do not call `reviewer_delegate` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"tool:reviewer_delegate:depth","text":"Delegation depth for `reviewer_delegate`: current 1, maximum 1, remaining levels 0. Do not call `reviewer_delegate` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nDelegation depth for `reviewer_delegate`: current 1, maximum 1, remaining levels 0. Do not call `reviewer_delegate` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"tool:reviewer_delegate:depth","text":"Delegation depth for `reviewer_delegate`: current 1, maximum 1, remaining levels 0. Do not call `reviewer_delegate` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly the word","messageSeqs":[10],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-archive-lineage/session.1.v4.jsonl b/snapshots/session/subagent-archive-lineage/session.1.v4.jsonl index c29300ad07..ba37cda623 100644 --- a/snapshots/session/subagent-archive-lineage/session.1.v4.jsonl +++ b/snapshots/session/subagent-archive-lineage/session.1.v4.jsonl @@ -10,7 +10,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:8}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with DONE.","messageSeqs":[10],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-archive-lineage/session.2.v4.jsonl b/snapshots/session/subagent-archive-lineage/session.2.v4.jsonl index 5244e25c40..a1127c04f6 100644 --- a/snapshots/session/subagent-archive-lineage/session.2.v4.jsonl +++ b/snapshots/session/subagent-archive-lineage/session.2.v4.jsonl @@ -10,7 +10,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:12}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 2, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 2, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 2, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 2, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 2, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 2, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 2, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 2, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with DONE.","messageSeqs":[10],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-child-question-rejection/session.1.v4.jsonl b/snapshots/session/subagent-child-question-rejection/session.1.v4.jsonl index bba60d00bc..99c7c7736b 100644 --- a/snapshots/session/subagent-child-question-rejection/session.1.v4.jsonl +++ b/snapshots/session/subagent-child-question-rejection/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Call ask_user_question once to ask whether deployment should use the CUDA fallback. If the tool returns an error, include the unresolved question verbatim in your final result."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Call ask_user_question once to ask","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-depth-two-rejection/session.1.v4.jsonl b/snapshots/session/subagent-depth-two-rejection/session.1.v4.jsonl index 0f3435e07c..311b781f19 100644 --- a/snapshots/session/subagent-depth-two-rejection/session.1.v4.jsonl +++ b/snapshots/session/subagent-depth-two-rejection/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Call subagent once. Ask that child to attempt one further subagent call, then report the result."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Call subagent once. Ask that","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl b/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl index dfa91ecadc..8ee62bf7c6 100644 --- a/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl +++ b/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:16}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Attempt one subagent call beyond the configured cap, then report the rejection."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 2, maximum 2, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 2, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 2, maximum 2, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 2, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 2, maximum 2, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 2, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 2, maximum 2, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 2, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Attempt one subagent call beyond","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-max-tokens-partial/session.1.v4.jsonl b/snapshots/session/subagent-max-tokens-partial/session.1.v4.jsonl index f2650839c3..eeba0b0a5e 100644 --- a/snapshots/session/subagent-max-tokens-partial/session.1.v4.jsonl +++ b/snapshots/session/subagent-max-tokens-partial/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Write the words 'partial one', call todo_write once, then keep going until you are cut off."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Write the words 'partial one',","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-multi/writer.1.expected.jsonl b/snapshots/session/subagent-multi/writer.1.expected.jsonl index b075fda0c0..dcd07b256c 100644 --- a/snapshots/session/subagent-multi/writer.1.expected.jsonl +++ b/snapshots/session/subagent-multi/writer.1.expected.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:12}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly the word","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-multi/writer.2.expected.jsonl b/snapshots/session/subagent-multi/writer.2.expected.jsonl index 37b742eec6..e45c4a496e 100644 --- a/snapshots/session/subagent-multi/writer.2.expected.jsonl +++ b/snapshots/session/subagent-multi/writer.2.expected.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:16}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word BETA and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly the word","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-parallel/session.1.v4.jsonl b/snapshots/session/subagent-parallel/session.1.v4.jsonl index c131526718..7e2d815ada 100644 --- a/snapshots/session/subagent-parallel/session.1.v4.jsonl +++ b/snapshots/session/subagent-parallel/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:12}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly the word","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-parallel/session.2.v4.jsonl b/snapshots/session/subagent-parallel/session.2.v4.jsonl index 6525354d1e..28708982d9 100644 --- a/snapshots/session/subagent-parallel/session.2.v4.jsonl +++ b/snapshots/session/subagent-parallel/session.2.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:16}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly the word","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-spawn-in-process/session.1.v4.jsonl b/snapshots/session/subagent-spawn-in-process/session.1.v4.jsonl index f074f5e678..e68b196770 100644 --- a/snapshots/session/subagent-spawn-in-process/session.1.v4.jsonl +++ b/snapshots/session/subagent-spawn-in-process/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly the word","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-structured-parent/session.1.v4.jsonl b/snapshots/session/subagent-structured-parent/session.1.v4.jsonl index 9f3180e9f2..73fd031599 100644 --- a/snapshots/session/subagent-structured-parent/session.1.v4.jsonl +++ b/snapshots/session/subagent-structured-parent/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:9}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Submit answer 41 through structured_output."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:8}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:10}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:10}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Submit answer 41 through structured_outp","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/subagent-tool-filter/session.1.v4.jsonl b/snapshots/session/subagent-tool-filter/session.1.v4.jsonl index 9c2e91a3aa..5bc7d5d835 100644 --- a/snapshots/session/subagent-tool-filter/session.1.v4.jsonl +++ b/snapshots/session/subagent-tool-filter/session.1.v4.jsonl @@ -10,7 +10,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly the word","messageSeqs":[10],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/workflow-run/session.1.v4.jsonl b/snapshots/session/workflow-run/session.1.v4.jsonl index 5085aaa87e..c7a7977247 100644 --- a/snapshots/session/workflow-run/session.1.v4.jsonl +++ b/snapshots/session/workflow-run/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:8}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word WF_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly the word","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl b/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl index 4e79a3846a..12daf4b503 100644 --- a/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl +++ b/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl @@ -26,7 +26,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":2,"step":1}} {"type":"user/message","data":{"content":[{"type":"text","text":"Call schedule_create and schedule_list once each, then schedule_edit with update and delete, then reply CHILD_DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\".\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:8}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\".\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:8}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"resume"}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_schedule_create","name":"schedule_create","arguments":"{\"title\":\"Child reminder\",\"prompt\":\"Check this\",\"rrule\":\"DTSTART:20990101T090000Z\\nRRULE:FREQ=DAILY;COUNT=1\",\"target\":\"this_session\"}"},{"type":"tool-call","id":"call_schedule_list","name":"schedule_list","arguments":"{}"},{"type":"tool-call","id":"call_schedule_update","name":"schedule_edit","arguments":"{\"id\":\"missing-reminder\",\"action\":\"update\",\"prompt\":\"Forbidden child edit\"}"},{"type":"tool-call","id":"call_schedule_delete","name":"schedule_edit","arguments":"{\"id\":\"missing-reminder\",\"action\":\"delete\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:9}}"},"stream":[{"type":"chunk","time":1793795800838,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793795800838,"index":0,"dt":[],"id":"call_schedule_create","name":"schedule_create","args":["{\"title\":\"Child reminder\",\"prompt\":\"Check this\",\"rrule\":\"DTSTART:20990101T090000Z\\nRRULE:FREQ=DAILY;COUNT=1\",\"target\":\"this_session\"}"]},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_schedule_create","name":"schedule_create","arguments":"{\"title\":\"Child reminder\",\"prompt\":\"Check this\",\"rrule\":\"DTSTART:20990101T090000Z\\nRRULE:FREQ=DAILY;COUNT=1\",\"target\":\"this_session\"}"}}},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793795800838,"index":1,"dt":[],"id":"call_schedule_list","name":"schedule_list","args":["{}"]},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_schedule_list","name":"schedule_list","arguments":"{}"}}},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-start","index":2,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793795800838,"index":2,"dt":[],"id":"call_schedule_update","name":"schedule_edit","args":["{\"id\":\"missing-reminder\",\"action\":\"update\",\"prompt\":\"Forbidden child edit\"}"]},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-end","index":2,"block":{"type":"tool-call","id":"call_schedule_update","name":"schedule_edit","arguments":"{\"id\":\"missing-reminder\",\"action\":\"update\",\"prompt\":\"Forbidden child edit\"}"}}},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-start","index":3,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793795800838,"index":3,"dt":[],"id":"call_schedule_delete","name":"schedule_edit","args":["{\"id\":\"missing-reminder\",\"action\":\"delete\"}"]},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-end","index":3,"block":{"type":"tool-call","id":"call_schedule_delete","name":"schedule_edit","arguments":"{\"id\":\"missing-reminder\",\"action\":\"delete\"}"}}},{"type":"chunk","time":1793795800838,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":2,"step":1,"callId":"call_schedule_create","name":"schedule_create","arguments":"{\"title\":\"Child reminder\",\"prompt\":\"Check this\",\"rrule\":\"DTSTART:20990101T090000Z\\nRRULE:FREQ=DAILY;COUNT=1\",\"target\":\"this_session\"}"}} From db364733721161eb3f2249ed230c15e4ecde2e52 Mon Sep 17 00:00:00 2001 From: Shigma Date: Mon, 16 Nov 2026 17:55:56 +0800 Subject: [PATCH 42/48] fix(app-boot): resolve drive-letter include paths as Include does --- .../app-boot/src/compatibility-preflight.ts | 3 ++- .../app-boot/src/config-schema/collect.ts | 5 +++-- .../boot/app-boot/src/include-filename.ts | 22 +++++++++++++++++++ .../boot/app-boot/tests/config-schema.spec.ts | 15 +++++++++++++ .../app-boot/tests/include-filename.spec.ts | 17 ++++++++++++++ 5 files changed, 59 insertions(+), 3 deletions(-) create mode 100644 packages/boot/app-boot/src/include-filename.ts create mode 100644 packages/boot/app-boot/tests/include-filename.spec.ts diff --git a/packages/boot/app-boot/src/compatibility-preflight.ts b/packages/boot/app-boot/src/compatibility-preflight.ts index 0cfe31d15b..c31bfac7b9 100644 --- a/packages/boot/app-boot/src/compatibility-preflight.ts +++ b/packages/boot/app-boot/src/compatibility-preflight.ts @@ -12,6 +12,7 @@ import type {} from './profile-resolution/service.ts' import type {} from './profile-context.ts' import { evaluatePluginCompatibility, pluginCompatibilityWarning } from './plugin-compatibility.ts' import { readProfileCompatibility } from './profile-compatibility.ts' +import { includeFilename } from './include-filename.ts' function readManifest(filename: string): object { return JSON.parse(readFileSync(filename, 'utf8')) as object @@ -144,7 +145,7 @@ function preflight( // A dynamic Include is resolved by the Include plugin itself; this walk cannot judge its rows. return undefined } - const requested = isAbsolute(config.path) ? config.path : fileURLToPath(new URL(config.path, base)) + const requested = includeFilename(config.path, base) const filename = existsSync(requested) ? realpathSync(requested) : requested if (includes.has(filename)) return undefined includes.add(filename) diff --git a/packages/boot/app-boot/src/config-schema/collect.ts b/packages/boot/app-boot/src/config-schema/collect.ts index ef57de682e..ad630f17f8 100644 --- a/packages/boot/app-boot/src/config-schema/collect.ts +++ b/packages/boot/app-boot/src/config-schema/collect.ts @@ -2,7 +2,7 @@ import { readFile, realpath } from 'node:fs/promises' import { extname, join } from 'node:path' -import { fileURLToPath, pathToFileURL } from 'node:url' +import { pathToFileURL } from 'node:url' import Loader, { EntryGroup, ModuleLoader, isJsExpr, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader' import Group from '@deepseek-ai/cordis-plugin-group' import Include, { applyEntryPatches, entryYamlErrorPosition, parseEntryYaml, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' @@ -11,6 +11,7 @@ import { installRuntimeInterception } from '../profile-resolution/resolver.ts' import { buildConfigSchemaDocument } from './document.ts' import type { CollectedConfigEntry, ConfigSchemaDiagnostic, ConfigSchemaDump } from './types.ts' import { isNativeConfigSchema } from './native.ts' +import { includeFilename } from '../include-filename.ts' interface ParsedEntry { id?: string @@ -129,7 +130,7 @@ export async function collectConfigSchemas( if (config === undefined) throw new Error('include config is missing') if (!record(config) || isJsExpr(config)) throw new Error('include config must be literal; config expressions are not evaluated') if (typeof config.path !== 'string') throw new Error('include path must be literal; config expressions are not evaluated') - const filename = fileURLToPath(new URL(config.path, baseUrl)) + const filename = includeFilename(config.path, baseUrl) const extension = extname(filename) if (!['.json', '.yaml', '.yml'].includes(extension)) throw new Error(`include extension ${JSON.stringify(extension)} is not supported`) let source: unknown diff --git a/packages/boot/app-boot/src/include-filename.ts b/packages/boot/app-boot/src/include-filename.ts new file mode 100644 index 0000000000..9daebba362 --- /dev/null +++ b/packages/boot/app-boot/src/include-filename.ts @@ -0,0 +1,22 @@ +/** Resolve an Include `path` to the file the Include plugin reads. */ + +import { fileURLToPath, pathToFileURL } from 'node:url' + +// A Windows drive-letter path, e.g. `C:\app\cordis.yml` or `C:/app/cordis.yml`. +const DRIVE_LETTER = /^[A-Za-z]:[\\/]/u + +/** + * Resolve an Include `path` as the vendored Include does: on Windows a drive-letter path is a file path, and every + * other path is a URL reference resolved against the owning tree's base URL. + * @param path - literal Include `path`. + * @param baseUrl - base URL of the tree that owns the Include entry. + * @param platform - platform whose path rules apply; defaults to the running one. + * @returns the absolute filename. + * @throws when `path` resolves to a URL that is not a `file:` URL. + */ +export function includeFilename(path: string, baseUrl: string, platform: NodeJS.Platform = process.platform): string { + if (platform === 'win32' && DRIVE_LETTER.test(path)) { + return fileURLToPath(pathToFileURL(path, { windows: true }), { windows: true }) + } + return fileURLToPath(new URL(path, baseUrl)) +} diff --git a/packages/boot/app-boot/tests/config-schema.spec.ts b/packages/boot/app-boot/tests/config-schema.spec.ts index e63a12cfab..339005826d 100644 --- a/packages/boot/app-boot/tests/config-schema.spec.ts +++ b/packages/boot/app-boot/tests/config-schema.spec.ts @@ -445,6 +445,21 @@ describe('collectConfigSchemas', () => { expect(result['x-cordis'].complete).toBe(false) }) + it('resolves a drive-letter include path on Windows as Include does', async () => { + modules.set('good', { Config: Schema.string() }) + const platform = Object.getOwnPropertyDescriptor(process, 'platform')! + Object.defineProperty(process, 'platform', { ...platform, value: 'win32' }) + try { + const result = await collectConfigSchemas(profile, [ + row('cordis:include', { path: 'C:/dsh-missing/extra.yml', initial: [row('good')] }), + ], resolution) + expect(result['x-cordis'].diagnostics).toEqual([]) + expect(result['x-cordis'].entries.map(entry => [entry.path, entry.status])).toEqual([['/0', 'absent'], ['/0/include/0', 'schema']]) + } finally { + Object.defineProperty(process, 'platform', platform) + } + }) + it('leaves the caller\'s include patches unchanged when a patch replaces a group config', async () => { const patches = [{ id: 'group', config: [{ name: 'noop' }] }] await collectConfigSchemas(profile, [row('cordis:include', { diff --git a/packages/boot/app-boot/tests/include-filename.spec.ts b/packages/boot/app-boot/tests/include-filename.spec.ts new file mode 100644 index 0000000000..ef24820fdb --- /dev/null +++ b/packages/boot/app-boot/tests/include-filename.spec.ts @@ -0,0 +1,17 @@ +/** Include `path` resolution shared by the schema collector and compatibility preflight. */ +import { describe, expect, it } from 'vitest' +import { includeFilename } from '../src/include-filename.ts' + +describe('includeFilename', () => { + it('reads a drive-letter path as a Windows file path on Windows', () => { + expect(includeFilename('C:/config/extra.yml', 'file:///D:/app/', 'win32')).toBe('C:\\config\\extra.yml') + expect(includeFilename('c:\\config\\extra.yml', 'file:///D:/app/', 'win32')).toBe('c:\\config\\extra.yml') + }) + + it('resolves other paths against the tree base URL', () => { + expect(includeFilename('./extra.yml', 'file:///app/cordis.yml', 'linux')).toBe('/app/extra.yml') + expect(includeFilename('file:///etc/extra.yml', 'file:///app/', 'linux')).toBe('/etc/extra.yml') + // Off Windows, Include reads `C:` as a URL scheme too. + expect(() => includeFilename('C:/config/extra.yml', 'file:///app/', 'linux')).toThrow() + }) +}) From 077a9cde0bc0955f5e27cf48431ca8fec609b324 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Mon, 16 Nov 2026 18:10:15 +0800 Subject: [PATCH 43/48] feat(cua): add toggleMouse with initial Windows support (#8425) * feat(cua-windows): implement window-level mouse button toggles * Update guidance * Fix prompt test --- .../profiles/cua-mcp/expected/reference.md | 10 +- .../CuaNative/NativeProtocol.generated.swift | 2 + .../cua-macos/native/protocol.schema.json | 53 +++++++ .../experimental/cua-macos/src/guidance.ts | 1 + .../cua-macos/tests/guidance.spec.ts | 54 +++++-- .../native/desktop-tests/Program.cs | 70 +++++++++ .../native/entry/DesktopExecutor.cs | 6 + .../cua-windows/native/entry/Input.cs | 12 ++ .../cua-windows/native/protocol.schema.json | 53 +++++++ .../cua-windows/native/tests/Program.cs | 22 +++ .../experimental/cua-windows/src/index.ts | 2 +- .../tests/desktop-toggle-mouse.spec.ts | 145 ++++++++++++++++++ .../tests/loader-composition.spec.ts | 6 + .../tests/provider-lifecycle.spec.ts | 1 + packages/experimental/cua/src/api.ts | 3 + packages/experimental/cua/src/guidance.ts | 10 +- packages/experimental/cua/src/protocol.ts | 1 + packages/experimental/cua/src/types.ts | 10 +- packages/experimental/cua/tests/api.spec.ts | 32 ++++ .../cua/tests/native-schema.spec.ts | 7 + .../experimental/cua/tests/protocol.spec.ts | 22 +++ .../cua-run-code/system-prompt.expected.md | 10 +- .../cua-native/system-prompt.expected.md | 10 +- .../cua-native/tool-schemas.expected.json | 49 ++++++ .../session/cua-ptc/system-prompt.expected.md | 10 +- .../system-prompt.expected.md | 10 +- .../cua-run-code/system-prompt.expected.md | 10 +- .../system-prompt.expected.md | 10 +- 28 files changed, 600 insertions(+), 31 deletions(-) create mode 100644 packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts diff --git a/apps/cli/tests/profiles/cua-mcp/expected/reference.md b/apps/cli/tests/profiles/cua-mcp/expected/reference.md index c7ef7c99e1..ea7301ee1b 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/reference.md +++ b/apps/cli/tests/profiles/cua-mcp/expected/reference.md @@ -31,10 +31,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -48,6 +52,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift index 39e9f04e49..a7317d8e38 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift @@ -30,6 +30,7 @@ enum NativeProtocol { "sendKeyEvent": ["appHandle", "direction", "key", "runId", "windowId"], "setValue": ["appHandle", "elementId", "snapshotId", "value", "windowId"], "show": ["appHandle", "windowId"], + "toggleMouse": ["appHandle", "direction", "mouseButton", "windowId"], "typeText": ["appHandle", "text", "windowId"], ] static let stringEnums: [String: [String: Set]] = [ @@ -40,5 +41,6 @@ enum NativeProtocol { "requestPermission": ["permission": ["accessibility", "screenRecording"]], "selectText": ["selectionType": ["cursor_after", "cursor_before", "text"]], "sendKeyEvent": ["direction": ["down", "up"]], + "toggleMouse": ["direction": ["down", "up"], "mouseButton": ["left", "middle", "right"]], ] } diff --git a/packages/experimental/cua-macos/native/protocol.schema.json b/packages/experimental/cua-macos/native/protocol.schema.json index 801414e010..472c3f3b80 100644 --- a/packages/experimental/cua-macos/native/protocol.schema.json +++ b/packages/experimental/cua-macos/native/protocol.schema.json @@ -451,6 +451,59 @@ ], "additionalProperties": false }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "toggleMouse" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "string", + "minLength": 1 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "direction": { + "type": "string", + "enum": [ + "down", + "up" + ] + } + }, + "required": [ + "appHandle", + "windowId", + "mouseButton", + "direction" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, { "type": "object", "properties": { diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 332d36f163..20f5257334 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -13,6 +13,7 @@ function operationGuidance(treeAdvice: string): string { ['sendKeyEvent', "Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients."], ['getAccessibilityTree', `macOS accepts maxElements up to 100000 and maxDepth up to 512. If the tree is truncated, select a narrower window or raise the reported limit on the next read. ${treeAdvice} Use element ids from the file only while that observation is current.`], ['mouseMove', 'With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again.'], + ['toggleMouse', 'Not implemented on macOS.'], ['drag', 'Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window.'], ['click', 'click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying.'], ]) diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index f31ca9e6b7..3fb53d70e3 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -1,4 +1,4 @@ -/** Model-facing guidance enumerates the full available object API without unavailable operations. */ +/** Model-facing guidance lists the object API with platform availability and input constraints. */ import { expect, it } from 'vitest' import type { CuaApi, CuaApp, CuaSurface, CuaWindow } from '@deepseek-ai/dsh-cua/api' import { COMMON_GUIDANCE, withSystemPointerGuidance } from '@deepseek-ai/dsh-cua/guidance' @@ -9,7 +9,7 @@ const accessibilityNames: Array> = [ 'getAccessibilityTree', 'listActions', 'invoke', 'performAction', 'setValue', 'selectText', ] const appNames: Array = ['appHandle', 'activate', 'getWindows', 'getWindow'] -const windowNames: Array = ['windowId', 'getScreenshot', 'mouseMove', 'click', 'scroll', 'drag'] +const windowNames: Array = ['windowId', 'getScreenshot', 'mouseMove', 'toggleMouse', 'click', 'scroll', 'drag'] it('keeps file-tool instructions in PTC and limits the program guidance to available bindings', () => { for (const name of ['tools.write', 'tools.grep', 'tools.read']) { @@ -20,11 +20,13 @@ it('keeps file-tool instructions in PTC and limits the program guidance to avail expect(PROGRAM_GUIDANCE).toContain('session’s file tools') }) -it('keeps exactly three ordered operation headings', () => { - const heads = COMMON_GUIDANCE.match(/^## .+$/gm) - expect(heads).toEqual(['## Accessibility tree', '## Simulated mouse', '## Simulated keyboard']) - expect(COMMON_GUIDANCE.indexOf('## Accessibility tree')).toBeLessThan(COMMON_GUIDANCE.indexOf('## Simulated mouse')) - expect(COMMON_GUIDANCE.indexOf('## Simulated mouse')).toBeLessThan(COMMON_GUIDANCE.indexOf('## Simulated keyboard')) +it('places observation chapters before simulated input with screenshots in their own chapter', () => { + for (const catalog of [COMMON_GUIDANCE, GUIDANCE, PROGRAM_GUIDANCE]) { + expect(catalog.match(/^## .+$/gm)).toEqual(['## Accessibility tree', '## Screenshots', '## Simulated mouse', '## Simulated keyboard']) + const screenshots = catalog.slice(catalog.indexOf('## Screenshots'), catalog.indexOf('## Simulated mouse')) + expect(screenshots).toContain('- getScreenshot() -> Image') + expect(catalog.slice(catalog.indexOf('## Simulated mouse'))).not.toContain('- getScreenshot(') + } }) it('prefixes concise platform guidance before the shared catalog', () => { @@ -67,7 +69,23 @@ it('states the macOS accessibility, keyboard, and mouse levels', () => { } }) -it('enumerates every available method once in its catalog entry', () => { +it('documents explicit mouse-button events immediately after mouseMove', () => { + const lines = COMMON_GUIDANCE.split('\n') + const index = lines.findIndex(line => line.startsWith('- toggleMouse(')) + expect(lines[index - 1]).toMatch(/^- mouseMove\(/) + expect(lines[index]).toBe("- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically.") + expect(index).toBeGreaterThan(lines.indexOf('## Simulated mouse')) + expect(index).toBeLessThan(lines.indexOf('## Simulated keyboard')) +}) + +it.each([GUIDANCE, PROGRAM_GUIDANCE])('marks toggleMouse as unavailable in the macOS method entry', (catalog) => { + const shared = COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- toggleMouse(')) + const entry = catalog.split('\n').find(line => line.startsWith('- toggleMouse(')) + expect(entry).toBe(`${shared} Not implemented on macOS.`) + expect(PLATFORM_GUIDANCE).not.toContain('toggleMouse') +}) + +it('enumerates every public method once in its catalog entry', () => { const signatures = [ ...apiNames.map(name => `cua.${name}(`), ...appNames.filter(name => name !== 'appHandle').map(name => `app.${name}(`), @@ -79,8 +97,8 @@ it('enumerates every available method once in its catalog entry', () => { for (const catalog of [COMMON_GUIDANCE, GUIDANCE, PROGRAM_GUIDANCE]) { for (const signature of signatures) expect(catalog.split('\n').filter(line => line.startsWith(`- ${signature}`))).toHaveLength(1) } - expect(signatures).toHaveLength(25) - expect(new Set(signatures.map(signature => signature.slice(signature.indexOf('.') + 1, -1))).size).toBe(24) + expect(signatures).toHaveLength(26) + expect(new Set(signatures.map(signature => signature.slice(signature.indexOf('.') + 1, -1))).size).toBe(25) expect(COMMON_GUIDANCE).toContain('app.appHandle') expect(COMMON_GUIDANCE).toContain('window.windowId') }) @@ -128,7 +146,8 @@ it('references Modifier without defining its members in shared guidance', () => }) it('states platform-dependent levels without qualifying grouped method names', () => { - expect(COMMON_GUIDANCE).toContain('## Simulated mouse\nUse an explicit window for screenshots and pointer input.') + expect(COMMON_GUIDANCE).toContain('## Screenshots\nUse an explicit window for screenshots.') + expect(COMMON_GUIDANCE).toContain('## Simulated mouse\nUse an explicit window for pointer input.') for (const heading of ['Accessibility tree', 'Simulated keyboard']) { expect(COMMON_GUIDANCE).toContain(`## ${heading}\nAvailable at app or window level depending on the platform.`) } @@ -139,6 +158,15 @@ it('states platform-dependent levels without qualifying grouped method names', ( expect(COMMON_GUIDANCE).toContain('from: [number, number]') }) +it('guides complex input combinations through platform-supported primitive operations', () => { + const advice = 'click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform.' + for (const catalog of [COMMON_GUIDANCE, GUIDANCE, PROGRAM_GUIDANCE]) { + expect(catalog).toContain(advice) + expect(catalog.indexOf(advice)).toBeGreaterThan(catalog.indexOf('- sendKeyEvent(')) + expect(catalog.indexOf(advice)).toBeLessThan(catalog.indexOf('Raw tools use { method, params }')) + } +}) + it('keeps consent, lock, observation, and no-replay rules', () => { expect(COMMON_GUIDANCE).toContain('consent') expect(COMMON_GUIDANCE).toContain('SESSION_LOCKED') @@ -159,6 +187,6 @@ it('documents explicit inspection and separate key arguments', () => { expect(COMMON_GUIDANCE).toContain('perform a left-button double-click') }) -it('omits stale names and unavailable platform operations', () => { - for (const stale of ['getAXState', 'emit', 'disableDiffing', 'performSecondaryAction', 'hover(', 'keyChord', 'window.typeText', 'window.pressKey', 'elementIndex', 'verified: false', 'browser tabs', 'not implemented']) expect(GUIDANCE).not.toContain(stale) +it('omits stale names and unrelated operations', () => { + for (const stale of ['getAXState', 'emit', 'disableDiffing', 'performSecondaryAction', 'hover(', 'keyChord', 'window.typeText', 'window.pressKey', 'elementIndex', 'verified: false', 'browser tabs']) expect(GUIDANCE).not.toContain(stale) }) diff --git a/packages/experimental/cua-windows/native/desktop-tests/Program.cs b/packages/experimental/cua-windows/native/desktop-tests/Program.cs index 58421dec24..3371433909 100644 --- a/packages/experimental/cua-windows/native/desktop-tests/Program.cs +++ b/packages/experimental/cua-windows/native/desktop-tests/Program.cs @@ -11,6 +11,7 @@ internal sealed class FixtureForm : Form internal readonly TextBox Editor = new() { Name = "editor", AccessibleName = "CUA test text", Multiline = true, Bounds = new(20, 20, 440, 100) }; private readonly Button button = new() { Name = "submit", Text = "Record click", Bounds = new(20, 140, 180, 40) }; private int clicks; + private int leftDowns, leftUps, rightDowns, rightUps, middleDowns, middleUps; private readonly ToolTip tooltip = new(); internal FixtureForm(string title) @@ -22,13 +23,55 @@ internal sealed class FixtureForm : Form Controls.Add(Editor); Controls.Add(button); button.Click += (_, _) => clicks++; + button.MouseDown += (_, e) => Count(e.Button, down: true); + button.MouseUp += (_, e) => Count(e.Button, down: false); + Editor.MouseDown += (_, e) => Count(e.Button, down: true); + Editor.MouseUp += (_, e) => Count(e.Button, down: false); tooltip.SetToolTip(button, "CUA hover is retained"); } + private void Count(MouseButtons pressed, bool down) + { + switch (pressed) + { + case MouseButtons.Left: if (down) leftDowns++; else leftUps++; break; + case MouseButtons.Right: if (down) rightDowns++; else rightUps++; break; + case MouseButtons.Middle: if (down) middleDowns++; else middleUps++; break; + } + } + + internal void PointAtButton() => Cursor.Position = button.PointToScreen(new Point(button.Width / 2, button.Height / 2)); + + internal void PointOutside() + { + var bounds = RectangleToScreen(ClientRectangle); + Cursor.Position = new Point(bounds.Right + 40, bounds.Top + 20); + } + + internal void Cover(FixtureForm cover) + { + cover.Bounds = Bounds; + cover.TopMost = true; + cover.Show(); + Activate(); + PointAtButton(); + } + + internal void Uncover(FixtureForm cover) + { + if (cover.Visible) cover.Hide(); + cover.TopMost = false; + Activate(); + PointAtButton(); + } + internal object Inspect() => new { text = Editor.Text, clicks, window = Handle.ToString(CultureInfo.InvariantCulture), foreground = GetForegroundWindow().ToString(CultureInfo.InvariantCulture), cursor = new { x = Cursor.Position.X, y = Cursor.Position.Y }, + under = GetAncestor(WindowFromPoint(Cursor.Position), 2).ToString(CultureInfo.InvariantCulture), + downs = new { left = leftDowns, right = rightDowns, middle = middleDowns }, + ups = new { left = leftUps, right = rightUps, middle = middleUps }, button = new { x = button.Left + button.Width / 2, y = button.Top + button.Height / 2 }, selection = new { start = Editor.SelectionStart, length = Editor.SelectionLength }, buttons = MouseButtons.ToString(), minimized = WindowState == FormWindowState.Minimized, visible = Visible, @@ -41,12 +84,31 @@ internal sealed class FixtureForm : Form } [DllImport("user32.dll")] private static extern nint GetForegroundWindow(); + [DllImport("user32.dll")] private static extern nint WindowFromPoint(Point point); + [DllImport("user32.dll")] private static extern nint GetAncestor(nint window, uint flags); } internal static class Program { private static void Write(object value) { Console.WriteLine(JsonSerializer.Serialize(value)); Console.Out.Flush(); } + private static void ReleaseButtons() + { + var inputs = new[] { 0x0004u, 0x0010u, 0x0040u } + .Select(flags => new Input { Type = 0, Data = new MouseInput { Flags = flags } }).ToArray(); + if (SendInput((uint)inputs.Length, inputs, Marshal.SizeOf()) != inputs.Length) + { + Console.Error.WriteLine("Fixture could not release every mouse button"); + Environment.ExitCode = 1; + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct MouseInput { public int X, Y; public uint Data, Flags, Time; public nuint ExtraInfo; } + + [StructLayout(LayoutKind.Sequential)] + private struct Input { public uint Type; public MouseInput Data; } + [STAThread] private static void Main() { @@ -68,6 +130,11 @@ internal static class Program case "sibling": sibling.Show(); sibling.Activate(); sibling.Editor.Focus(); Write(sibling.Inspect()); break; case "inspect": Write(form.Inspect()); break; case "focus": form.Activate(); form.Editor.Focus(); Write(form.Inspect()); break; + case "pointer": form.PointAtButton(); Write(form.Inspect()); break; + case "pointer-outside": form.PointOutside(); Write(form.Inspect()); break; + case "cover": form.Cover(sibling); Write(new { form = form.Inspect(), sibling = sibling.Inspect() }); break; + case "uncover": form.Uncover(sibling); Write(form.Inspect()); break; + case "release-input": ReleaseButtons(); Write(form.Inspect()); break; case "minimize": form.WindowState = FormWindowState.Minimized; Write(form.Inspect()); break; case "hide": form.Hide(); Write(form.Inspect()); break; case "resize": form.Width += 50; Write(form.Inspect()); break; @@ -93,4 +160,7 @@ internal static class Program [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool AllowSetForegroundWindow(uint processId); + + [DllImport("user32.dll", SetLastError = true)] + private static extern uint SendInput(uint count, [In] Input[] inputs, int size); } diff --git a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs index 666bd9c48a..6af36d042f 100644 --- a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs +++ b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs @@ -169,6 +169,12 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA var pointed = Coordinate(app, parameters, context); return Input.MouseMove(app, pointed.Window, pointed.X, pointed.Y, context); } + case "toggleMouse": + { + var target = Selected(app, parameters, context); + Input.ToggleMouse(app, target, String(parameters, "mouseButton"), String(parameters, "direction"), context); + return ActionResult(foreground); + } case "scroll": { var target = Coordinate(app, parameters, context); diff --git a/packages/experimental/cua-windows/native/entry/Input.cs b/packages/experimental/cua-windows/native/entry/Input.cs index 7493acc990..9d186055d5 100644 --- a/packages/experimental/cua-windows/native/entry/Input.cs +++ b/packages/experimental/cua-windows/native/entry/Input.cs @@ -162,6 +162,18 @@ internal static class Input return new { dispatched = true, hoverRoute = "system-pointer", systemPointerMoved = before.X != point.X || before.Y != point.Y }; } + internal static void ToggleMouse(AppState app, WindowState window, string button, string direction, RequestContext context) + { + var flags = Button(button); + if (direction == "down") + { + if (!Win32.GetCursorPos(out var point)) throw new NativeFailure("INPUT_UNAVAILABLE", "The current pointer position is unavailable"); + Hit(app, window, point, context); + } + else Windows.RequireForeground(app, window, context); + Send(Mouse(direction == "down" ? flags.Down : flags.Up)); + } + internal static void Click(AppState app, WindowState window, double x, double y, string button, int count, string[] modifiers, RequestContext context) { if (button != "left" && count != 1) throw new NativeFailure("UNSUPPORTED", "Only left clicks support double-click"); diff --git a/packages/experimental/cua-windows/native/protocol.schema.json b/packages/experimental/cua-windows/native/protocol.schema.json index bb03a5a331..22763d1b61 100644 --- a/packages/experimental/cua-windows/native/protocol.schema.json +++ b/packages/experimental/cua-windows/native/protocol.schema.json @@ -451,6 +451,59 @@ ], "additionalProperties": false }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "toggleMouse" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "string", + "minLength": 1 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "direction": { + "type": "string", + "enum": [ + "down", + "up" + ] + } + }, + "required": [ + "appHandle", + "windowId", + "mouseButton", + "direction" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, { "type": "object", "properties": { diff --git a/packages/experimental/cua-windows/native/tests/Program.cs b/packages/experimental/cua-windows/native/tests/Program.cs index 1a76604edb..520a805ab6 100644 --- a/packages/experimental/cua-windows/native/tests/Program.cs +++ b/packages/experimental/cua-windows/native/tests/Program.cs @@ -56,6 +56,28 @@ foreach (var method in new[] { "listActions", "performAction", "invoke", "mouseM }))); Check(operation.Params.GetProperty("elementId").GetString() == "42/-7/9", "Element operations preserve slash-separated RuntimeIds: " + method); } +foreach (var mouseButton in new[] { "left", "right", "middle" }) +foreach (var direction in new[] { "down", "up" }) +{ + var toggle = NativeRequest.Parse(WireJson.Parse(System.Text.Json.JsonSerializer.Serialize(new + { + id = "mouse", method = "toggleMouse", @params = new { appHandle = "app", windowId = "1", mouseButton, direction }, + }))); + Check(toggle.Params.GetProperty("mouseButton").GetString() == mouseButton + && toggle.Params.GetProperty("direction").GetString() == direction, + "Mouse-button events retain the explicit button and direction"); +} +foreach (var invalid in new[] +{ + """{"appHandle":"app","windowId":"1","mouseButton":"left"}""", + """{"appHandle":"app","windowId":"1","direction":"down"}""", + """{"appHandle":"app","mouseButton":"left","direction":"down"}""", + """{"appHandle":"app","windowId":"1","mouseButton":"back","direction":"down"}""", + """{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"press"}""", + """{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"down","x":1,"y":2}""", +}) + Refuses(() => NativeRequest.Parse(WireJson.Parse("{\"id\":\"mouse\",\"method\":\"toggleMouse\",\"params\":" + invalid + "}")), "INVALID_ARGUMENT"); + var launch = NativeRequest.Parse(WireJson.Parse("""{"id":"launch","method":"launchApp","params":{"appHandle":"pending"}}""")); Check(launch.Method == "launchApp" && launch.Params.GetProperty("appHandle").GetString() == "pending", "Host launch continuation retains the selected application handle"); diff --git a/packages/experimental/cua-windows/src/index.ts b/packages/experimental/cua-windows/src/index.ts index 8e63904c91..3be20956f5 100644 --- a/packages/experimental/cua-windows/src/index.ts +++ b/packages/experimental/cua-windows/src/index.ts @@ -14,7 +14,7 @@ const CAPABILITIES: CuaStartupCapabilities = { platform: 'windows', methods: [ 'getCapabilities', 'listApps', 'getApp', 'activate', 'show', 'listWindows', 'getState', - 'listActions', 'performAction', 'invoke', 'mouseMove', 'click', 'setValue', 'selectText', + 'listActions', 'performAction', 'invoke', 'mouseMove', 'toggleMouse', 'click', 'setValue', 'selectText', 'typeText', 'paste', 'pressKey', 'sendKeyEvent', 'scroll', 'drag', 'screenshot', ], appLevelAccessibility: false, diff --git a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts new file mode 100644 index 0000000000..25a37bb8e2 --- /dev/null +++ b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts @@ -0,0 +1,145 @@ +/** Opt-in real Windows mouse-button toggles through the native helper. */ +import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process' +import { createInterface } from 'node:readline' +import { Context } from '@deepseek-ai/cordis' +import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' +import { NativeClient } from '@deepseek-ai/dsh-cua/native-client' +import { expect, it } from 'vitest' +import { z } from 'zod' +import { Config } from '../src/index.ts' +import { WindowsNativeRuntime } from '../src/native-runtime.ts' + +const helperPath = process.env.DSH_CUA_DESKTOP_TEST_HELPER +const fixturePath = process.env.DSH_CUA_DESKTOP_TEST_FIXTURE +const Counts = z.object({ left: z.number().int(), right: z.number().int(), middle: z.number().int() }) +const FixtureState = z.object({ + window: z.string(), foreground: z.string(), + cursor: z.object({ x: z.number().int(), y: z.number().int() }), + under: z.string(), buttons: z.string(), clicks: z.number().int(), downs: Counts, ups: Counts, +}) +const Initial = z.object({ pid: z.number().int(), state: FixtureState }) +const Cover = z.object({ form: FixtureState, sibling: FixtureState }) +const App = z.object({ appHandle: z.string(), running: z.boolean() }) +const Windows = z.array(z.object({ windowId: z.string(), title: z.string() })) +const ToggleResult = z.object({ dispatched: z.boolean() }) + +interface Fixture { + readonly child: ChildProcessWithoutNullStreams + readonly exit: Promise + read(schema: z.ZodType): Promise + command(text: string, schema: z.ZodType): Promise +} + +function fixtureProcess(path: string): Fixture { + const child = spawn(path, [], { windowsHide: true }) + child.stderr.pipe(process.stderr) + const reader = createInterface({ input: child.stdout }) + const iterator = reader[Symbol.asyncIterator]() + const exit = new Promise((resolve) => { + child.once('error', (error) => { reader.close(); resolve(error) }) + child.once('exit', (code, signal) => { + reader.close() + resolve(code === 0 ? undefined : new Error(`Fixture exited with code ${code}, signal ${signal}`)) + }) + }) + const read = async (schema: z.ZodType): Promise => { + const next = await iterator.next() + if (next.done) throw new Error('The fixture exited before replying') + return schema.parse(JSON.parse(next.value)) + } + return { child, exit, read, command: async (text, schema) => { child.stdin.write(text + '\n'); return read(schema) } } +} + +async function releaseAndClose(fixture: Fixture): Promise { + let forced = false + const timer = setTimeout(() => { forced = true; fixture.child.kill() }, 5000) + try { + if (fixture.child.exitCode === null && fixture.child.signalCode === null && fixture.child.pid !== undefined) { + // The fixture processes release before close even if an earlier inspection is still awaiting its reply. + fixture.child.stdin.end('release-input\nclose\n') + } + const error = await fixture.exit + if (forced) throw new Error('Fixture shutdown timed out; mouse-button release could not be confirmed', { cause: error }) + if (error) throw error + } finally { clearTimeout(timer) } +} + +it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( + 'toggles mouse buttons without movement, observation, or implicit release', + async ({ onTestFinished, signal }) => { + const fixture = fixtureProcess(fixturePath!) + const ctx = new Context() + const cleanups: Array<() => Promise> = [] + onTestFinished(async () => { + const errors: unknown[] = [] + for (const cleanup of [ + () => releaseAndClose(fixture), ...cleanups.toReversed(), () => ctx.fiber.dispose(), + ]) { + try { await cleanup() } catch (error) { errors.push(error) } + } + if (errors.length > 0) throw new AggregateError(errors, 'Desktop mouse test cleanup failed') + }) + const inspect = () => fixture.command('inspect', FixtureState) + const observed = async (expected: object) => { + let state = await inspect() + await expect.poll(async () => { state = await inspect(); return state }, { timeout: 5000, interval: 25 }).toMatchObject(expected) + return state + } + const initial = await fixture.read(Initial) + const focused = await fixture.command('focus', FixtureState) + expect(focused.window).toBe(initial.state.window) + expect(focused.foreground, 'Windows denied foreground to the private fixture').toBe(focused.window) + expect(focused.buttons).toBe('None') + + await ctx.plugin(LocalSubprocessRuntime) + const nativeRuntime = new WindowsNativeRuntime(ctx, 25, 1000, 'pipe') + cleanups.push(() => nativeRuntime.dispose()) + const native = new NativeClient(ctx, { ...Config({}), helperPath: helperPath!, cwd: process.cwd() }, + (_owner, config) => nativeRuntime.connect(config)) + cleanups.push(() => native.dispose()) + const app = App.parse(await native.request('getApp', { selector: fixturePath! }, signal)) + expect(app.running).toBe(true) + const windows = Windows.parse(await native.request('listWindows', { appHandle: app.appHandle }, signal)) + const windowId = initial.state.window + expect(windows.some(window => window.windowId === windowId)).toBe(true) + const toggle = async (mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') => + ToggleResult.parse(await native.request('toggleMouse', { appHandle: app.appHandle, windowId, mouseButton, direction }, signal)) + + const { cursor } = await fixture.command('pointer', FixtureState) + for (const mouseButton of ['left', 'right', 'middle'] as const) { + const before = await inspect() + expect((await toggle(mouseButton, 'down')).dispatched).toBe(true) + const down = await observed({ cursor, buttons: { left: 'Left', right: 'Right', middle: 'Middle' }[mouseButton], + downs: { [mouseButton]: before.downs[mouseButton] + 1 }, ups: before.ups }) + await native.request('getCapabilities', {}, signal) + expect(await inspect()).toMatchObject({ cursor, buttons: down.buttons, ups: down.ups }) + expect((await toggle(mouseButton, 'up')).dispatched).toBe(true) + await observed({ cursor, buttons: 'None', ups: { [mouseButton]: down.ups[mouseButton] + 1 }, + clicks: down.clicks + (mouseButton === 'left' ? 1 : 0) }) + } + + const sibling = await fixture.command('sibling', FixtureState) + expect(sibling.foreground).toBe(sibling.window) + const background = await inspect() + await expect(toggle('left', 'down')).rejects.toMatchObject({ code: 'FOREGROUND_REQUIRED' }) + expect(await inspect()).toMatchObject({ buttons: 'None', downs: background.downs }) + const restored = await fixture.command('focus', FixtureState) + expect(restored.foreground).toBe(restored.window) + + const cover = await fixture.command('cover', Cover) + expect(cover.form.foreground).toBe(cover.form.window) + expect(cover.form.under).toBe(cover.sibling.window) + await expect(toggle('left', 'down')).rejects.toMatchObject({ code: 'WINDOW_OBSCURED' }) + expect(await inspect()).toMatchObject({ buttons: 'None', downs: cover.form.downs }) + const uncovered = await fixture.command('uncover', FixtureState) + expect(uncovered.foreground).toBe(uncovered.window) + + expect((await toggle('left', 'down')).dispatched).toBe(true) + const pressed = await observed({ buttons: 'Left', downs: { left: uncovered.downs.left + 1 } }) + const outside = await fixture.command('pointer-outside', FixtureState) + expect(outside.cursor).not.toEqual(pressed.cursor) + expect(outside.foreground).toBe(outside.window) + expect(outside.under).not.toBe(outside.window) + expect((await toggle('left', 'up')).dispatched).toBe(true) + await observed({ buttons: 'None', cursor: outside.cursor, ups: { left: pressed.ups.left + 1 }, clicks: pressed.clicks }) + }, 120_000) diff --git a/packages/experimental/cua-windows/tests/loader-composition.spec.ts b/packages/experimental/cua-windows/tests/loader-composition.spec.ts index 3f2dc48b47..e90acbbf49 100644 --- a/packages/experimental/cua-windows/tests/loader-composition.spec.ts +++ b/packages/experimental/cua-windows/tests/loader-composition.spec.ts @@ -31,6 +31,12 @@ it.skipIf(process.platform !== 'win32')('loads the Windows provider and rejects const prompt = await ctx.systemPrompt.assemble({ scope: agent }) expect(prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text).toContain('Windows:') expect(prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text).not.toContain('useSystemPointer') + const toggleMouse = prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text + .split('\n').find(line => line.startsWith('- toggleMouse(')) + expect(toggleMouse).toContain("toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult") + expect(toggleMouse).toContain("Release held buttons explicitly with 'up'; the opposite event is not sent automatically.") + expect(toggleMouse).toContain('press or release the specified mouse button at the current pointer position without moving it.') + expect(toggleMouse).not.toContain('Not implemented') expect(JSON.stringify(ctx.tools.get('cua', agent)!.parameters)).not.toContain('useSystemPointer') const batch = await ctx.tools.execute({ agent, signal: new AbortController().signal, calls: [{ type: 'tool-call', id: brandString('invalid-window'), name: 'cua', diff --git a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts index 9e8c2601bf..dcee6fa104 100644 --- a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts @@ -49,6 +49,7 @@ it('uses an absolute fixture without compiling and disposes the Host runtime', a expect(backend.permissionParameters('requestPermission', 'accessibility', 'en')).toEqual({ permission: 'accessibility' }) expect(backend.capabilities).toMatchObject({ platform: 'windows', appLevelAccessibility: false, keyboard: ['window'] }) expect(backend.capabilities.methods).toContain('sendKeyEvent') + expect(backend.capabilities.methods).toContain('toggleMouse') expect(backend.sendKeyEvent).toBeUndefined() const channel = { marker: 'native stream' } native.connect.mockReturnValue(channel) diff --git a/packages/experimental/cua/src/api.ts b/packages/experimental/cua/src/api.ts index 319b2888f6..7e98c2a041 100644 --- a/packages/experimental/cua/src/api.ts +++ b/packages/experimental/cua/src/api.ts @@ -191,6 +191,9 @@ function createCuaObjects(call: ReturnType): { const [x, y] = targetPoint return HoverResult.parse(await base.call('mouseMove', { ...coordinateParams(appHandle, windowId), x, y, ...relative }, options)) }, + async toggleMouse(mouseButton, direction) { + return base.action('toggleMouse', { mouseButton, direction }) + }, async click(targetPoint, options) { const mouseButton = options?.mouseButton ?? 'left' const clickCount = options?.clickCount ?? 1 diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 35524cf70d..de995fa93e 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -36,10 +36,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - ${hoverSignature} -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -53,6 +57,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.` /** diff --git a/packages/experimental/cua/src/protocol.ts b/packages/experimental/cua/src/protocol.ts index 081ff2adc4..7ee5d6f017 100644 --- a/packages/experimental/cua/src/protocol.ts +++ b/packages/experimental/cua/src/protocol.ts @@ -72,6 +72,7 @@ function requestSchema(hover: H, drag: operation('listActions', snapshot), operation('performAction', { ...snapshot, action: z.string().min(1), argument: jsonValue.optional() }), operation('invoke', snapshot), + operation('toggleMouse', { ...window, mouseButton: pointer.mouseButton.unwrap(), direction: z.enum(['down', 'up']) }), z.object({ method: z.literal('mouseMove'), params: hover }).strict(), z.object({ method: z.literal('click'), params: z.union([ z.object({ ...snapshot, ...click }).strict(), diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index 4c6d173c24..b38229c220 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -62,7 +62,7 @@ export interface CuaCoordinateOptions { export type CuaShowResult = z.output /** Modifiers attached to a window-directed pointer gesture. */ export type CuaPointerModifier = NonNullable['modifiers']>[number] -/** Buttons supported by window-directed clicks and drags. */ +/** Buttons supported by window-directed mouse input. */ export type CuaMouseButton = NonNullable['mouseButton']> /** * Left clicks support one or two presses; right and middle clicks support one. @@ -191,6 +191,14 @@ export interface CuaWindow extends CuaSurface { */ mouseMove(target: CuaElementId | readonly [number, number], options?: CuaCoordinateOptions & { useSystemPointer?: boolean }): Promise + /** + * Send one mouse-button down or up event without moving the pointer. + * Does not send the opposite event; callers explicitly release a pressed button. + * @param mouseButton - Mouse button to press or release. + * @param direction - Explicit event direction. + * @returns Whether the provider successfully executed the requested operation. + */ + toggleMouse(mouseButton: CuaMouseButton, direction: 'down' | 'up'): Promise /** * Click a current element id or screenshot-local point. * Cancellation or timeout releases the held button; received input cannot be undone. The operation deadline includes holdMs. diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index c17a0ea7b7..de8325bfb2 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -953,6 +953,38 @@ describe('input actions', () => { expect(windowFixture.dispatch).not.toHaveBeenCalled() }) + it.each(['left', 'right', 'middle'] as const)('dispatches one %s mouse-button event without an observation', async (mouseButton) => { + const f = fixture() + const app = await f.api.getApp('Editor') + const window = await app.getWindow('23') + expect(app).not.toHaveProperty('toggleMouse') + expectTypeOf().not.toHaveProperty('toggleMouse') + expectTypeOf().parameters.toEqualTypeOf<[ + mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', + ]>() + for (const direction of ['down', 'up'] as const) { + f.dispatch.mockClear() + await expect(window.toggleMouse(mouseButton, direction)).resolves.toEqual(delivered) + expect(f.dispatch).toHaveBeenCalledExactlyOnceWith({ method: 'toggleMouse', params: { + appHandle: 'app-17', windowId: '23', mouseButton, direction, + } }) + } + }) + + it('preserves mouse-button dispatch failures without retries or an opposite event', async () => { + const f = fixture() + const window = await (await f.api.getApp('Editor')).getWindow('23') + f.dispatch.mockClear() + f.dispatch.mockResolvedValueOnce({ dispatched: false }) + await expect(window.toggleMouse('left', 'down')).resolves.toEqual({ dispatched: false }) + const failure = new Error('Mouse-button input is not supported') + f.dispatch.mockRejectedValueOnce(failure) + await expect(window.toggleMouse('left', 'up')).rejects.toBe(failure) + f.dispatch.mockResolvedValueOnce({ dispatched: 'yes' }) + await expect(window.toggleMouse('right', 'up')).rejects.toThrow() + expect(f.dispatch).toHaveBeenCalledTimes(3) + }) + it('retains the snapshot identity for element right and double clicks', async () => { const f = fixture() const app = await f.api.getApp('Editor') diff --git a/packages/experimental/cua/tests/native-schema.spec.ts b/packages/experimental/cua/tests/native-schema.spec.ts index eca0803ce5..68689e2a16 100644 --- a/packages/experimental/cua/tests/native-schema.spec.ts +++ b/packages/experimental/cua/tests/native-schema.spec.ts @@ -57,6 +57,13 @@ it('admits key events with only an explicit direction enum', () => { expect(native.enums.get('sendKeyEvent')?.has('key') ?? false).toBe(false) }) +it('admits mouse-button events with explicit button and direction enums and no coordinates', () => { + const native = nativeProtocol() + expect(native.fields.get('toggleMouse')).toEqual(new Set(['appHandle', 'windowId', 'mouseButton', 'direction'])) + expect(native.enums.get('toggleMouse')?.get('mouseButton')).toEqual(new Set(['left', 'right', 'middle'])) + expect(native.enums.get('toggleMouse')?.get('direction')).toEqual(new Set(['down', 'up'])) +}) + it('accepts a parameter-free object schema without a properties dictionary', () => { replacements.values.set(0, { properties: { method: { const: 'getCapabilities' }, params: { type: 'object' } } }) expect(nativeProtocol().fields.get('getCapabilities')).toEqual(new Set()) diff --git a/packages/experimental/cua/tests/protocol.spec.ts b/packages/experimental/cua/tests/protocol.spec.ts index 8067bb10c4..9716a5ff5e 100644 --- a/packages/experimental/cua/tests/protocol.spec.ts +++ b/packages/experimental/cua/tests/protocol.spec.ts @@ -71,6 +71,28 @@ it('admits arbitrary key names with an explicit key-event direction', () => { expect(Request.parse(request)).toEqual(request) }) +it.each(['left', 'right', 'middle'])('admits explicit %s mouse-button events without coordinates', (mouseButton) => { + for (const schema of [Request, SystemPointerRequest]) { + for (const direction of ['down', 'up']) { + const request = { method: 'toggleMouse', params: { appHandle: 'app', windowId: '23', mouseButton, direction } } + expect(schema.parse(request)).toEqual(request) + } + } +}) + +it.each([ + { mouseButton: undefined }, { mouseButton: 'back' }, + { direction: undefined }, { direction: 'press' }, + { appHandle: undefined }, { windowId: undefined }, + { x: 1 }, { y: 2 }, { relative: true }, { elementId: '0' }, { snapshotId: 'snapshot' }, + { modifiers: [] }, { useSystemPointer: true }, +])('rejects invalid mouse-button event parameters %j', (invalid) => { + const params = { appHandle: 'app', windowId: '23', mouseButton: 'left', direction: 'down', ...invalid } + for (const schema of [Request, SystemPointerRequest]) { + expect(schema.safeParse({ method: 'toggleMouse', params }).success).toBe(false) + } +}) + it.each([ { appHandle: 'app', snapshotId: 'snapshot', elementId: '0' }, { appHandle: 'app', windowId: '23', x: 1, y: 2 }, diff --git a/snapshots/sdk/cua-run-code/system-prompt.expected.md b/snapshots/sdk/cua-run-code/system-prompt.expected.md index 92190be4ef..db7bd43972 100644 --- a/snapshots/sdk/cua-run-code/system-prompt.expected.md +++ b/snapshots/sdk/cua-run-code/system-prompt.expected.md @@ -65,10 +65,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -82,6 +86,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 572b8f2eb0..3cc3ebd954 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -66,12 +66,16 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. +## Screenshots +Use an explicit window for screenshots. +- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + ## Simulated mouse Leave useSystemPointer unset for ordinary mouseMove and drag calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it. -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. -- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Not implemented on macOS. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -85,6 +89,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement. diff --git a/snapshots/session/cua-native/tool-schemas.expected.json b/snapshots/session/cua-native/tool-schemas.expected.json index 1afadeca68..ec3478d7c2 100644 --- a/snapshots/session/cua-native/tool-schemas.expected.json +++ b/snapshots/session/cua-native/tool-schemas.expected.json @@ -462,6 +462,55 @@ ], "additionalProperties": false }, + { + "type": "object", + "properties": { + "method": { + "type": "string", + "const": "toggleMouse" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "string", + "minLength": 1 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "direction": { + "type": "string", + "enum": [ + "down", + "up" + ] + } + }, + "required": [ + "appHandle", + "windowId", + "mouseButton", + "direction" + ], + "additionalProperties": false + } + }, + "required": [ + "method", + "params" + ], + "additionalProperties": false + }, { "type": "object", "properties": { diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index ff53e75417..e081a0a66c 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -68,12 +68,16 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. +## Screenshots +Use an explicit window for screenshots. +- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + ## Simulated mouse Leave useSystemPointer unset for ordinary mouseMove and drag calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it. -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. -- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Not implemented on macOS. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -87,6 +91,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement. diff --git a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md index 893532843c..bb4eb419d5 100644 --- a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md @@ -66,10 +66,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -83,6 +87,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/snapshots/session/cua-run-code/system-prompt.expected.md b/snapshots/session/cua-run-code/system-prompt.expected.md index 1545776e2c..a194b2db34 100644 --- a/snapshots/session/cua-run-code/system-prompt.expected.md +++ b/snapshots/session/cua-run-code/system-prompt.expected.md @@ -64,10 +64,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -81,6 +85,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 0b31f65856..c2333aa706 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -68,12 +68,16 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. +## Screenshots +Use an explicit window for screenshots. +- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + ## Simulated mouse Leave useSystemPointer unset for ordinary mouseMove and drag calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it. -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. -- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Not implemented on macOS. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -87,6 +91,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement. From 8cbd73efff1edc494723f8f0f28a1943585b39ce Mon Sep 17 00:00:00 2001 From: ZiyaZhang <199893125+ZiyaZhang@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:48:59 -0800 Subject: [PATCH 44/48] feat(ui-schedule): scope the weekly review to the user's own work The weekly review request now asks for what the user did in the current workspace this week. In a code repository it looks only at the user's commits this week and the pull requests the user opened that merged this week or are still open, instead of every commit and pull request in the repository. The tile description follows the same scope in all eight languages. --- .../schedule-recommendations-en.expected.md | 2 +- .../schedule-recommendations-zh.expected.md | 2 +- .../src/client/recommendation-locales.ts | 32 +++++++++---------- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/apps/web/tests/expected/schedule-recommendations-en.expected.md b/apps/web/tests/expected/schedule-recommendations-en.expected.md index b11eeadea2..a51962831d 100644 --- a/apps/web/tests/expected/schedule-recommendations-en.expected.md +++ b/apps/web/tests/expected/schedule-recommendations-en.expected.md @@ -4,7 +4,7 @@ - listitem: - button "Daily brief": Daily brief Recent changes in the workspace and what needs follow-up, with what to do first today. Weekdays at 9:00 - listitem: - - button "Weekly review": Weekly review This week's changes in the workspace, with loose ends and what to do first next week. Fridays at {{clock}} + - button "Weekly review": Weekly review Your work in the workspace this week, with loose ends and what to do first next week. Fridays at {{clock}} - listitem: - button "Issue scan": Issue scan Sort new issues into bugs, requests, and questions, and flag duplicates and ones that need a reply. Weekdays at {{clock}} - listitem: diff --git a/apps/web/tests/expected/schedule-recommendations-zh.expected.md b/apps/web/tests/expected/schedule-recommendations-zh.expected.md index f4d7e76203..2bf44e32c5 100644 --- a/apps/web/tests/expected/schedule-recommendations-zh.expected.md +++ b/apps/web/tests/expected/schedule-recommendations-zh.expected.md @@ -4,7 +4,7 @@ - listitem: - button "每日简报": 每日简报 汇总工作区最近的变化和待跟进的事,列出今天先做什么。 工作日 9:00 - listitem: - - button "每周回顾": 每周回顾 回顾这周工作区的变化,列出没收尾的事和下周先做什么。 周五 {{clock}} + - button "每周回顾": 每周回顾 回顾自己这周在工作区做的事,列出没收尾的事和下周先做什么。 周五 {{clock}} - listitem: - button "Issue 扫描": Issue 扫描 把新开的 issue 分成 bug、需求、提问,标出重复的和需要回复的。 工作日 {{clock}} - listitem: diff --git a/packages/client/ui-schedule/src/client/recommendation-locales.ts b/packages/client/ui-schedule/src/client/recommendation-locales.ts index ab52e0392c..c7c685dac7 100644 --- a/packages/client/ui-schedule/src/client/recommendation-locales.ts +++ b/packages/client/ui-schedule/src/client/recommendation-locales.ts @@ -8,9 +8,9 @@ export const recommendationEn = { 'recommend.dailyBrief.schedule': 'Weekdays at 9:00', 'recommend.dailyBrief.prompt': 'Create an automation task named "Daily brief": every weekday at 9:00, review the last 24 hours of changes in the current workspace and list what needs my follow-up and what to do first today; when the workspace is a code repository, also cover new commits, pull requests awaiting my review, and failing CI.', 'recommend.weeklyReview.title': 'Weekly review', - 'recommend.weeklyReview.description': 'This week\'s changes in the workspace, with loose ends and what to do first next week.', + 'recommend.weeklyReview.description': 'Your work in the workspace this week, with loose ends and what to do first next week.', 'recommend.weeklyReview.schedule': 'Fridays at 16:00', - 'recommend.weeklyReview.prompt': 'Create an automation task named "Weekly review": every Friday at 16:00, review this week\'s changes in the current workspace, summarize what got done, and list what is still unfinished and what to do first next week; when the workspace is a code repository, also cover this week\'s commits, merged pull requests, and pull requests still open. Summarize here only; do not change files in the workspace.', + 'recommend.weeklyReview.prompt': 'Create an automation task named "Weekly review": every Friday at 16:00, review what I did in the current workspace this week and list what is still unfinished and what to do first next week; when the workspace is a code repository, look only at my commits this week and the pull requests I opened that were merged this week or are still open. Summarize here only; do not change files in the workspace.', 'recommend.issueScan.title': 'Issue scan', 'recommend.issueScan.description': 'Sort new issues into bugs, requests, and questions, and flag duplicates and ones that need a reply.', 'recommend.issueScan.schedule': 'Weekdays at 10:00', @@ -45,9 +45,9 @@ export const recommendationZh: Record = { 'recommend.dailyBrief.schedule': '工作日 9:00', 'recommend.dailyBrief.prompt': '创建一个名为「每日简报」的自动化任务:每个工作日 9:00 查看当前工作区过去 24 小时的变化,列出需要我跟进的事和今天先做的事;工作区是代码仓库时,也看新提交、待我评审的 PR 和失败的 CI。', 'recommend.weeklyReview.title': '每周回顾', - 'recommend.weeklyReview.description': '回顾这周工作区的变化,列出没收尾的事和下周先做什么。', + 'recommend.weeklyReview.description': '回顾自己这周在工作区做的事,列出没收尾的事和下周先做什么。', 'recommend.weeklyReview.schedule': '周五 16:00', - 'recommend.weeklyReview.prompt': '创建一个名为「每周回顾」的自动化任务:每周五 16:00 回顾当前工作区这一周的变化,总结这周做了什么,列出还没收尾的事和下周先做的事;工作区是代码仓库时,也看这周的提交、合入的 PR 和还开着的 PR。只在这里汇总,不改工作区里的文件。', + 'recommend.weeklyReview.prompt': '创建一个名为「每周回顾」的自动化任务:每周五 16:00 回顾我这一周在当前工作区做了什么,列出还没收尾的事和下周先做的事;工作区是代码仓库时,只看我这周的提交,以及我提的、这周合入或还开着的 PR。只在这里汇总,不改工作区里的文件。', 'recommend.issueScan.title': 'Issue 扫描', 'recommend.issueScan.description': '把新开的 issue 分成 bug、需求、提问,标出重复的和需要回复的。', 'recommend.issueScan.schedule': '工作日 10:00', @@ -82,9 +82,9 @@ export const recommendationJa: Record = { 'recommend.dailyBrief.schedule': '平日 9:00', 'recommend.dailyBrief.prompt': '「デイリーブリーフィング」という名前の自動化タスクを作成してください。平日は毎日 9:00 に、現在のワークスペースの過去24時間の変化を確認し、私がフォローすべきことと今日最初にやることを挙げてください。ワークスペースがコードリポジトリの場合は、新しいコミット、私のレビュー待ちのプルリクエスト、失敗した CI も確認してください。', 'recommend.weeklyReview.title': '週次レビュー', - 'recommend.weeklyReview.description': '今週のワークスペースの変化を振り返り、やり残したことと来週最初にやることを挙げます。', + 'recommend.weeklyReview.description': '今週ワークスペースで自分がしたことを振り返り、やり残したことと来週最初にやることを挙げます。', 'recommend.weeklyReview.schedule': '毎週金曜日 16:00', - 'recommend.weeklyReview.prompt': '「週次レビュー」という名前の自動化タスクを作成してください。毎週金曜日の 16:00 に、現在のワークスペースの今週の変化を振り返り、今週やったことをまとめて、まだ終わっていないことと来週最初にやることを挙げてください。ワークスペースがコードリポジトリの場合は、今週のコミット、マージされたプルリクエスト、まだオープンのプルリクエストも確認してください。まとめはここでだけ行い、ワークスペースのファイルは変更しないでください。', + 'recommend.weeklyReview.prompt': '「週次レビュー」という名前の自動化タスクを作成してください。毎週金曜日の 16:00 に、今週私が現在のワークスペースでしたことを振り返り、まだ終わっていないことと来週最初にやることを挙げてください。ワークスペースがコードリポジトリの場合は、今週の私のコミットと、私が作成したプルリクエストのうち今週マージされたものとまだオープンのものだけを確認してください。まとめはここでだけ行い、ワークスペースのファイルは変更しないでください。', 'recommend.issueScan.title': 'Issue スキャン', 'recommend.issueScan.description': '新しい Issue をバグ・要望・質問に分類し、重複しているものと返信が必要なものを指摘します。', 'recommend.issueScan.schedule': '平日 10:00', @@ -119,9 +119,9 @@ export const recommendationEs: Record = { 'recommend.dailyBrief.schedule': 'De lunes a viernes a las 9:00', 'recommend.dailyBrief.prompt': 'Crea una tarea de automatización llamada «Resumen diario»: de lunes a viernes a las 9:00, revisa los cambios de las últimas 24 horas en el espacio de trabajo actual y enumera lo que requiere mi seguimiento y lo primero que debo hacer hoy; si el espacio de trabajo es un repositorio de código, incluye también los commits nuevos, los pull requests pendientes de mi revisión y los fallos de CI.', 'recommend.weeklyReview.title': 'Revisión semanal', - 'recommend.weeklyReview.description': 'Cambios de la semana en el espacio de trabajo, con lo pendiente y lo primero que hacer la próxima semana.', + 'recommend.weeklyReview.description': 'Tu trabajo de la semana en el espacio de trabajo, con lo pendiente y lo primero que hacer la próxima semana.', 'recommend.weeklyReview.schedule': 'Los viernes a las 16:00', - 'recommend.weeklyReview.prompt': 'Crea una tarea de automatización llamada «Revisión semanal»: todos los viernes a las 16:00, repasa los cambios de esta semana en el espacio de trabajo actual, resume lo que se hizo y enumera lo que queda pendiente y lo primero que debo hacer la próxima semana; si el espacio de trabajo es un repositorio de código, incluye también los commits de la semana, los pull requests fusionados y los que siguen abiertos. Haz el resumen solo aquí; no modifiques archivos del espacio de trabajo.', + 'recommend.weeklyReview.prompt': 'Crea una tarea de automatización llamada «Revisión semanal»: todos los viernes a las 16:00, repasa lo que hice esta semana en el espacio de trabajo actual y enumera lo que queda pendiente y lo primero que debo hacer la próxima semana; si el espacio de trabajo es un repositorio de código, revisa solo mis commits de esta semana y los pull requests que abrí que se fusionaron esta semana o siguen abiertos. Haz el resumen solo aquí; no modifiques archivos del espacio de trabajo.', 'recommend.issueScan.title': 'Revisión de issues', 'recommend.issueScan.description': 'Clasifica los issues nuevos en bugs, solicitudes y preguntas, y señala los duplicados y los que necesitan respuesta.', 'recommend.issueScan.schedule': 'De lunes a viernes a las 10:00', @@ -156,9 +156,9 @@ export const recommendationFr: Record = { 'recommend.dailyBrief.schedule': 'Du lundi au vendredi à 9:00', 'recommend.dailyBrief.prompt': 'Crée une tâche d\'automatisation nommée « Résumé quotidien » : du lundi au vendredi à 9:00, passe en revue les changements des dernières 24 heures dans l\'espace de travail actuel et liste ce qui demande mon suivi et ce que je dois faire en premier aujourd\'hui ; si l\'espace de travail est un dépôt de code, couvre aussi les nouveaux commits, les pull requests en attente de ma revue et les échecs de CI.', 'recommend.weeklyReview.title': 'Bilan hebdomadaire', - 'recommend.weeklyReview.description': 'Changements de la semaine dans l\'espace de travail, avec ce qui reste à terminer et les priorités de la semaine prochaine.', + 'recommend.weeklyReview.description': 'Votre travail de la semaine dans l\'espace de travail, avec ce qui reste à terminer et les priorités de la semaine prochaine.', 'recommend.weeklyReview.schedule': 'Le vendredi à 16:00', - 'recommend.weeklyReview.prompt': 'Crée une tâche d\'automatisation nommée « Bilan hebdomadaire » : tous les vendredis à 16:00, passe en revue les changements de la semaine dans l\'espace de travail actuel, résume ce qui a été fait et liste ce qui reste à terminer et ce que je dois faire en premier la semaine prochaine ; si l\'espace de travail est un dépôt de code, couvre aussi les commits de la semaine, les pull requests fusionnées et celles encore ouvertes. Fais le résumé ici uniquement ; ne modifie pas les fichiers de l\'espace de travail.', + 'recommend.weeklyReview.prompt': 'Crée une tâche d\'automatisation nommée « Bilan hebdomadaire » : tous les vendredis à 16:00, passe en revue ce que j\'ai fait cette semaine dans l\'espace de travail actuel et liste ce qui reste à terminer et ce que je dois faire en premier la semaine prochaine ; si l\'espace de travail est un dépôt de code, ne regarde que mes commits de la semaine et les pull requests que j\'ai ouvertes qui ont été fusionnées cette semaine ou sont encore ouvertes. Fais le résumé ici uniquement ; ne modifie pas les fichiers de l\'espace de travail.', 'recommend.issueScan.title': 'Analyse des issues', 'recommend.issueScan.description': 'Trie les nouvelles issues en bugs, demandes et questions, et signale les doublons et celles qui nécessitent une réponse.', 'recommend.issueScan.schedule': 'Du lundi au vendredi à 10:00', @@ -193,9 +193,9 @@ export const recommendationDe: Record = { 'recommend.dailyBrief.schedule': 'Mo–Fr um 9:00', 'recommend.dailyBrief.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Tagesüberblick“: Prüfe montags bis freitags um 9:00 Uhr die Änderungen der letzten 24 Stunden im aktuellen Arbeitsbereich und liste auf, was ich nachverfolgen muss und was heute zuerst ansteht; ist der Arbeitsbereich ein Code-Repository, berücksichtige auch neue Commits, auf mein Review wartende Pull Requests und fehlgeschlagene CI-Läufe.', 'recommend.weeklyReview.title': 'Wochenrückblick', - 'recommend.weeklyReview.description': 'Änderungen der Woche im Arbeitsbereich, dazu offene Punkte und was nächste Woche zuerst ansteht.', + 'recommend.weeklyReview.description': 'Die eigene Arbeit dieser Woche im Arbeitsbereich, dazu offene Punkte und was nächste Woche zuerst ansteht.', 'recommend.weeklyReview.schedule': 'Freitags um 16:00', - 'recommend.weeklyReview.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Wochenrückblick“: Blicke freitags um 16:00 Uhr auf die Änderungen dieser Woche im aktuellen Arbeitsbereich zurück, fasse zusammen, was erledigt wurde, und liste auf, was noch offen ist und was nächste Woche zuerst ansteht; ist der Arbeitsbereich ein Code-Repository, berücksichtige auch die Commits dieser Woche sowie gemergte und noch offene Pull Requests. Fasse alles nur hier zusammen; ändere keine Dateien im Arbeitsbereich.', + 'recommend.weeklyReview.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Wochenrückblick“: Blicke freitags um 16:00 Uhr darauf zurück, was ich diese Woche im aktuellen Arbeitsbereich gemacht habe, und liste auf, was noch offen ist und was nächste Woche zuerst ansteht; ist der Arbeitsbereich ein Code-Repository, berücksichtige nur meine Commits dieser Woche und die von mir eröffneten Pull Requests, die diese Woche gemergt wurden oder noch offen sind. Fasse alles nur hier zusammen; ändere keine Dateien im Arbeitsbereich.', 'recommend.issueScan.title': 'Issue-Sichtung', 'recommend.issueScan.description': 'Sortiert neue Issues in Bugs, Feature-Wünsche und Fragen und hebt Duplikate sowie Issues hervor, die eine Antwort brauchen.', 'recommend.issueScan.schedule': 'Mo–Fr um 10:00', @@ -230,9 +230,9 @@ export const recommendationRu: Record = { 'recommend.dailyBrief.schedule': 'По будням в 9:00', 'recommend.dailyBrief.prompt': 'Создай задачу автоматизации под названием «Ежедневная сводка»: по будням в 9:00 просматривай изменения в текущей рабочей области за последние 24 часа и перечисляй, что требует моего внимания и с чего начать сегодня; если рабочая область — репозиторий кода, учитывай также новые коммиты, пул-реквесты, ожидающие моего ревью, и сбои CI.', 'recommend.weeklyReview.title': 'Еженедельный обзор', - 'recommend.weeklyReview.description': 'Изменения за неделю в рабочем пространстве, незавершённые дела и первоочередные задачи на следующую неделю.', + 'recommend.weeklyReview.description': 'Ваша работа за неделю в рабочем пространстве, незавершённые дела и первоочередные задачи на следующую неделю.', 'recommend.weeklyReview.schedule': 'По пятницам в 16:00', - 'recommend.weeklyReview.prompt': 'Создай задачу автоматизации под названием «Еженедельный обзор»: по пятницам в 16:00 просматривай изменения за эту неделю в текущем рабочем пространстве, подводи итог сделанного и перечисляй, что ещё не завершено и с чего начать на следующей неделе; если рабочее пространство — репозиторий кода, учитывай также коммиты за неделю, слитые и ещё открытые пул-реквесты. Сводку пиши только здесь; файлы в рабочем пространстве не меняй.', + 'recommend.weeklyReview.prompt': 'Создай задачу автоматизации под названием «Еженедельный обзор»: по пятницам в 16:00 просматривай мою работу за эту неделю в текущем рабочем пространстве и перечисляй, что ещё не завершено и с чего начать на следующей неделе; если рабочее пространство — репозиторий кода, учитывай только мои коммиты за неделю и мои пул-реквесты, слитые на этой неделе или ещё открытые. Сводку пиши только здесь; файлы в рабочем пространстве не меняй.', 'recommend.issueScan.title': 'Обзор issues', 'recommend.issueScan.description': 'Делит новые issues на баги, пожелания и вопросы и выделяет дубликаты и те, на которые нужно ответить.', 'recommend.issueScan.schedule': 'По будням в 10:00', @@ -267,9 +267,9 @@ export const recommendationPt: Record = { 'recommend.dailyBrief.schedule': 'Segunda a sexta às 9:00', 'recommend.dailyBrief.prompt': 'Crie uma tarefa de automação chamada “Resumo diário”: de segunda a sexta às 9:00, revise as mudanças das últimas 24 horas no espaço de trabalho atual e liste o que precisa do meu acompanhamento e o que fazer primeiro hoje; se o espaço de trabalho for um repositório de código, inclua também os novos commits, os pull requests aguardando minha revisão e as falhas de CI.', 'recommend.weeklyReview.title': 'Revisão semanal', - 'recommend.weeklyReview.description': 'Mudanças da semana no espaço de trabalho, com o que ficou pendente e o que fazer primeiro na próxima semana.', + 'recommend.weeklyReview.description': 'Seu trabalho da semana no espaço de trabalho, com o que ficou pendente e o que fazer primeiro na próxima semana.', 'recommend.weeklyReview.schedule': 'Sextas às 16:00', - 'recommend.weeklyReview.prompt': 'Crie uma tarefa de automação chamada “Revisão semanal”: toda sexta-feira às 16:00, revise as mudanças desta semana no espaço de trabalho atual, resuma o que foi feito e liste o que ainda está pendente e o que fazer primeiro na próxima semana; se o espaço de trabalho for um repositório de código, inclua também os commits da semana, os pull requests mesclados e os que continuam abertos. Faça o resumo só aqui; não altere arquivos do espaço de trabalho.', + 'recommend.weeklyReview.prompt': 'Crie uma tarefa de automação chamada “Revisão semanal”: toda sexta-feira às 16:00, revise o que eu fiz esta semana no espaço de trabalho atual e liste o que ainda está pendente e o que fazer primeiro na próxima semana; se o espaço de trabalho for um repositório de código, veja só os meus commits da semana e os pull requests que eu abri que foram mesclados esta semana ou continuam abertos. Faça o resumo só aqui; não altere arquivos do espaço de trabalho.', 'recommend.issueScan.title': 'Varredura de issues', 'recommend.issueScan.description': 'Classifica as novas issues em bugs, solicitações e perguntas e destaca as duplicadas e as que precisam de resposta.', 'recommend.issueScan.schedule': 'Segunda a sexta às 10:00', From 11f155707f8943d532ac1f484205eb4197e42ede Mon Sep 17 00:00:00 2001 From: Shigma Date: Mon, 16 Nov 2026 19:59:42 +0800 Subject: [PATCH 45/48] chore(cordis): backport include unresolved-alias locations from upstream --- scripts/cordis-entry-yaml.spec.ts | 1 + vendor/README.md | 6 ++-- vendor/include/src/index.ts | 55 ++++++++++++++++++------------- 3 files changed, 37 insertions(+), 25 deletions(-) diff --git a/scripts/cordis-entry-yaml.spec.ts b/scripts/cordis-entry-yaml.spec.ts index d2426d8b49..a91d8b96d9 100644 --- a/scripts/cordis-entry-yaml.spec.ts +++ b/scripts/cordis-entry-yaml.spec.ts @@ -46,5 +46,6 @@ describe('Include YAML dialect', () => { alias = caught } expect(entryYamlErrorPosition(alias)).toEqual({ line: 2, column: 11 }) + expect(() => parseEntryYaml('- id: a\n config: *later\n- id: b\n config: &later {}\n')).toThrow('Alias *later must follow its anchor') }) }) diff --git a/vendor/README.md b/vendor/README.md index a0e73b7813..f4830a221d 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -26,7 +26,7 @@ Intentionally **not** vendored (verified unused by this set): `reggol`, `@cordis ## Local modifications -Keep this log exhaustive — every divergence from upstream must be listed. Each entry has a stable ID: remove an entry when its divergence no longer exists, and never renumber or reuse IDs. The next new entry is V30. +Keep this log exhaustive — every divergence from upstream must be listed. Each entry has a stable ID: remove an entry when its divergence no longer exists, and never renumber or reuse IDs. The next new entry is V31. - **V1 · `hmr/src/index.ts`**: removed the `./locales/en-US.yml` / `./locales/zh-CN.yml` imports, the `.i18n({...})` call on the `Config` schema, and the `src/locales/` directory. Rationale: those imports require a runtime YAML loader hook (`@cordisjs/unyaml`) that we do not vendor; the i18n texts only localize config descriptions. - **V2 · All `package.json` files**: regenerated for Harness releases with scoped names, release versions, publication metadata, precise bundled-runtime and `lib/types/**/*.d.ts` / `.d.ts.map` file entries, source exports where applicable, and declaration metadata pointing at `lib/types`. References within the vendored set use `workspace:~`. HMR declares `esbuild` as a direct dev dependency for its imported `BuildFailure` type, Loader requires `node-addon-require-builtin@^0.1.4` to match published app runtimes, and Include declares `yaml@^2.9.0` instead of upstream's `^2.9.1` so the workspace installs one copy of `yaml`. @@ -37,7 +37,7 @@ Keep this log exhaustive — every divergence from upstream must be listed. Each - **V7 · JSDoc enrichment**: added `@param`/`@returns` tags and contract documentation (disposal semantics, waterfall veto, bail conditions, error cases) across the public plugin-author surface — `Context` (class, statics, the `isolate()` rule that isolated scopes never fall back to an injected view, and the `Context` interface properties incl. `[Context.root]`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `ValidationError` and its path helpers, `RegistryService`, `ReflectService`, `Service` and its intercept-metadata members, `LoggerService` and their `declare module './context.ts'` overloads. The upstream line comment on `reflect.ts`'s exported `locate()` is rewritten as JSDoc. Loader documentation covers `loader/src/{index,internal,config/entry,config/group,config/isolate,config/tree,config/utils}.ts`, including entry ownership, tree mutation methods, the `!!js` discriminator, entry option validation, source positions and `ModuleNotFoundError`. The upstream `EventsService.dispatch()` deprecation annotation is omitted: DSH enumerates callbacks to contain each observer failure independently, which the typed dispatch methods do not provide. Timer retains its local class and helper summaries; its README is local documentation because the upstream package has none. Cosmokit and Schemastery add summaries to their exported helpers, types and namespaces, logger-console to its exporters and config namespace, and HMR to its build-failure logger in `hmr/src/error.ts`. Comment-only; no code changes. Motivation: the website API-reference generator renders these docs and hard-errors on undocumented members. Retire this entry when the enrichment is upstreamed. - **V9 · `hmr/src/index.ts` module-watcher readiness and native paths**: realpath the existing watch base, classify framework modules and attach listeners before reporting readiness, and compare config paths using both canonical and configured spellings. This preserves Node module-cache identity across Windows short-name paths and filesystem aliases. The main watcher uses `ignoreInitial: true` so startup reads do not trigger another refresh; exact profile patch watching is owned by `packages/boot/hmr/src/watch-config.ts`. The Include change listener logs a rejected `Include.refresh()` instead of leaving the rejection unhandled; the rejection reports unsaved runtime changes while Include keeps its running tree. Covered by `packages/boot/hmr/tests/watch-config.spec.ts` and `scripts/cordis-vendor-hmr-include.spec.ts`. - **V10 · Vendored Node-compatible TypeScript**: marked erased imports explicitly across `cordis`, `loader`, `include`, `hmr`, and `schemastery` so Node's native TypeScript transform does not request types as runtime exports. Schemastery's source uses an ESM default export and its package declares `type: module`. Conditional exports select `.mjs` for import and `.cjs` for require; without them, concurrent imports under module-hook hosts reach the CJS entry and can race its require of ESM Cosmokit (`ERR_REQUIRE_ESM_RACE_CONDITION`). -- **V11 · Include patch and YAML exports**: `include/src/index.ts` exports upstream `applyPatches` as `applyEntryPatches` with its `PatchResult` type, so `dsh --dump-config` composes entries with the same algorithm that mounting uses. It also exports `parseEntryYaml`, `stringifyEntryYaml` and `entryYamlErrorPosition` over the `!!js` YAML dialect, using the `yaml` options with which `_read()` parses Include's own file, so every DSH reader and writer of Include-dialect YAML uses Include's parser. `parseEntryYaml` throws the first parse error or warning, such as an unknown tag, and returns `undefined` for an empty document; `stringifyEntryYaml` always writes with `aliasDuplicateObjects: false`, matching the previous `noRefs` output, and offers no option to emit aliases, while Include's own writer keeps upstream's options. Covered by `packages/boot/app-boot/tests/config-reload.spec.ts`, `scripts/cordis-entry-commit.spec.ts` and `scripts/cordis-entry-yaml.spec.ts`. +- **V11 · Include patch and YAML exports**: `include/src/index.ts` exports upstream `applyPatches` as `applyEntryPatches` with its `PatchResult` type, so `dsh --dump-config` composes entries with the same algorithm that mounting uses. It also exports `parseEntryYaml`, `stringifyEntryYaml` and `entryYamlErrorPosition` over the `!!js` YAML dialect, using the `yaml` options with which `_read()` parses Include's own file, so every DSH reader and writer of Include-dialect YAML uses Include's parser. `parseEntryYaml` throws the first parse error or warning, such as an unknown tag or an alias without a preceding anchor (V30), adds line positions to alias errors so `entryYamlErrorPosition` reads them, and returns `undefined` for an empty document; `stringifyEntryYaml` always writes with `aliasDuplicateObjects: false`, matching the previous `noRefs` output, and offers no option to emit aliases, while Include's own writer keeps upstream's options. Covered by `packages/boot/app-boot/tests/config-reload.spec.ts`, `scripts/cordis-entry-commit.spec.ts` and `scripts/cordis-entry-yaml.spec.ts`. - **V14 · Include persistence results**: `include/src/index.ts` keeps an error for unsaved journal changes. `flush()` retries pending writes and rejects while changes remain unsaved; `stop()` returns the same result and always stops the child tree; a later successful flush clears previous errors. A failed `refresh()` can also reject while runtime changes remain unsaved. Patch-owned changes route to the parent Include, so callers that need them persisted must flush that parent too. The constructor omits upstream's `ctx.hmr.watch(this.filename, () => this.refresh())` registration because neither HMR provider exposes `watch()`; both find each Include by scanning loader entries for its `filename` and call `refresh()`. Ordinary Fiber teardown keeps its error containment. Covered by `scripts/cordis-include-journal.spec.ts` and `packages/host/directory-picker-auto/tests/loader-composition.spec.ts`. - **V15 · Configuration access across Core, Loader, Include and HMR**: rc.11 Core owns raw `Fiber.config`, `internal/config(fiber, next)`, `internal/commit` and awaited `internal/update(config, next)`. Root-fiber candidate resolution remains available without a plugin schema. Local `rawConfig`, `resolveConfig(candidate)` and `effectiveConfig` accessors retain the DSH consumer API. Fiber caches the object passed to activation or a successful update that keeps the instance; candidate resolution is pure, failed or superseded updates cannot replace the cache, and volatile updates retain references. Loader resolves only entry roots and excludes Group/Include tree carriers, so nested `!!js` expressions wait for their own injections. Include retains its tree-carrier marker and public patch exports, and HMR transfers raw config through the accessors. Covered by `scripts/cordis-config-access.spec.ts`, `scripts/cordis-core-lifecycle.spec.ts` and the boot/HMR suites. - **V16 · `cordis/package.json` publishes `src`**: added `src` to the `files` list, joining the other eight vendored packages. Cordis declares `"./src/*": "./src/*"` in its exports, so a tarball without `src` publishes an export map pointing at absent files; the release change judgement also reads `files` to decide whether a diff reaches the payload, and a package whose only published paths are build output has no tracked path to match. @@ -48,7 +48,7 @@ Keep this log exhaustive — every divergence from upstream must be listed. Each - **V25 · Loader lifecycle adaptations**: before a combined context/config update, Loader refreshes dependencies locally, which prevents activation against stale isolation bindings; disabled-entry updates await disposal. Failed fibers require an explicit update after correcting their input or dependencies. Core retains the effect hardening in V6; rc.11 owns dependency teardown ordering and superseded-activation handling. - **V26 · `loader/src/config/tree.ts` cross-tree moves**: backports [cordiverse/cordis#271](https://github.com/cordiverse/cordis/pull/271), merged after `v4.0.0-rc.12`. When `EntryTree.update()` moves an entry into a group of another tree, the entry and the same-tree members of its group move their store registrations to the target tree, and the move is rejected before either tree changes when the target tree already holds one of their ids. The source tree receives a removal and the target tree a creation, without `legacy` or `from`. Upstream at `v4.0.0-rc.12` keeps the entry registered in the source tree and the target receives an update with `legacy`, so the Include journal writes a partial row and reconciling the target file creates a second Entry. Retire this entry when the vendored Loader includes the upstream fix. Covered by `scripts/cordis-include-journal.spec.ts`. - **V27 · `loader/src/config/utils.ts` explicit ids with `:`**: `validateOptions()` accepts ids containing `EntryTree.sep`, so `EntryTree.create()`, `EntryTree.update()` and group reconciliation admit them; upstream rejects them with an `id must not contain` issue. `validateOptions()` keeps its upstream `sep` parameter. Generated bundles from `@deepseek-ai/dsh-creation-recommendations` prefix their row ids with `:`, and installed profiles already contain such rows. `resolve()` still splits ids on `:`, so these entries cannot be addressed by nested path. Covered by `scripts/cordis-entry-commit.spec.ts`, `scripts/cordis-loader-rc9.spec.ts` and `packages/experimental/creation-recommendations/tests/loader-composition.spec.ts`. -- **V29 · `include/src/index.ts` unresolved aliases**: `_read()` and `parseEntryYaml()` report each alias without a preceding anchor as a `YAMLParseError` with code `BAD_ALIAS` and its position. Upstream leaves these to `document.toJS()`, which throws an unlocated `ReferenceError` outside `ConfigFileError`. Retire this entry when upstream reports them. Covered by `scripts/cordis-loader-rc9.spec.ts` and `scripts/cordis-entry-yaml.spec.ts`. +- **V30 · `include/src/index.ts` unresolved aliases**: backports [cordiverse/cordis#354](https://github.com/cordiverse/cordis/pull/354) (`c9fe179ce5ac484620a387a1697409cb007d4178`), merged after `v4.0.0-rc.12`. `_read()` reports each alias without a preceding anchor as a `BAD_ALIAS` `YAMLParseError` with its position, distinguishing an unknown anchor from one written after the alias; at the tag, `document.toJS()` throws an unlocated `ReferenceError` outside `ConfigFileError`. `unresolvedAliases()` matches the upstream commit verbatim. Retire this entry when the vendored Include includes #354. Covered by `scripts/cordis-loader-rc9.spec.ts` and `scripts/cordis-entry-yaml.spec.ts`. ### Resolver adaptations diff --git a/vendor/include/src/index.ts b/vendor/include/src/index.ts index 2fe77103f0..d60c4eb2c1 100644 --- a/vendor/include/src/index.ts +++ b/vendor/include/src/index.ts @@ -7,7 +7,7 @@ import { setTimeout as sleep } from 'node:timers/promises' import { fileURLToPath, pathToFileURL } from 'node:url' import { isAlias, isMap, isNode, isScalar, isSeq, LineCounter, parseDocument, Scalar, stringify, visit, YAMLError, YAMLParseError, - type Document, type Range, type ScalarTag, type SchemaOptions, + type Alias, type Document, type Range, type ScalarTag, type SchemaOptions, } from 'yaml' import { stringifyString } from 'yaml/util' import { applyJournal, flatten, type Journal, merge, reconcile, record } from './journal.ts' @@ -53,29 +53,15 @@ export interface EntryYamlStringifyOptions { export function parseEntryYaml(content: string): unknown { const lines = new LineCounter() const document = parseDocument(content, { ...yamlOptions, lineCounter: lines }) - const [error] = [...document.errors, ...document.warnings, ...unresolvedAliases(document, lines)] - if (error) throw error + const [error] = [...document.errors, ...document.warnings, ...unresolvedAliases(document)] + if (error) { + // Alias errors carry offsets only; the parser's own errors already carry line positions. + error.linePos ??= [lines.linePos(error.pos[0]), lines.linePos(error.pos[1])] + throw error + } return document.contents === null ? undefined : document.toJS() } -/** - * The parser reports an alias without a preceding anchor only when `toJS()` throws an unlocated `ReferenceError`; - * report each one as a located parse error instead. - */ -function unresolvedAliases(document: Document, lines: LineCounter): YAMLParseError[] { - const errors: YAMLParseError[] = [] - visit(document, { - Alias(_, node) { - if (node.resolve(document) || !node.range) return - const [start, end] = node.range - const error = new YAMLParseError([start, end], 'BAD_ALIAS', `Unresolved alias (the anchor must be set before the alias): ${node.source}`) - error.linePos = [lines.linePos(start), lines.linePos(end)] - errors.push(error) - }, - }) - return errors -} - /** * Serialize a value in Include's YAML dialect. JavaScript expression nodes are written as `!!js` scalars. The output * never contains anchors or aliases: repeated object references are written out in full, and no option changes this. @@ -118,6 +104,31 @@ function parseSyntax(content: string): Syntax { return { document, lines } } +/** + * The parser accepts an alias without a preceding anchor, which only fails in + * `toJS()` with an unlocated `ReferenceError`. Nodes are visited in document + * order, so an anchor is known exactly when it precedes the alias. + */ +function unresolvedAliases(document: Document) { + const anchors = new Set() + const unresolved: Alias[] = [] + visit(document, (_, node) => { + if (isAlias(node)) { + if (!anchors.has(node.source)) unresolved.push(node) + } else if (isNode(node) && node.anchor) { + anchors.add(node.anchor) + } + }) + // every anchor is known once the scan ends + return unresolved.map((node) => { + const [start, end] = node.range! + const message = anchors.has(node.source) + ? `Alias *${node.source} must follow its anchor` + : `Unresolved alias: *${node.source}` + return new YAMLParseError([start, end], 'BAD_ALIAS', message) + }) +} + interface Snapshot { content: string data: EntryOptions[] @@ -405,7 +416,7 @@ export class Include extends EntryTree { syntax = parseSyntax(content) const { document, lines } = syntax // unknown tags are only warnings to the parser, but leave the data incomplete - const errors: YAMLError[] = [...document.errors, ...document.warnings, ...unresolvedAliases(document, lines)] + const errors: YAMLError[] = [...document.errors, ...document.warnings, ...unresolvedAliases(document)] if (errors.length) { const issues = errors.map(error => ({ message: error.message, location: this._locate(lines, error.pos[0]) })) throw new ConfigFileError('parse', this.filename, undefined, issues) From 0fcc29cee0022c6e280381676448d3858d6d55f3 Mon Sep 17 00:00:00 2001 From: Shigma Date: Mon, 16 Nov 2026 23:52:08 +0800 Subject: [PATCH 46/48] fix(app-boot): apply the requested platform's path rules to include filenames --- packages/boot/app-boot/src/include-filename.ts | 9 ++++----- packages/boot/app-boot/tests/include-filename.spec.ts | 1 + 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/boot/app-boot/src/include-filename.ts b/packages/boot/app-boot/src/include-filename.ts index 9daebba362..b45c61469f 100644 --- a/packages/boot/app-boot/src/include-filename.ts +++ b/packages/boot/app-boot/src/include-filename.ts @@ -10,13 +10,12 @@ const DRIVE_LETTER = /^[A-Za-z]:[\\/]/u * other path is a URL reference resolved against the owning tree's base URL. * @param path - literal Include `path`. * @param baseUrl - base URL of the tree that owns the Include entry. - * @param platform - platform whose path rules apply; defaults to the running one. + * @param platform - platform whose path rules apply to both branches; defaults to the running one. * @returns the absolute filename. * @throws when `path` resolves to a URL that is not a `file:` URL. */ export function includeFilename(path: string, baseUrl: string, platform: NodeJS.Platform = process.platform): string { - if (platform === 'win32' && DRIVE_LETTER.test(path)) { - return fileURLToPath(pathToFileURL(path, { windows: true }), { windows: true }) - } - return fileURLToPath(new URL(path, baseUrl)) + const windows = platform === 'win32' + if (windows && DRIVE_LETTER.test(path)) return fileURLToPath(pathToFileURL(path, { windows }), { windows }) + return fileURLToPath(new URL(path, baseUrl), { windows }) } diff --git a/packages/boot/app-boot/tests/include-filename.spec.ts b/packages/boot/app-boot/tests/include-filename.spec.ts index ef24820fdb..96b9dade5d 100644 --- a/packages/boot/app-boot/tests/include-filename.spec.ts +++ b/packages/boot/app-boot/tests/include-filename.spec.ts @@ -13,5 +13,6 @@ describe('includeFilename', () => { expect(includeFilename('file:///etc/extra.yml', 'file:///app/', 'linux')).toBe('/etc/extra.yml') // Off Windows, Include reads `C:` as a URL scheme too. expect(() => includeFilename('C:/config/extra.yml', 'file:///app/', 'linux')).toThrow() + expect(includeFilename('./extra.yml', 'file:///D:/app/cordis.yml', 'win32')).toBe('D:\\app\\extra.yml') }) }) From 0c8078e19652d98ab6dbba0a2a42137d536ec189 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Tue, 17 Nov 2026 00:13:00 +0800 Subject: [PATCH 47/48] feat(forge): name worktree branches, start them from remote branches, and show changes being read (#8536) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(forge): name worktree branches, start them from remote branches, and show changes being read The New Session worktree option's base menu now searches local branches and each remote's branches, pins the current branch and every remote's default branch, and names each remote group by its repository. Its last row opens a dialog that names the new branch, starting from `worktreePrefix` and checking Git's branch-name rules; the Host refuses an invalid or taken name. A request records the full ref of its base and the optional name; every attempt uses the name. A remote-tracking base is fetched first: the worktree service gains a `fetch` request field and a `fetch` phase, fetching only that branch without tags. A failed fetch leaves the message waiting with Retry, Use the last fetched version, and Continue without a worktree; a taken name offers Rename. While the changes view reads changes it has not shown yet, it says "Reading changes" above file card placeholders, and the files menu names no count. * fix(worktree): forward only the declared create_worktree arguments The create_worktree parameter object is open, and the tool passed it to the worktree runtime unchanged. Now that a runtime request can ask to fetch, an undeclared `fetch: true` from the model would have fetched, or refused a local `from`. The tool now forwards only `name` and `from`, so it never fetches. * docs(forge): say that only generated worktree branch names come from the Session id * fix(forge): keep the collapsed change request status on one line In the Session panel the collapsed card's number line kept every part at full width inside a clipping row, so a narrow panel cut the most urgent flag off without an ellipsis, such as "有冲突" after "3 项检查失败". The number and status now form one MarqueeText line as wide as the row. While the line with failed checks does not fit, they take the shorter wording without their count; a line that still does not fit ends in an ellipsis and crawls into view with the title while the pointer rests on the card's head. The line measures again when its width or the fonts change. Expanded cards keep their branch names as before. * fix(forge): hide remote credentials and read the branch a tag shares its name with The base menu named an unrecognized remote's group by its fetch URL as `git remote -v` prints it, so a token in the URL, such as `https://oauth2:glpat-...@gitlab.example/...`, reached the browser and showed in the menu. The group now shows the URL without its user name and password. Inspection read the checked-out branch with `symbolic-ref --short HEAD`, which prints `heads/main` while a tag is also named `main`; the New Session option then requested `refs/heads/heads/main` and every worktree attempt failed. Inspection now reads the full ref and takes the name under `refs/heads/`, so the option, the pinned current branch, and the checkout row name `main`. HEAD that names a ref outside `refs/heads/` reads as no branch. * test(worktree): set up nested remotes and line endings the CI runners' Git accepts Git 2.55 on the CI runners refuses `git remote add team` next to an existing `team/fork` remote; the check runs only in `git remote add`, so the longest-remote case now writes the second remote with `git config`, as configuration written earlier or by hand holds it. The test clone also turns off `core.autocrlf`, as `repository` does, because the Windows runner's global setting checked the fetched file out with CRLF. --- apps/web/tests/forge-panel.e2e.ts | 8 +- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/subsystems/forge.md | 120 +++++-- docs/subsystems/forge.zh.md | 120 +++++-- docs/subsystems/worktrees.i18n.yaml | 4 +- docs/subsystems/worktrees.md | 28 +- docs/subsystems/worktrees.zh.md | 28 +- .../client-ui-forge/README.i18n.yaml | 12 +- .../experimental/client-ui-forge/README.md | 20 +- .../experimental/client-ui-forge/README.zh.md | 20 +- .../client-ui-forge/src/branch-name.ts | 74 ++++ .../client-ui-forge/src/client/BaseMenu.tsx | 54 +-- .../src/client/ChangeRequestCard.tsx | 106 +++++- .../src/client/ChangedFiles.tsx | 10 +- .../src/client/ChangesLoading.module.css | 110 ++++++ .../src/client/ChangesLoading.tsx | 69 ++++ .../client-ui-forge/src/client/ChangesTab.tsx | 9 +- .../src/client/Forge.module.css | 27 +- .../src/client/SessionHoverForge.tsx | 3 +- .../src/client/WorktreeNameDialog.module.css | 53 +++ .../src/client/WorktreeNameDialog.tsx | 93 +++++ .../src/client/WorktreeProgress.tsx | 135 ++++++-- .../src/client/WorktreeToggle.module.css | 156 ++++++++- .../src/client/WorktreeToggle.tsx | 240 +++++++++---- .../src/client/branch-search.tsx | 90 +++++ .../client-ui-forge/src/client/checkout.ts | 3 +- .../client-ui-forge/src/client/locales.ts | 320 +++++++++++++++++- .../client-ui-forge/src/client/mount.ts | 26 +- .../experimental/client-ui-forge/src/git.ts | 45 +-- .../experimental/client-ui-forge/src/index.ts | 101 +++--- .../client-ui-forge/src/local-diff.ts | 4 +- .../experimental/client-ui-forge/src/panel.ts | 5 +- .../experimental/client-ui-forge/src/parse.ts | 96 +++++- .../experimental/client-ui-forge/src/types.ts | 79 ++++- .../client-ui-forge/src/worktree.ts | 96 ++++-- .../tests/branch-name.host.spec.ts | 76 +++++ .../tests/change-request-card.client.spec.tsx | 74 +++- .../tests/changes-tab.client.spec.tsx | 31 +- .../tests/client-fixtures.client.ts | 17 +- .../tests/controller.host.spec.ts | 240 +++++++++---- .../client-ui-forge/tests/git.host.spec.ts | 110 ++---- .../tests/mount.client.spec.ts | 60 ++-- .../client-ui-forge/tests/parse.host.spec.ts | 89 ++++- .../worktree-name-dialog.client.spec.tsx | 141 ++++++++ .../tests/worktree-progress.client.spec.tsx | 61 +++- .../tests/worktree-toggle.client.spec.tsx | 268 ++++++++++----- .../tests/worktree.host.spec.ts | 106 ++++-- .../client-ui-forge/tsconfig.client.json | 1 + .../client-ui-forge/tsconfig.host.json | 1 + .../tool-worktree/README.i18n.yaml | 4 +- packages/experimental/tool-worktree/README.md | 2 +- .../experimental/tool-worktree/README.zh.md | 2 +- .../experimental/tool-worktree/src/index.ts | 5 +- .../tests/loader-composition.spec.ts | 7 + .../experimental/worktree/README.i18n.yaml | 8 +- packages/experimental/worktree/README.md | 4 +- packages/experimental/worktree/README.zh.md | 4 +- packages/experimental/worktree/src/index.ts | 61 +++- packages/experimental/worktree/src/types.ts | 12 +- .../worktree/tests/worktree.spec.ts | 87 +++++ .../extensions/tool-cordis/src/api-catalog.ts | 62 ++-- scripts/gen-cordis-catalog.ts | 4 +- scripts/type-equiv.manifest.json | 12 +- 64 files changed, 3111 insertions(+), 806 deletions(-) create mode 100644 packages/experimental/client-ui-forge/src/branch-name.ts create mode 100644 packages/experimental/client-ui-forge/src/client/ChangesLoading.module.css create mode 100644 packages/experimental/client-ui-forge/src/client/ChangesLoading.tsx create mode 100644 packages/experimental/client-ui-forge/src/client/WorktreeNameDialog.module.css create mode 100644 packages/experimental/client-ui-forge/src/client/WorktreeNameDialog.tsx create mode 100644 packages/experimental/client-ui-forge/src/client/branch-search.tsx create mode 100644 packages/experimental/client-ui-forge/tests/branch-name.host.spec.ts create mode 100644 packages/experimental/client-ui-forge/tests/worktree-name-dialog.client.spec.tsx diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 92014005f5..04fd421940 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -839,8 +839,8 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me expect(await git(directory, 'rev-parse', 'HEAD')).toBe(baseCommit) const events = await readPersistedEvents(scaffold, sessionId) expect(worktreeRecords(events)).toEqual([ - { action: 'request', from: 'main' }, - { action: 'request', from: 'release' }, + { action: 'request', from: 'refs/heads/main' }, + { action: 'request', from: 'refs/heads/release' }, { created: { path: directory, branch, baseCommit, repositoryRoot: project } }, ]) // The worktree existed before the turn, so the first model request carried its directory notice. @@ -978,7 +978,9 @@ it.skipIf(MODE === 'record')('keeps the first message waiting when the worktree if (session === undefined) throw new Error('The Session must stay loaded') expect(scaffold.ctx.workingDirectory.get(session)).toBe(project) const events = await readPersistedEvents(scaffold, sessionId) - expect(worktreeRecords(events)).toEqual([{ action: 'request', from: 'main' }, { action: 'request', from: 'release' }, { action: 'cancel' }]) + expect(worktreeRecords(events)).toEqual([ + { action: 'request', from: 'refs/heads/main' }, { action: 'request', from: 'refs/heads/release' }, { action: 'cancel' }, + ]) expect(events.filter(event => event.type === 'turn/start')).toHaveLength(1) expect(events.some(event => event.type === 'user/message' && event.data.source.kind === 'working-directory')).toBe(false) const checkout = (await showSessionPanel(page)).locator('[data-forge-checkout]') diff --git a/docs/config-catalog.md b/docs/config-catalog.md index ffb33f34a6..2beea90aec 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1182,7 +1182,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:485`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:530`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 10a6bbfc1a..6d18e77f5c 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1184,7 +1184,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:485`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:530`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index 11c33f58c9..edf3a8c2d9 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -915,7 +915,10 @@ interface ForgeSessionWorktree { readonly path: string /** Branch created for the checkout. */ readonly branch: string - /** Requested base branch, or null when the checkout started from HEAD of the source checkout. */ + /** + * Requested base: the full name of a local or remote-tracking branch, a short branch name that earlier panels + * recorded, or null when the checkout started from HEAD of the source checkout. + */ readonly from: string | null /** Commit object name the branch started from. */ readonly baseCommit: string @@ -928,8 +931,11 @@ interface ForgeSessionWorktree { ```ts type-equiv /** Payload of the `plugin:client-ui-forge/worktree` record. */ type WorktreeRecord = - /** Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null. */ - | { readonly action: 'request'; readonly from: string | null } + /** + * Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null, on the + * branch `name`, or on a generated branch name when `name` is absent. + */ + | { readonly action: 'request'; readonly from: string | null; readonly name?: string } /** Withdraw the open request. */ | { readonly action: 'cancel' } /** The requested worktree was created and became the Session's working directory. */ @@ -943,8 +949,13 @@ type WorktreeRecord = ```ts type-equiv /** One open worktree request. */ interface ForgeWorktreeRequest { - /** Base branch, or null for HEAD of the source checkout. */ + /** + * Base: the full name of a local or remote-tracking branch, a short branch name that earlier panels recorded, or + * null for HEAD of the source checkout. A remote-tracking branch is fetched before each attempt that does not skip it. + */ readonly from: string | null + /** New branch name the user chose, which every attempt uses, or null for a generated name per attempt. */ + readonly name: string | null } ``` @@ -962,12 +973,17 @@ type ForgeWorktreeBlocker = ```ts type-equiv /** One running worktree creation. */ interface ForgeWorktreeCreation { - /** Running step: `prepare` validates and creates the branch, then `checkout` writes the files. */ - readonly phase: 'prepare' | 'checkout' + /** + * Running step: `fetch` fetches a remote base branch, `prepare` validates and creates the branch, then + * `checkout` writes the files. + */ + readonly phase: 'fetch' | 'prepare' | 'checkout' /** Branch the attempt creates. */ readonly branch: string - /** Base branch, or null for HEAD. */ + /** Base as the request names it, or null for HEAD. */ readonly from: string | null + /** Whether the attempt fetches its remote base branch first. */ + readonly fetch: boolean /** * Whether a message waits for the creation before its turn starts. Only * such a creation can be stopped, after which the message keeps waiting; a @@ -990,12 +1006,16 @@ interface ForgeWorktreeRestoration { interface ForgeWorktreeFailure { /** Branch the attempt created, or null when it failed before naming one. */ readonly branch: string | null - /** Base branch of the attempt, or null for HEAD. */ + /** Base of the attempt as the request names it, or null for HEAD. */ readonly from: string | null + /** Whether the attempt fetched, or tried to fetch, its remote base branch first. */ + readonly fetch: boolean /** Step that failed. */ - readonly phase: 'prepare' | 'checkout' + readonly phase: 'fetch' | 'prepare' | 'checkout' /** Failure text. */ readonly message: string + /** Whether the branch or the checkout directory of that name already existed, which another name avoids. */ + readonly exists: boolean } ``` @@ -1026,6 +1046,8 @@ interface ForgePanelWorktree { readonly editable: boolean /** Why the checkout cannot host a worktree, or null when it can, before the first inspection, and after a failed one. */ readonly blocker: ForgeWorktreeBlocker | null + /** Prefix of generated branch names, the Config `worktreePrefix`, which a name the user types starts from. */ + readonly namePrefix: string /** Open request, or null without one. */ readonly request: ForgeWorktreeRequest | null /** Created worktree, or null before creation. */ @@ -1086,12 +1108,39 @@ interface ForgePanelState { ``` ```ts type-equiv -/** Local branches offered as the base of a new worktree. */ -interface ForgeBranches { - /** Checked-out branch, or null when HEAD is detached. */ - readonly current: string | null - /** Local branch names, `current` first and then most recently committed first, at most `maxBranches`. */ - readonly branches: readonly string[] +/** Branches offered as the base of a new worktree whose names contain a query. */ +interface ForgeWorktreeBases { + /** Checked-out branch, or null when HEAD is detached or its name does not contain the query. */ + readonly current: ForgeBaseBranch | null + /** Default branch of each remote that names one with `refs/remotes//HEAD`, in remote order. */ + readonly defaults: readonly ForgeRemoteDefault[] + /** Other local branches, most recently committed first, at most `maxBranches`. */ + readonly local: readonly ForgeBaseBranch[] + /** + * Remote-tracking branches of each configured remote in remote order: the remote the checked-out branch tracks, + * then `origin`, then the others as Git lists them. Remotes without a matching branch are left out. + */ + readonly remotes: readonly ForgeRemoteBranches[] +} +``` + +```ts type-equiv +/** A remote's default branch, which `refs/remotes//HEAD` names. */ +interface ForgeRemoteDefault extends ForgeBaseBranch { + /** Remote the branch belongs to; it may contain `/`. */ + readonly remote: string +} +``` + +```ts type-equiv +/** Remote-tracking branches of one remote, without its default branch. */ +interface ForgeRemoteBranches { + /** Remote name such as `origin`; it may contain `/`. */ + readonly name: string + /** `owner/name` of the repository a provider recognizes from the remote's URLs, else its fetch URL, or null without one. */ + readonly repository: string | null + /** Branches named `/`, most recently committed first, at most `maxBranches`. */ + readonly branches: readonly ForgeBaseBranch[] } ``` @@ -1775,13 +1824,16 @@ Serves the forge panel. Following a Session inspects the checkout of its current @Remote async worktreeCleanup(session: Session, revision: number | null): Promise /** - * List the local branches that can start a worktree of the Session's current checkout. - * @param session - Session whose current directory is listed. + * List the branches that can start a worktree of the Session's current checkout: the checked-out branch, each + * remote's default branch, other local branches, and each remote's other remote-tracking branches, remotes in the + * order the panel recognizes code hosts. + * @param session - Session whose checkout is read. + * @param query - text the branch names must contain, ignoring case; empty for every branch. * @param signal - request cancellation. - * @returns the checked-out branch and at most `maxBranches` local branches, the checked-out one first. - * @throws when the current directory is not inside a checkout or Git fails. + * @returns the branches, at most `maxBranches` local branches and `maxBranches` per remote, most recently committed first. + * @throws `forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`. */ -@Remote async branches(session: Session, signal: AbortSignal): Promise +@Remote async worktreeBases(session: Session, query: string, signal: AbortSignal): Promise /** * List the branches the `branch` scope of the Session's current checkout can compare with. @@ -2114,18 +2166,23 @@ registerLens(lens: ForgeLens): () => Promise /** * Ask for a new worktree before the Session's first turn, replacing an open * request and forgetting a failed attempt. While the next message waits in - * the inbox, or else at the first step proposal, the panel creates a branch - * from `from`, or from HEAD of the current checkout when it is null, and - * enters its checkout. A message that already waits after a failed or - * stopped attempt keeps waiting for {@link ForgePanelController.retryWorktree}. + * the inbox, or else at the first step proposal, the panel creates the + * branch `name`, or a generated branch per attempt when it is null, from + * `from`, or from HEAD of the current checkout when it is null, and enters + * its checkout; a remote-tracking `from` is fetched first. A message that + * already waits after a failed or stopped attempt keeps waiting for + * {@link ForgePanelController.retryWorktree}. * @param session - Session without a started turn. - * @param from - local base branch, or null for HEAD. + * @param from - full name of a local or remote-tracking base branch, or null for HEAD. + * @param name - new branch name, or null to generate one per attempt. * @param signal - request cancellation. - * @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/worktrees-unavailable` + * @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/invalid-name` when `name` breaks + * a branch-name rule; `forgePanel/branch-exists` when the checkout has a local branch named `name`; + * `forgePanel/not-a-checkout` when a name is checked outside a checkout; `forgePanel/worktrees-unavailable` * without a worktree service; `forgePanel/session-started` after a turn started or the worktree was * created; `forgePanel/session-busy` while the worktree is being created. */ -@Remote async requestWorktree(session: Session, from: string | null, signal: AbortSignal): Promise +@Remote async requestWorktree(session: Session, from: string | null, name: string | null, signal: AbortSignal): Promise /** * Withdraw the open worktree request of a Session with its failed attempt, @@ -2148,13 +2205,16 @@ registerLens(lens: ForgeLens): () => Promise @Remote async stopCreation(session: Session, signal: AbortSignal): Promise /** - * Make another attempt, with a new branch name, at the worktree a message - * of the Session waits for after a failed or stopped attempt. + * Make another attempt, on the requested branch name or a new generated + * one, at the worktree a message of the Session waits for after a failed or + * stopped attempt. * @param session - Session whose message waits. + * @param fetch - false skips fetching a remote-tracking base branch for this attempt, which then starts from the + * commit last fetched. * @param signal - request cancellation. * @throws `forgePanel/not-waiting` when no message waits or an attempt is running. */ -@Remote async retryWorktree(session: Session, signal: AbortSignal): Promise +@Remote async retryWorktree(session: Session, fetch: boolean, signal: AbortSignal): Promise /** * Check out the created worktree of a Session again at its recorded diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index a73e3ecdd2..1f962fae0e 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -917,7 +917,10 @@ interface ForgeSessionWorktree { readonly path: string /** Branch created for the checkout. */ readonly branch: string - /** Requested base branch, or null when the checkout started from HEAD of the source checkout. */ + /** + * Requested base: the full name of a local or remote-tracking branch, a short branch name that earlier panels + * recorded, or null when the checkout started from HEAD of the source checkout. + */ readonly from: string | null /** Commit object name the branch started from. */ readonly baseCommit: string @@ -930,8 +933,11 @@ interface ForgeSessionWorktree { ```ts type-equiv /** Payload of the `plugin:client-ui-forge/worktree` record. */ type WorktreeRecord = - /** Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null. */ - | { readonly action: 'request'; readonly from: string | null } + /** + * Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null, on the + * branch `name`, or on a generated branch name when `name` is absent. + */ + | { readonly action: 'request'; readonly from: string | null; readonly name?: string } /** Withdraw the open request. */ | { readonly action: 'cancel' } /** The requested worktree was created and became the Session's working directory. */ @@ -945,8 +951,13 @@ type WorktreeRecord = ```ts type-equiv /** One open worktree request. */ interface ForgeWorktreeRequest { - /** Base branch, or null for HEAD of the source checkout. */ + /** + * Base: the full name of a local or remote-tracking branch, a short branch name that earlier panels recorded, or + * null for HEAD of the source checkout. A remote-tracking branch is fetched before each attempt that does not skip it. + */ readonly from: string | null + /** New branch name the user chose, which every attempt uses, or null for a generated name per attempt. */ + readonly name: string | null } ``` @@ -964,12 +975,17 @@ type ForgeWorktreeBlocker = ```ts type-equiv /** One running worktree creation. */ interface ForgeWorktreeCreation { - /** Running step: `prepare` validates and creates the branch, then `checkout` writes the files. */ - readonly phase: 'prepare' | 'checkout' + /** + * Running step: `fetch` fetches a remote base branch, `prepare` validates and creates the branch, then + * `checkout` writes the files. + */ + readonly phase: 'fetch' | 'prepare' | 'checkout' /** Branch the attempt creates. */ readonly branch: string - /** Base branch, or null for HEAD. */ + /** Base as the request names it, or null for HEAD. */ readonly from: string | null + /** Whether the attempt fetches its remote base branch first. */ + readonly fetch: boolean /** * Whether a message waits for the creation before its turn starts. Only * such a creation can be stopped, after which the message keeps waiting; a @@ -992,12 +1008,16 @@ interface ForgeWorktreeRestoration { interface ForgeWorktreeFailure { /** Branch the attempt created, or null when it failed before naming one. */ readonly branch: string | null - /** Base branch of the attempt, or null for HEAD. */ + /** Base of the attempt as the request names it, or null for HEAD. */ readonly from: string | null + /** Whether the attempt fetched, or tried to fetch, its remote base branch first. */ + readonly fetch: boolean /** Step that failed. */ - readonly phase: 'prepare' | 'checkout' + readonly phase: 'fetch' | 'prepare' | 'checkout' /** Failure text. */ readonly message: string + /** Whether the branch or the checkout directory of that name already existed, which another name avoids. */ + readonly exists: boolean } ``` @@ -1028,6 +1048,8 @@ interface ForgePanelWorktree { readonly editable: boolean /** Why the checkout cannot host a worktree, or null when it can, before the first inspection, and after a failed one. */ readonly blocker: ForgeWorktreeBlocker | null + /** Prefix of generated branch names, the Config `worktreePrefix`, which a name the user types starts from. */ + readonly namePrefix: string /** Open request, or null without one. */ readonly request: ForgeWorktreeRequest | null /** Created worktree, or null before creation. */ @@ -1088,12 +1110,39 @@ interface ForgePanelState { ``` ```ts type-equiv -/** Local branches offered as the base of a new worktree. */ -interface ForgeBranches { - /** Checked-out branch, or null when HEAD is detached. */ - readonly current: string | null - /** Local branch names, `current` first and then most recently committed first, at most `maxBranches`. */ - readonly branches: readonly string[] +/** Branches offered as the base of a new worktree whose names contain a query. */ +interface ForgeWorktreeBases { + /** Checked-out branch, or null when HEAD is detached or its name does not contain the query. */ + readonly current: ForgeBaseBranch | null + /** Default branch of each remote that names one with `refs/remotes//HEAD`, in remote order. */ + readonly defaults: readonly ForgeRemoteDefault[] + /** Other local branches, most recently committed first, at most `maxBranches`. */ + readonly local: readonly ForgeBaseBranch[] + /** + * Remote-tracking branches of each configured remote in remote order: the remote the checked-out branch tracks, + * then `origin`, then the others as Git lists them. Remotes without a matching branch are left out. + */ + readonly remotes: readonly ForgeRemoteBranches[] +} +``` + +```ts type-equiv +/** A remote's default branch, which `refs/remotes//HEAD` names. */ +interface ForgeRemoteDefault extends ForgeBaseBranch { + /** Remote the branch belongs to; it may contain `/`. */ + readonly remote: string +} +``` + +```ts type-equiv +/** Remote-tracking branches of one remote, without its default branch. */ +interface ForgeRemoteBranches { + /** Remote name such as `origin`; it may contain `/`. */ + readonly name: string + /** `owner/name` of the repository a provider recognizes from the remote's URLs, else its fetch URL, or null without one. */ + readonly repository: string | null + /** Branches named `/`, most recently committed first, at most `maxBranches`. */ + readonly branches: readonly ForgeBaseBranch[] } ``` @@ -1777,13 +1826,16 @@ Serves the forge panel. Following a Session inspects the checkout of its current @Remote async worktreeCleanup(session: Session, revision: number | null): Promise /** - * List the local branches that can start a worktree of the Session's current checkout. - * @param session - Session whose current directory is listed. + * List the branches that can start a worktree of the Session's current checkout: the checked-out branch, each + * remote's default branch, other local branches, and each remote's other remote-tracking branches, remotes in the + * order the panel recognizes code hosts. + * @param session - Session whose checkout is read. + * @param query - text the branch names must contain, ignoring case; empty for every branch. * @param signal - request cancellation. - * @returns the checked-out branch and at most `maxBranches` local branches, the checked-out one first. - * @throws when the current directory is not inside a checkout or Git fails. + * @returns the branches, at most `maxBranches` local branches and `maxBranches` per remote, most recently committed first. + * @throws `forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`. */ -@Remote async branches(session: Session, signal: AbortSignal): Promise +@Remote async worktreeBases(session: Session, query: string, signal: AbortSignal): Promise /** * List the branches the `branch` scope of the Session's current checkout can compare with. @@ -2116,18 +2168,23 @@ registerLens(lens: ForgeLens): () => Promise /** * Ask for a new worktree before the Session's first turn, replacing an open * request and forgetting a failed attempt. While the next message waits in - * the inbox, or else at the first step proposal, the panel creates a branch - * from `from`, or from HEAD of the current checkout when it is null, and - * enters its checkout. A message that already waits after a failed or - * stopped attempt keeps waiting for {@link ForgePanelController.retryWorktree}. + * the inbox, or else at the first step proposal, the panel creates the + * branch `name`, or a generated branch per attempt when it is null, from + * `from`, or from HEAD of the current checkout when it is null, and enters + * its checkout; a remote-tracking `from` is fetched first. A message that + * already waits after a failed or stopped attempt keeps waiting for + * {@link ForgePanelController.retryWorktree}. * @param session - Session without a started turn. - * @param from - local base branch, or null for HEAD. + * @param from - full name of a local or remote-tracking base branch, or null for HEAD. + * @param name - new branch name, or null to generate one per attempt. * @param signal - request cancellation. - * @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/worktrees-unavailable` + * @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/invalid-name` when `name` breaks + * a branch-name rule; `forgePanel/branch-exists` when the checkout has a local branch named `name`; + * `forgePanel/not-a-checkout` when a name is checked outside a checkout; `forgePanel/worktrees-unavailable` * without a worktree service; `forgePanel/session-started` after a turn started or the worktree was * created; `forgePanel/session-busy` while the worktree is being created. */ -@Remote async requestWorktree(session: Session, from: string | null, signal: AbortSignal): Promise +@Remote async requestWorktree(session: Session, from: string | null, name: string | null, signal: AbortSignal): Promise /** * Withdraw the open worktree request of a Session with its failed attempt, @@ -2150,13 +2207,16 @@ registerLens(lens: ForgeLens): () => Promise @Remote async stopCreation(session: Session, signal: AbortSignal): Promise /** - * Make another attempt, with a new branch name, at the worktree a message - * of the Session waits for after a failed or stopped attempt. + * Make another attempt, on the requested branch name or a new generated + * one, at the worktree a message of the Session waits for after a failed or + * stopped attempt. * @param session - Session whose message waits. + * @param fetch - false skips fetching a remote-tracking base branch for this attempt, which then starts from the + * commit last fetched. * @param signal - request cancellation. * @throws `forgePanel/not-waiting` when no message waits or an attempt is running. */ -@Remote async retryWorktree(session: Session, signal: AbortSignal): Promise +@Remote async retryWorktree(session: Session, fetch: boolean, signal: AbortSignal): Promise /** * Check out the created worktree of a Session again at its recorded diff --git a/docs/subsystems/worktrees.i18n.yaml b/docs/subsystems/worktrees.i18n.yaml index a6b14d164b..26785f48c6 100644 --- a/docs/subsystems/worktrees.i18n.yaml +++ b/docs/subsystems/worktrees.i18n.yaml @@ -6,8 +6,8 @@ en: 3a3d69d2b12a78f9 zh: a7a7d12487968bbc /git-worktrees/creation-and-retention: - en: 4c28ae6baae4ef5f - zh: 0c83d90ea3cd3c2e + en: f4e935f589e661fb + zh: b14e021570f2a884 /git-worktrees/request-and-result: en: fbab866bf824d6e0 zh: 73d2a1ee350e1434 diff --git a/docs/subsystems/worktrees.md b/docs/subsystems/worktrees.md index a837e99625..de1ba9722d 100644 --- a/docs/subsystems/worktrees.md +++ b/docs/subsystems/worktrees.md @@ -6,7 +6,7 @@ The experimental [`dsh-experimental-worktree`](../../packages/experimental/workt ## Creation and retention -The calling Session's current directory selects the source repository. Creation pins the requested local commit, branch, or tag before allocating the checkout; omission selects `HEAD`. Each name must identify a new branch and an unused checkout path. The operation neither fetches missing objects nor copies staged, unstaged, untracked, or ignored files from the source checkout. +The calling Session's current directory selects the source repository. Creation pins the requested local commit, branch, or tag before allocating the checkout; omission selects `HEAD`. A request may instead ask to fetch a remote-tracking branch of a configured remote first, which fetches only that branch and pins the fetched commit. Each name must identify a new branch and an unused checkout path. The operation neither fetches other commits or missing objects nor copies staged, unstaged, untracked, or ignored files from the source checkout. The default destination is `/.agents/worktrees/`. `repositoryRoot` is the top-level directory of the caller’s current checkout; a linked checkout therefore contains its own pool. The service writes a `.gitignore` containing `*` and a trailing newline only when its allocation creates the configured pool directory. Existing files and ignore rules are preserved. The calling Session’s existing sandbox policy must permit writes to the destination and shared Git administration directory. Successful Git setup precedes the working-directory change. @@ -17,12 +17,17 @@ Leaving through `working_directory({ cd: path })` retains the checkout and branc The request selects only the new name and local revision. The result identifies the created checkout and exact commit; it does not change the Session's original project or write permissions. An optional callback receives each stage of the creation before it begins. A restoration checks a removed checkout out again at its recorded directory, from its branch or, when the branch is gone, from its base commit. ```ts type-equiv -/** A new checkout from a locally available Git commit, branch, or tag. */ +/** A new checkout from a locally available Git commit, branch, or tag, or from a remote branch fetched first. */ interface CreateWorktreeRequest { /** New branch name, also used as the relative checkout directory; omission generates a name. */ name?: string /** Local revision to resolve before creation; omission selects HEAD. */ from?: string + /** + * Fetch `from` from its remote before resolving it. `from` must then be the full name of a remote-tracking + * branch, `refs/remotes//`, of a configured remote; only that branch is fetched, without tags. + */ + fetch?: boolean } ``` @@ -42,12 +47,13 @@ interface CreatedWorktree { ```ts type-equiv /** - * Stage of one creation or restoration, reported before it begins: `prepare` + * Stage of one creation or restoration, reported before it begins: `fetch` + * fetches the remote base branch of a creation that asks for it; `prepare` * validates the request, allocates the checkout directory, and creates the * branch, which a restoration creates again only when it is gone; `checkout` * writes the files and, for a creation, enters the checkout. */ -type CreateWorktreePhase = 'prepare' | 'checkout' +type CreateWorktreePhase = 'fetch' | 'prepare' | 'checkout' ``` ```ts type-equiv @@ -113,19 +119,21 @@ Creates retained Git worktrees under the mounted filesystem and sandbox provider ```ts cordis-catalog /** - * Create a fresh branch and checkout at a pinned local revision, then enter it. + * Create a fresh branch and checkout at a pinned local revision, then enter it. A request that asks to fetch + * first fetches its remote-tracking branch, only that branch and without tags, then pins the fetched commit. * Existing branches or checkout paths fail. Uncommitted files stay in the source checkout. * Checkout disables configured clean, smudge, and process filters without changing Git config. * Repository-local replacement refs still apply; baseCommit reports the resolved object name. * The new checkout becomes current only after Git setup succeeds. Failures may retain newly * allocated Git/filesystem artifacts; no branch or checkout is removed automatically. * @param agent - caller whose current directory selects the source repository and file policy. - * @param request - optional new name and local revision; defaults are generated name and HEAD. + * @param request - optional new name, local revision, and fetch switch; defaults are generated name, HEAD, and no fetch. * @param signal - cancellation of lookup, creation, and working-directory publication. * @param onPhase - receives each stage before it begins; it must not throw. * @returns canonical checkout path, branch name, pinned commit, and source repository root. - * @throws {WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out - * command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. + * @throws {WorktreeError} for an invalid request, a fetch request whose `from` is not a remote-tracking branch of a + * configured remote, an existing branch or path, or a failed, oversized, or timed-out command, including the + * fetch; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise @@ -140,12 +148,12 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS * @param agent - caller whose sandbox policy confines the commands. * @param request - recorded directory, branch, base commit, and source repository root. * @param signal - cancellation of the restoration. - * @param onPhase - receives each stage before it begins; it must not throw. + * @param onPhase - receives each stage before it begins, never `fetch`; it must not throw. * @returns the directory and whether the branch was created again. * @throws {WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized, * or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ -async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise +async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: Exclude) => void, ): Promise /** * Read the archive cleanup of a Session's created checkout; waiting never diff --git a/docs/subsystems/worktrees.zh.md b/docs/subsystems/worktrees.zh.md index 3d2b4d7286..0000bd609c 100644 --- a/docs/subsystems/worktrees.zh.md +++ b/docs/subsystems/worktrees.zh.md @@ -6,7 +6,7 @@ ## 创建与保留 -调用方 Session 的当前目录决定源仓库。创建操作在分配检出目录前,将请求的本地提交、分支或标签固定为具体提交;省略时选择 `HEAD`。每个名称必须对应新分支与未使用的检出路径。操作既不获取缺失对象,也不复制源检出目录中的暂存、未暂存、未跟踪或被忽略文件。 +调用方 Session 的当前目录决定源仓库。创建操作在分配检出目录前,将请求的本地提交、分支或标签固定为具体提交;省略时选择 `HEAD`。请求也可以要求先获取某个已配置远程的远程跟踪分支,此时只获取这一个分支,并固定获取到的提交。每个名称必须对应新分支与未使用的检出路径。操作既不获取其他提交或缺失对象,也不复制源检出目录中的暂存、未暂存、未跟踪或被忽略文件。 默认目标为 `/.agents/worktrees/`。`repositoryRoot` 是调用方当前检出目录的顶层目录;因此,链接检出目录会在自身内部保存工作树父目录。仅当服务的分配操作创建了配置指定的父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`。已有文件与忽略规则保持不变。调用方 Session 的现有沙箱策略必须允许写入目标目录与共享 Git 管理目录。Git 初始化成功后才改变工作目录。 @@ -17,12 +17,17 @@ 请求只选择新名称与本地版本。结果标识创建的检出目录与确切提交;它不会改变 Session 的原始项目或写权限。可选的回调会在创建的每个阶段开始之前收到该阶段。恢复会在记录的目录重新检出已删除的检出目录:从它的分支检出;分支也已删除时,从它的基准提交检出。 ```ts type-equiv -/** A new checkout from a locally available Git commit, branch, or tag. */ +/** A new checkout from a locally available Git commit, branch, or tag, or from a remote branch fetched first. */ interface CreateWorktreeRequest { /** New branch name, also used as the relative checkout directory; omission generates a name. */ name?: string /** Local revision to resolve before creation; omission selects HEAD. */ from?: string + /** + * Fetch `from` from its remote before resolving it. `from` must then be the full name of a remote-tracking + * branch, `refs/remotes//`, of a configured remote; only that branch is fetched, without tags. + */ + fetch?: boolean } ``` @@ -42,12 +47,13 @@ interface CreatedWorktree { ```ts type-equiv /** - * Stage of one creation or restoration, reported before it begins: `prepare` + * Stage of one creation or restoration, reported before it begins: `fetch` + * fetches the remote base branch of a creation that asks for it; `prepare` * validates the request, allocates the checkout directory, and creates the * branch, which a restoration creates again only when it is gone; `checkout` * writes the files and, for a creation, enters the checkout. */ -type CreateWorktreePhase = 'prepare' | 'checkout' +type CreateWorktreePhase = 'fetch' | 'prepare' | 'checkout' ``` ```ts type-equiv @@ -113,19 +119,21 @@ Creates retained Git worktrees under the mounted filesystem and sandbox provider ```ts cordis-catalog /** - * Create a fresh branch and checkout at a pinned local revision, then enter it. + * Create a fresh branch and checkout at a pinned local revision, then enter it. A request that asks to fetch + * first fetches its remote-tracking branch, only that branch and without tags, then pins the fetched commit. * Existing branches or checkout paths fail. Uncommitted files stay in the source checkout. * Checkout disables configured clean, smudge, and process filters without changing Git config. * Repository-local replacement refs still apply; baseCommit reports the resolved object name. * The new checkout becomes current only after Git setup succeeds. Failures may retain newly * allocated Git/filesystem artifacts; no branch or checkout is removed automatically. * @param agent - caller whose current directory selects the source repository and file policy. - * @param request - optional new name and local revision; defaults are generated name and HEAD. + * @param request - optional new name, local revision, and fetch switch; defaults are generated name, HEAD, and no fetch. * @param signal - cancellation of lookup, creation, and working-directory publication. * @param onPhase - receives each stage before it begins; it must not throw. * @returns canonical checkout path, branch name, pinned commit, and source repository root. - * @throws {WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out - * command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. + * @throws {WorktreeError} for an invalid request, a fetch request whose `from` is not a remote-tracking branch of a + * configured remote, an existing branch or path, or a failed, oversized, or timed-out command, including the + * fetch; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise @@ -140,12 +148,12 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS * @param agent - caller whose sandbox policy confines the commands. * @param request - recorded directory, branch, base commit, and source repository root. * @param signal - cancellation of the restoration. - * @param onPhase - receives each stage before it begins; it must not throw. + * @param onPhase - receives each stage before it begins, never `fetch`; it must not throw. * @returns the directory and whether the branch was created again. * @throws {WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized, * or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ -async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise +async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: Exclude) => void, ): Promise /** * Read the archive cleanup of a Session's created checkout; waiting never diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index a8be717a1b..0116a96b2a 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: 9b31d4a0e8a0ed01 - zh: 38915fb69b6535ce + en: f63d4a049eea1ede + zh: e61269b6df6afcd4 /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 37eef1a98654b29a - zh: 0d8bad512b8a2360 + en: 43e18d718e1bda7b + zh: c58f6b5bda5c0c45 /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b @@ -30,8 +30,8 @@ en: 2bc25a99e17789c4 zh: 4bec723fbf249d28 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: 8801648dd9433da6 - zh: be520fb644ea8895 + en: 49fd22a6073c1680 + zh: a2ca41e361799b19 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index 64cf0da82d..b1f17893c1 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -29,17 +29,17 @@ Enable the [forge bundle](../forge-bundle/README.md) on the Plugins page; it com Panel text follows the application language: Chinese, English, Japanese, Spanish, French, German, Russian, or Portuguese. -- **Worktree option** — on the New Session screen, New worktree sits beside the current branch at the right end of the row with the workspace and mode pickers. Both stay hidden outside a Git checkout. The branch is read-only until New worktree is checked, when it becomes the base branch selector; the menu lists recent local branches. If permissions block an existing request, its selected base stays visible without a selector and the request can still be withdrawn. Hovering, focusing, or tapping the read-only branch or base shows its full description. The option is disabled, with the reason in its tooltip, in a read-only Session and when the checkout or its Git directory lies outside the Session's writable root, as for a project that is itself a linked worktree. Sending the first message hands it to the Session at once, and it waits there while the branch `dsh--<4 random hexadecimal digits>` is created from the base under the repository's `.agents/worktrees/` and its checkout becomes the Session's working directory; the message's turn starts once the worktree exists. +- **Worktree option** — on the New Session screen, New worktree sits beside the current branch at the right end of the row with the workspace and mode pickers. Both stay hidden outside a Git checkout. The branch is read-only until New worktree is checked, when it becomes the base branch selector. The selector's searchable menu lists, most recently committed first, the current branch, then each remote's default branch, then local branches, then one group per remote headed by its name and its repository, `owner/name` for a recognized code host or else its fetch URL without the user name and password a URL can carry; typing filters the rows at once and lists the branches whose names contain the text after a short pause, and Enter chooses the first row. A remote branch is fetched, only that branch and without tags, when the worktree is created. The menu's last row, Name the new branch, opens a dialog whose field starts with the `worktreePrefix` and checks Git's branch-name rules while the name is typed; Save asks the Host, which also refuses a name the checkout already uses as a branch, and keeps the dialog open with the reason. With a chosen name, the selector shows the name before the base, and the dialog offers to use a generated name again. If permissions block an existing request, its selected base stays visible without a selector and the request can still be withdrawn. Hovering, focusing, or tapping the read-only branch or base shows its full description. The option is disabled, with the reason in its tooltip, in a read-only Session and when the checkout or its Git directory lies outside the Session's writable root, as for a project that is itself a linked worktree. Sending the first message hands it to the Session at once, and it waits there while the chosen branch, or else `dsh--<4 random hexadecimal digits>`, is created from the base under the repository's `.agents/worktrees/` and its checkout becomes the Session's working directory; the message's turn starts once the worktree exists. - **Archive cleanup** — archiving a Session lets the [worktree service](../worktree/README.md) reclaim the clean, unreferenced worktree it created, whether through the New Session option or the model's `create_worktree` tool, while retaining the branch and its commits. A scheduled cleanup uses the archive notice “Archived; the worktree will be cleaned up”; one that ends retained returns to the ordinary notice, and one that fails replaces it with a warning while the Session stays archived. Undo cancels deletion before admission or waits for an admitted deletion; a removed checkout uses the existing Restore worktree flow. The bundle's worktree row on the Plugins page offers Keep worktrees when archiving: once saved, archiving keeps every worktree and shows the ordinary archive notice; the switch is read at each archive, so it does not affect a cleanup already scheduled. -- **Creation card** — while the worktree is created, a card above the composer shows the new branch and its two steps, creating the branch and checking out files; More details adds the branch and base. Cancel stops the attempt. After a stopped or failed attempt the message keeps waiting, and the card shows the reason of a failure: Retry tries again with a new branch name, and Continue without a worktree withdraws the request so the message goes on in the current checkout. +- **Creation card** — while the worktree is created, a card above the composer shows the new branch and its steps: fetching a remote base branch, creating the branch, and checking out files; More details adds the branch and base. Cancel stops the attempt. After a stopped or failed attempt the message keeps waiting, and the card shows the reason of a failure: Retry tries again, on the chosen name or a new generated one, and Continue without a worktree withdraws the request so the message goes on in the current checkout. A failed fetch also offers Use the last fetched version, which starts from the remote branch as last fetched. When the chosen branch or its directory already exists, Rename opens the naming dialog, whose Retry saves the new name and tries again. - **Removed worktree** — when the worktree the Session works in has been removed outside the Session, a card above the composer says so, and a message sent meanwhile waits without starting its turn until the worktree is restored or left; the card then says that the message goes on afterwards. Restore worktree, also offered as Restore in the Session panel's checkout row, checks the branch out again at the same directory, or creates the branch again at the commit it started from when the branch is gone too; while it runs, the card follows its two steps, preparing the worktree and checking out files, and the checkout row's Restore turns into a spinner. Continue in the project moves the Session to the source checkout. Meanwhile the checkout row shows a warning glyph. - **Session panel** — the Environment section of the Session panel gains the checkout and local changes rows after the project row, and the connection row at its end while the panel stream is lost, and a Change requests section follows it. The panel has no refresh control: when it opens and when the window regains focus, it inspects the checkout again, checks sign-in, and polls every change request, at most once every 10 seconds per Session, so changes made outside the Session appear on return. A yellow dot on the panel toggle in the Session header marks an open change request with failed checks, requested changes, or conflicts, also while the panel is hidden. - **Checkout row** — names the checked-out branch, or Not on a branch with the abbreviated commit on a detached HEAD, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip, shown after 500ms of hover, adds the path with the Host home shortened to `~`, and a branch name the row clips crawls into view while the pointer rests on the row. The row and its More button open the directory menu of the checkout root. For a removed worktree it shows a warning glyph and offers Restore. When Git cannot be read, the row says so, and its info button shows the failure after 500ms of hover, at once on keyboard focus, or on a press; outside a Git checkout there is no row. - **Connection row** — when the Session's panel stream ends, also before it delivered a first state, a status row at the end of the Environment section says the status stopped updating and that the Git and change request details may be out of date; Retry opens the stream again and the row goes away. - **Session list** — after a Session row's time, a branch glyph shows while the Session works in the worktree the panel created for it, and a glyph shows the state of its most urgent change request: one needing attention first, then open, draft, not yet polled, merged, and closed. The glyph of an open change request keeps the row's subdued color, with its head branch end filled in the color of running, passed, or failed checks; merged and closed ones keep their state colors. The row's hover card names the worktree branch and what it started from, then up to three change requests with their number, title, state, and checks, and how many more there are. A restart shows the states known before it until the next poll. -- **Change requests section** — shows while the Session has bound change requests or the repository's host needs sign-in. Its title carries their count. A status row above the cards asks to sign in to the host: with the sign-in command the provider names, such as `gh auth login --hostname github.com`, which crawls into view on hover, and Copy; when the provider names none, and when the sign-in check fails, with the host's reason behind an info button, as the checkout row shows its failure. The section shows with this row alone while the Session binds no change request. Each change request card shows a glyph for its state, its title on one line, which crawls into view on hover and opens it in the browser, and its number; the glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the toggle's yellow dot does. The card's More menu offers Open in browser, Copy change request link, View changes for a change request a provider serves, Ready for review for an open draft, and Remove from this Session, whose toast offers Undo. Cancelled checks have a separate count; a collapsed card names cancellations when no listed check failed. A collapsed card adds the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended. An expanded card shows the head and base branches, then one row per fact, each a glyph and its value. For an open change request, the rows are the checks, whose menu groups the failed, running, and cancelled checks with their durations and links, lists the passed and skipped ones on request, and offers Rerun failed when the user may rerun checks and a failed check names a rerun none of whose checks is still running; the review decision with the first three reviewers' avatars and how many more, whose menu lists each reviewer with their kind and latest outcome, notes an outcome given before the latest commit, and, when the user may request reviews, re-requests a review from a reviewer or requests one from someone else through a search that lists the host's suggestions first; the merge state, which names a head behind its base and, when the user may update it, offers Update branch, whose menu chooses merge or rebase, pins the displayed head when opened, and disables Confirm update once a poll names another head; the changed lines, formatted in the selected UI language, with the unresolved threads, whose count ends in `+` when the provider counted only some threads, in a row that opens the changes view; and the linked issues the host closes when the change request merges, each linking to its page. The thread count and an issue's title show in a tooltip after 500ms of hover. A merged or closed one shows when it ended and the changed lines. Rerun failed, a review request, Update branch, Ready for review, and Merge report their outcome in a toast, which asks to check the change request in the browser when the host did not confirm the outcome, and new commits since the displayed head stop a rerun or an update. A change request the host would merge now offers Merge below its rows, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. When the Session binds exactly one change request, its card starts expanded whatever its state; with several, every card starts collapsed. A card the user expands or collapses keeps that choice across updates and while the panel is hidden, for as long as the Session stays open; a card the user never toggled follows the default. +- **Change requests section** — shows while the Session has bound change requests or the repository's host needs sign-in. Its title carries their count. A status row above the cards asks to sign in to the host: with the sign-in command the provider names, such as `gh auth login --hostname github.com`, which crawls into view on hover, and Copy; when the provider names none, and when the sign-in check fails, with the host's reason behind an info button, as the checkout row shows its failure. The section shows with this row alone while the Session binds no change request. Each change request card shows a glyph for its state, its title on one line, which crawls into view on hover and opens it in the browser, and its number; the glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the toggle's yellow dot does. The card's More menu offers Open in browser, Copy change request link, View changes for a change request a provider serves, Ready for review for an open draft, and Remove from this Session, whose toast offers Undo. Cancelled checks have a separate count; a collapsed card names cancellations when no listed check failed. A collapsed card adds the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended, on one line: while the line with failed checks does not fit, they take the shorter wording without their count, and a line that still does not fit ends in an ellipsis and crawls into view with the title. An expanded card shows the head and base branches, then one row per fact, each a glyph and its value. For an open change request, the rows are the checks, whose menu groups the failed, running, and cancelled checks with their durations and links, lists the passed and skipped ones on request, and offers Rerun failed when the user may rerun checks and a failed check names a rerun none of whose checks is still running; the review decision with the first three reviewers' avatars and how many more, whose menu lists each reviewer with their kind and latest outcome, notes an outcome given before the latest commit, and, when the user may request reviews, re-requests a review from a reviewer or requests one from someone else through a search that lists the host's suggestions first; the merge state, which names a head behind its base and, when the user may update it, offers Update branch, whose menu chooses merge or rebase, pins the displayed head when opened, and disables Confirm update once a poll names another head; the changed lines, formatted in the selected UI language, with the unresolved threads, whose count ends in `+` when the provider counted only some threads, in a row that opens the changes view; and the linked issues the host closes when the change request merges, each linking to its page. The thread count and an issue's title show in a tooltip after 500ms of hover. A merged or closed one shows when it ended and the changed lines. Rerun failed, a review request, Update branch, Ready for review, and Merge report their outcome in a toast, which asks to check the change request in the browser when the host did not confirm the outcome, and new commits since the displayed head stop a rerun or an update. A change request the host would merge now offers Merge below its rows, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. When the Session binds exactly one change request, its card starts expanded whatever its state; with several, every card starts collapsed. A card the user expands or collapses keeps that choice across updates and while the panel is hidden, for as long as the Session stays open; a card the user never toggled follows the default. - **Local changes row** — whenever the `branch` scope changes files, independently of bound change requests, the row names the number of changed files with the added and deleted lines and opens the changes view. Its More menu offers View changes and, when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, Create change request, which sends the Session a user message in the UI language that asks the Agent to create a change request for these changes; a toast reports whether it was sent. -- **Changes view** — The Changes row and View changes item of a change request card and the local changes row open a right-sidebar tab that lists the changed files, closing the Session panel while it floats over the conversation. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Its icon buttons and the header's Open in browser name their action after 500ms of hover or at once on keyboard focus. The toolbar and the header each keep one line: as the toolbar narrows, the line totals, expanding all files, two columns, and wrapping move into a More menu first, then the test file switch, with the viewed progress label shortened to a bare count beside its ring, and then refresh, while header buttons keep their labels on one line and the menus and title shorten. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Each file is a separate card, with a tinted header that stays at the top while its lines scroll. Files are named before their directories, which use smaller subdued type and shorten first; hovering one for 500ms shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. When the header is narrow, the path, the badges, and Changed since viewed shorten, so the line counts, Viewed, and the menu stay whole. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A row of at most 20 lines expands with one click. A longer row expands 20 lines at a time, down from the hunk above it or up from the hunk below it, the row before the first hunk only up and the row after the last hunk only down, and shows how many lines it still hides; the first click on the unknown lines after the last hunk reads the file and shows their first 20. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. Expanded unchanged lines and pending file reads survive a refresh of review marks for the same commit range, head, and patches. +- **Changes view** — The Changes row and View changes item of a change request card and the local changes row open a right-sidebar tab that lists the changed files, closing the Session panel while it floats over the conversation. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Its icon buttons and the header's Open in browser name their action after 500ms of hover or at once on keyboard focus. The toolbar and the header each keep one line: as the toolbar narrows, the line totals, expanding all files, two columns, and wrapping move into a More menu first, then the test file switch, with the viewed progress label shortened to a bare count beside its ring, and then refresh, while header buttons keep their labels on one line and the menus and title shorten. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Each file is a separate card, with a tinted header that stays at the top while its lines scroll. Files are named before their directories, which use smaller subdued type and shorten first; hovering one for 500ms shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. When the header is narrow, the path, the badges, and Changed since viewed shorten, so the line counts, Viewed, and the menu stay whole. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A row of at most 20 lines expands with one click. A longer row expands 20 lines at a time, down from the hunk above it or up from the hunk below it, the row before the first hunk only up and the row after the last hunk only down, and shows how many lines it still hides; the first click on the unknown lines after the last hunk reads the file and shows their first 20. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. While the view reads changes it has not shown yet, it says Reading changes above file cards drawn as pulsing placeholders, one changed file in two columns when sides are split, and the files menu names no count; reduced motion keeps the placeholders still. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. Expanded unchanged lines and pending file reads survive a refresh of review marks for the same commit range, head, and patches. - **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; when the counts do not fit the tree's width, it shows the layer names alone and each count in the hover text of its layer. Where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, as a ring filled to the viewed share and a label such as 2 / 3 viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. The file tree draws a viewed file subdued, and a directory once every file in it is viewed, so the files left to review stand out; a file changed since it was viewed draws as unviewed, and assistive technology reads the state as each row's description. A change of the file mode alone, such as `chmod +x`, also counts as a new change. A change request's view of all its commits uses the viewed marks its provider keeps on the code host, as the GitHub provider does: the view reads them with the diff, shows a mark at once, and saves it at the displayed head, keeping that file's checkbox disabled until the host answers; a file GitHub reports as changed since it was viewed shows Changed since viewed. A mark the host refuses, or one that new commits made stale, returns to its previous state, and a toast says why; a mark the host may have saved without confirming it stays, and a toast says to refresh to see where it stands. When the marks cannot be read, a notice says so and offers Retry, and no file can be marked. Hovering a checkbox tells where its mark is kept. Other marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits. - **Review threads** — A change request view overlays the review threads its code host read at the shown head. A thread on lines follows the row of its last line, on the side it was written on, or the collapsed unchanged lines that hold it; it shows the place it was written, each comment's avatar, author, time, and Markdown with raw HTML left out, and tags for the change request's author, bots, and comments still pending in the signed-in user's review. A resolved thread folds into one row that unfolds on request. Threads on a whole file open the file, and threads later commits made outdated gather after its lines in a section that shows the end of the hunk they were written on and offers View file at that commit, which reads the file at the commit they were written on with their lines marked. Chosen commits show only new-side threads whose lines number the last chosen commit. The file tree and each file header count unresolved threads. Each click on the count in a header goes to the file's next unresolved thread in the order the file shows them, threads the chosen commits do not hold last, and from the last back to the first; the Threads toolbar button opens the thread list, which groups the threads by file in file tree order and orders each file's threads the same way, shows the Unresolved, Resolved, or All threads, Unresolved first, and opens each thread at its place, choosing all commits for one the chosen commits do not hold. The list docks beside the files in a view at least 1,040px wide, floats over them in a narrower one and closes before it opens a thread there, and takes their whole width below 480px. The list names a truncated read. A thread offers Add to input, which quotes the whole thread, View on GitHub, and the writes the signed-in user may make. Without a pending review, its reply field replies at once, and its menu starts a pending review with the reply; with one, the field adds the reply to it, as GitHub adds every reply of the user to the pending review. Resolve thread and Unresolve thread change its state, and the menu of the user's own comment edits or deletes it after asking, saying when deleting the only comment deletes the thread. A resolved thread stays open while the user writes a reply or an edit in it. A write the code host refuses keeps the text and says why; a write whose outcome is unknown reads the threads again and asks the user to check them before trying again. Every write reads the threads again, since resolving a thread does not change a GitHub pull request's update time. Threads are read again at each status while the view shows, and from the code host after Refresh even while the panel keeps an earlier read; a failed read keeps the last threads and offers Retry, and a provider that does not read reviews shows none. @@ -63,9 +63,9 @@ All files opens a searchable directory tree with the selected file scrolled to i `ForgePanelController` keeps one `SessionPanel` per followed Session and disposes it when the last follower leaves. A panel starts with the Session's working directory and bindings, re-inspects after each `working-directory/change`, `tool/result`, and `sandbox/mode` event, and publishes a new `ForgePanelState` only when the state differs from the published one, so a reinspection that finds the same checkout reaches no follower. Each change request keeps the latest snapshot a poll returned while later polls fail. A failed parallel Git read cancels and joins its siblings. Inspections run one at a time with one trailing rerun, and a result for a directory the Session has since left is dropped. The code host comes from the remotes in order: the upstream's remote, then `origin`, then the rest. When an inspection finds an upstream branch on a remote a provider recognizes, the panel asks `ctx.forgeSession.discoverBranch` to bind that branch's open change requests, once per remote and branch until a refresh. A sign-in probe runs when the recognized host changes and on refresh, within `readinessTimeoutMs`; a refresh settles once the inspection and the probe it started have ended, and poll results arrive later. -Inspection runs `rev-parse --show-toplevel`, `rev-parse --path-format=absolute --git-common-dir`, `rev-parse --path-format=absolute --git-dir`, `symbolic-ref --short HEAD`, `rev-parse --short HEAD`, `rev-parse --abbrev-ref @{upstream}`, and `remote -v`; `branches` runs `symbolic-ref` and `for-each-ref --count=`; `diffBases` finds the default fork point as `localDiff` does below, runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, leaves out symbolic refs such as `origin/HEAD`, and keeps at most `maxBranches` branches of each kind whose names contain the query. Inspection then sizes the `branch` scope for the local changes row: it finds the fork point, runs `diff --numstat -z -M` against it with the same helper and submodule restrictions as `localDiff` below, and lists untracked files. Every command uses the Session's resolved sandbox mode: `read-only` and `workspace-write` require confinement, while `danger-full-access` runs without a sandbox backend. Commands disable optional index writes, hooks, the filesystem monitor, prompts, and lazy object fetches, remove inherited Git selectors and secret-bearing variables, and use their own `gitTimeoutMs` deadline and `maxOutputBytes` limit per stream. The top-level, Git, and common Git directories Git prints are resolved through `ctx.fs` into the canonical process paths that the working-directory service records; a checkout whose Git directory differs from the common one is a linked worktree. The worktree option is usable under the `danger-full-access` sandbox mode, never under `read-only`, and under `workspace-write` only when both directories lie inside the canonical workspace root of the Session's sandbox policy. +Inspection runs `rev-parse --show-toplevel`, `rev-parse --path-format=absolute --git-common-dir`, `rev-parse --path-format=absolute --git-dir`, `symbolic-ref --quiet HEAD`, which names the checked-out branch when it is under `refs/heads/`, `rev-parse --short HEAD`, `rev-parse --abbrev-ref @{upstream}`, and `remote -v`; `worktreeBases` runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, takes each remote's default branch from its `refs/remotes//HEAD`, leaves out other symbolic refs and the branches of unconfigured remotes, and keeps at most `maxBranches` local branches and `maxBranches` branches per remote whose names contain the query, with remotes in the code host order below; `requestWorktree` with a name checks it against Git's branch-name rules and runs `show-ref` in the checkout; `diffBases` finds the default fork point as `localDiff` does below, runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, leaves out symbolic refs such as `origin/HEAD`, and keeps at most `maxBranches` branches of each kind whose names contain the query. Inspection then sizes the `branch` scope for the local changes row: it finds the fork point, runs `diff --numstat -z -M` against it with the same helper and submodule restrictions as `localDiff` below, and lists untracked files. Every command uses the Session's resolved sandbox mode: `read-only` and `workspace-write` require confinement, while `danger-full-access` runs without a sandbox backend. Commands disable optional index writes, hooks, the filesystem monitor, prompts, and lazy object fetches, remove inherited Git selectors and secret-bearing variables, and use their own `gitTimeoutMs` deadline and `maxOutputBytes` limit per stream. The top-level, Git, and common Git directories Git prints are resolved through `ctx.fs` into the canonical process paths that the working-directory service records; a checkout whose Git directory differs from the common one is a linked worktree. The worktree option is usable under the `danger-full-access` sandbox mode, never under `read-only`, and under `workspace-write` only when both directories lie inside the canonical workspace root of the Session's sandbox policy. -A worktree request is a `plugin:client-ui-forge/worktree` record, folded by the `forgeWorktree` projection: requests and withdrawals apply until the first `turn/start` or creation, and the first creation of an open request, read from the worktree service's `plugin:worktree/created` record or from the `created` record earlier panels wrote, applies until the first `step/start`. The projection also records the Session's directory from its header and each `working-directory/change`; its client view, which the Session summary carries, is the created worktree while that directory is the worktree or lies below it, else null. `requestWorktree` refuses with `forgePanel/session-started` after a turn started or the worktree was created, with `forgePanel/worktrees-unavailable` without a `worktrees` service, and with `forgePanel/invalid-branch` for an empty branch; `cancelWorktree` refuses only with the first and needs no `worktrees` service; both forget a failed attempt. When a message enters the inbox of a Session whose request is open, an `agent/inbox/inserted` listener starts maintenance of the Session's Agent before the delivery wakes it, so the Agent latches the wake and starts the message's turn once that hold ends. The hold makes one attempt with a new branch name, publishing the running stage in the panel state with `held` set and `waiting` as `creation`, and records `created` with the source repository root. After a failed attempt, whose branch, base, failed step, and reason stay in the panel state as `failure`, or after `stopCreation`, the hold waits: `retryWorktree` makes another attempt, refused with `forgePanel/not-waiting` while none waits or one runs, and withdrawing the request lets the message go on in the current checkout. Each message that enters while the Agent is idle and the Session works in its created worktree starts a hold that checks whether the worktree is missing; while it is, the hold waits with `waiting` as `restoration`, and `restoreWorktree` or `continueInProject` runs inside it and then lets the message go on; a check that cannot answer lets the message go at once. The Agent's cancellation and the Remote's stop end a hold, and a message that enters while the Agent runs a turn or other maintenance gets none. The worktree service queues the working-directory notice, which the first step claims. An `agent/pre-step` listener creates the worktree at step 1 of a Session whose request is still open, which covers a message no hold took; it moves the notice into the proposed messages, and a failure ends the turn with the request kept. `restoreWorktree` and `continueInProject` run as maintenance of their own while no message waits; `restoreWorktree` publishes its running step as `restoration`, and clears `missing` in the same state that ends it. `track` rejects a URL no provider recognizes with `forgePanel/unrecognized-url`. `markReady` and `merge` act only on a visible binding of the Session that a provider serves, else they refuse with `forgePanel/not-bound`; `merge` passes the head commit the card showed, and a moved head refuses with `forgePanel/stale-head`, while any other refusal is `forgePanel/action-failed` with the host's reason. +A worktree request is a `plugin:client-ui-forge/worktree` record, folded by the `forgeWorktree` projection: requests and withdrawals apply until the first `turn/start` or creation, and the first creation of an open request, read from the worktree service's `plugin:worktree/created` record or from the `created` record earlier panels wrote, applies until the first `step/start`. The projection also records the Session's directory from its header and each `working-directory/change`; its client view, which the Session summary carries, is the created worktree while that directory is the worktree or lies below it, else null. A request names its base by the full name of a local or remote-tracking branch, as earlier panels' short local names still resolve, and may name its branch. `requestWorktree` refuses with `forgePanel/session-started` after a turn started or the worktree was created, with `forgePanel/worktrees-unavailable` without a `worktrees` service, with `forgePanel/invalid-branch` for an empty base, with `forgePanel/invalid-name` for a branch name Git refuses, and with `forgePanel/branch-exists` for a branch name the checkout already uses; `cancelWorktree` refuses only with the first and needs no `worktrees` service; both forget a failed attempt. When a message enters the inbox of a Session whose request is open, an `agent/inbox/inserted` listener starts maintenance of the Session's Agent before the delivery wakes it, so the Agent latches the wake and starts the message's turn once that hold ends. The hold makes one attempt on the requested branch name, or on a new generated one, asking the worktree service to fetch a remote-tracking base branch first; it publishes the running stage in the panel state with `held` set and `waiting` as `creation`, and records `created` with the source repository root. After a failed attempt, whose branch, base, fetch, failed step, reason, and whether the branch or directory existed stay in the panel state as `failure`, or after `stopCreation`, the hold waits: `retryWorktree` makes another attempt, without the fetch when its `fetch` argument is false, refused with `forgePanel/not-waiting` while none waits or one runs; `requestWorktree` with another name changes the next attempt; and withdrawing the request lets the message go on in the current checkout. Each message that enters while the Agent is idle and the Session works in its created worktree starts a hold that checks whether the worktree is missing; while it is, the hold waits with `waiting` as `restoration`, and `restoreWorktree` or `continueInProject` runs inside it and then lets the message go on; a check that cannot answer lets the message go at once. The Agent's cancellation and the Remote's stop end a hold, and a message that enters while the Agent runs a turn or other maintenance gets none. The worktree service queues the working-directory notice, which the first step claims. An `agent/pre-step` listener creates the worktree at step 1 of a Session whose request is still open, which covers a message no hold took; it moves the notice into the proposed messages, and a failure ends the turn with the request kept. `restoreWorktree` and `continueInProject` run as maintenance of their own while no message waits; `restoreWorktree` publishes its running step as `restoration`, and clears `missing` in the same state that ends it. `track` rejects a URL no provider recognizes with `forgePanel/unrecognized-url`. `markReady` and `merge` act only on a visible binding of the Session that a provider serves, else they refuse with `forgePanel/not-bound`; `merge` passes the head commit the card showed, and a moved head refuses with `forgePanel/stale-head`, while any other refusal is `forgePanel/action-failed` with the host's reason. Restoration records `restoring` before mutation and `restored` only after success. Projection version 3 retains incomplete restoration across reloads. Directory existence alone cannot release a waiting message: the checkout root and shared Git directory must match the recorded worktree. Plugin unload cancels and joins all creation, restoration, and waiting tasks before releasing panel readers and the projection. @@ -85,6 +85,7 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t | [`src/index.ts`](src/index.ts) | `forgePanel` Remote and per-Session panels | | [`src/panel.ts`](src/panel.ts) | Panel state, inspection scheduling, and sign-in probes | | [`src/worktree.ts`](src/worktree.ts) | Worktree record, projection, waiting messages, and creation at the first step | +| [`src/branch-name.ts`](src/branch-name.ts) | Branch-name rules and branch labels for the Host and the Client | | [`src/states.ts`](src/states.ts) | Change request states for the Session list | | [`src/git.ts`](src/git.ts) | Git queries under Session permissions | | [`src/parse.ts`](src/parse.ts) | Git output parsing and remote order | @@ -114,7 +115,10 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t | [`src/client/host-viewed.ts`](src/client/host-viewed.ts) | Viewed marks the code host keeps, with marks being saved | | [`src/client/menu-search.ts`](src/client/menu-search.ts) | Keys of the search field at the top of a menu | | [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | Changed file label: name, then directory | -| [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | New Session worktree option | +| [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | New Session worktree option and its base menu | +| [`src/client/WorktreeNameDialog.tsx`](src/client/WorktreeNameDialog.tsx) | Naming dialog of a worktree branch | +| [`src/client/branch-search.tsx`](src/client/branch-search.tsx) | Search state and status rows of the branch menus | +| [`src/client/ChangesLoading.tsx`](src/client/ChangesLoading.tsx) | Changes view while it reads | | [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | Worktree creation and removed-worktree card | | [`src/client/SessionRowForge.tsx`](src/client/SessionRowForge.tsx) | Session row icons | | [`src/client/SessionHoverForge.tsx`](src/client/SessionHoverForge.tsx) | Session row hover card section | @@ -149,7 +153,7 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Polling while shown** — status is polled only while a Session list row or an active panel surface for the Session subscribes; retained hidden changes bodies do not subscribe; there are no notifications for checks that finish meanwhile. - **Unopened Sessions in the list** — the Session list reads the worktree and bindings of a Session that is not loaded from its cached summary: a Session without one shows neither, and one last used before this version shows its worktree only after it is opened. - **Inspection triggers** — the checkout is inspected after Session tool results and directory changes; a change made outside the Session appears when the Session panel opens or the window regains focus, at most once every 10 seconds, or after the next tool result. -- **Retained checkouts** — the panel creates a worktree only before a Session's first step and does not remove existing checkout directories or branches; a failed or cancelled attempt can leave its branch or checkout behind. Branch names come from the Session id and random digits, not from the Session title, which does not exist yet. +- **Retained checkouts** — the panel creates a worktree only before a Session's first step and does not remove existing checkout directories or branches; a failed or cancelled attempt can leave its branch or checkout behind. Generated branch names come from the Session id and random digits, not from the Session title, which does not exist yet; a name chosen in the naming dialog replaces them. - **Messages during a turn** — a message that enters while the Agent runs a turn or other maintenance gets no hold: a requested worktree is then created at the first step, where a failure ends the turn without the message, and a removed worktree is not checked, so the working-directory service moves the Session back to the project directory. - **Waiting messages** — while a message waits, the Agent stays idle in maintenance and the composer offers no stop; the card's actions, the Agent's cancellation, or the Remote's stop release it, and callers that wait for the Agent to become idle wait as well. - **Restoring** — restoring recreates the checkout from the branch, or from the commit the branch started from when the branch is gone; changes that were never committed are lost with the removed directory. The [worktree service](../worktree/README.md#use-this-package) validates the recorded target and removes only its missing, unlocked registration. An existing or incomplete directory stays blocked; preserve its files and remove the directory before retrying, or continue in the source project. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index a35862ac65..0ac9c13997 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -29,17 +29,17 @@ kind: "package-reference" 面板文案跟随应用语言,支持中文、英文、日语、西班牙语、法语、德语、俄语和葡萄牙语。 -- **工作树选项**——在新会话页面上,“新建工作树”与当前分支一起位于工作区与模式选择器那一行的右端。不在 Git 检出中时,两者均隐藏。分支默认为只读展示;勾选“新建工作树”后,它变为基准分支选择器,菜单列出最近的本地分支。权限阻止已有请求时,仍只读显示已选基准,并允许取消请求。悬停、聚焦或轻点只读分支或基准会显示完整说明。Session 为只读,或检出及其 Git 目录不在 Session 的可写根内(例如项目本身就是链接 worktree)时,该选项不可用,提示中说明原因。发送第一条消息后,消息立即交给 Session 并在那里等待,同时从基准分支在仓库的 `.agents/worktrees/` 下创建分支 `dsh--<4 位随机十六进制数>`,并把它的检出设为 Session 的工作目录;worktree 建好后这条消息的这一轮才开始。 +- **工作树选项**——在新会话页面上,“新建工作树”与当前分支一起位于工作区与模式选择器那一行的右端。不在 Git 检出中时,两者均隐藏。分支默认为只读展示;勾选“新建工作树”后,它变为基准分支选择器。选择器的菜单可搜索,按最近提交排序依次列出:当前分支、每个远程的默认分支、本地分支,然后每个远程一组,组名旁显示该远程对应的仓库(识别出代码托管仓库时为 `owner/name`,否则为去掉用户名和密码后的获取地址);输入时已列出的行立即过滤,短暂停顿后列出名称包含所输入文字的分支,按 Enter 选择第一行。远程分支在创建 worktree 时获取,只获取这一个分支,不获取标签。菜单最后一行“指定新分支名称…”打开对话框:输入框以 `worktreePrefix` 开头,输入时检查 Git 的分支名规则;“确定”交给 Host,Host 还会拒绝检出中已有的分支名,拒绝时对话框保持打开并显示原因。指定名称后,选择器在基准前显示该名称,对话框也提供“改回自动命名”。权限阻止已有请求时,仍只读显示已选基准,并允许取消请求。悬停、聚焦或轻点只读分支或基准会显示完整说明。Session 为只读,或检出及其 Git 目录不在 Session 的可写根内(例如项目本身就是链接 worktree)时,该选项不可用,提示中说明原因。发送第一条消息后,消息立即交给 Session 并在那里等待,同时从基准分支在仓库的 `.agents/worktrees/` 下创建指定的分支,未指定时为 `dsh--<4 位随机十六进制数>`,并把它的检出设为 Session 的工作目录;worktree 建好后这条消息的这一轮才开始。 - **归档清理**——归档一个会话后,由[工作树服务](../worktree/README.zh.md)回收它创建的干净且无人引用的工作树,无论来自新会话选项还是模型的 `create_worktree` 工具,分支及其提交保留。清理排队后,归档提示为“已归档,工作树将被清理”;最终保留时恢复为普通归档提示,失败时替换为警告而会话仍保持归档。撤销归档会取消尚未获准的删除,或等待已获准的删除结束;已移除的工作树使用现有的“恢复工作树”流程。插件页上该套件的 worktree 行提供“归档时不删除工作树”开关:保存后,归档会保留所有工作树并显示普通归档提示;开关在每次归档时读取,不影响已排队的清理。 -- **创建卡片**——创建 worktree 期间,输入框上方的卡片显示新分支以及“创建分支”“检出文件”两个步骤;“更多详情”会列出分支与基准。“取消”停止这次尝试。尝试被停止或失败后,消息继续等待,失败时卡片显示原因:“重试”换一个新分支名再试;“不使用工作树”撤回请求,消息在当前检出中继续发送。 +- **创建卡片**——创建 worktree 期间,输入框上方的卡片显示新分支及其步骤:获取远程基准分支、创建分支、检出文件;“更多详情”会列出分支与基准。“取消”停止这次尝试。尝试被停止或失败后,消息继续等待,失败时卡片显示原因:“重试”再试一次,使用指定的名称或新的自动名称;“不使用工作树”撤回请求,消息在当前检出中继续发送。获取失败时还提供“使用上次获取的版本”,从上次获取的远程分支开始。指定的分支或其目录已存在时,“更改名称”打开命名对话框,其中的“重试”保存新名称并再试一次。 - **工作树已被删除**——Session 所在的 worktree 在 Session 之外被删除后,输入框上方的卡片会说明这一点;此期间发送的消息会等待、不开始这一轮,直到该 worktree 被恢复或离开,卡片也会说明消息之后会接着发送。“恢复工作树”(会话面板检出行中的“恢复”与之相同)在原目录重新检出该分支;分支也已删除时,从它开始时的提交重新创建分支;恢复期间卡片显示“准备工作树”“检出文件”两个步骤,检出行中的“恢复”变为加载状态。“在项目目录继续”把 Session 移回源检出。此期间检出行显示警示图标。 - **会话面板**——会话面板的“环境”分栏在项目行之后增加检出行与本地变更行,面板流断开时末尾再加连接行,其后是“变更请求”分栏。面板没有刷新控件:打开时以及窗口重新获得焦点时,它会重新检查检出与登录状态,并轮询每个变更请求,每个会话每 10 秒最多一次,因此在 Session 之外做的改动在切回来时就会出现。打开中的变更请求存在检查失败、被要求修改或冲突时,会话标题栏中的面板开关带黄点,面板隐藏时也会显示。 - **检出行**——显示当前检出的分支(分离 HEAD 时为“不在分支上”与缩写提交),并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);悬停 500ms 后出现的提示给出路径,宿主主目录缩写为 `~`;分支名放不下时,指针停在这一行上会滚动显示全文。这一行及其“更多”按钮打开检出根目录的目录菜单。worktree 已被删除时显示警示图标并提供“恢复”。无法读取 Git 时,这一行说明这一点,行尾的信息按钮在悬停 500ms、键盘聚焦或按下时给出失败原因;不在 Git 检出中时不显示这一行。 - **连接行**——Session 的面板流结束时(包括还没收到第一份状态就结束),环境分栏末尾的状态行说明状态已停止更新,Git 与变更请求信息可能已过时;「重试」重新打开流,这一行随即消失。 - **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,head 分支端点填充为检查进行中、已通过或失败对应的颜色;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。 -- **变更请求分栏**——Session 有已绑定的变更请求,或仓库所在托管平台需要登录时显示。分栏标题旁显示数量。卡片上方的状态行请用户登录托管平台:显示提供方给出的登录命令(例如 `gh auth login --hostname github.com`,悬停时滚动显示全文)和「复制」;提供方没有给出命令以及登录检查失败时,平台给出的原因收在信息按钮里,与检出行显示失败的方式相同。Session 没有绑定变更请求时,分栏只显示这一行。每张变更请求卡片显示状态图标、单行标题(悬停时滚动显示全文,点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与面板开关的黄点一致。卡片的“更多”菜单提供“在浏览器中打开”“复制变更请求链接”、由提供方服务的变更请求的“查看变更”、打开中草稿的“标记为可评审”,以及“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。展开的卡片显示源分支与目标分支,下面每项一行,由图标与取值组成。打开的变更请求依次是:检查,其菜单按失败、运行中、已取消分组列出检查及其耗时与链接,按需列出通过与跳过的检查,用户可以重跑检查、且有失败检查指向一个其中没有检查仍在进行的重跑时提供“重跑失败项”;评审结论,带前三位评审者的头像与其余人数,其菜单列出每位评审者的类型与最近结论,注明早于最新提交的结论,用户可以请求评审时还能重新请求某位评审者,或通过先列出托管平台建议的搜索向其他人请求评审;合并状态,会注明 head 落后于基线,用户可以更新时提供“更新分支”,其菜单在 merge 与 rebase 之间选择,打开时固定卡片显示的 head,轮询发现 head 变化后禁用“确认更新”;按所选界面语言格式化的变更行数与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`),点击该行打开变更视图;以及合并时托管平台会关闭的关联 issue,各自链接到其页面。讨论数和 issue 标题在悬停 500ms 后以提示显示。已合并或已关闭的显示结束时间与变更行数。“重跑失败项”、评审请求、“更新分支”、“标记为可评审”与“合并”的结果都以 toast 报告,托管平台未确认结果时提示到浏览器中查看变更请求;显示的 head 之后有新提交时不会重跑或更新。主机现在就会合并的变更请求在各行下方提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。Session 只绑定了一个变更请求时,无论其状态如何,它的卡片默认展开;绑定多个时,所有卡片默认收起。用户展开或收起某张卡片后,在 Session 保持打开期间,更新和隐藏面板都不会改变这一选择;用户没有动过的卡片仍按默认规则。 +- **变更请求分栏**——Session 有已绑定的变更请求,或仓库所在托管平台需要登录时显示。分栏标题旁显示数量。卡片上方的状态行请用户登录托管平台:显示提供方给出的登录命令(例如 `gh auth login --hostname github.com`,悬停时滚动显示全文)和「复制」;提供方没有给出命令以及登录检查失败时,平台给出的原因收在信息按钮里,与检出行显示失败的方式相同。Session 没有绑定变更请求时,分栏只显示这一行。每张变更请求卡片显示状态图标、单行标题(悬停时滚动显示全文,点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与面板开关的黄点一致。卡片的“更多”菜单提供“在浏览器中打开”“复制变更请求链接”、由提供方服务的变更请求的“查看变更”、打开中草稿的“标记为可评审”,以及“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。这些内容只占一行:含失败检查的一行放不下时,失败检查改用不带数量的短文案;仍放不下的一行末尾显示省略号,并随标题一起滚动显示。展开的卡片显示源分支与目标分支,下面每项一行,由图标与取值组成。打开的变更请求依次是:检查,其菜单按失败、运行中、已取消分组列出检查及其耗时与链接,按需列出通过与跳过的检查,用户可以重跑检查、且有失败检查指向一个其中没有检查仍在进行的重跑时提供“重跑失败项”;评审结论,带前三位评审者的头像与其余人数,其菜单列出每位评审者的类型与最近结论,注明早于最新提交的结论,用户可以请求评审时还能重新请求某位评审者,或通过先列出托管平台建议的搜索向其他人请求评审;合并状态,会注明 head 落后于基线,用户可以更新时提供“更新分支”,其菜单在 merge 与 rebase 之间选择,打开时固定卡片显示的 head,轮询发现 head 变化后禁用“确认更新”;按所选界面语言格式化的变更行数与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`),点击该行打开变更视图;以及合并时托管平台会关闭的关联 issue,各自链接到其页面。讨论数和 issue 标题在悬停 500ms 后以提示显示。已合并或已关闭的显示结束时间与变更行数。“重跑失败项”、评审请求、“更新分支”、“标记为可评审”与“合并”的结果都以 toast 报告,托管平台未确认结果时提示到浏览器中查看变更请求;显示的 head 之后有新提交时不会重跑或更新。主机现在就会合并的变更请求在各行下方提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。Session 只绑定了一个变更请求时,无论其状态如何,它的卡片默认展开;绑定多个时,所有卡片默认收起。用户展开或收起某张卡片后,在 Session 保持打开期间,更新和隐藏面板都不会改变这一选择;用户没有动过的卡片仍按默认规则。 - **本地变更行**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。这一行显示变更的文件数以及新增、删除行数,点击打开变更视图。它的“更多”菜单提供“查看变更”;识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,还提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。 -- **变更视图**——变更请求卡片上的“变更”一行与“查看变更”菜单项、以及本地变更行会打开一个右侧边栏标签页,列出所有变更的文件;会话面板浮在对话上方时随之关闭。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。工具栏的图标按钮和标题栏的“在浏览器中打开”悬停 500ms 后显示操作说明,键盘聚焦时立即显示。工具栏和标题栏各自保持一行:工具栏变窄时,先把变更行数、全部展开、左右对比与自动换行收进“更多视图选项”菜单,再收起“隐藏测试文件”开关,已审阅进度的文字缩短为圆环旁的计数,最后收起刷新;标题栏的按钮文字不换行,菜单和标题先缩短。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停 500ms 后显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。标题变窄时,路径、标记和“有新改动”会缩短,行数、“已审阅”和文件菜单始终完整显示。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。不超过 20 行的折叠行点一次全部展开。更长的折叠行每次展开 20 行,可以从上方 hunk 向下展开,也可以从下方 hunk 向上展开;第一个 hunk 之前的折叠行只能向上展开,最后一个 hunk 之后的只能向下展开;折叠行上显示还隐藏的行数。最后一个 hunk 之后行数未知的折叠行,第一次点击时读取文件并显示前 20 行。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。刷新评审标记时,如果比较的提交范围、末端提交和补丁都相同,已经展开的未变更行和正在读取的文件内容会保留。 +- **变更视图**——变更请求卡片上的“变更”一行与“查看变更”菜单项、以及本地变更行会打开一个右侧边栏标签页,列出所有变更的文件;会话面板浮在对话上方时随之关闭。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。工具栏的图标按钮和标题栏的“在浏览器中打开”悬停 500ms 后显示操作说明,键盘聚焦时立即显示。工具栏和标题栏各自保持一行:工具栏变窄时,先把变更行数、全部展开、左右对比与自动换行收进“更多视图选项”菜单,再收起“隐藏测试文件”开关,已审阅进度的文字缩短为圆环旁的计数,最后收起刷新;标题栏的按钮文字不换行,菜单和标题先缩短。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停 500ms 后显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。标题变窄时,路径、标记和“有新改动”会缩短,行数、“已审阅”和文件菜单始终完整显示。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。不超过 20 行的折叠行点一次全部展开。更长的折叠行每次展开 20 行,可以从上方 hunk 向下展开,也可以从下方 hunk 向上展开;第一个 hunk 之前的折叠行只能向上展开,最后一个 hunk 之后的只能向下展开;折叠行上显示还隐藏的行数。最后一个 hunk 之后行数未知的折叠行,第一次点击时读取文件并显示前 20 行。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。视图读取尚未显示过的变更时,会在显示为脉动占位的文件卡片上方写出“正在读取变更…”,并排视图下其中一个已修改文件画成两栏,文件菜单不显示数量;开启“减少动态效果”时占位不动。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。刷新评审标记时,如果比较的提交范围、末端提交和补丁都相同,已经展开的未变更行和正在读取的文件内容会保留。 - **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;文件树宽度放不下数量时,只显示各层名称,数量在悬停提示里。不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏以按已审阅比例填充的圆环和“已审阅 2 / 3”这样的文字显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。文件树把已审阅的文件置灰,目录下的文件全部已审阅时目录也置灰,以便看出还没审阅的文件;有新改动的文件按未审阅显示,辅助技术把这一状态读作每行的描述。只改文件模式(例如 `chmod +x`)也算新改动。变更请求的全部提交视图使用提供方保存在代码托管平台上的已审阅标记(GitHub 提供方即如此):视图随 diff 一起读取这些标记,勾选后立即显示,并在显示的 head 上保存,平台答复前该文件的复选框保持禁用;GitHub 报告为标记后又有改动的文件显示“有新改动”。平台拒绝或因新提交而过期的标记恢复原状,并以 toast 说明原因;平台可能已保存但未确认的标记保持不变,toast 提示刷新查看实际状态。无法读取标记时,提示条说明原因并提供“重试”,此时不能标记任何文件。悬停复选框会说明标记保存在哪里。其他标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。 - **评审讨论**——变更请求视图会叠加代码托管平台在所显示 head 处读到的评审讨论。行级讨论显示在它最后一行所在的行之后,位于写下时所在的那一侧;若该行折叠在未变更的行中,则显示在折叠行之后。讨论标明写下时的位置,每条评论显示头像、作者、时间和 Markdown 正文(不显示原始 HTML),并用标签标出变更请求作者、机器人账号,以及当前登录用户尚未提交的评审中的评论。已解决的讨论折叠成一行,可以展开。针对整个文件的讨论显示在文件开头;被后续提交改到而过期的讨论集中在文件的行之后,显示写下时那段 hunk 的末尾,并提供“查看当时的文件”,读取写下讨论时那个提交上的文件并标出相应的行。选择了部分提交时,只显示行号对应最后一个所选提交的新版本侧讨论。文件树和每个文件标题都显示未解决讨论数。每点击一次文件标题上的计数,就按文件中的显示顺序跳到该文件的下一条未解决讨论(所选提交中没有的讨论排在最后),到最后一条后回到第一条;工具栏的“讨论”按钮打开讨论列表。列表按文件树顺序分组,组内讨论的顺序与文件中相同,可显示未解决、已解决或全部讨论,默认显示未解决的讨论;点击讨论会跳到它的位置,若所选提交中没有该讨论,会先切换到全部提交。视图宽度不小于 1,040px 时列表停靠在文件旁;更窄时浮在文件之上,并在跳到讨论前先关闭;窄于 480px 时占满文件区的宽度。读取被截断时,列表会注明。讨论上提供“添加到输入框”(把整个讨论作为引用插入)、“在 GitHub 中查看”,以及当前登录用户可以执行的写操作。没有待提交评审时,回复框立即回复,其下拉菜单可以带着这条回复开始待提交评审;有待提交评审时,回复框把回复加入其中,因为 GitHub 会把用户的每条回复都加入待提交评审。“解决讨论”和“取消解决”切换讨论状态;用户自己评论的菜单可以编辑或删除该评论,删除前会先确认,删除讨论中唯一的评论会一并删除讨论,确认时会说明这一点。用户正在讨论中写回复或编辑评论时,即使讨论已被解决,也保持展开。代码托管平台拒绝写操作时保留输入的文字并说明原因;结果不明时会重新读取讨论,并请用户核对后再重试。每次写操作后都会重新读取讨论,因为解决讨论不会改变 GitHub pull request 的更新时间。视图显示期间,每收到一次状态就重新读取讨论;点击刷新后,即使面板还保留着之前的读取结果,也会从代码托管平台重新读取;读取失败时保留上次的讨论并提供重试,提供方不支持读取讨论时不显示讨论。 @@ -63,9 +63,9 @@ diff 按文件树的深度优先顺序排列:同层目录在前、文件在后 `ForgePanelController` 为每个被关注的 Session 保留一个 `SessionPanel`,最后一个关注方离开时销毁它。面板从 Session 的工作目录与绑定开始,在每个 `working-directory/change`、`tool/result` 与 `sandbox/mode` 事件之后重新检查,只在状态与已发布的不同时发布新的 `ForgePanelState`,所以检查结果与原来相同时不会通知任何关注方。每个变更请求在后续轮询失败时保留最近一次轮询得到的快照。并行 Git 读取失败时会取消并等待同批读取结束。检查一次只运行一个,最多再追加一次;Session 已离开的目录的结果会被丢弃。代码托管平台按远端顺序识别:先是上游所在的远端,然后是 `origin`,最后是其余远端。检查发现提供方识别的远端上有上游分支时,面板调用 `ctx.forgeSession.discoverBranch` 绑定该分支打开状态的变更请求;同一远端与分支在刷新前只查找一次。识别出的托管平台变化时以及刷新时,会在 `readinessTimeoutMs` 内检查登录状态;一次刷新在它触发的检查与登录状态检查结束后完成,轮询结果之后才到达。 -检查运行 `rev-parse --show-toplevel`、`rev-parse --path-format=absolute --git-common-dir`、`rev-parse --path-format=absolute --git-dir`、`symbolic-ref --short HEAD`、`rev-parse --short HEAD`、`rev-parse --abbrev-ref @{upstream}` 与 `remote -v`;`branches` 运行 `symbolic-ref` 与 `for-each-ref --count=`;`diffBases` 像下文的 `localDiff` 一样找出默认分叉点,在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,排除 `origin/HEAD` 等符号引用,每类最多保留 `maxBranches` 个名称包含查询文字的分支。之后,检查会为本地变更行统计 `branch` 范围的规模:找出分叉点,对它运行 `diff --numstat -z -M`,采用与下文 `localDiff` 相同的辅助程序和子模块限制,并列出未跟踪文件。每个命令都使用 Session 解析出的沙箱模式:`read-only` 与 `workspace-write` 需要沙箱,`danger-full-access` 无需沙箱后端。命令禁用可选的索引写入、钩子、文件系统监视器、提示与对象的延迟获取,移除继承的 Git 选择器与携带密钥的变量,并各自受 `gitTimeoutMs` 时限与每个输出流的 `maxOutputBytes` 上限约束。Git 打印的顶层目录、Git 目录与公共 Git 目录经 `ctx.fs` 解析为工作目录服务记录的规范进程路径;Git 目录与公共 Git 目录不同的检出是链接 worktree。工作树选项在 `danger-full-access` 沙箱模式下可用,在 `read-only` 下不可用,在 `workspace-write` 下只有两个目录都位于 Session 沙箱策略的规范工作区根内时才可用。 +检查运行 `rev-parse --show-toplevel`、`rev-parse --path-format=absolute --git-common-dir`、`rev-parse --path-format=absolute --git-dir`、`symbolic-ref --quiet HEAD`(指向 `refs/heads/` 下的分支时即为当前分支)、`rev-parse --short HEAD`、`rev-parse --abbrev-ref @{upstream}` 与 `remote -v`;`worktreeBases` 在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,从 `refs/remotes//HEAD` 取每个远程的默认分支,略过其他符号引用与未配置远程的分支,并按下文的代码托管识别顺序排列远程,各保留最多 `maxBranches` 个名称包含查询文字的本地分支与每个远程的分支;带名称的 `requestWorktree` 按 Git 的分支名规则检查名称,并在检出中运行 `show-ref`;`diffBases` 像下文的 `localDiff` 一样找出默认分叉点,在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,排除 `origin/HEAD` 等符号引用,每类最多保留 `maxBranches` 个名称包含查询文字的分支。之后,检查会为本地变更行统计 `branch` 范围的规模:找出分叉点,对它运行 `diff --numstat -z -M`,采用与下文 `localDiff` 相同的辅助程序和子模块限制,并列出未跟踪文件。每个命令都使用 Session 解析出的沙箱模式:`read-only` 与 `workspace-write` 需要沙箱,`danger-full-access` 无需沙箱后端。命令禁用可选的索引写入、钩子、文件系统监视器、提示与对象的延迟获取,移除继承的 Git 选择器与携带密钥的变量,并各自受 `gitTimeoutMs` 时限与每个输出流的 `maxOutputBytes` 上限约束。Git 打印的顶层目录、Git 目录与公共 Git 目录经 `ctx.fs` 解析为工作目录服务记录的规范进程路径;Git 目录与公共 Git 目录不同的检出是链接 worktree。工作树选项在 `danger-full-access` 沙箱模式下可用,在 `read-only` 下不可用,在 `workspace-write` 下只有两个目录都位于 Session 沙箱策略的规范工作区根内时才可用。 -worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWorktree` 投影折叠:请求与撤回在第一个 `turn/start` 或创建之前生效;在第一个 `step/start` 之前,未完成请求的第一条 `created` 记录生效。该投影还从 Session 头部与每个 `working-directory/change` 记录 Session 的目录;它的客户端视图随 Session 摘要下发,在该目录就是所创建的 worktree 或位于其下时为该 worktree,否则为 null。一轮开始或 worktree 已创建之后,`requestWorktree` 以 `forgePanel/session-started` 拒绝;没有 `worktrees` 服务时以 `forgePanel/worktrees-unavailable` 拒绝;分支名为空时以 `forgePanel/invalid-branch` 拒绝;`cancelWorktree` 只以第一种拒绝,也不需要 `worktrees` 服务;两者都会忘掉失败的尝试。消息进入有未完成请求的 Session 的收件箱时,一个 `agent/inbox/inserted` 监听器在这次投递唤醒 Agent 之前启动 Session 所属 Agent 的维护任务,因此 Agent 会暂存唤醒,等这次暂留结束后才开始这条消息的这一轮。暂留使用新分支名进行一次尝试,在面板状态中发布正在进行的阶段,设置 `held`,`waiting` 为 `creation`,并记录带源仓库根目录的 `created`。尝试失败(其分支、基准、失败步骤与原因以 `failure` 留在面板状态中)或经 `stopCreation` 停止后,暂留继续等待:`retryWorktree` 再做一次尝试,没有消息等待或已有尝试进行时以 `forgePanel/not-waiting` 拒绝;撤回请求则让消息在当前检出中继续。Agent 空闲且 Session 在所创建 worktree 中工作时,进入的每条消息都会启动一次暂留,检查该 worktree 是否缺失;缺失期间暂留以 `waiting` 为 `restoration` 等待,`restoreWorktree` 或 `continueInProject` 在暂留内运行,之后放行消息;检查无法给出结果时立即放行。Agent 的取消与 Remote 的停止都会结束暂留;Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留。worktree 服务把工作目录通知排进队列,由第一步认领。一个 `agent/pre-step` 监听器在请求仍未完成的 Session 的第 1 步创建 worktree,覆盖没有被暂留的消息;它把通知移入本步提议的消息,失败时这一轮结束、请求保留。没有消息等待时,`restoreWorktree` 与 `continueInProject` 以各自的维护任务运行;`restoreWorktree` 以 `restoration` 发布正在进行的步骤,并在结束恢复的同一状态中清除 `missing`。套件把它的 `worktrees` 服务隔离,因此同时启用 Git Worktrees 时会有两个互不影响的服务。`track` 以 `forgePanel/unrecognized-url` 拒绝没有提供方识别的 URL。`markReady` 与 `merge` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;`merge` 带上卡片显示的 head 提交,head 已变化时以 `forgePanel/stale-head` 拒绝,其他拒绝都是带主机原因的 `forgePanel/action-failed`。 +worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWorktree` 投影折叠:请求与撤回在第一个 `turn/start` 或创建之前生效;在第一个 `step/start` 之前,未完成请求的第一条 `created` 记录生效。该投影还从 Session 头部与每个 `working-directory/change` 记录 Session 的目录;它的客户端视图随 Session 摘要下发,在该目录就是所创建的 worktree 或位于其下时为该 worktree,否则为 null。请求用本地分支或远程跟踪分支的完整引用名指定基准(早期面板记录的本地短名称仍可解析),并可指定分支名。一轮开始或 worktree 已创建之后,`requestWorktree` 以 `forgePanel/session-started` 拒绝;没有 `worktrees` 服务时以 `forgePanel/worktrees-unavailable` 拒绝;基准为空时以 `forgePanel/invalid-branch` 拒绝;Git 不接受分支名时以 `forgePanel/invalid-name` 拒绝;检出中已有同名分支时以 `forgePanel/branch-exists` 拒绝;`cancelWorktree` 只以第一种拒绝,也不需要 `worktrees` 服务;两者都会忘掉失败的尝试。消息进入有未完成请求的 Session 的收件箱时,一个 `agent/inbox/inserted` 监听器在这次投递唤醒 Agent 之前启动 Session 所属 Agent 的维护任务,因此 Agent 会暂存唤醒,等这次暂留结束后才开始这条消息的这一轮。暂留用请求的分支名或新的自动名称进行一次尝试,基准是远程跟踪分支时请 worktree 服务先获取它;它在面板状态中发布正在进行的阶段,设置 `held`,`waiting` 为 `creation`,并记录带源仓库根目录的 `created`。尝试失败(其分支、基准、是否获取、失败步骤、原因以及分支或目录是否已存在以 `failure` 留在面板状态中)或经 `stopCreation` 停止后,暂留继续等待:`retryWorktree` 再做一次尝试,`fetch` 参数为 false 时不获取,没有消息等待或已有尝试进行时以 `forgePanel/not-waiting` 拒绝;用另一个名称调用 `requestWorktree` 会改变下一次尝试;撤回请求则让消息在当前检出中继续。Agent 空闲且 Session 在所创建 worktree 中工作时,进入的每条消息都会启动一次暂留,检查该 worktree 是否缺失;缺失期间暂留以 `waiting` 为 `restoration` 等待,`restoreWorktree` 或 `continueInProject` 在暂留内运行,之后放行消息;检查无法给出结果时立即放行。Agent 的取消与 Remote 的停止都会结束暂留;Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留。worktree 服务把工作目录通知排进队列,由第一步认领。一个 `agent/pre-step` 监听器在请求仍未完成的 Session 的第 1 步创建 worktree,覆盖没有被暂留的消息;它把通知移入本步提议的消息,失败时这一轮结束、请求保留。没有消息等待时,`restoreWorktree` 与 `continueInProject` 以各自的维护任务运行;`restoreWorktree` 以 `restoration` 发布正在进行的步骤,并在结束恢复的同一状态中清除 `missing`。套件把它的 `worktrees` 服务隔离,因此同时启用 Git Worktrees 时会有两个互不影响的服务。`track` 以 `forgePanel/unrecognized-url` 拒绝没有提供方识别的 URL。`markReady` 与 `merge` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;`merge` 带上卡片显示的 head 提交,head 已变化时以 `forgePanel/stale-head` 拒绝,其他拒绝都是带主机原因的 `forgePanel/action-failed`。 恢复在修改前记录 `restoring`,仅在成功后记录 `restored`。投影版本 3 在重载后保留未完成的恢复。目录存在本身不能放行等待的消息:检出根目录与公共 Git 目录必须匹配记录的工作树。插件卸载会取消并等待所有创建、恢复与消息等待任务,然后释放面板读取器和投影。 @@ -85,6 +85,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi | [`src/index.ts`](src/index.ts) | `forgePanel` Remote 与按 Session 的面板 | | [`src/panel.ts`](src/panel.ts) | 面板状态、检查调度与登录检查 | | [`src/worktree.ts`](src/worktree.ts) | worktree 记录、投影、等待中的消息,以及在第一步创建 worktree | +| [`src/branch-name.ts`](src/branch-name.ts) | Host 与 Client 共用的分支名规则与分支显示名 | | [`src/states.ts`](src/states.ts) | 会话列表用的变更请求状态 | | [`src/git.ts`](src/git.ts) | 按 Session 权限执行 Git 查询 | | [`src/parse.ts`](src/parse.ts) | Git 输出解析与远端顺序 | @@ -114,7 +115,10 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi | [`src/client/host-viewed.ts`](src/client/host-viewed.ts) | 代码托管平台保存的已审阅标记,以及正在保存的标记 | | [`src/client/menu-search.ts`](src/client/menu-search.ts) | 菜单顶部搜索框的按键处理 | | [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | 变更文件的标签:文件名在前,目录在后 | -| [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | 新会话的工作树选项 | +| [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | 新会话的工作树选项及其基准菜单 | +| [`src/client/WorktreeNameDialog.tsx`](src/client/WorktreeNameDialog.tsx) | worktree 分支的命名对话框 | +| [`src/client/branch-search.tsx`](src/client/branch-search.tsx) | 分支菜单的搜索状态与状态行 | +| [`src/client/ChangesLoading.tsx`](src/client/ChangesLoading.tsx) | 读取中的变更视图 | | [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | worktree 创建卡片与 worktree 缺失卡片 | | [`src/client/SessionRowForge.tsx`](src/client/SessionRowForge.tsx) | 会话行图标 | | [`src/client/SessionHoverForge.tsx`](src/client/SessionHoverForge.tsx) | 会话行悬浮卡片中的部分 | @@ -149,7 +153,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **只在显示时轮询**——只有会话列表的某一行或该 Session 的活动面板界面订阅时才会轮询状态,保活但隐藏的变更正文不订阅;其间检查结束不会有通知。 - **会话列表中未打开的 Session**——会话列表从缓存的摘要中读取未加载 Session 的 worktree 与绑定:没有缓存摘要的 Session 两者都不显示;此版本之前最后使用的 Session 要打开之后才显示其 worktree。 - **检查触发时机**——检出只在 Session 的工具结果与目录变化之后检查;Session 之外的改动在会话面板打开或窗口重新获得焦点时出现(每 10 秒最多一次),否则要等到下一个工具结果。 -- **保留检出**——面板只在 Session 的第一步之前创建 worktree,不删除已有的检出目录或分支;失败或被取消的尝试可能留下分支或检出。分支名取自 Session id 与随机数字,而不是 Session 标题,因为那时标题还不存在。 +- **保留检出**——面板只在 Session 的第一步之前创建 worktree,不删除已有的检出目录或分支;失败或被取消的尝试可能留下分支或检出。自动生成的分支名取自 Session id 与随机数字,而不是 Session 标题,因为那时标题还不存在;在命名对话框中指定的名称会取代它。 - **一轮进行中的消息**——Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留:所请求的 worktree 改为在第一步创建,失败时这一轮结束且不带这条消息;已删除的 worktree 不会被检查,工作目录服务会把 Session 移回项目目录。 - **等待中的消息**——消息等待期间,Agent 以空闲状态处于维护任务中,输入框不提供停止;只有卡片上的操作、Agent 的取消或 Remote 的停止能放行它,等待 Agent 空闲的调用方也会一并等待。 - **恢复**——恢复会从分支重新检出;分支也已删除时,从它开始时的提交重新创建。从未提交的修改随被删除的目录一起丢失。[worktree 服务](../worktree/README.zh.md#use-this-package)校验记录的目标,只移除该目标缺失且未锁定的登记。已有或未恢复完成的目录仍会阻止恢复;请先保存其中的文件并移除目录再重试,或在源项目继续。 diff --git a/packages/experimental/client-ui-forge/src/branch-name.ts b/packages/experimental/client-ui-forge/src/branch-name.ts new file mode 100644 index 0000000000..8b55b4fe86 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/branch-name.ts @@ -0,0 +1,74 @@ +/** Branch-name rules and branch labels shared by the Host and the Client; free of Node imports. */ + +/** Prefix of the full names of local branches. */ +export const LOCAL_REF_PREFIX = 'refs/heads/' + +/** Prefix of the full names of remote-tracking branches. */ +export const REMOTE_REF_PREFIX = 'refs/remotes/' + +/** + * Why a name cannot be a new branch name: Git's rules for `refs/heads/`, plus the worktree service's + * refusal of a leading `-`. + */ +export type BranchNameProblem = + | 'empty' + | 'space' + | 'character' + | 'leading-dash' + | 'leading-slash' + | 'trailing-slash' + | 'double-slash' + | 'double-dot' + | 'trailing-dot' + | 'at' + | 'at-brace' + | 'dot-segment' + | 'lock-segment' + +/** Characters Git refuses anywhere in a ref name: ASCII controls, `~ ^ : ? * [`, and the backslash. */ +const FORBIDDEN = /[\u0000-\u001f\u007f~^:?*[\\]/ + +/** + * Find the first rule a new branch name breaks. `git check-ref-format` stays the final check on the Host. + * @param name - candidate branch name. + * @returns the broken rule, or null when the name passes every rule. + */ +export function branchNameProblem(name: string): BranchNameProblem | null { + if (name.length === 0) return 'empty' + if (/\s/.test(name)) return 'space' + if (FORBIDDEN.test(name)) return 'character' + if (name.startsWith('-')) return 'leading-dash' + if (name.startsWith('/')) return 'leading-slash' + if (name.endsWith('/')) return 'trailing-slash' + if (name.includes('//')) return 'double-slash' + if (name.includes('..')) return 'double-dot' + if (name.endsWith('.')) return 'trailing-dot' + if (name === '@') return 'at' + if (name.includes('@{')) return 'at-brace' + const segments = name.split('/') + if (segments.some(segment => segment.startsWith('.'))) return 'dot-segment' + if (segments.some(segment => segment.endsWith('.lock'))) return 'lock-segment' + return null +} + +/** + * The name a branch shows: a full local or remote-tracking branch name without its `refs/heads/` or + * `refs/remotes/` prefix; any other revision, such as a short name an earlier panel recorded, as it is. + * @param ref - branch or revision. + * @returns the shown name. + */ +export function branchLabel(ref: string): string { + for (const prefix of [LOCAL_REF_PREFIX, REMOTE_REF_PREFIX]) { + if (ref.startsWith(prefix) && ref.length > prefix.length) return ref.slice(prefix.length) + } + return ref +} + +/** + * Whether a revision is the full name of a remote-tracking branch, which a worktree creation fetches first. + * @param ref - branch or revision, or null for HEAD. + * @returns whether `ref` lies under `refs/remotes/`. + */ +export function isRemoteRef(ref: string | null): boolean { + return ref !== null && ref.startsWith(REMOTE_REF_PREFIX) && ref.length > REMOTE_REF_PREFIX.length +} diff --git a/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx b/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx index 0bcabc3408..c0305f7623 100644 --- a/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx +++ b/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx @@ -1,21 +1,19 @@ /** Base branch picker of the local changes view's `branch` scope: the automatic fork point, then remote-tracking and local branches. */ -import { useEffect, useRef, useState, type ReactNode } from 'react' +import { useState, type ReactNode } from 'react' import clsx from 'clsx' import { - Button, IconBranchOutlineRegular, IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconSearchOutlineRegular, - IconWarningTriangleOutlineRegular, Input, Menu, MenuItemButton, StateDot, Tooltip, + IconBranchOutlineRegular, IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconSearchOutlineRegular, + IconWarningTriangleOutlineRegular, Input, Menu, MenuItemButton, Tooltip, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import type { ForgeBaseBranch, ForgeBaseBranches } from '../types.ts' +import { branchSearchStatus, useBranchSearch } from './branch-search.tsx' import type { NS } from './locales.ts' import { searchFieldKeyDown } from './menu-search.ts' import css from './BaseMenu.module.css' -/** Milliseconds between the last keystroke of a search and the listing it reads. */ -const SEARCH_DELAY_MS = 150 - /** Props of the base branch picker. */ export interface BaseMenuProps extends PropsLocale { /** Chosen branch, or null for the automatic fork point. */ @@ -49,32 +47,11 @@ interface BaseOption { */ export function BaseMenu({ chosen, label, missing, visible, list, choose, t }: BaseMenuProps): ReactNode { const [open, setOpen] = useState(false) - const [query, setQuery] = useState('') - const [attempt, setAttempt] = useState(0) - const [listing, setListing] = useState | null>(null) - const search = useRef(null) const shown = visible && open - useEffect(() => { - if (!shown) return - const controller = new AbortController() - const timer = setTimeout(() => { - void list(query, controller.signal).then((result) => { if (!controller.signal.aborted) setListing(result) }) - }, query === '' ? 0 : SEARCH_DELAY_MS) - return () => { - clearTimeout(timer) - controller.abort() - } - }, [shown, query, attempt, list]) - // The portalled menu measures itself hidden before its first frame, and a hidden field cannot take the keyboard. - // A touch screen keeps its on-screen keyboard closed until the field is tapped. - useEffect(() => { - if (!shown || (typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches)) return - const frame = requestAnimationFrame(() => { search.current?.focus() }) - return () => { cancelAnimationFrame(frame) } - }, [shown]) + const { query, setQuery, listing, retry, reset, field } = useBranchSearch(shown, list) const close = (): void => { setOpen(false) - setQuery('') + reset() } const pick = (base: ForgeBaseBranch | null): void => { close() @@ -110,20 +87,8 @@ export function BaseMenu({ chosen, label, missing, visible, list, choose, t }: B ].filter(group => group.options.length > 0) const first = groups[0]?.options[0] - let body: ReactNode - if (listing === null) { - body =
{t('diff.base.loading')}
- } else if (!listing.ok) { - body = ( -
- {t('toast.branchesFailed')} - -
- ) - } else if (groups.length === 0) { - body =
{t('diff.base.empty')}
- } else { - body = groups.map(group => ( + const body: ReactNode = branchSearchStatus({ listing, empty: groups.length === 0, retry, className: css.status, t }) + ?? groups.map(group => (
{/* The automatic row's tag names it, so its group shows no heading. */} {group.id !== 'automatic' &&
{group.label}
} @@ -142,7 +107,6 @@ export function BaseMenu({ chosen, label, missing, visible, list, choose, t }: B })}
)) - } return (
- } value={query} + } value={query} aria-label={t('diff.base.search')} placeholder={t('diff.base.search')} onChange={(event) => { setQuery(event.target.value) }} onKeyDown={(event) => { searchFieldKeyDown(event, first === undefined ? undefined : () => { pick(first.base) }) }} /> diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx index f87e7d2912..11f3742b79 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx @@ -1,13 +1,15 @@ /** * One change request as a card: its one-line title links to the host and * crawls into view while the pointer rests on the card's head, a one-line - * summary shows while collapsed, and while expanded one row per fact (checks, - * review, merge state, the changed lines, which open its changes, and the - * linked issues) above the merge action. Opening, copying, viewing changes, - * marking a draft ready, and removing live in the card's actions menu. + * summary shows while collapsed, taking the short wording of failed checks + * while the full one does not fit and crawling with the title past that, and + * while expanded one row per fact (checks, review, merge state, the changed + * lines, which open its changes, and the linked issues) above the merge + * action. Opening, copying, viewing changes, marking a draft ready, and + * removing live in the card's actions menu. */ -import { useId, useRef, useState, type ReactNode } from 'react' +import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type PointerEvent, type ReactNode, type RefObject } from 'react' import clsx from 'clsx' import { Button, IconCheckCircleOutlineRegular, IconChevronDownOutlineRegular, IconCloseOutlineRegular, IconCopyOutlineRegular, @@ -170,10 +172,14 @@ function finished(snapshot: ChangeRequestSnapshot, now: number, t: Translate): s return ago === undefined ? state : t('time.finished', { state, time: ago }) } -/** Collapsed status after the number: checks and the most urgent flag, the merge or close time, or a read in progress. */ -function Summary({ snapshot, now, t }: { +/** + * Collapsed status after the number: checks and the most urgent flag, the merge or close time, or a read in progress. + * With `short`, failed checks take the wording without their count. + */ +function Summary({ snapshot, now, short, t }: { readonly snapshot: ChangeRequestSnapshot | null readonly now: number + readonly short: boolean readonly t: Translate }): ReactNode { if (snapshot === null) return @@ -187,7 +193,7 @@ function Summary({ snapshot, now, t }: { {ci.kind !== 'none' && } {ci.kind === 'failed' - ? ci.count > 0 ? t('change.ci.failed', { count: ci.count }) : t('change.ci.failedUnlisted') + ? ci.count > 0 && !short ? t('change.ci.failed', { count: ci.count }) : t('change.ci.failedUnlisted') : ci.kind === 'cancelled' ? t('change.ci.cancelled', { count: ci.count }) : t(`change.ci.${ci.kind}`)} {flag !== undefined && {t(`change.flag.${flag}`)}} @@ -195,6 +201,61 @@ function Summary({ snapshot, now, t }: { ) } +/** + * What the collapsed status line shows when its failed checks can take the shorter wording without their count: the full + * wording and the flag, which decide the line's width. Null for any other status, and where the language's short wording + * is no shorter. + * @param snapshot - change request status. + * @param t - copy. + * @returns the line's full text after the number, or null. + */ +function shortenable(snapshot: ChangeRequestSnapshot | null, t: Translate): string | null { + if (snapshot?.state !== 'open') return null + const ci = ciSummary(snapshot) + if (ci.kind !== 'failed' || ci.count === 0) return null + const full = t('change.ci.failed', { count: ci.count }) + if (t('change.ci.failedUnlisted').length >= full.length) return null + const flag = flagOf(snapshot) + return flag === undefined ? full : `${full} ${t(`change.flag.${flag}`)}` +} + +/** + * Whether the collapsed status line shows the short wording of failed checks: only while the line with the full wording + * does not fit. A change of the line's width, of the fonts, or of `full` shows the full wording again for one layout pass, + * which measures it and switches before the frame is painted. + * @param line - the clipping status line. + * @param full - the line's full text after the number, from {@link shortenable}; null measures nothing. + * @returns whether the line takes the short wording. + */ +function useShortWording(line: RefObject, full: string | null): boolean { + const [measured, setMeasured] = useState<{ readonly full: string | null; readonly short: boolean }>({ full: null, short: false }) + const short = full !== null && measured.full === full && measured.short + useLayoutEffect(() => { + if (full === null || short) return + const element = line.current + /* v8 ignore next -- the status line is mounted whenever there is a full wording to measure */ + if (element === null) return + if (element.scrollWidth > element.clientWidth) setMeasured({ full, short: true }) + }) + useEffect(() => { + if (full === null) return + const element = line.current + /* v8 ignore next -- the status line is mounted whenever there is a full wording to measure */ + if (element === null) return + // A new object renders again even when the line already shows the full wording, so the layout effect measures. + const measure = (): void => { setMeasured({ full, short: false }) } + const observer = new ResizeObserver(measure) + observer.observe(element) + const fonts = document.fonts + fonts.addEventListener('loadingdone', measure) + return () => { + observer.disconnect() + fonts.removeEventListener('loadingdone', measure) + } + }, [line, full]) + return short +} + /** Expanded identity after the number: draft state and the head and base branches. */ function Target({ snapshot, t }: { readonly snapshot: ChangeRequestSnapshot; readonly t: Translate }): ReactNode { return ( @@ -432,11 +493,32 @@ export function ChangeRequestCard({ entry, expanded, onToggle, now, actions, loc const tone = toneOf(snapshot) const name = number === null ? snapshot?.title ?? url : t('change.number', { number }) const titleRef = useRef(null) - const marquee = useHoverMarquee(titleRef) + const lineRef = useRef(null) + const titleMarquee = useHoverMarquee(titleRef) + const lineMarquee = useHoverMarquee(lineRef) + // One hover on the head carries every text it clips: the title, and the collapsed number and status line. + const marquee = useMemo(() => ({ + onPointerEnter: (event: PointerEvent): void => { + titleMarquee.onPointerEnter(event) + lineMarquee.onPointerEnter(event) + }, + onPointerLeave: (): void => { + titleMarquee.onPointerLeave() + lineMarquee.onPointerLeave() + }, + }), [titleMarquee, lineMarquee]) + const short = useShortWording(lineRef, expanded || notice !== undefined ? null : shortenable(snapshot, t)) // A notice replaces the collapsed summary, so a failed read never shows its stale status beside it. const meta = expanded ? snapshot === null ? null : - : notice === undefined ? : null + : notice === undefined ? : null + const parts = ( + <> + {number !== null && {t('change.number', { number })}} + {number !== null && meta !== null && } + {meta} + + ) return (
  • @@ -456,9 +538,7 @@ export function ChangeRequestCard({ entry, expanded, onToggle, now, actions, loc {(number !== null || meta !== null) && (
    - {number !== null && {t('change.number', { number })}} - {number !== null && meta !== null && } - {meta} + {expanded ? parts : {parts}}
    )}
    diff --git a/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx b/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx index d3be9bd0c7..51f6a10d55 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx @@ -160,15 +160,19 @@ export function ChangedFiles(props: ChangedFilesProps): ReactNode { /** * Open directory navigation through the existing files toolbar entry. - * @param props - navigator data and whether its owning tab is visible. + * @param props - navigator data, whether its owning tab is visible, and whether the files are still being read, when + * the entry names no count. * @returns the toolbar entry and its portalled menu. */ -export function ChangedFilesMenu({ visible, ...props }: ChangedFilesProps & { readonly visible: boolean }): ReactNode { +export function ChangedFilesMenu({ visible, loading = false, ...props }: ChangedFilesProps & { + readonly visible: boolean + readonly loading?: boolean +}): ReactNode { const [open, setOpen] = useState(false) return { setOpen(false) }} anchor={}> { setOpen(false); props.jump(path) }} /> diff --git a/packages/experimental/client-ui-forge/src/client/ChangesLoading.module.css b/packages/experimental/client-ui-forge/src/client/ChangesLoading.module.css new file mode 100644 index 0000000000..715a958a97 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/ChangesLoading.module.css @@ -0,0 +1,110 @@ +/* The changes view while it reads: one status line, then file cards drawn as skeletons. The cards copy `.file` and + `.fileHeader` of ChangesTab.module.css; the fill and pulse copy the Plugins page skeleton. */ + +.status { + display: flex; + align-items: center; + min-height: 20px; + margin: 0 0 10px; + padding: 0 4px; + color: var(--dsw-alias-label-secondary); + font-size: var(--dsh-content-font-size-secondary, 13px); + line-height: 20px; +} + +.fill { + border-radius: var(--dsw-radius-xs); + background: var(--dsw-alias-bg-skeleton); + animation: forge-skeleton-pulse 2s cubic-bezier(0.36, 0, 0.64, 1) infinite; +} + +@keyframes forge-skeleton-pulse { + 0% { opacity: 1; } + 40% { opacity: 0.6; } + 80%, 100% { opacity: 1; } +} + +@media (prefers-reduced-motion: reduce) { + .fill { animation: none; } +} + +.file { + overflow: clip; + border: 0.5px solid var(--dsw-alias-border-l4); + border-radius: var(--dsw-radius-lg); + background: var(--forge-changes-bg); +} + +.file + .file { + margin-top: 12px; +} + +@container forge-changes (max-width: 380px) { + .file + .file { + margin-top: 8px; + } +} + +.header { + display: flex; + align-items: center; + gap: 8px; + box-sizing: border-box; + min-height: 36px; + padding: 0 10px 0 12px; + border-bottom: 0.5px solid var(--dsw-alias-border-l3); + background: linear-gradient(var(--dsw-alias-interactive-bg-hover), var(--dsw-alias-interactive-bg-hover)), var(--forge-changes-bg); +} + +.folded .header { + border-bottom: 0; +} + +.icon, +.box { + flex: none; + width: 14px; + height: 14px; +} + +.path { + height: 10px; +} + +.counts { + flex: none; + width: 52px; + height: 10px; + margin-left: auto; +} + +.lines { + display: grid; + padding: 5px 0; +} + +.split { + grid-template-columns: 1fr 1fr; +} + +.column + .column { + border-left: 0.5px solid var(--dsw-alias-border-l3); +} + +.line { + display: flex; + align-items: center; + gap: 12px; + height: 18px; + padding: 0 12px; +} + +.number { + flex: none; + width: 20px; + height: 8px; +} + +.code { + height: 8px; +} diff --git a/packages/experimental/client-ui-forge/src/client/ChangesLoading.tsx b/packages/experimental/client-ui-forge/src/client/ChangesLoading.tsx new file mode 100644 index 0000000000..d0c6f88916 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/ChangesLoading.tsx @@ -0,0 +1,69 @@ +/** The changes view's body while it reads: a status line above file cards drawn as skeletons. */ + +import clsx from 'clsx' +import type { ReactNode } from 'react' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { NS } from './locales.ts' +import css from './ChangesLoading.module.css' + +/** Widths, in percent of a line, that the skeleton's code bars cycle through. */ +const CODE_WIDTHS = [62, 48, 74, 35, 81, 56, 44, 69, 28, 52, 77, 39] as const + +/** + * The skeleton cards: a changed file shown in two columns when the view splits sides, an added file, and two + * collapsed files. `path` is the path bar's width in percent of the header. + */ +const FILES = [ + { path: 46, lines: 7, sides: 2 }, + { path: 34, lines: 4, sides: 1 }, + { path: 52, lines: 0, sides: 1 }, + { path: 28, lines: 0, sides: 1 }, +] as const + +function Column({ lines, offset }: { readonly lines: number; readonly offset: number }): ReactNode { + return ( +
    + {Array.from({ length: lines }, (_, index) => ( +
    + + +
    + ))} +
    + ) +} + +/** + * Render the reading state of the changes view. The status line is the only text and announces itself politely; + * the cards are hidden from assistive technology. + * @param props - whether changed files show their sides in two columns, and copy. + * @returns the status line and the skeleton cards. + */ +export function ChangesLoading({ split, t }: { readonly split: boolean } & PropsLocale): ReactNode { + return ( + <> +
    {t('diff.loading')}
    + + + ) +} diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index 620fe36e57..c05b0d3feb 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -19,7 +19,7 @@ import { Button, IconBranchOutlineRegular, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconCompareSplitOutlineRegular, IconInfoOutlineRegular, IconFilesDiffOutlineRegular, IconNowrapFillRegular, IconRightUpOutlineRegular, IconWorkspaceTreeOutlineRegular, IconWrapFillRegular, - Menu, StateDot, Tooltip, + Menu, Tooltip, type MenuEntry, } from '@deepseek-ai/dsh-client-ui-primitives' import type { HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' @@ -53,6 +53,7 @@ import { SectionReach } from './section-reach.ts' import { FileTreePane, type FileTreePosition } from './FileTreePane.tsx' import { changedFileTree, filesInTreeOrder } from './file-tree.ts' import { ChangedFilesMenu, type ChangedFilesProps, type ChangedFilesState } from './ChangedFiles.tsx' +import { ChangesLoading } from './ChangesLoading.tsx' import { drawnLines, matchesHunks, revealGap, textLines, type GapExpansion, type GapReveal } from './diff-rows.ts' import { ChangeRequestGlyph } from './glyphs.tsx' import type { ForgePanelKey, NS } from './locales.ts' @@ -1218,7 +1219,7 @@ export function ChangesTab({
  • ) } else if (failed === null) { - body =
    + body =
    } else { body = (
    @@ -1332,7 +1333,9 @@ export function ChangesTab({ {treeShown &&
    }
    {tab.visible && source.kind === 'local' && { actions.scoped(tab.id, next) }} t={t} />} - {tab.visible && } + {tab.visible && ( + + )} {tab.visible && allFiles.length > 0 && ( )} diff --git a/packages/experimental/client-ui-forge/src/client/Forge.module.css b/packages/experimental/client-ui-forge/src/client/Forge.module.css index 002a582fb6..3b5b1312a2 100644 --- a/packages/experimental/client-ui-forge/src/client/Forge.module.css +++ b/packages/experimental/client-ui-forge/src/client/Forge.module.css @@ -217,12 +217,35 @@ color: var(--dsw-alias-label-tertiary); } -/* Only the branch names shorten; the number, checks, and flags keep whole words on one line. */ -.meta > :not(.ellipsis) { +/* Only the branch names and the collapsed status line shorten; the number, checks, and flags keep whole words on one line. */ +.meta > :not(.ellipsis):not(.statusLine) { flex: none; white-space: nowrap; } +/* The collapsed number and status: one line as wide as the row, so a change of its wording never resizes it. It clips + with an ellipsis and crawls with the title; its parts sit inline so the ellipsis cuts between characters. */ +.statusLine { + flex: 1; +} + +.statusLine .dot { + margin: 0 6px; +} + +.statusLine .ci { + display: inline; +} + +.statusLine .checkGlyph { + margin-inline-end: 5px; + vertical-align: -2px; +} + +.statusLine .flag { + margin-inline-start: 6px; +} + .finished { color: var(--dsw-alias-label-secondary); } diff --git a/packages/experimental/client-ui-forge/src/client/SessionHoverForge.tsx b/packages/experimental/client-ui-forge/src/client/SessionHoverForge.tsx index 5a4f69749e..0287d4380a 100644 --- a/packages/experimental/client-ui-forge/src/client/SessionHoverForge.tsx +++ b/packages/experimental/client-ui-forge/src/client/SessionHoverForge.tsx @@ -9,6 +9,7 @@ import { IconBranchOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' // Type-only: pulls the ui-workspace SlotMap merge (the Session row seats). import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' +import { branchLabel } from '../branch-name.ts' import { ChangeRequestGlyph } from './glyphs.tsx' import type { NS } from './locales.ts' import { useSessionForgeFacts, type SessionListInjected } from './session-list.ts' @@ -41,7 +42,7 @@ export function SessionHoverForge({ sessionId, useSessions, useStates, t }: Sess {worktree.branch} - {t('checkout.worktreeFrom', { base: worktree.from ?? worktree.baseCommit.slice(0, 7) })} + {t('checkout.worktreeFrom', { base: worktree.from === null ? worktree.baseCommit.slice(0, 7) : branchLabel(worktree.from) })}
    )} diff --git a/packages/experimental/client-ui-forge/src/client/WorktreeNameDialog.module.css b/packages/experimental/client-ui-forge/src/client/WorktreeNameDialog.module.css new file mode 100644 index 0000000000..d2c6ff08b8 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/WorktreeNameDialog.module.css @@ -0,0 +1,53 @@ +/* Naming dialog of a worktree branch: the Modal body's field, its message line, and the footer's left action. */ + +.form { + display: flex; + flex-direction: column; + gap: 6px; + min-width: 0; +} + +.label { + color: var(--dsw-alias-label-secondary); + font-size: 13px; + line-height: 20px; +} + +.field { + box-sizing: border-box; + width: 100%; +} + +.field input { + font-family: var(--ds-font-family-code); + font-size: 13px; +} + +.field.invalid, +.field.invalid:focus-within { + border-color: var(--dsw-alias-state-error-primary); +} + +/* Reserves two lines, so a longer reason replacing the hint does not move the footer. */ +.message { + min-height: 36px; + margin: 0; + color: var(--dsw-alias-label-tertiary); + font-size: 12px; + line-height: 18px; + overflow-wrap: anywhere; +} + +.error { + color: var(--dsw-alias-state-error-primary); +} + +.auto { + margin-right: auto; +} + +@media (pointer: coarse) { + .field input { + font-size: 16px; + } +} diff --git a/packages/experimental/client-ui-forge/src/client/WorktreeNameDialog.tsx b/packages/experimental/client-ui-forge/src/client/WorktreeNameDialog.tsx new file mode 100644 index 0000000000..ecba7f09a3 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/WorktreeNameDialog.tsx @@ -0,0 +1,93 @@ +/** Dialog that names the new branch of a requested worktree, from the New Session option or after a failed attempt. */ + +import { useId, useState, type ReactNode } from 'react' +import clsx from 'clsx' +import { Button, Input, Modal } from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import { branchLabel, branchNameProblem } from '../branch-name.ts' +import type { NS } from './locales.ts' +import css from './WorktreeNameDialog.module.css' + +/** + * Outcome of a worktree request: accepted; refused for its branch name, which the dialog shows; or failed otherwise, + * which the request reports itself. + */ +export type WorktreeRequestResult = 'accepted' | 'invalid-name' | 'branch-exists' | 'failed' + +/** Props of the naming dialog. */ +export interface WorktreeNameDialogProps extends PropsLocale { + /** `name` names the branch of the open request; `retry` renames it after a failed attempt, then tries again. */ + readonly mode: 'name' | 'retry' + /** Text the field starts with: the chosen name, or the prefix of generated names. */ + readonly initial: string + /** Prefix of generated names; a field that holds only the prefix names no branch yet. */ + readonly prefix: string + /** Base of the request, or null for HEAD. */ + readonly from: string | null + /** Whether the request already names its branch, which offers a return to generated names. */ + readonly named: boolean + /** + * Request the worktree on `name`, or on generated names for null; in `retry` mode the caller also tries again + * once the request is accepted. + */ + readonly submit: (name: string | null) => Promise + /** Close the dialog without a request. */ + readonly close: () => void +} + +/** + * Render the dialog: one branch name field checked against Git's branch-name rules while it is typed, and checked by + * the Host when it is confirmed. A refused name keeps the dialog open with the reason under the field; an accepted + * request closes it. + * @param props - mode, starting text, prefix, base, the request, and copy. + * @returns the dialog. + */ +export function WorktreeNameDialog({ mode, initial, prefix, from, named, submit, close, t }: WorktreeNameDialogProps): ReactNode { + const [value, setValue] = useState(initial) + const [refusal, setRefusal] = useState<{ readonly name: string; readonly text: string } | null>(null) + const [busy, setBusy] = useState(false) + const fieldId = useId() + const messageId = useId() + // The starting prefix names no branch yet, so it gets the hint rather than a rule it breaks, such as a trailing `/`. + const blank = value === prefix + const problem = blank ? null : branchNameProblem(value) + const error = problem !== null ? t(`branchName.${problem}`) : refusal?.name === value ? refusal.text : null + const retry = mode === 'retry' + const send = (name: string | null): void => { + setBusy(true) + void submit(name).then((result) => { + setBusy(false) + if (result === 'accepted') close() + else if (name !== null && result === 'branch-exists') setRefusal({ name, text: t('branchName.exists', { name }) }) + else if (name !== null && result === 'invalid-name') setRefusal({ name, text: t('branchName.invalid') }) + }) + } + const confirmable = !busy && error === null && !blank + const base = from === null ? null : branchLabel(from) + const hint = blank && prefix !== '' ? t('nameDialog.prefixOnly') : base === null ? t('nameDialog.hintHead') : t('nameDialog.hint', { branch: base }) + return ( + + {named && !retry && ( + + )} + + + }> +
    + + { setValue(event.target.value) }} + onKeyDown={(event) => { + if (event.key !== 'Enter' || event.nativeEvent.isComposing) return + event.preventDefault() + if (confirmable) send(value) + }} /> +

    {error ?? hint}

    +
    +
    + ) +} diff --git a/packages/experimental/client-ui-forge/src/client/WorktreeProgress.tsx b/packages/experimental/client-ui-forge/src/client/WorktreeProgress.tsx index bc3cc19c71..d5ccdc4eb1 100644 --- a/packages/experimental/client-ui-forge/src/client/WorktreeProgress.tsx +++ b/packages/experimental/client-ui-forge/src/client/WorktreeProgress.tsx @@ -11,9 +11,11 @@ import { import type { HostObservable, InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' import { assertNever } from '@deepseek-ai/dsh-util-values' +import { branchLabel } from '../branch-name.ts' import type { ForgeMissingWorktree, ForgePanelWorktree, ForgeSessionWorktree, ForgeWorktreeRestoration } from '../types.ts' import type { ForgePanelKey, NS } from './locales.ts' import type { PanelSnapshot } from './source.ts' +import { WorktreeNameDialog, type WorktreeRequestResult } from './WorktreeNameDialog.tsx' import css from './WorktreeProgress.module.css' /** Business face of the card. */ @@ -22,8 +24,18 @@ export interface WorktreeProgressInjected { readonly hooks: { readonly panel: HostObservable } /** Stop the running attempt a message waits for; the message keeps waiting. */ readonly stop: () => void - /** Make another attempt at the worktree a message waits for. */ - readonly retry: () => void + /** + * Make another attempt at the worktree a message waits for. + * @param fetch - false starts from the remote base branch as last fetched, without fetching it. + */ + readonly retry: (fetch: boolean) => void + /** + * Request the worktree again from the same base on another branch name, before another attempt. + * @param from - base of the open request, or null for HEAD. + * @param name - new branch name. + * @returns the outcome; a failure other than a refused name is already reported. + */ + readonly request: (from: string | null, name: string | null) => Promise /** Withdraw the worktree request, so the waiting message goes on without a worktree. */ readonly withdraw: () => void /** @@ -42,43 +54,57 @@ type Translate = WorktreeProgressProps['t'] type StepState = 'done' | 'running' | 'waiting' | 'failed' -type Phase = 'prepare' | 'checkout' +type Phase = 'fetch' | 'prepare' | 'checkout' -type StepList = readonly { readonly phase: Phase; readonly label: ForgePanelKey }[] +/** Steps in the order they run, each with its label. */ +type StepList = readonly { readonly phase: Phase; readonly label: ReactNode }[] -const CREATION_STEPS: StepList = [ - { phase: 'prepare', label: 'creation.prepare' }, - { phase: 'checkout', label: 'creation.checkout' }, -] - -const RESTORATION_STEPS: StepList = [ - { phase: 'prepare', label: 'restoration.prepare' }, - { phase: 'checkout', label: 'creation.checkout' }, -] - -function stepState(current: 'prepare' | 'checkout', failed: boolean, phase: 'prepare' | 'checkout'): StepState { - if (phase === current) return failed ? 'failed' : 'running' - return phase === 'prepare' ? 'done' : 'waiting' +function stepState(steps: StepList, current: Phase, failed: boolean, phase: Phase): StepState { + const at = steps.findIndex(step => step.phase === current) + const index = steps.findIndex(step => step.phase === phase) + if (index === at) return failed ? 'failed' : 'running' + return index < at ? 'done' : 'waiting' } -function Steps({ steps, phase, failed, t }: { +function Steps({ steps, phase, failed }: { readonly steps: StepList readonly phase: Phase readonly failed: boolean - readonly t: Translate }): ReactNode { return (
      - {steps.map(step => ( -
    • - - {t(step.label)} -
    • - ))} + {steps.map((step) => { + const state = stepState(steps, phase, failed, step.phase) + return ( +
    • + + {step.label} +
    • + ) + })}
    ) } +/** The steps of a creation, which fetches a remote base branch first when it asks to. */ +function creationSteps(creation: CreationView, t: Translate): StepList { + const from = creation.from === null ? null : branchLabel(creation.from) + return [ + ...creation.fetch && from !== null + ? [{ phase: 'fetch' as const, label: t('creation.fetch', { branch: from }) }] + : [], + { phase: 'prepare', label: t('creation.prepare') }, + { phase: 'checkout', label: t('creation.checkout') }, + ] +} + +function restorationSteps(t: Translate): StepList { + return [ + { phase: 'prepare', label: t('restoration.prepare') }, + { phase: 'checkout', label: t('creation.checkout') }, + ] +} + function StepIcon({ state }: { readonly state: StepState }): ReactNode { switch (state) { case 'done': return @@ -93,11 +119,15 @@ function StepIcon({ state }: { readonly state: StepState }): ReactNode { /** One creation as the card shows it: the running attempt, or the failed or stopped one a message waits after. */ interface CreationView { readonly state: 'running' | 'failed' | 'stopped' - readonly phase: 'prepare' | 'checkout' + readonly phase: Phase readonly branch: string | null readonly from: string | null + /** Whether the attempt fetches its remote base branch first. */ + readonly fetch: boolean /** Failure text, or null unless the attempt failed. */ readonly message: string | null + /** Whether the failed attempt found its branch or checkout directory taken. */ + readonly exists: boolean /** Whether a message waits for the running attempt, which can then be stopped. */ readonly held: boolean } @@ -105,10 +135,12 @@ interface CreationView { /** The running attempt, else the failed or stopped one a message waits after, or undefined without either. */ function creationOf(worktree: ForgePanelWorktree): CreationView | undefined { const { creation, failure, waiting } = worktree - if (creation !== null) return { ...creation, state: 'running', message: null } + if (creation !== null) return { ...creation, state: 'running', message: null, exists: false } if (waiting !== 'creation') return undefined if (failure !== null) return { ...failure, state: 'failed', held: false } - return { state: 'stopped', phase: 'prepare', branch: null, from: worktree.request?.from ?? null, message: null, held: false } + return { + state: 'stopped', phase: 'prepare', branch: null, from: worktree.request?.from ?? null, fetch: false, message: null, exists: false, held: false, + } } function Details({ creation, t }: { readonly creation: CreationView; readonly t: Translate }): ReactNode { @@ -121,7 +153,7 @@ function Details({ creation, t }: { readonly creation: CreationView; readonly t: )}
    {t('creation.base')}
    -
    {creation.from ?? t('creation.head')}
    +
    {creation.from === null ? t('creation.head') : branchLabel(creation.from)}
    {creation.message !== null && ( <>
    {t('creation.error')}
    @@ -138,17 +170,38 @@ const CREATION_TITLE: Record = { stopped: 'creation.stopped', } -function CreationCard({ creation, stop, retry, withdraw, t }: { +/** The buttons of a failed or stopped attempt before withdrawing; the first one is the primary action. */ +function waitingActions(creation: CreationView, named: boolean, retry: WorktreeProgressInjected['retry'], rename: () => void, t: Translate): ReactNode { + const again = { key: 'retry', label: t('creation.retry'), act: () => { retry(true) } } + const actions = creation.state === 'failed' && creation.phase === 'fetch' + ? [again, { key: 'fetched', label: t('creation.useFetched'), act: () => { retry(false) } }] + : creation.state === 'failed' && creation.exists && named + ? [{ key: 'rename', label: t('creation.rename'), act: rename }, again] + : [again] + return actions.map((action, index) => ( + + )) +} + +function CreationCard({ creation, open: openRequest, prefix, stop, retry, withdraw, request, t }: { readonly creation: CreationView + /** The open request, whose base a rename keeps and whose branch name it replaces. */ + readonly open: ForgePanelWorktree['request'] + /** Prefix of generated branch names. */ + readonly prefix: string readonly stop: WorktreeProgressInjected['stop'] readonly retry: WorktreeProgressInjected['retry'] readonly withdraw: WorktreeProgressInjected['withdraw'] + readonly request: WorktreeProgressInjected['request'] readonly t: Translate }): ReactNode { const [open, setOpen] = useState(false) + const [renaming, setRenaming] = useState(false) const running = creation.state === 'running' const failed = creation.state === 'failed' const title = t(CREATION_TITLE[creation.state]) + const name = openRequest?.name ?? null + const from = openRequest?.from ?? null return (
    @@ -157,7 +210,7 @@ function CreationCard({ creation, stop, retry, withdraw, t }: { {title} {creation.branch !== null && {creation.branch}}
    - {creation.state !== 'stopped' && } + {creation.state !== 'stopped' && } {(open || failed) &&
    } {!running &&

    {t('creation.waiting')}

    }
    @@ -169,7 +222,7 @@ function CreationCard({ creation, stop, retry, withdraw, t }: { )} {!running && ( - + {waitingActions(creation, name !== null, retry, () => { setRenaming(true) }, t)} )} @@ -180,6 +233,15 @@ function CreationCard({ creation, stop, retry, withdraw, t }: { )}
    + {renaming && name !== null && ( + { + const result = await request(from, next) + if (result === 'accepted') retry(true) + return result + }} + close={() => { setRenaming(false) }} t={t} /> + )}
    ) } @@ -222,7 +284,7 @@ function MissingCard({ created, missing, restoration, waiting, restore, leave, t {t('restoration.title')} {created.branch}
    - + ) @@ -260,11 +322,14 @@ function MissingCard({ created, missing, restoration, waiting, restore, leave, t * @param props - panel hook, actions, and copy. * @returns the card, or nothing while no attempt runs, no message waits, and the worktree exists. */ -export function WorktreeProgress({ usePanel, stop, retry, withdraw, restore, leave, t }: WorktreeProgressProps): ReactNode { +export function WorktreeProgress({ usePanel, stop, retry, withdraw, request, restore, leave, t }: WorktreeProgressProps): ReactNode { const worktree = usePanel(snapshot => snapshot.state?.worktree ?? null) if (worktree === null) return null const creation = creationOf(worktree) - if (creation !== undefined) return + if (creation !== undefined) { + return + } if (worktree.missing === null || worktree.created === null) return null return ( } /** - * Request a worktree from a base branch, replacing an open request. - * @param from - base branch, or null for HEAD. - * @returns whether the Host accepted it. + * Request a worktree from a base on a branch name, replacing an open request. + * @param from - full name of a local or remote-tracking base branch, or null for HEAD. + * @param name - new branch name, or null for a generated one. + * @returns the outcome; a failure other than a refused name is already reported. */ - readonly request: (from: string | null) => Promise + readonly request: (from: string | null, name: string | null) => Promise /** * Withdraw the open request. * @returns whether the Host accepted it. */ readonly cancel: () => Promise /** - * List the local branches of the Session's checkout. - * @returns the branches, or undefined when they could not be read. + * List the branches a worktree of the Session's checkout can start from whose names contain `query`. + * @param query - search text; empty for every branch. + * @param signal - aborts the read. + * @returns the branches, or the failure the menu shows. */ - readonly branches: () => Promise + readonly bases: (query: string, signal: AbortSignal) => Promise> } /** Full props of the New Session option. */ @@ -38,59 +48,156 @@ export type WorktreeToggleProps = InjectFace & PropsLoca type Translate = WorktreeToggleProps['t'] -function BaseMenu({ base, held, branches, request, t }: { - readonly base: string | null - /** Whether the worktree is being created, which freezes the base. */ +/** One selectable branch row: the branch, the remote it belongs to, and the tag that names a pinned row. */ +interface BaseRow { + readonly branch: ForgeBaseBranch + readonly remote?: string + readonly tag?: string +} + +/** What the option says about a request's base. */ +function baseTextOf(from: string | null, t: Translate): string { + return from === null ? t('worktree.baseHead') : t('worktree.base', { branch: branchLabel(from) }) +} + +/** What the option says about a request that names its branch. */ +function namedTipOf(name: string, from: string | null, t: Translate): string { + return from === null ? t('worktree.namedTipHead', { name }) : t('worktree.namedTip', { name, branch: branchLabel(from) }) +} + +/** The full name of a request's base; earlier panels recorded local branches by their short names. */ +function refOf(from: string | null): string | null { + return from === null || from.startsWith('refs/') ? from : `${LOCAL_REF_PREFIX}${from}` +} + +/** A branch name split into a remote's prefix and the rest; local branches have no prefix. */ +function nameParts(branch: ForgeBaseBranch, remote: string | undefined): { readonly prefix: string; readonly rest: string } { + return remote !== undefined && branch.ref.startsWith(REMOTE_REF_PREFIX) + ? { prefix: `${remote}/`, rest: branch.name.slice(remote.length + 1) } + : { prefix: '', rest: branch.name } +} + +function BranchRows({ rows, chosen, pick }: { + readonly rows: readonly BaseRow[] + readonly chosen: string | null + readonly pick: (ref: string) => void +}): ReactNode { + return rows.map(({ branch, remote, tag }) => { + const selected = branch.ref === chosen + const parts = nameParts(branch, remote) + return ( + } current={selected} + onSelect={() => { pick(branch.ref) }}> + + + {parts.prefix !== '' && {parts.prefix}} + {parts.rest} + + {tag !== undefined && {tag}} + {selected && } + + + ) + }) +} + +function WorktreeMenu({ from, name, held, bases, choose, nameBranch, t }: { + readonly from: string | null + readonly name: string | null + /** Whether the worktree is being created, which freezes the request. */ readonly held: boolean - readonly branches: WorktreeToggleInjected['branches'] - readonly request: WorktreeToggleInjected['request'] + readonly bases: WorktreeToggleInjected['bases'] + readonly choose: (ref: string) => void + readonly nameBranch: () => void readonly t: Translate }): ReactNode { - const [listed, setListed] = useState(null) const [open, setOpen] = useState(false) - const [loading, setLoading] = useState(false) - const show = (): void => { - if (open) { - setOpen(false) - return - } - setLoading(true) - void branches().then((result) => { - setLoading(false) - if (result === undefined) return - setListed(result) - setOpen(true) - }) + const { query, setQuery, listing, retry, reset, field } = useBranchSearch(open, bases) + const chosen = refOf(from) + const close = (): void => { + setOpen(false) + reset() } - const items: MenuEntry[] = [ - { type: 'label', id: 'title', text: t('worktree.baseMenu') }, - ...(listed?.branches ?? []).map(name => ({ - id: name, - label: name === listed?.current - ? {name}{t('worktree.currentBranch')} - : {name}, - })), - ] + const pick = (ref: string): void => { + close() + if (ref !== chosen) choose(ref) + } + const value = listing?.ok === true ? listing.value : null + const needle = query.trim().toLowerCase() + const matches = (branch: ForgeBaseBranch): boolean => branch.name.toLowerCase().includes(needle) + const pinned: BaseRow[] = value === null ? [] : [ + ...value.current === null ? [] : [{ branch: value.current, tag: t('worktree.currentBranch') }], + ...value.defaults.map(({ remote, ...branch }) => ({ branch, remote, tag: t('worktree.remoteDefault') })), + ].filter(row => matches(row.branch)) + const local = (value?.local ?? []).filter(matches).map(branch => ({ branch })) + const remotes = (value?.remotes ?? []).map(remote => ({ + ...remote, rows: remote.branches.filter(matches).map(branch => ({ branch, remote: remote.name })), + })) + .filter(remote => remote.rows.length > 0) + const first = pinned[0] ?? local[0] ?? remotes[0]?.rows[0] + + const body: ReactNode = branchSearchStatus({ listing, empty: first === undefined, retry, className: css.status, t }) ?? <> + {pinned.length > 0 &&
    } + {local.length > 0 && ( +
    +
    {t('diff.base.local')}
    + +
    + )} + {remotes.map(remote => ( +
    +
    + {t('worktree.remoteGroup', { remote: remote.name })} + {remote.repository !== null && {remote.repository}} +
    + +
    + ))} + + + const baseText = baseTextOf(from, t) + const label = name === null ? baseText : namedTipOf(name, from, t) return ( { - setOpen(false) - if (id !== base) void request(id) - }} - onClose={() => { setOpen(false) }} side="bottom" align="end" portal + dense + className={css.anchor} + listClassName={css.menu} + onClose={close} anchor={ - + + + } - /> + > +
    +
    + } value={query} + aria-label={t('diff.base.search')} placeholder={t('diff.base.search')} + onChange={(event) => { setQuery(event.target.value) }} + onKeyDown={(event) => { searchFieldKeyDown(event, first === undefined ? undefined : () => { pick(first.branch.ref) }) }} /> +
    +
    {body}
    +
    + : } + onSelect={() => { close(); nameBranch() }}> + + {t(name === null ? 'worktree.name.add' : 'worktree.name.label')} + {name ?? t('worktree.name.auto')} + + +
    +
    +
    ) } @@ -110,35 +217,42 @@ function optionOf(state: ForgePanelState | null): { /** * Render the worktree option while the Session can still start in a worktree: - * the current branch, or the base branch menu once requested, then the checkbox. - * A blocked request keeps its selected base visible without a menu; the checkbox - * only withdraws it. Branch details support pointer, touch, and keyboard access. - * The request stays fixed while the worktree is being created. - * @param props - panel snapshot hook, request actions, and copy. + * the current branch, or the base and branch name menu once requested, then the + * checkbox. The menu searches local branches and each remote's branches and + * opens the naming dialog. A blocked request keeps its selected base visible + * without a menu; the checkbox only withdraws it. Branch details support + * pointer, touch, and keyboard access. The request stays fixed while the + * worktree is being created. + * @param props - panel snapshot hook, request actions, the base listing, and copy. * @returns the option, or nothing outside a known Git checkout, once a turn started, * the request settled, or no worktree service is mounted. */ -export function WorktreeToggle({ usePanel, request, cancel, branches, t }: WorktreeToggleProps): ReactNode { +export function WorktreeToggle({ usePanel, request, cancel, bases, t }: WorktreeToggleProps): ReactNode { const state = usePanel(snapshot => snapshot.state) const [pending, setPending] = useState(null) + const [naming, setNaming] = useState(false) const option = optionOf(state) if (state === null || option === undefined) return null const held = state.worktree.creation !== null const requested = pending ?? state.worktree.request !== null const usable = option.blocker === null const disabled = held || pending !== null || (!usable && !requested) + const currentRef = option.current === null ? null : `${LOCAL_REF_PREFIX}${option.current}` const current = option.current ?? (option.commit === null ? t('checkout.detached') : t('worktree.detachedTip', { commit: option.commit })) - const base = state.worktree.request === null ? option.current : state.worktree.request.from - const branchText = requested ? base === null ? t('worktree.baseHead') : t('worktree.base', { branch: base }) : current + const from = state.worktree.request === null ? currentRef : state.worktree.request.from + const name = state.worktree.request?.name ?? null + const requestedText = name === null ? baseTextOf(from, t) : namedTipOf(name, from, t) + const branchText = requested ? requestedText : current const branchTip = requested || option.current === null ? branchText : t('worktree.currentBranchTip', { branch: option.current }) const change = (checked: boolean): void => { setPending(checked) - void (checked ? request(option.current) : cancel()).then(() => { setPending(null) }) + void (checked ? request(currentRef, null) : cancel()).then(() => { setPending(null) }) } return ( {requested && usable ? ( - + { void request(ref, name) }} nameBranch={() => { setNaming(true) }} /> ) : ( + + ) + } + return empty ?
    {t('diff.base.empty')}
    : null +} diff --git a/packages/experimental/client-ui-forge/src/client/checkout.ts b/packages/experimental/client-ui-forge/src/client/checkout.ts index 1e2a9d4684..d7a390c109 100644 --- a/packages/experimental/client-ui-forge/src/client/checkout.ts +++ b/packages/experimental/client-ui-forge/src/client/checkout.ts @@ -2,6 +2,7 @@ import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import { abbreviateHomePath } from '@deepseek-ai/dsh-util-workspace-path' +import { branchLabel } from '../branch-name.ts' import type { ForgePanelState } from '../types.ts' import type { NS } from './locales.ts' @@ -52,7 +53,7 @@ export function checkoutLabel(state: ForgePanelState, home: string | undefined, const { root, branch, linked, commit } = state.checkout.checkout const path = abbreviateHomePath(root, home) if (created !== null && created.path === root) { - const base = created.from ?? created.baseCommit.slice(0, 7) + const base = created.from === null ? created.baseCommit.slice(0, 7) : branchLabel(created.from) return { name: branch ?? commit, detached: branch === null, diff --git a/packages/experimental/client-ui-forge/src/client/locales.ts b/packages/experimental/client-ui-forge/src/client/locales.ts index a93ae5afd7..a2a27a90d9 100644 --- a/packages/experimental/client-ui-forge/src/client/locales.ts +++ b/packages/experimental/client-ui-forge/src/client/locales.ts @@ -330,7 +330,6 @@ export const zh = { 'worktree.blocked.read-only': '只读模式下无法使用工作树', 'worktree.base': '基于 {branch}', 'worktree.baseHead': '基于当前 HEAD', - 'worktree.baseMenu': '选择基准分支', 'worktree.currentBranch': '当前分支', 'worktree.currentBranchTip': '当前分支:{branch}', 'worktree.detachedTip': '未在分支上 · {commit}', @@ -347,6 +346,45 @@ export const zh = { 'creation.cancel': '取消', 'creation.stopped': '已停止创建工作树', 'creation.retry': '重试', + 'diff.loading': '正在读取变更…', + 'diff.allFilesLoading': '全部文件', + 'worktree.pinned': '当前分支与远程默认分支', + 'worktree.remoteDefault': '远程默认', + 'worktree.remoteGroup': '远程 · {remote}', + 'worktree.namedTip': '新分支 {name},基于 {branch}', + 'worktree.namedTipHead': '新分支 {name},基于当前 HEAD', + 'worktree.name.add': '指定新分支名称…', + 'worktree.name.label': '新分支名称', + 'worktree.name.auto': '自动命名', + 'nameDialog.title': '命名新分支', + 'nameDialog.retryTitle': '更改分支名称', + 'nameDialog.field': '分支名称', + 'nameDialog.hint': '发送第一条消息时基于 {branch} 新建此分支,工作树目录与分支同名', + 'nameDialog.hintHead': '发送第一条消息时基于当前 HEAD 新建此分支,工作树目录与分支同名', + 'nameDialog.prefixOnly': '在前缀后输入名称', + 'nameDialog.auto': '改回自动命名', + 'nameDialog.cancel': '取消', + 'nameDialog.confirm': '确定', + 'nameDialog.retry': '重试', + 'nameDialog.close': '关闭', + 'branchName.empty': '输入分支名称', + 'branchName.space': '分支名不能包含空格', + 'branchName.character': '分支名不能包含 ~ ^ : ? * [ \\ 这些字符', + 'branchName.leading-dash': '分支名不能以“-”开头', + 'branchName.leading-slash': '分支名不能以“/”开头', + 'branchName.trailing-slash': '分支名不能以“/”结尾', + 'branchName.double-slash': '分支名不能包含连续的“/”', + 'branchName.double-dot': '分支名不能包含“..”', + 'branchName.trailing-dot': '分支名不能以“.”结尾', + 'branchName.at': '分支名不能是“@”', + 'branchName.at-brace': '分支名不能包含“@{”', + 'branchName.dot-segment': '“/”分隔的每一段都不能以“.”开头', + 'branchName.lock-segment': '“/”分隔的每一段都不能以“.lock”结尾', + 'branchName.exists': '分支 {name} 已存在', + 'branchName.invalid': 'Git 不接受这个分支名', + 'creation.fetch': '获取 {branch}', + 'creation.useFetched': '使用上次获取的版本', + 'creation.rename': '更改名称', 'creation.waiting': '消息会在工作树建好后发送', 'missing.title': '工作树不可用', 'missing.unknown': '工作树恢复尚未完成,暂时无法确认分支 {branch} 的状态。请排除恢复错误后重试,或在项目目录继续', @@ -780,7 +818,6 @@ export const en: Record = { 'worktree.blocked.read-only': 'A read-only Session cannot use a worktree', 'worktree.base': 'From {branch}', 'worktree.baseHead': 'From the current HEAD', - 'worktree.baseMenu': 'Base branch', 'worktree.currentBranch': 'Current', 'worktree.currentBranchTip': 'Current branch: {branch}', 'worktree.detachedTip': 'Not on a branch · {commit}', @@ -797,6 +834,45 @@ export const en: Record = { 'creation.cancel': 'Cancel', 'creation.stopped': 'Worktree creation stopped', 'creation.retry': 'Retry', + 'diff.loading': 'Reading changes…', + 'diff.allFilesLoading': 'All files', + 'worktree.pinned': 'Current and remote default branches', + 'worktree.remoteDefault': 'Remote default', + 'worktree.remoteGroup': 'Remote · {remote}', + 'worktree.namedTip': 'New branch {name} from {branch}', + 'worktree.namedTipHead': 'New branch {name} from the current HEAD', + 'worktree.name.add': 'Name the new branch…', + 'worktree.name.label': 'New branch name', + 'worktree.name.auto': 'Generated', + 'nameDialog.title': 'Name the new branch', + 'nameDialog.retryTitle': 'Rename the branch', + 'nameDialog.field': 'Branch name', + 'nameDialog.hint': 'The first message creates this branch from {branch}; the worktree directory takes its name', + 'nameDialog.hintHead': 'The first message creates this branch from the current HEAD; the worktree directory takes its name', + 'nameDialog.prefixOnly': 'Type a name after the prefix', + 'nameDialog.auto': 'Use a generated name', + 'nameDialog.cancel': 'Cancel', + 'nameDialog.confirm': 'Save', + 'nameDialog.retry': 'Retry', + 'nameDialog.close': 'Close', + 'branchName.empty': 'Enter a branch name', + 'branchName.space': 'Branch names cannot contain spaces', + 'branchName.character': 'Branch names cannot contain ~ ^ : ? * [ or \\', + 'branchName.leading-dash': 'Branch names cannot start with “-”', + 'branchName.leading-slash': 'Branch names cannot start with “/”', + 'branchName.trailing-slash': 'Branch names cannot end with “/”', + 'branchName.double-slash': 'Branch names cannot contain “//”', + 'branchName.double-dot': 'Branch names cannot contain “..”', + 'branchName.trailing-dot': 'Branch names cannot end with “.”', + 'branchName.at': 'A branch cannot be named “@”', + 'branchName.at-brace': 'Branch names cannot contain “@{”', + 'branchName.dot-segment': 'No part between slashes can start with “.”', + 'branchName.lock-segment': 'No part between slashes can end with “.lock”', + 'branchName.exists': 'A branch named {name} already exists', + 'branchName.invalid': 'Git does not accept this branch name', + 'creation.fetch': 'Fetch {branch}', + 'creation.useFetched': 'Use the last fetched version', + 'creation.rename': 'Rename', 'creation.waiting': 'The message is sent once the worktree exists', 'missing.title': 'The worktree is unavailable', 'missing.unknown': 'Worktree restoration is incomplete and branch {branch} cannot be inspected. Resolve the restoration error and retry, or continue in the project.', @@ -1234,7 +1310,6 @@ export const ja: Record = { 'worktree.blocked.read-only': '読み取り専用のセッションではワークツリーを使用できません', 'worktree.base': '基点 {branch}', 'worktree.baseHead': '現在の HEAD を基点にする', - 'worktree.baseMenu': '基準ブランチ', 'worktree.currentBranch': '現在', 'worktree.currentBranchTip': '現在のブランチ:{branch}', 'worktree.detachedTip': 'ブランチ上にありません · {commit}', @@ -1251,6 +1326,45 @@ export const ja: Record = { 'creation.cancel': 'キャンセル', 'creation.stopped': 'ワークツリーの作成を停止しました', 'creation.retry': '再試行', + 'diff.loading': '変更を読み取り中…', + 'diff.allFilesLoading': 'すべてのファイル', + 'worktree.pinned': '現在のブランチとリモートのデフォルト', + 'worktree.remoteDefault': 'リモートのデフォルト', + 'worktree.remoteGroup': 'リモート · {remote}', + 'worktree.namedTip': '新しいブランチ {name}、基点 {branch}', + 'worktree.namedTipHead': '新しいブランチ {name}、基点は現在の HEAD', + 'worktree.name.add': '新しいブランチに名前を付ける…', + 'worktree.name.label': '新しいブランチ名', + 'worktree.name.auto': '自動生成', + 'nameDialog.title': '新しいブランチに名前を付ける', + 'nameDialog.retryTitle': 'ブランチ名を変更', + 'nameDialog.field': 'ブランチ名', + 'nameDialog.hint': '最初のメッセージの送信時に {branch} からこのブランチを作成し、ワークツリーのディレクトリも同じ名前になります', + 'nameDialog.hintHead': '最初のメッセージの送信時に現在の HEAD からこのブランチを作成し、ワークツリーのディレクトリも同じ名前になります', + 'nameDialog.prefixOnly': 'プレフィックスの後に名前を入力してください', + 'nameDialog.auto': '自動生成の名前に戻す', + 'nameDialog.cancel': 'キャンセル', + 'nameDialog.confirm': '保存', + 'nameDialog.retry': '再試行', + 'nameDialog.close': '閉じる', + 'branchName.empty': 'ブランチ名を入力してください', + 'branchName.space': 'ブランチ名に空白は使えません', + 'branchName.character': 'ブランチ名に ~ ^ : ? * [ \\ は使えません', + 'branchName.leading-dash': 'ブランチ名を「-」で始めることはできません', + 'branchName.leading-slash': 'ブランチ名を「/」で始めることはできません', + 'branchName.trailing-slash': 'ブランチ名を「/」で終えることはできません', + 'branchName.double-slash': 'ブランチ名に「//」は使えません', + 'branchName.double-dot': 'ブランチ名に「..」は使えません', + 'branchName.trailing-dot': 'ブランチ名を「.」で終えることはできません', + 'branchName.at': 'ブランチ名を「@」にすることはできません', + 'branchName.at-brace': 'ブランチ名に「@{」は使えません', + 'branchName.dot-segment': '「/」で区切った各部分を「.」で始めることはできません', + 'branchName.lock-segment': '「/」で区切った各部分を「.lock」で終えることはできません', + 'branchName.exists': 'ブランチ {name} はすでに存在します', + 'branchName.invalid': 'Git がこのブランチ名を受け付けません', + 'creation.fetch': '{branch} を取得', + 'creation.useFetched': '前回取得したバージョンを使う', + 'creation.rename': '名前を変更', 'creation.waiting': 'ワークツリーの作成後にメッセージを送信します', 'missing.title': 'ワークツリーを利用できません', 'missing.unknown': 'ワークツリーの復元が未完了のため、ブランチ {branch} を確認できません。復元エラーを解消して再試行するか、プロジェクトで続行してください', @@ -1681,7 +1795,6 @@ export const es: Record = { 'worktree.blocked.read-only': 'Una sesión de solo lectura no puede usar un árbol de trabajo', 'worktree.base': 'Desde {branch}', 'worktree.baseHead': 'Desde el HEAD actual', - 'worktree.baseMenu': 'Rama base', 'worktree.currentBranch': 'Actual', 'worktree.currentBranchTip': 'Rama actual: {branch}', 'worktree.detachedTip': 'Sin rama activa · {commit}', @@ -1698,6 +1811,45 @@ export const es: Record = { 'creation.cancel': 'Cancelar', 'creation.stopped': 'Creación del árbol de trabajo detenida', 'creation.retry': 'Reintentar', + 'diff.loading': 'Leyendo los cambios…', + 'diff.allFilesLoading': 'Todos los archivos', + 'worktree.pinned': 'Rama actual y ramas predeterminadas remotas', + 'worktree.remoteDefault': 'Predeterminada remota', + 'worktree.remoteGroup': 'Remoto · {remote}', + 'worktree.namedTip': 'Rama nueva {name} desde {branch}', + 'worktree.namedTipHead': 'Rama nueva {name} desde el HEAD actual', + 'worktree.name.add': 'Poner nombre a la rama nueva…', + 'worktree.name.label': 'Nombre de la rama nueva', + 'worktree.name.auto': 'Generado', + 'nameDialog.title': 'Poner nombre a la rama nueva', + 'nameDialog.retryTitle': 'Cambiar el nombre de la rama', + 'nameDialog.field': 'Nombre de la rama', + 'nameDialog.hint': 'El primer mensaje crea esta rama desde {branch}; el directorio del árbol de trabajo toma su nombre', + 'nameDialog.hintHead': 'El primer mensaje crea esta rama desde el HEAD actual; el directorio del árbol de trabajo toma su nombre', + 'nameDialog.prefixOnly': 'Escribe un nombre después del prefijo', + 'nameDialog.auto': 'Usar un nombre generado', + 'nameDialog.cancel': 'Cancelar', + 'nameDialog.confirm': 'Guardar', + 'nameDialog.retry': 'Reintentar', + 'nameDialog.close': 'Cerrar', + 'branchName.empty': 'Escribe un nombre de rama', + 'branchName.space': 'El nombre de una rama no puede contener espacios', + 'branchName.character': 'El nombre de una rama no puede contener ~ ^ : ? * [ ni \\', + 'branchName.leading-dash': 'El nombre de una rama no puede empezar por «-»', + 'branchName.leading-slash': 'El nombre de una rama no puede empezar por «/»', + 'branchName.trailing-slash': 'El nombre de una rama no puede terminar en «/»', + 'branchName.double-slash': 'El nombre de una rama no puede contener «//»', + 'branchName.double-dot': 'El nombre de una rama no puede contener «..»', + 'branchName.trailing-dot': 'El nombre de una rama no puede terminar en «.»', + 'branchName.at': 'Una rama no puede llamarse «@»', + 'branchName.at-brace': 'El nombre de una rama no puede contener «@{»', + 'branchName.dot-segment': 'Ninguna parte entre barras puede empezar por «.»', + 'branchName.lock-segment': 'Ninguna parte entre barras puede terminar en «.lock»', + 'branchName.exists': 'Ya existe una rama llamada {name}', + 'branchName.invalid': 'Git no acepta este nombre de rama', + 'creation.fetch': 'Obtener {branch}', + 'creation.useFetched': 'Usar la última versión obtenida', + 'creation.rename': 'Cambiar nombre', 'creation.waiting': 'El mensaje se enviará cuando exista el árbol de trabajo', 'missing.title': 'El árbol de trabajo no está disponible', 'missing.unknown': 'La restauración está incompleta y no se puede consultar la rama {branch}. Resuelve el error y reintenta, o continúa en el proyecto', @@ -2128,7 +2280,6 @@ export const fr: Record = { 'worktree.blocked.read-only': 'Une session en lecture seule ne peut pas utiliser d’arbre de travail', 'worktree.base': 'Depuis {branch}', 'worktree.baseHead': 'Depuis le HEAD actuel', - 'worktree.baseMenu': 'Branche de base', 'worktree.currentBranch': 'Actuelle', 'worktree.currentBranchTip': 'Branche actuelle : {branch}', 'worktree.detachedTip': 'Aucune branche active · {commit}', @@ -2145,6 +2296,45 @@ export const fr: Record = { 'creation.cancel': 'Annuler', 'creation.stopped': 'Création de l’arbre de travail arrêtée', 'creation.retry': 'Réessayer', + 'diff.loading': 'Lecture des modifications…', + 'diff.allFilesLoading': 'Tous les fichiers', + 'worktree.pinned': 'Branche actuelle et branches par défaut des dépôts distants', + 'worktree.remoteDefault': 'Par défaut distante', + 'worktree.remoteGroup': 'Distant · {remote}', + 'worktree.namedTip': 'Nouvelle branche {name} depuis {branch}', + 'worktree.namedTipHead': 'Nouvelle branche {name} depuis le HEAD actuel', + 'worktree.name.add': 'Nommer la nouvelle branche…', + 'worktree.name.label': 'Nom de la nouvelle branche', + 'worktree.name.auto': 'Généré', + 'nameDialog.title': 'Nommer la nouvelle branche', + 'nameDialog.retryTitle': 'Renommer la branche', + 'nameDialog.field': 'Nom de la branche', + 'nameDialog.hint': 'Le premier message crée cette branche depuis {branch} ; le répertoire de l’arbre de travail prend son nom', + 'nameDialog.hintHead': 'Le premier message crée cette branche depuis le HEAD actuel ; le répertoire de l’arbre de travail prend son nom', + 'nameDialog.prefixOnly': 'Saisissez un nom après le préfixe', + 'nameDialog.auto': 'Utiliser un nom généré', + 'nameDialog.cancel': 'Annuler', + 'nameDialog.confirm': 'Enregistrer', + 'nameDialog.retry': 'Réessayer', + 'nameDialog.close': 'Fermer', + 'branchName.empty': 'Saisissez un nom de branche', + 'branchName.space': 'Un nom de branche ne peut pas contenir d’espaces', + 'branchName.character': 'Un nom de branche ne peut pas contenir ~ ^ : ? * [ ni \\', + 'branchName.leading-dash': 'Un nom de branche ne peut pas commencer par « - »', + 'branchName.leading-slash': 'Un nom de branche ne peut pas commencer par « / »', + 'branchName.trailing-slash': 'Un nom de branche ne peut pas finir par « / »', + 'branchName.double-slash': 'Un nom de branche ne peut pas contenir « // »', + 'branchName.double-dot': 'Un nom de branche ne peut pas contenir « .. »', + 'branchName.trailing-dot': 'Un nom de branche ne peut pas finir par « . »', + 'branchName.at': 'Une branche ne peut pas s’appeler « @ »', + 'branchName.at-brace': 'Un nom de branche ne peut pas contenir « @{ »', + 'branchName.dot-segment': 'Aucune partie entre barres obliques ne peut commencer par « . »', + 'branchName.lock-segment': 'Aucune partie entre barres obliques ne peut finir par « .lock »', + 'branchName.exists': 'Une branche nommée {name} existe déjà', + 'branchName.invalid': 'Git refuse ce nom de branche', + 'creation.fetch': 'Récupérer {branch}', + 'creation.useFetched': 'Utiliser la dernière version récupérée', + 'creation.rename': 'Renommer', 'creation.waiting': 'Le message sera envoyé après la création de l’arbre de travail', 'missing.title': 'L’arbre de travail est indisponible', 'missing.unknown': 'La restauration est incomplète et la branche {branch} ne peut pas être inspectée. Corrigez l’erreur puis réessayez, ou continuez dans le projet', @@ -2575,7 +2765,6 @@ export const de: Record = { 'worktree.blocked.read-only': 'Eine schreibgeschützte Sitzung kann keinen Arbeitsbaum verwenden', 'worktree.base': 'Aus {branch}', 'worktree.baseHead': 'Aus dem aktuellen HEAD', - 'worktree.baseMenu': 'Basis-Branch', 'worktree.currentBranch': 'Aktuell', 'worktree.currentBranchTip': 'Aktueller Branch: {branch}', 'worktree.detachedTip': 'Auf keinem Branch · {commit}', @@ -2592,6 +2781,45 @@ export const de: Record = { 'creation.cancel': 'Abbrechen', 'creation.stopped': 'Erstellung des Arbeitsbaums angehalten', 'creation.retry': 'Erneut versuchen', + 'diff.loading': 'Änderungen werden gelesen…', + 'diff.allFilesLoading': 'Alle Dateien', + 'worktree.pinned': 'Aktueller Branch und Standard-Branches der Remotes', + 'worktree.remoteDefault': 'Remote-Standard', + 'worktree.remoteGroup': 'Remote · {remote}', + 'worktree.namedTip': 'Neuer Branch {name} aus {branch}', + 'worktree.namedTipHead': 'Neuer Branch {name} aus dem aktuellen HEAD', + 'worktree.name.add': 'Neuen Branch benennen…', + 'worktree.name.label': 'Name des neuen Branches', + 'worktree.name.auto': 'Generiert', + 'nameDialog.title': 'Neuen Branch benennen', + 'nameDialog.retryTitle': 'Branch umbenennen', + 'nameDialog.field': 'Branch-Name', + 'nameDialog.hint': 'Die erste Nachricht erstellt diesen Branch aus {branch}; das Arbeitsbaumverzeichnis erhält denselben Namen', + 'nameDialog.hintHead': 'Die erste Nachricht erstellt diesen Branch aus dem aktuellen HEAD; das Arbeitsbaumverzeichnis erhält denselben Namen', + 'nameDialog.prefixOnly': 'Namen nach dem Präfix eingeben', + 'nameDialog.auto': 'Generierten Namen verwenden', + 'nameDialog.cancel': 'Abbrechen', + 'nameDialog.confirm': 'Speichern', + 'nameDialog.retry': 'Erneut versuchen', + 'nameDialog.close': 'Schließen', + 'branchName.empty': 'Branch-Namen eingeben', + 'branchName.space': 'Branch-Namen dürfen keine Leerzeichen enthalten', + 'branchName.character': 'Branch-Namen dürfen ~ ^ : ? * [ und \\ nicht enthalten', + 'branchName.leading-dash': 'Branch-Namen dürfen nicht mit „-“ beginnen', + 'branchName.leading-slash': 'Branch-Namen dürfen nicht mit „/“ beginnen', + 'branchName.trailing-slash': 'Branch-Namen dürfen nicht auf „/“ enden', + 'branchName.double-slash': 'Branch-Namen dürfen „//“ nicht enthalten', + 'branchName.double-dot': 'Branch-Namen dürfen „..“ nicht enthalten', + 'branchName.trailing-dot': 'Branch-Namen dürfen nicht auf „.“ enden', + 'branchName.at': 'Ein Branch darf nicht „@“ heißen', + 'branchName.at-brace': 'Branch-Namen dürfen „@{“ nicht enthalten', + 'branchName.dot-segment': 'Kein Teil zwischen Schrägstrichen darf mit „.“ beginnen', + 'branchName.lock-segment': 'Kein Teil zwischen Schrägstrichen darf auf „.lock“ enden', + 'branchName.exists': 'Ein Branch namens {name} existiert bereits', + 'branchName.invalid': 'Git akzeptiert diesen Branch-Namen nicht', + 'creation.fetch': '{branch} abrufen', + 'creation.useFetched': 'Zuletzt abgerufene Version verwenden', + 'creation.rename': 'Umbenennen', 'creation.waiting': 'Die Nachricht wird gesendet, sobald der Arbeitsbaum erstellt ist', 'missing.title': 'Arbeitsbaum nicht verfügbar', 'missing.unknown': 'Die Wiederherstellung ist unvollständig und Branch {branch} kann nicht geprüft werden. Den Fehler beheben und erneut versuchen oder im Projekt fortfahren', @@ -3022,7 +3250,6 @@ export const ru: Record = { 'worktree.blocked.read-only': 'Сеанс только для чтения не может использовать рабочее дерево', 'worktree.base': 'На основе {branch}', 'worktree.baseHead': 'На основе текущего HEAD', - 'worktree.baseMenu': 'Базовая ветка', 'worktree.currentBranch': 'Текущая', 'worktree.currentBranchTip': 'Текущая ветка: {branch}', 'worktree.detachedTip': 'Вне ветки · {commit}', @@ -3039,6 +3266,45 @@ export const ru: Record = { 'creation.cancel': 'Отмена', 'creation.stopped': 'Создание рабочего дерева остановлено', 'creation.retry': 'Повторить', + 'diff.loading': 'Чтение изменений…', + 'diff.allFilesLoading': 'Все файлы', + 'worktree.pinned': 'Текущая ветка и ветки по умолчанию удалённых репозиториев', + 'worktree.remoteDefault': 'По умолчанию на удалённом', + 'worktree.remoteGroup': 'Удалённый · {remote}', + 'worktree.namedTip': 'Новая ветка {name} от {branch}', + 'worktree.namedTipHead': 'Новая ветка {name} от текущего HEAD', + 'worktree.name.add': 'Назвать новую ветку…', + 'worktree.name.label': 'Имя новой ветки', + 'worktree.name.auto': 'Создаётся автоматически', + 'nameDialog.title': 'Назвать новую ветку', + 'nameDialog.retryTitle': 'Переименовать ветку', + 'nameDialog.field': 'Имя ветки', + 'nameDialog.hint': 'Первое сообщение создаст эту ветку от {branch}; каталог рабочего дерева получит то же имя', + 'nameDialog.hintHead': 'Первое сообщение создаст эту ветку от текущего HEAD; каталог рабочего дерева получит то же имя', + 'nameDialog.prefixOnly': 'Введите имя после префикса', + 'nameDialog.auto': 'Использовать созданное имя', + 'nameDialog.cancel': 'Отмена', + 'nameDialog.confirm': 'Сохранить', + 'nameDialog.retry': 'Повторить', + 'nameDialog.close': 'Закрыть', + 'branchName.empty': 'Введите имя ветки', + 'branchName.space': 'Имя ветки не может содержать пробелы', + 'branchName.character': 'Имя ветки не может содержать ~ ^ : ? * [ и \\', + 'branchName.leading-dash': 'Имя ветки не может начинаться с «-»', + 'branchName.leading-slash': 'Имя ветки не может начинаться с «/»', + 'branchName.trailing-slash': 'Имя ветки не может заканчиваться на «/»', + 'branchName.double-slash': 'Имя ветки не может содержать «//»', + 'branchName.double-dot': 'Имя ветки не может содержать «..»', + 'branchName.trailing-dot': 'Имя ветки не может заканчиваться на «.»', + 'branchName.at': 'Ветка не может называться «@»', + 'branchName.at-brace': 'Имя ветки не может содержать «@{»', + 'branchName.dot-segment': 'Ни одна часть между косыми чертами не может начинаться с «.»', + 'branchName.lock-segment': 'Ни одна часть между косыми чертами не может заканчиваться на «.lock»', + 'branchName.exists': 'Ветка {name} уже существует', + 'branchName.invalid': 'Git не принимает это имя ветки', + 'creation.fetch': 'Получение {branch}', + 'creation.useFetched': 'Использовать последнюю полученную версию', + 'creation.rename': 'Переименовать', 'creation.waiting': 'Сообщение будет отправлено после создания рабочего дерева', 'missing.title': 'Рабочее дерево недоступно', 'missing.unknown': 'Восстановление не завершено, ветка {branch} недоступна для проверки. Устраните ошибку и повторите попытку или продолжите в проекте', @@ -3469,7 +3735,6 @@ export const pt: Record = { 'worktree.blocked.read-only': 'Uma sessão somente leitura não pode usar uma árvore de trabalho', 'worktree.base': 'A partir de {branch}', 'worktree.baseHead': 'A partir do HEAD atual', - 'worktree.baseMenu': 'Branch base', 'worktree.currentBranch': 'Atual', 'worktree.currentBranchTip': 'Branch atual: {branch}', 'worktree.detachedTip': 'Fora de uma branch · {commit}', @@ -3486,6 +3751,45 @@ export const pt: Record = { 'creation.cancel': 'Cancelar', 'creation.stopped': 'Criação da árvore de trabalho interrompida', 'creation.retry': 'Tentar novamente', + 'diff.loading': 'Lendo as alterações…', + 'diff.allFilesLoading': 'Todos os arquivos', + 'worktree.pinned': 'Branch atual e branches padrão remotos', + 'worktree.remoteDefault': 'Padrão remoto', + 'worktree.remoteGroup': 'Remoto · {remote}', + 'worktree.namedTip': 'Branch novo {name} a partir de {branch}', + 'worktree.namedTipHead': 'Branch novo {name} a partir do HEAD atual', + 'worktree.name.add': 'Dar nome ao branch novo…', + 'worktree.name.label': 'Nome do branch novo', + 'worktree.name.auto': 'Gerado', + 'nameDialog.title': 'Dar nome ao branch novo', + 'nameDialog.retryTitle': 'Renomear o branch', + 'nameDialog.field': 'Nome do branch', + 'nameDialog.hint': 'A primeira mensagem cria este branch a partir de {branch}; o diretório da árvore de trabalho recebe o mesmo nome', + 'nameDialog.hintHead': 'A primeira mensagem cria este branch a partir do HEAD atual; o diretório da árvore de trabalho recebe o mesmo nome', + 'nameDialog.prefixOnly': 'Digite um nome depois do prefixo', + 'nameDialog.auto': 'Usar um nome gerado', + 'nameDialog.cancel': 'Cancelar', + 'nameDialog.confirm': 'Salvar', + 'nameDialog.retry': 'Tentar novamente', + 'nameDialog.close': 'Fechar', + 'branchName.empty': 'Digite um nome de branch', + 'branchName.space': 'Nomes de branch não podem conter espaços', + 'branchName.character': 'Nomes de branch não podem conter ~ ^ : ? * [ nem \\', + 'branchName.leading-dash': 'Nomes de branch não podem começar com “-”', + 'branchName.leading-slash': 'Nomes de branch não podem começar com “/”', + 'branchName.trailing-slash': 'Nomes de branch não podem terminar com “/”', + 'branchName.double-slash': 'Nomes de branch não podem conter “//”', + 'branchName.double-dot': 'Nomes de branch não podem conter “..”', + 'branchName.trailing-dot': 'Nomes de branch não podem terminar com “.”', + 'branchName.at': 'Um branch não pode se chamar “@”', + 'branchName.at-brace': 'Nomes de branch não podem conter “@{”', + 'branchName.dot-segment': 'Nenhuma parte entre barras pode começar com “.”', + 'branchName.lock-segment': 'Nenhuma parte entre barras pode terminar com “.lock”', + 'branchName.exists': 'Já existe um branch chamado {name}', + 'branchName.invalid': 'O Git não aceita este nome de branch', + 'creation.fetch': 'Obter {branch}', + 'creation.useFetched': 'Usar a última versão obtida', + 'creation.rename': 'Renomear', 'creation.waiting': 'A mensagem será enviada após a criação da árvore de trabalho', 'missing.title': 'A árvore de trabalho está indisponível', 'missing.unknown': 'A restauração está incompleta e não é possível inspecionar a branch {branch}. Corrija o erro e tente novamente ou continue no projeto', diff --git a/packages/experimental/client-ui-forge/src/client/mount.ts b/packages/experimental/client-ui-forge/src/client/mount.ts index 0561acb9db..95c90a1fd2 100644 --- a/packages/experimental/client-ui-forge/src/client/mount.ts +++ b/packages/experimental/client-ui-forge/src/client/mount.ts @@ -49,6 +49,7 @@ import { createNoticeSource, createPanelSource, createStreamSource, foldStates, type PanelSource, } from './source.ts' import { numberOf } from './status.ts' +import type { WorktreeRequestResult } from './WorktreeNameDialog.tsx' import { WorktreeProgress, type WorktreeProgressInjected } from './WorktreeProgress.tsx' import { WorktreeSettings } from './WorktreeSettings.tsx' import { WorktreeSettingsForm, type WorktreeSettings as WorktreeSettingsFields } from './worktree-settings-form.ts' @@ -388,6 +389,15 @@ function registerUi(ctx: Context): void { }, } } + /** Request a worktree; a refused branch name goes back to the naming dialog, any other failure to a toast. */ + const requestWorktree = async (sessionId: SessionId, from: string | null, name: string | null): Promise => { + const result = await ctx.remote.forgePanel.requestWorktree(sessionId, from, name) + if (result.ok) return 'accepted' + if (result.error.code === 'forgePanel/branch-exists') return 'branch-exists' + if (result.error.code === 'forgePanel/invalid-name') return 'invalid-name' + settled(result, 'toast.worktreeFailed', { 'forgePanel/session-started': 'toast.worktreeStarted' }) + return 'failed' + } const progressFace = (sessionId: SessionId): WorktreeProgressInjected => { const store = storesOf(sessionId) return { @@ -395,9 +405,10 @@ function registerUi(ctx: Context): void { stop: () => { void ctx.remote.forgePanel.stopCreation(sessionId).then(result => settled(result, 'toast.worktreeFailed')) }, - retry: () => { - void ctx.remote.forgePanel.retryWorktree(sessionId).then(result => settled(result, 'toast.worktreeFailed')) + retry: (fetch) => { + void ctx.remote.forgePanel.retryWorktree(sessionId, fetch).then(result => settled(result, 'toast.worktreeFailed')) }, + request: async (from, name) => await requestWorktree(sessionId, from, name), withdraw: () => { void ctx.remote.forgePanel.cancelWorktree(sessionId).then(result => settled(result, 'toast.worktreeFailed')) }, @@ -408,16 +419,13 @@ function registerUi(ctx: Context): void { } } const worktreeFace = (sessionId: SessionId): WorktreeToggleInjected => { - const worktreeCodes: Partial> = { 'forgePanel/session-started': 'toast.worktreeStarted' } const store = storesOf(sessionId) return { hooks: { panel: store.panel.hooks.panel }, - request: async from => settled(await ctx.remote.forgePanel.requestWorktree(sessionId, from), 'toast.worktreeFailed', worktreeCodes), - cancel: async () => settled(await ctx.remote.forgePanel.cancelWorktree(sessionId), 'toast.worktreeFailed', worktreeCodes), - branches: async () => { - const result = await ctx.remote.forgePanel.branches(sessionId) - return settled(result, 'toast.branchesFailed') && result.ok ? result.value : undefined - }, + request: async (from, name) => await requestWorktree(sessionId, from, name), + cancel: async () => settled(await ctx.remote.forgePanel.cancelWorktree(sessionId), 'toast.worktreeFailed', + { 'forgePanel/session-started': 'toast.worktreeStarted' }), + bases: (query, signal) => ctx.remote.forgePanel.worktreeBases(sessionId, query, signal), } } ctx.slots.inject('conversation.session.panel.section', function* () { diff --git a/packages/experimental/client-ui-forge/src/git.ts b/packages/experimental/client-ui-forge/src/git.ts index c8db71c7a9..076bde1f46 100644 --- a/packages/experimental/client-ui-forge/src/git.ts +++ b/packages/experimental/client-ui-forge/src/git.ts @@ -7,9 +7,10 @@ import type {} from '@deepseek-ai/dsh-sandbox-policy' import type { Session } from '@deepseek-ai/dsh-session' import type { SubprocessCollectedOutputs } from '@deepseek-ai/dsh-subprocess' import { deadline } from '@deepseek-ai/dsh-timeout' -import { baseBranches, parseName, parseRemotes, parseTopLevel } from './parse.ts' +import { LOCAL_REF_PREFIX } from './branch-name.ts' +import { parseName, parseRemotes, parseTopLevel } from './parse.ts' import type { GitRemote } from './parse.ts' -import type { ForgeBranches, ForgeCheckout } from './types.ts' +import type { ForgeCheckout } from './types.ts' /** Resolved Git executable and process limits. */ export interface GitConfig { @@ -128,36 +129,6 @@ export async function inspectCheckout( } } -/** - * List the local branches that can start a worktree of the checkout containing - * `directory`, using the Session's permissions as in {@link inspectCheckout}. - * @param ctx - context that provides `subprocess`, `sandbox`, and `sandboxPolicy`. - * @param config - executable and process limits. - * @param session - Session whose sandbox policy and execution world apply. - * @param directory - absolute directory inside the checkout. - * @param limit - most branch names to return. - * @param signal - cancellation of every command. - * @returns the checked-out branch and local branches, the checked-out one first and then most recently committed first. - * @throws when `directory` is not inside a checkout, or Git cannot run, fails, times out, or prints more than `maxOutputBytes`. - */ -export async function listBranches( - ctx: Context, - config: GitConfig, - session: Session, - directory: string, - limit: number, - signal: AbortSignal, -): Promise { - const [current, refs] = await together(signal, (signal) => { - const git = gitIn(ctx, config, session, directory, signal) - return [ - currentBranch(git), - git('for-each-ref', ['for-each-ref', '--sort=-committerdate', `--count=${limit}`, '--format=%(refname:lstrip=2)', 'refs/heads/']), - ] as const - }) - return { current, branches: baseBranches(current, refs.stdout, limit) } -} - /** A failed read cancels its siblings and returns only after every read has finished cleanup. */ async function together[]>( signal: AbortSignal, @@ -215,10 +186,14 @@ export function gitIn(ctx: Context, config: GitConfig, session: Session, directo runGit(ctx, config, policy, directory, name, args, signal, allowedExitCodes, configOverrides) } -/** Read the checked-out branch, including an unborn one; null when HEAD is detached. */ +/** + * Read the checked-out local branch, including an unborn one; null when HEAD is detached or names a ref outside + * `refs/heads/`. The full ref is read because the short form turns `main` into `heads/main` while a tag shares the name. + */ async function currentBranch(git: Git): Promise { - const head = await git('symbolic-ref', ['symbolic-ref', '--quiet', '--short', 'HEAD'], [0, 1]) - return head.exitCode === 0 ? parseName(head.stdout) : null + const head = await git('symbolic-ref', ['symbolic-ref', '--quiet', 'HEAD'], [0, 1]) + const ref = head.exitCode === 0 ? parseName(head.stdout) : null + return ref !== null && ref.startsWith(LOCAL_REF_PREFIX) ? ref.slice(LOCAL_REF_PREFIX.length) : null } /** Read the abbreviated commit HEAD names; null while the checked-out branch has no commit. */ diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index ebc09dcb61..cc2d4c9494 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -21,8 +21,9 @@ import type {} from '@deepseek-ai/dsh-session-query' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' import { assertNever } from '@deepseek-ai/dsh-util-values' -import { gitIn, inspectCheckout, listBranches } from './git.ts' +import { gitIn, hasBranch, inspectCheckout } from './git.ts' import type { Inspection } from './git.ts' +import { branchNameProblem } from './branch-name.ts' import { parseDiff } from './diff.ts' import { aheadOf, BaseMissing, baseBranches, chosenForkPoint, CommitsMissing, CommitsNotLinear, DiffTooLarge, FilterConfigError, forkPoint, @@ -35,14 +36,15 @@ import { lensVersion } from './lens-version.ts' import { rangeStart } from './commit-range.ts' import { ATTRIBUTES_PATH, FileLayers } from './layers.ts' import { missingWorktree, SessionPanel } from './panel.ts' +import { BASE_REF_PREFIXES, parseWorktreeBases, remoteOrder, remoteRepository } from './parse.ts' import { PatchCache } from './patch-cache.ts' import { ReviewCache } from './review-cache.ts' import { ChangeRequestStates, changeRequestStatesDomain } from './states.ts' import type { PanelConfig } from './panel.ts' import type { - Config, ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeDiffFile, + Config, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeDiffFile, ForgeExtensionState, ForgeLens, ForgeLensFrame, ForgeLensRequest, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, - ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState, + ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeBases, ForgeWorktreeState, } from './types.ts' import { forgeWorktreeProjection, messageOf, within, WORKTREE_RECORD, WorktreeCreations } from './worktree.ts' import type { HeldWork } from './worktree.ts' @@ -56,11 +58,10 @@ declare module '@deepseek-ai/cordis' { } } -/** Panel limits plus the branch and commit listing limits, the worktree branch prefix, and the lens and annotation limits. */ +/** Panel limits and worktree branch prefix plus the branch and commit listing limits and the lens and annotation limits. */ type ControllerConfig = PanelConfig & { readonly maxBranches: number readonly maxCommits: number - readonly worktreePrefix: string readonly lensTimeoutMs: number readonly maxLensReadBytes: number readonly maxCachedLensBytes: number @@ -141,7 +142,8 @@ export class ForgePanelController extends TypertRemoteService { ] as const) { if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-panel: ${key} must be a positive integer`) } - if (!branchPrefix(resolved.worktreePrefix)) throw new Error('forge-panel: worktreePrefix must start a valid Git branch name') + // Generated names append hexadecimal digits, so the prefix followed by one digit must be a valid branch name. + if (branchNameProblem(`${resolved.worktreePrefix}0`) !== null) throw new Error('forge-panel: worktreePrefix must start a valid Git branch name') for (const key of ['testPaths', 'interfacePaths'] as const) { if (resolved[key].some(glob => glob.trim() === '')) throw new Error(`forge-panel: ${key} entries must not be empty`) } @@ -241,15 +243,24 @@ export class ForgePanelController extends TypertRemoteService { } /** - * List the local branches that can start a worktree of the Session's current checkout. - * @param session - Session whose current directory is listed. + * List the branches that can start a worktree of the Session's current checkout: the checked-out branch, each + * remote's default branch, other local branches, and each remote's other remote-tracking branches, remotes in the + * order the panel recognizes code hosts. + * @param session - Session whose checkout is read. + * @param query - text the branch names must contain, ignoring case; empty for every branch. * @param signal - request cancellation. - * @returns the checked-out branch and at most `maxBranches` local branches, the checked-out one first. - * @throws when the current directory is not inside a checkout or Git fails. + * @returns the branches, at most `maxBranches` local branches and `maxBranches` per remote, most recently committed first. + * @throws `forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`. */ @Remote - async branches(session: Session, signal: AbortSignal): Promise { - return await listBranches(this.home, this.config, session, this.home.workingDirectory.get(session), this.config.maxBranches, signal) + async worktreeBases(session: Session, query: string, signal: AbortSignal): Promise { + signal.throwIfAborted() + const inspection = await this.checkoutOf(session, signal) + // A search can match any branch, so every ref is listed; a repository's refs can far exceed other short Git output. + const git = gitIn(this.home, { ...this.config, maxOutputBytes: this.config.maxDiffBytes }, session, inspection.checkout.root, signal) + const refs = await git('worktree-bases', ['for-each-ref', '--sort=-committerdate', '--format=%(refname)%00%(symref)', ...BASE_REF_PREFIXES]) + return parseWorktreeBases(refs.stdout, inspection.checkout.branch, remoteOrder(inspection.upstream, inspection.remotes), query, + this.config.maxBranches, remote => remoteRepository(remote, url => this.home.forge.repositoryFromRemote(url))) } /** @@ -820,24 +831,34 @@ export class ForgePanelController extends TypertRemoteService { /** * Ask for a new worktree before the Session's first turn, replacing an open * request and forgetting a failed attempt. While the next message waits in - * the inbox, or else at the first step proposal, the panel creates a branch - * from `from`, or from HEAD of the current checkout when it is null, and - * enters its checkout. A message that already waits after a failed or - * stopped attempt keeps waiting for {@link ForgePanelController.retryWorktree}. + * the inbox, or else at the first step proposal, the panel creates the + * branch `name`, or a generated branch per attempt when it is null, from + * `from`, or from HEAD of the current checkout when it is null, and enters + * its checkout; a remote-tracking `from` is fetched first. A message that + * already waits after a failed or stopped attempt keeps waiting for + * {@link ForgePanelController.retryWorktree}. * @param session - Session without a started turn. - * @param from - local base branch, or null for HEAD. + * @param from - full name of a local or remote-tracking base branch, or null for HEAD. + * @param name - new branch name, or null to generate one per attempt. * @param signal - request cancellation. - * @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/worktrees-unavailable` + * @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/invalid-name` when `name` breaks + * a branch-name rule; `forgePanel/branch-exists` when the checkout has a local branch named `name`; + * `forgePanel/not-a-checkout` when a name is checked outside a checkout; `forgePanel/worktrees-unavailable` * without a worktree service; `forgePanel/session-started` after a turn started or the worktree was * created; `forgePanel/session-busy` while the worktree is being created. */ @Remote - async requestWorktree(session: Session, from: string | null, signal: AbortSignal): Promise { + async requestWorktree(session: Session, from: string | null, name: string | null, signal: AbortSignal): Promise { signal.throwIfAborted() if (from?.length === 0) throw new RemoteError('forgePanel/invalid-branch', 'The base branch name is empty', {}) this.editableWorktree(session) + if (name !== null) { + await this.checkBranchName(session, name, signal) + // The Session may have started or begun a creation while Git answered. + this.editableWorktree(session) + } this.creations.forget(session) - appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from }) + appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from, ...name === null ? {} : { name } }) this.creations.recheck(session) } @@ -873,16 +894,19 @@ export class ForgePanelController extends TypertRemoteService { } /** - * Make another attempt, with a new branch name, at the worktree a message - * of the Session waits for after a failed or stopped attempt. + * Make another attempt, on the requested branch name or a new generated + * one, at the worktree a message of the Session waits for after a failed or + * stopped attempt. * @param session - Session whose message waits. + * @param fetch - false skips fetching a remote-tracking base branch for this attempt, which then starts from the + * commit last fetched. * @param signal - request cancellation. * @throws `forgePanel/not-waiting` when no message waits or an attempt is running. */ @Remote - async retryWorktree(session: Session, signal: AbortSignal): Promise { + async retryWorktree(session: Session, fetch: boolean, signal: AbortSignal): Promise { signal.throwIfAborted() - if (!this.creations.retry(session)) { + if (!this.creations.retry(session, fetch)) { throw new RemoteError('forgePanel/not-waiting', 'No message waits for another attempt at the worktree', {}) } } @@ -1060,6 +1084,18 @@ export class ForgePanelController extends TypertRemoteService { return this.worktreeStates.stateOf(session) } + /** + * Refuse a new branch name that breaks a branch-name rule or names a local branch of the Session's checkout. The + * rules cover every name `git check-ref-format` refuses, which the worktree service runs again at creation. + */ + private async checkBranchName(session: Session, name: string, signal: AbortSignal): Promise { + if (branchNameProblem(name) !== null) throw new RemoteError('forgePanel/invalid-name', 'The new branch name is invalid', {}) + const root = (await this.checkoutOf(session, signal)).checkout.root + if (await hasBranch(this.home, this.config, session, root, name, signal)) { + throw new RemoteError('forgePanel/branch-exists', `A local branch named ${name} exists`, {}) + } + } + private editableWorktree(session: Session): ForgeWorktreeState { if (this.home.get('worktrees') === undefined) { throw new RemoteError('forgePanel/worktrees-unavailable', 'No worktree service is mounted', {}) @@ -1346,21 +1382,4 @@ function actionError(failure: ForgeActionFailure): RemoteError { return new RemoteError(code, failure.message, {}) } -/** - * Whether `prefix` followed by hexadecimal digits is a branch name that Git - * accepts: no leading `-` or `/`, no empty component, no component that - * starts with `.` or ends with `.lock`, and none of `..`, `@{`, whitespace, - * control characters, `~`, `^`, `:`, `?`, `*`, `[`, or `\`. - * @param prefix - configured worktree branch prefix. - * @returns whether every generated name passes `git check-ref-format --branch`. - */ -function branchPrefix(prefix: string): boolean { - const name = `${prefix}0` - if (name.startsWith('-') || name.includes('..') || name.includes('@{')) return false - for (const char of name) { - if (char <= ' ' || char === '\x7f' || '~^:?*[\\'.includes(char)) return false - } - return name.split('/').every(part => part.length > 0 && !part.startsWith('.') && !part.endsWith('.lock')) -} - export default ForgePanelController diff --git a/packages/experimental/client-ui-forge/src/local-diff.ts b/packages/experimental/client-ui-forge/src/local-diff.ts index 17c753643a..8568571bf6 100644 --- a/packages/experimental/client-ui-forge/src/local-diff.ts +++ b/packages/experimental/client-ui-forge/src/local-diff.ts @@ -17,6 +17,7 @@ import { gitIn, GitOutputTooLarge } from './git.ts' import type { Git, GitConfig, GitOutput, Inspection } from './git.ts' import { ATTRIBUTES_PATH } from './layers.ts' import type { FileLayers } from './layers.ts' +import { branchLabel } from './branch-name.ts' import { BASE_REF_PREFIXES, parseBaseBranches, parseName, remoteOrder } from './parse.ts' import type { ForgeCommitRange, ForgeLocalChanges, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgeBaseBranches, ForgeSessionWorktree, @@ -114,7 +115,8 @@ const BINARY_PROBE = 8000 */ export async function forkPoint(git: Git, inspection: Inspection, created: ForgeSessionWorktree | null): Promise { if (created !== null && created.path === inspection.checkout.root) { - return { commit: created.baseCommit, label: created.from ?? created.baseCommit.slice(0, 7), worktree: true } + const label = created.from === null ? created.baseCommit.slice(0, 7) : branchLabel(created.from) + return { commit: created.baseCommit, label, worktree: true } } for (const remote of remoteOrder(inspection.upstream, inspection.remotes)) { const head = await git('remote-head', ['symbolic-ref', '--quiet', '--short', `refs/remotes/${remote.name}/HEAD`], [0, 1, 128]) diff --git a/packages/experimental/client-ui-forge/src/panel.ts b/packages/experimental/client-ui-forge/src/panel.ts index 6d4adc4ce0..30db0ee3d1 100644 --- a/packages/experimental/client-ui-forge/src/panel.ts +++ b/packages/experimental/client-ui-forge/src/panel.ts @@ -27,6 +27,8 @@ import type { WorktreeCreations } from './worktree.ts' export interface PanelConfig extends DiffConfig { /** Deadline in milliseconds for one provider sign-in probe. */ readonly readinessTimeoutMs: number + /** Prefix of generated worktree branch names, which a name the user types starts from. */ + readonly worktreePrefix: string } /** The checkout's upstream branch and the remote URL its change requests are looked up at. */ @@ -70,7 +72,7 @@ export class SessionPanel { /** * @param ctx - service context that provides the forge, Session, directory, and process services. - * @param config - Git limits and the sign-in probe deadline. + * @param config - Git limits, the sign-in probe deadline, and the worktree branch name prefix. * @param session - Session the panel describes. * @param worktreeStates - reads the `forgeWorktree` projection of the Session. * @param creations - reads the running creation and restoration, the last failed creation, and what a message of the @@ -229,6 +231,7 @@ export class SessionPanel { return { editable: this.ctx.get('worktrees') !== undefined && !state.locked && state.created === null, blocker: this.blocker, + namePrefix: this.config.worktreePrefix, request: state.request, created: state.created, creation: this.creations.of(this.session), diff --git a/packages/experimental/client-ui-forge/src/parse.ts b/packages/experimental/client-ui-forge/src/parse.ts index b163c40e4a..4041299795 100644 --- a/packages/experimental/client-ui-forge/src/parse.ts +++ b/packages/experimental/client-ui-forge/src/parse.ts @@ -1,6 +1,6 @@ /** Parsers for the porcelain output of the read-only Git commands the panel runs. */ -import type { ForgeBaseBranch } from './types.ts' +import type { ForgeBaseBranch, ForgeRemoteDefault, ForgeWorktreeBases } from './types.ts' /** One remote with the URLs `git remote -v` prints for it. */ export interface GitRemote { @@ -23,7 +23,7 @@ export function parseTopLevel(output: string): string { } /** - * Read the first line of a one-name output such as `git symbolic-ref --short HEAD`. + * Read the first line of a one-name output such as `git symbolic-ref --quiet HEAD`. * @param output - stdout of the command. * @returns the name, or null when the command printed none. */ @@ -67,16 +67,73 @@ export function parseBaseBranches( } /** - * Order worktree base branches: the checked-out branch first, then the other - * listed branches in listed order. + * Select the branches a new worktree can start from out of `git for-each-ref` output, keeping its order within + * each group: the checked-out branch, each remote's default branch, the other local branches, and the other + * remote-tracking branches of each remote. A remote's default branch is the branch its `refs/remotes//HEAD` + * names; remote-tracking branches of unconfigured remotes and other symbolic refs are left out. + * @param output - stdout of `git for-each-ref --format=%(refname)%00%(symref)` over {@link BASE_REF_PREFIXES}. * @param current - checked-out branch, or null when HEAD is detached. - * @param output - stdout of `git for-each-ref --format=%(refname:lstrip=2) refs/heads/`. - * @param limit - most names to return. - * @returns distinct branch names, at most `limit`. + * @param remotes - configured remotes in the order their groups take. + * @param query - text the names must contain, ignoring case; empty or blank for every branch. + * @param limit - most branches in the local group and in each remote's group. + * @param repositoryOf - the repository a remote's group names. + * @returns the branches, with remotes that have no listed branch left out. */ -export function baseBranches(current: string | null, output: string, limit: number): string[] { - const listed = output.split(/\r?\n/).filter(name => name.length > 0 && name !== current) - return (current === null ? listed : [current, ...listed]).slice(0, limit) +export function parseWorktreeBases( + output: string, + current: string | null, + remotes: readonly GitRemote[], + query: string, + limit: number, + repositoryOf: (remote: GitRemote) => string | null, +): ForgeWorktreeBases { + const [heads, tracking] = BASE_REF_PREFIXES + const needle = query.trim().toLowerCase() + const matches = (name: string): boolean => name.toLowerCase().includes(needle) + const listed: string[] = [] + const remoteHeads = new Map() + for (const line of output.split(/\r?\n/)) { + const [ref = '', symref = ''] = line.split('\0') + if (ref.length === 0) continue + if (symref.length === 0) { + listed.push(ref) + continue + } + const owner = ref.startsWith(tracking) ? upstreamBranch(ref.slice(tracking.length), remotes) : undefined + if (owner?.branch === 'HEAD') remoteHeads.set(owner.remote.name, symref) + } + const present = new Set(listed) + const defaultRefs = new Set() + const defaults: ForgeRemoteDefault[] = [] + for (const remote of remotes) { + const target = remoteHeads.get(remote.name) + if (target === undefined || !present.has(target) || !target.startsWith(`${tracking}${remote.name}/`)) continue + defaultRefs.add(target) + const name = target.slice(tracking.length) + if (matches(name)) defaults.push({ ref: target, name, remote: remote.name }) + } + const local: ForgeBaseBranch[] = [] + const groups = remotes.map(remote => ({ remote, branches: [] as ForgeBaseBranch[] })) + for (const ref of listed) { + if (ref.startsWith(heads)) { + const name = ref.slice(heads.length) + if (name !== current && local.length < limit && matches(name)) local.push({ ref, name }) + continue + } + if (!ref.startsWith(tracking) || defaultRefs.has(ref)) continue + const name = ref.slice(tracking.length) + const owner = upstreamBranch(name, remotes)?.remote + const group = groups.find(candidate => candidate.remote === owner) + if (group !== undefined && group.branches.length < limit && matches(name)) group.branches.push({ ref, name }) + } + const currentRef = `${heads}${current ?? ''}` + return { + current: current !== null && present.has(currentRef) && matches(current) ? { ref: currentRef, name: current } : null, + defaults, + local, + remotes: groups.filter(group => group.branches.length > 0) + .map(({ remote, branches }) => ({ name: remote.name, repository: repositoryOf(remote), branches })), + } } /** @@ -123,6 +180,25 @@ export function upstreamBranch( return remote === undefined ? undefined : { remote, branch: upstream.slice(remote.name.length + 1) } } +/** + * Name the repository a remote's group shows: `owner/name` of the first URL a provider recognizes, else the first URL + * without the user name and password a URL can carry as a token, since the name reaches the browser. + * @param remote - remote with its URLs, fetch URL first. + * @param recognize - the repository a provider recognizes from a URL, or undefined. + * @returns the name, or null for a remote without a URL. + */ +export function remoteRepository( + remote: GitRemote, + recognize: (url: string) => { readonly owner: string; readonly name: string } | undefined, +): string | null { + for (const url of remote.urls) { + const repository = recognize(url) + if (repository !== undefined) return `${repository.owner}/${repository.name}` + } + // A URL's user information ends at the last `@` before its path, query, or fragment. + return remote.urls[0]?.replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/?#]*@/, '$1') ?? null +} + /** * Order remotes for code host recognition: the upstream's remote first, then * `origin`, then the rest in listed order. diff --git a/packages/experimental/client-ui-forge/src/types.ts b/packages/experimental/client-ui-forge/src/types.ts index a8b575a629..edf5da658d 100644 --- a/packages/experimental/client-ui-forge/src/types.ts +++ b/packages/experimental/client-ui-forge/src/types.ts @@ -34,7 +34,10 @@ export interface ForgeSessionWorktree { readonly path: string /** Branch created for the checkout. */ readonly branch: string - /** Requested base branch, or null when the checkout started from HEAD of the source checkout. */ + /** + * Requested base: the full name of a local or remote-tracking branch, a short branch name that earlier panels + * recorded, or null when the checkout started from HEAD of the source checkout. + */ readonly from: string | null /** Commit object name the branch started from. */ readonly baseCommit: string @@ -44,8 +47,11 @@ export interface ForgeSessionWorktree { /** Payload of the `plugin:client-ui-forge/worktree` record. */ export type WorktreeRecord = - /** Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null. */ - | { readonly action: 'request'; readonly from: string | null } + /** + * Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null, on the + * branch `name`, or on a generated branch name when `name` is absent. + */ + | { readonly action: 'request'; readonly from: string | null; readonly name?: string } /** Withdraw the open request. */ | { readonly action: 'cancel' } /** The requested worktree was created and became the Session's working directory. */ @@ -57,8 +63,13 @@ export type WorktreeRecord = /** One open worktree request. */ export interface ForgeWorktreeRequest { - /** Base branch, or null for HEAD of the source checkout. */ + /** + * Base: the full name of a local or remote-tracking branch, a short branch name that earlier panels recorded, or + * null for HEAD of the source checkout. A remote-tracking branch is fetched before each attempt that does not skip it. + */ readonly from: string | null + /** New branch name the user chose, which every attempt uses, or null for a generated name per attempt. */ + readonly name: string | null } /** Host-only state of the `forgeWorktree` projection. */ @@ -88,12 +99,17 @@ export type ForgeWorktreeBlocker = /** One running worktree creation. */ export interface ForgeWorktreeCreation { - /** Running step: `prepare` validates and creates the branch, then `checkout` writes the files. */ - readonly phase: 'prepare' | 'checkout' + /** + * Running step: `fetch` fetches a remote base branch, `prepare` validates and creates the branch, then + * `checkout` writes the files. + */ + readonly phase: 'fetch' | 'prepare' | 'checkout' /** Branch the attempt creates. */ readonly branch: string - /** Base branch, or null for HEAD. */ + /** Base as the request names it, or null for HEAD. */ readonly from: string | null + /** Whether the attempt fetches its remote base branch first. */ + readonly fetch: boolean /** * Whether a message waits for the creation before its turn starts. Only * such a creation can be stopped, after which the message keeps waiting; a @@ -112,12 +128,16 @@ export interface ForgeWorktreeRestoration { export interface ForgeWorktreeFailure { /** Branch the attempt created, or null when it failed before naming one. */ readonly branch: string | null - /** Base branch of the attempt, or null for HEAD. */ + /** Base of the attempt as the request names it, or null for HEAD. */ readonly from: string | null + /** Whether the attempt fetched, or tried to fetch, its remote base branch first. */ + readonly fetch: boolean /** Step that failed. */ - readonly phase: 'prepare' | 'checkout' + readonly phase: 'fetch' | 'prepare' | 'checkout' /** Failure text. */ readonly message: string + /** Whether the branch or the checkout directory of that name already existed, which another name avoids. */ + readonly exists: boolean } /** @@ -142,6 +162,8 @@ export interface ForgePanelWorktree { readonly editable: boolean /** Why the checkout cannot host a worktree, or null when it can, before the first inspection, and after a failed one. */ readonly blocker: ForgeWorktreeBlocker | null + /** Prefix of generated branch names, the Config `worktreePrefix`, which a name the user types starts from. */ + readonly namePrefix: string /** Open request, or null without one. */ readonly request: ForgeWorktreeRequest | null /** Created worktree, or null before creation. */ @@ -216,12 +238,35 @@ export interface ForgePanelState { readonly local: ForgeLocalChanges | null } -/** Local branches offered as the base of a new worktree. */ -export interface ForgeBranches { - /** Checked-out branch, or null when HEAD is detached. */ - readonly current: string | null - /** Local branch names, `current` first and then most recently committed first, at most `maxBranches`. */ - readonly branches: readonly string[] +/** Branches offered as the base of a new worktree whose names contain a query. */ +export interface ForgeWorktreeBases { + /** Checked-out branch, or null when HEAD is detached or its name does not contain the query. */ + readonly current: ForgeBaseBranch | null + /** Default branch of each remote that names one with `refs/remotes//HEAD`, in remote order. */ + readonly defaults: readonly ForgeRemoteDefault[] + /** Other local branches, most recently committed first, at most `maxBranches`. */ + readonly local: readonly ForgeBaseBranch[] + /** + * Remote-tracking branches of each configured remote in remote order: the remote the checked-out branch tracks, + * then `origin`, then the others as Git lists them. Remotes without a matching branch are left out. + */ + readonly remotes: readonly ForgeRemoteBranches[] +} + +/** A remote's default branch, which `refs/remotes//HEAD` names. */ +export interface ForgeRemoteDefault extends ForgeBaseBranch { + /** Remote the branch belongs to; it may contain `/`. */ + readonly remote: string +} + +/** Remote-tracking branches of one remote, without its default branch. */ +export interface ForgeRemoteBranches { + /** Remote name such as `origin`; it may contain `/`. */ + readonly name: string + /** `owner/name` of the repository a provider recognizes from the remote's URLs, else its fetch URL, or null without one. */ + readonly repository: string | null + /** Branches named `/`, most recently committed first, at most `maxBranches`. */ + readonly branches: readonly ForgeBaseBranch[] } /** A branch the `branch` scope can compare with. */ @@ -545,6 +590,10 @@ declare module '@deepseek-ai/dsh-typert-protocol' { 'forgePanel/worktrees-unavailable': Record /** The requested base branch name is empty. */ 'forgePanel/invalid-branch': Record + /** The requested new branch name breaks one of Git's branch-name rules, or the worktree service's refusal of a leading `-`. */ + 'forgePanel/invalid-name': Record + /** A local branch with the requested new branch name exists in the Session's checkout. */ + 'forgePanel/branch-exists': Record /** The Session has no created worktree to restore or leave. */ 'forgePanel/no-worktree': Record /** The Session's Agent is not loaded or has other work, so its checkout cannot change now. */ diff --git a/packages/experimental/client-ui-forge/src/worktree.ts b/packages/experimental/client-ui-forge/src/worktree.ts index 122a05efc5..5c8b83b254 100644 --- a/packages/experimental/client-ui-forge/src/worktree.ts +++ b/packages/experimental/client-ui-forge/src/worktree.ts @@ -11,9 +11,10 @@ import type { ProjectionDefinition, ProjectionHandle } from '@deepseek-ai/dsh-se import { assertNever } from '@deepseek-ai/dsh-util-values' import type {} from '@deepseek-ai/dsh-working-directory' import { z } from 'zod' +import { isRemoteRef } from './branch-name.ts' import type { - ForgeMissingWorktree, ForgeSessionWorktree, ForgeWorktreeCreation, ForgeWorktreeFailure, ForgeWorktreeRestoration, ForgeWorktreeState, - ForgeWorktreeWaiting, WorktreeRecord, + ForgeMissingWorktree, ForgeSessionWorktree, ForgeWorktreeCreation, ForgeWorktreeFailure, ForgeWorktreeRequest, ForgeWorktreeRestoration, + ForgeWorktreeState, ForgeWorktreeWaiting, WorktreeRecord, } from './types.ts' /** Plugin record type of worktree requests, withdrawals, and creations. */ @@ -30,7 +31,7 @@ const worktreeSchema: z.ZodType = z.object({ }).strict() const recordSchema: z.ZodType = z.discriminatedUnion('action', [ - z.object({ action: z.literal('request'), from: z.string().min(1).nullable() }).strict(), + z.object({ action: z.literal('request'), from: z.string().min(1).nullable(), name: z.string().min(1).exactOptional() }).strict(), z.object({ action: z.literal('cancel') }).strict(), z.object({ action: z.literal('created'), worktree: worktreeSchema }).strict(), z.object({ action: z.literal('restoring') }).strict(), @@ -38,7 +39,7 @@ const recordSchema: z.ZodType = z.discriminatedUnion('action', [ ]) const stateSchema: z.ZodType = z.object({ - request: z.object({ from: z.string().min(1).nullable() }).strict().nullable(), + request: z.object({ from: z.string().min(1).nullable(), name: z.string().min(1).nullable() }).strict().nullable(), created: worktreeSchema.nullable(), locked: z.boolean(), stepped: z.boolean(), @@ -59,7 +60,7 @@ const stateSchema: z.ZodType = z.object({ */ export const forgeWorktreeProjection = { key: 'forgeWorktree', - stateVersion: 5, + stateVersion: 6, stateSchema, init: header => ({ ...EMPTY, cwd: header.cwd ?? null }), apply, @@ -118,7 +119,7 @@ function applyRecord(state: ForgeWorktreeState, event: SessionEvent): ForgeWorkt const settled = state.created !== null switch (data.action) { case 'request': - return state.locked || settled ? state : { ...state, request: { from: data.from } } + return state.locked || settled ? state : { ...state, request: { from: data.from, name: data.name ?? null } } case 'cancel': return state.locked || settled || state.request === null ? state : { ...state, request: null } case 'created': @@ -134,6 +135,9 @@ function applyRecord(state: ForgeWorktreeState, event: SessionEvent): ForgeWorkt /** A failed attempt to create a requested worktree; `cause` holds the worktree service's error. */ export class CreationFailure extends Error { + /** Whether the branch or the checkout directory of that name already existed. */ + readonly exists: boolean + /** * @param branch - branch the attempt created. * @param phase - step that failed. @@ -143,21 +147,31 @@ export class CreationFailure extends Error { constructor(readonly branch: string, readonly phase: CreateWorktreePhase, readonly reason: string, cause: unknown) { super(`The requested worktree ${branch} could not be created`, { cause }) this.name = 'CreationFailure' + // The worktree service's failures are routed by name and code; a rebuilt error keeps both. + this.exists = cause instanceof Error && cause.name === 'WorktreeError' && 'code' in cause && cause.code === 'WORKTREE_ALREADY_EXISTS' } } /** * The failure a waiting message shows for an attempt. * @param error - what the attempt threw. - * @param from - base branch of the attempt, or null for HEAD. + * @param from - base of the attempt, or null for HEAD. + * @param fetch - whether the attempt fetched its remote base branch first. * @returns the failure. */ -function failureOf(error: unknown, from: string | null): ForgeWorktreeFailure { +function failureOf(error: unknown, from: string | null, fetch: boolean): ForgeWorktreeFailure { return error instanceof CreationFailure - ? { branch: error.branch, from, phase: error.phase, message: error.reason } - : { branch: null, from, phase: 'prepare', message: messageOf(error) } + ? { branch: error.branch, from, fetch, phase: error.phase, message: error.reason, exists: error.exists } + : { branch: null, from, fetch, phase: fetch ? 'fetch' : 'prepare', message: messageOf(error), exists: false } } +/** The next decision on a message that waits after a failed or stopped attempt. */ +type CreationDecision = + /** Make another attempt; `fetch` false skips fetching a remote base branch for it. */ + | { readonly kind: 'retry'; readonly fetch: boolean } + /** The request no longer asks for a worktree, so the message goes on. */ + | { readonly kind: 'recheck' } + /** Work on a Session's checkout that runs as maintenance of its Agent. */ export type HeldWork = (agent: Agent, signal: AbortSignal) => Promise @@ -167,7 +181,7 @@ interface CreationHold { /** Stops the running attempt. */ stop: AbortController | undefined /** The wait for the next decision: another attempt, or reading the request again. */ - next: PromiseWithResolvers<'retry' | 'recheck'> | undefined + next: PromiseWithResolvers | undefined } /** A message's wait for the restoration or leaving of the removed worktree the Session works in. */ @@ -182,8 +196,10 @@ interface RestorationHold { type Hold = CreationHold | RestorationHold /** - * Creates requested worktrees, one attempt with a new branch name per call, - * and holds the turn of a message while the Session's worktree is not ready. + * Creates requested worktrees, one attempt per call on the requested branch + * name or on a new generated one, fetching a remote-tracking base branch + * first unless the attempt skips it, and holds the turn of a message while + * the Session's worktree is not ready. * A hold is maintenance of the Session's Agent that starts while the message * enters the inbox, before the delivery wakes the Agent, so the Agent starts * the message's turn once the hold ends. A creation hold makes an attempt @@ -302,22 +318,27 @@ export class WorktreeCreations { /** * Make another attempt for the message that waits after a failed or stopped one. * @param session - Session whose message waits. + * @param fetch - false skips fetching a remote-tracking base branch for this attempt, which then starts from the + * commit last fetched. * @returns whether a waiting message without a running attempt took the decision. */ - retry(session: Session): boolean { + retry(session: Session, fetch: boolean): boolean { const hold = this.holds.get(session) if (hold?.kind !== 'creation' || hold.next === undefined) return false - hold.next.resolve('retry') + hold.next.resolve({ kind: 'retry', fetch }) return true } /** - * Read the request again after it changed; a withdrawn request lets the waiting message go on. + * Read the request again after it changed: a request that no longer asks for a worktree lets the waiting message + * go on, and a request that still does keeps it waiting for another attempt. * @param session - Session whose request changed. */ recheck(session: Session): void { const hold = this.holds.get(session) - if (hold?.kind === 'creation') hold.next?.resolve('recheck') + if (hold?.kind !== 'creation') return + const state = this.states.stateOf(session) + if (state.request === null || state.created !== null || state.locked) hold.next?.resolve({ kind: 'recheck' }) } /** @@ -395,32 +416,39 @@ export class WorktreeCreations { } /** - * Create a Session's requested worktree with a new branch name, enter it, and - * record it on the Session. The running creation is readable through - * {@link WorktreeCreations.of} until the record exists or the attempt fails. + * Create a Session's requested worktree on the requested branch name, or on a + * new generated one, enter it, and record it on the Session. The running + * creation is readable through {@link WorktreeCreations.of} until the record + * exists or the attempt fails. * @param agent - Agent of the Session. - * @param from - base branch, or null for HEAD of the current checkout. + * @param request - base, or null for HEAD of the current checkout, and branch name, or null to generate one. * @param signal - cancellation of the attempt. * @param held - whether a message waits for the creation before its turn starts. + * @param fetch - whether the attempt fetches its base first; true only for a remote-tracking base branch. * @returns the created worktree. * @throws {@link CreationFailure} when the attempt fails; the cancellation reason once `signal` aborts. */ - async create(agent: Agent, from: string | null, signal: AbortSignal, held: boolean): Promise { - return await this.run(signal, operation => this.createCheckout(agent, from, operation, held)) + async create(agent: Agent, request: ForgeWorktreeRequest, signal: AbortSignal, held: boolean, fetch: boolean): Promise { + return await this.run(signal, operation => this.createCheckout(agent, request, operation, held, fetch)) } - private async createCheckout(agent: Agent, from: string | null, signal: AbortSignal, held: boolean): Promise { + private async createCheckout( + agent: Agent, { from, name }: ForgeWorktreeRequest, signal: AbortSignal, held: boolean, fetch: boolean, + ): Promise { const worktrees = this.ctx.get('worktrees') if (worktrees === undefined) throw new Error('No worktree service is mounted') const session = agent.session - let status: ForgeWorktreeCreation = { phase: 'prepare', branch: generatedWorktreeName(this.prefix, session.id), from, held } + let status: ForgeWorktreeCreation = { + phase: fetch ? 'fetch' : 'prepare', branch: name ?? generatedWorktreeName(this.prefix, session.id), from, fetch, held, + } this.failures.delete(session) this.live.set(session, status) this.changed(session) try { let created: CreatedWorktree try { - created = await worktrees.create(agent, { name: status.branch, ...from === null ? {} : { from } }, signal, (phase) => { + const request = { name: status.branch, ...from === null ? {} : { from }, ...fetch ? { fetch } : {} } + created = await worktrees.create(agent, request, signal, (phase) => { status = { ...status, phase } this.live.set(session, status) this.changed(session) @@ -492,26 +520,28 @@ export class WorktreeCreations { */ private async runCreation(agent: Agent, hold: CreationHold, signal: AbortSignal): Promise { const session = agent.session + let skipFetch = false for (;;) { const state = this.states.stateOf(session) if (state.request === null || state.created !== null || state.locked) return const stop = new AbortController() hold.stop = stop + const fetch = !skipFetch && isRemoteRef(state.request.from) try { - await this.create(agent, state.request.from, AbortSignal.any([signal, stop.signal]), true) + await this.create(agent, state.request, AbortSignal.any([signal, stop.signal]), true, fetch) return } catch (error) { signal.throwIfAborted() if (stop.signal.aborted) this.failures.delete(session) - else this.failures.set(session, failureOf(error, state.request.from)) + else this.failures.set(session, failureOf(error, state.request.from, fetch)) this.changed(session) } finally { hold.stop = undefined } - while (await this.wait(hold, signal) !== 'retry') { - const current = this.states.stateOf(session) - if (current.request === null || current.created !== null || current.locked) return - } + const decision = await this.wait(hold, signal) + // A recheck decides only once the request no longer asks for a worktree. + if (decision.kind === 'recheck') return + skipFetch = !decision.fetch } } @@ -566,7 +596,7 @@ export class WorktreeCreations { private async preStep(agent: Agent, step: number, signal: AbortSignal, next: () => Promise): Promise { const state = this.states.stateOf(agent.session) if (step !== 1 || state.request === null || state.created !== null || state.stepped) return await next() - await this.create(agent, state.request.from, signal, false) + await this.create(agent, state.request, signal, false, isRemoteRef(state.request.from)) const decision = await next() if (decision.kind === 'reject' || decision.messages.length === 0) return decision const notices = agent.inbox.nextStep.filter(message => message.source.kind === 'working-directory') diff --git a/packages/experimental/client-ui-forge/tests/branch-name.host.spec.ts b/packages/experimental/client-ui-forge/tests/branch-name.host.spec.ts new file mode 100644 index 0000000000..f02f93e963 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/branch-name.host.spec.ts @@ -0,0 +1,76 @@ +/** Branch-name rules and branch labels shared by the Host and the Client. */ +import { execFileSync } from 'node:child_process' +import { describe, expect, it } from 'vitest' +import { branchLabel, branchNameProblem, isRemoteRef } from '../src/branch-name.ts' + +/** Whether Git accepts `name` as a new branch, as the worktree service checks it at creation. */ +function gitAccepts(name: string): boolean { + try { + execFileSync('git', ['check-ref-format', `refs/heads/${name}`], { stdio: 'ignore' }) + return true + } catch (error) { + void error // A nonzero exit is Git's refusal. + return false + } +} + +describe('branchNameProblem', () => { + it.each([ + ['', 'empty'], + ['fix login', 'space'], + ['fix\tlogin', 'space'], + ['fix\u007flogin', 'character'], + ['fix~1', 'character'], + ['fix^', 'character'], + ['a:b', 'character'], + ['a?b', 'character'], + ['a*b', 'character'], + ['a[b', 'character'], + ['a\\b', 'character'], + ['-fix', 'leading-dash'], + ['/fix', 'leading-slash'], + ['fix/', 'trailing-slash'], + ['fix//login', 'double-slash'], + ['fix..login', 'double-dot'], + ['fix.', 'trailing-dot'], + ['@', 'at'], + ['fix@{1}', 'at-brace'], + ['fix/.login', 'dot-segment'], + ['.fix', 'dot-segment'], + ['fix.lock/login', 'lock-segment'], + ['fix.lock', 'lock-segment'], + ] as const)('refuses %j as %s', (name, problem) => { + expect(branchNameProblem(name)).toBe(problem) + }) + + it.each(['fix-login', 'dsh-0a1b2c3d-9f3e', 'fix/login', 'a./b', 'a/@/b', 'é', 'HEAD'])('accepts %j', (name) => { + expect(branchNameProblem(name)).toBeNull() + }) + + it('refuses every name that Git refuses among these', () => { + for (const name of ['fix login', 'a..b', 'x@{y', 'a/.b', 'a/b.', 'aa.lock', 'fix//x', '/x', 'x/', 'a~b', 'a\\b', 'a[b']) { + expect(gitAccepts(name)).toBe(false) + expect(branchNameProblem(name)).not.toBeNull() + } + }) +}) + +describe('branchLabel', () => { + it('drops the prefix of a full local or remote-tracking branch name and keeps any other revision', () => { + expect(branchLabel('refs/heads/fix/login')).toBe('fix/login') + expect(branchLabel('refs/remotes/origin/main')).toBe('origin/main') + expect(branchLabel('main')).toBe('main') + expect(branchLabel('refs/heads/')).toBe('refs/heads/') + expect(branchLabel('refs/tags/v1')).toBe('refs/tags/v1') + }) +}) + +describe('isRemoteRef', () => { + it('recognizes the full name of a remote-tracking branch', () => { + expect(isRemoteRef('refs/remotes/origin/main')).toBe(true) + expect(isRemoteRef('refs/remotes/')).toBe(false) + expect(isRemoteRef('refs/heads/main')).toBe(false) + expect(isRemoteRef('origin/main')).toBe(false) + expect(isRemoteRef(null)).toBe(false) + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx b/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx index f52d042a69..fa1a11d9c0 100644 --- a/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom /** One change request card: state glyph, title link, collapsed summary, read notices, and expanded details and actions. */ import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import type { ForgeFailure, MergeRequest } from '@deepseek-ai/dsh-experimental-forge/types' import { ChangeRequestCard, type ChangeRequestActions } from '../src/client/ChangeRequestCard.tsx' @@ -10,6 +10,7 @@ import css from '../src/client/Forge.module.css' import overview from '../src/client/ChangeRequestOverview.module.css' import type { ForgePanelChangeRequest } from '../src/types.ts' import { check, entry, snapshot, unserved } from './client-fixtures.client.ts' +import './fonts-dom.client.ts' afterEach(cleanup) @@ -19,7 +20,7 @@ const NOW = Date.parse('2026-10-09T12:00:00Z') const MINUS = '−' /** Render one card inside its list, with every action recorded unless `actions` replaces it. */ -function card(value: ForgePanelChangeRequest, options: { expanded?: boolean; actions?: Partial } = {}) { +function card(value: ForgePanelChangeRequest, options: { expanded?: boolean; actions?: Partial; t?: typeof t } = {}) { const openLink = vi.fn<(url: string) => void>() const copyLink = vi.fn<(url: string) => void>() const retry = vi.fn<() => void>() @@ -28,7 +29,8 @@ function card(value: ForgePanelChangeRequest, options: { expanded?: boolean; act const actions: ChangeRequestActions = { openLink, copyLink, retry, remove, ...options.actions } const view = render(
      - +
    , ) const item = view.container.querySelector('[data-forge-change]') @@ -134,6 +136,19 @@ describe('ChangeRequestCard head', () => { } }) + it('crawls the collapsed number and status line with the title while the pointer rests on the head', () => { + const b = card(entry(7, snapshot(7))) + const line = metaOf(b).firstElementChild + if (!(line instanceof HTMLElement)) throw new Error('no status line') + expect(line.className).toContain(css.statusLine) + Object.defineProperty(line, 'scrollWidth', { value: 200, configurable: true }) + Object.defineProperty(line, 'clientWidth', { value: 150, configurable: true }) + fireEvent.pointerEnter(b.head) + expect([line.hasAttribute('data-marquee'), line.style.getPropertyValue('--dsh-marquee-range')]).toEqual([true, '50px']) + fireEvent.pointerLeave(b.head) + expect([line.hasAttribute('data-marquee'), line.style.getPropertyValue('--dsh-marquee-range')]).toEqual([false, '']) + }) + it('toggles from the chevron, while the number line stays plain text', () => { const b = card(entry(7, snapshot(7))) expect(b.item.hasAttribute('data-expanded')).toBe(false) @@ -189,6 +204,59 @@ describe('collapsed ChangeRequestCard', () => { expect(within(meta).getByText(text)).toBeTruthy() }) + /** + * Give status lines the given width and their content a width by wording, 200px with the full failed-checks wording and + * 150px with the short one, and capture the resize observer. Returns the setter of the width and the resize trigger. + */ + function fitting(initial: number) { + let available = initial + let resized: () => void = () => {} + vi.stubGlobal('ResizeObserver', class { + constructor(callback: () => void) { resized = callback } + observe = vi.fn() + disconnect = vi.fn() + }) + const isLine = (element: Element): boolean => element.matches(`.${css.statusLine}`) + const client = vi.spyOn(Element.prototype, 'clientWidth', 'get').mockImplementation(function (this: Element) { + return isLine(this) ? available : 0 + }) + const scroll = vi.spyOn(Element.prototype, 'scrollWidth', 'get').mockImplementation(function (this: Element) { + return isLine(this) ? (this.textContent ?? '').includes('2 checks failed') ? 200 : 150 : 0 + }) + onTestFinished(() => { + vi.unstubAllGlobals() + client.mockRestore() + scroll.mockRestore() + }) + return { + resize: (width: number): void => { available = width; act(() => { resized() }) }, + set: (width: number): void => { available = width }, + } + } + + const FAILING = { + checksRollup: 'failure', mergeability: 'conflicting', + checks: [check('lint', { state: 'failure' }), check('test'), check('types', { state: 'failure' })], + } as const + + it('takes the short wording of failed checks while the full line does not fit, and measures again on width and font changes', () => { + const fit = fitting(160) + const b = card(entry(1, snapshot(1, FAILING))) + const short = `#1·${en['change.ci.failedUnlisted']}${en['change.flag.conflicting']}` + expect(metaOf(b).textContent).toBe(short) + fit.resize(250) + expect(metaOf(b).textContent).toBe(`#1·2 checks failed${en['change.flag.conflicting']}`) + fit.set(160) + act(() => { document.fonts.dispatchEvent(new Event('loadingdone')) }) + expect(metaOf(b).textContent).toBe(short) + }) + + it('keeps the full wording of failed checks where the language has no shorter one', () => { + fitting(100) + const long = makeTranslate({ ...en, 'change.ci.failedUnlisted': 'Every check that ran has failed' }) + expect(metaOf(card(entry(1, snapshot(1, FAILING)), { t: long })).textContent).toBe(`#1·2 checks failed${en['change.flag.conflicting']}`) + }) + it.each([ ['merged three hours ago', { state: 'merged', closedAt: '2026-10-09T09:00:00Z' }, 'merged', 'Merged into main · 3 h ago'], ['closed without a close time', { state: 'closed' }, 'closed', en['change.state.closed']], diff --git a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx index 9addbc324e..defc8a96d0 100644 --- a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx @@ -224,6 +224,16 @@ function hostStream(frames: readonly F[], failure?: unknown): HostStream { } } +/** + * Whether the view shows its reading state: the reading status above file card placeholders, with the files menu naming + * no count. + */ +function reading(view: ReturnType): boolean { + return view.queryByRole('status')?.textContent === en['diff.loading'] + && view.container.querySelector('[data-forge-changes-skeleton]') !== null + && view.queryByRole('button', { name: en['diff.allFilesLoading'] }) !== null +} + /** Let the Remote reads the view awaits settle. */ async function settle(): Promise { await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)) }) @@ -576,9 +586,18 @@ describe('ChangesTab tooltips', () => { }) describe('ChangesTab local reads', () => { + it('draws the placeholders of a changed file in two columns only while sides are split', async () => { + const m = mount({ state: null }) + const columns = (): number => m.view.container.querySelectorAll('[data-forge-changes-skeleton] > :first-child > :last-child > *').length + expect(reading(m.view)).toBe(true) + expect(columns()).toBe(2) + act(() => { m.store.actions.toggledSplit(TAB) }) + expect(columns()).toBe(1) + }) + it('waits for the panel state, then reads the branch scope and draws its files', async () => { const m = mount({ state: null }) - expect(m.view.container.querySelector('[data-state="ongoing"]')).not.toBeNull() + expect(reading(m.view)).toBe(true) expect(m.view.queryByRole('button', { name: en['changes.local.create'] })).toBeNull() expect(m.view.container.querySelector('[data-forge-head]')?.textContent).toBe('HEAD') expect(m.faces.localDiff).not.toHaveBeenCalled() @@ -627,7 +646,7 @@ describe('ChangesTab local reads', () => { fireEvent.click(m.view.getByRole('button', { name: 'Branch' })) fireEvent.click(m.view.getByRole('menuitem', { name: 'Staged' })) expect(m.store.getSnapshot().byTab[TAB]?.scope).toBe('staged') - expect(m.view.container.querySelector('[data-state="ongoing"]')).not.toBeNull() + expect(reading(m.view)).toBe(true) expect(m.view.getByText('The index compared with HEAD')).toBeTruthy() expect(m.faces.localDiff).toHaveBeenLastCalledWith({ kind: 'staged' }, expect.any(AbortSignal)) await settle() @@ -858,7 +877,7 @@ describe('ChangesTab base branch', () => { fireEvent.click(m.view.getByRole('menuitem', { name: 'topic' })) expect(m.store.getSnapshot().byTab[TAB]?.base).toEqual(TOPIC) expect(m.faces.localDiff).toHaveBeenLastCalledWith({ kind: 'branch', base: TOPIC.ref, commits: null }, expect.any(AbortSignal)) - expect(m.view.container.querySelector('[data-state="ongoing"]')).not.toBeNull() + expect(reading(m.view)).toBe(true) await settle() expect(m.paths()).toHaveLength(6) @@ -1453,7 +1472,7 @@ describe('ChangesTab change requests', () => { const m = mount({ source, setup: (faces) => { faces.changeRequestDiff.mockResolvedValueOnce(REFUSED.staleHead) } }) await settle() expect(m.faces.changeRequestDiff).toHaveBeenCalledOnce() - expect(m.view.queryByRole('status')).toBeNull() + expect(reading(m.view)).toBe(true) expect(m.paths()).toEqual([]) // A later status with the same head reads again, as when the host's answers disagreed for a moment. @@ -1465,7 +1484,7 @@ describe('ChangesTab change requests', () => { act(() => { m.panel.set({ state: later(2, HEAD), disconnected: false }) }) await settle() expect(m.faces.changeRequestDiff).toHaveBeenCalledTimes(2) - expect(m.view.queryByRole('status')).toBeNull() + expect(reading(m.view)).toBe(true) act(() => { m.panel.set({ state: later(3, 'b'.repeat(40)), disconnected: false }) }) await settle() @@ -1520,7 +1539,7 @@ describe('ChangesTab change requests', () => { const m = mount({ source, state: ready({ changeRequests: [entry(7, null)] }) }) await settle() expect(m.faces.changeRequestDiff).not.toHaveBeenCalled() - expect(m.view.queryByRole('status')).toBeNull() + expect(reading(m.view)).toBe(true) act(() => { m.panel.set({ state: ready({ changeRequests: [entry(7, snapshot(7))] }), disconnected: false }) }) await settle() expect(m.faces.changeRequestDiff).toHaveBeenCalledOnce() diff --git a/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts b/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts index d2914b32e9..c7f42366f8 100644 --- a/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts +++ b/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts @@ -138,12 +138,12 @@ export function created(overrides: Partial = {}): ForgeSes /** Running creation of the branch `dsh/0a1b2c3d` from `main`, in its preparation step, that a message waits for. */ export function creation(overrides: Partial = {}): ForgeWorktreeCreation { - return { phase: 'prepare', branch: 'dsh/0a1b2c3d', from: 'main', held: true, ...overrides } + return { phase: 'prepare', branch: 'dsh/0a1b2c3d', from: 'main', fetch: false, held: true, ...overrides } } /** Failed attempt to create the branch `dsh/0a1b2c3d` from `main`, in its preparation step. */ export function failure(overrides: Partial = {}): ForgeWorktreeFailure { - return { branch: 'dsh/0a1b2c3d', from: 'main', phase: 'prepare', message: 'fatal: invalid reference: main', ...overrides } + return { branch: 'dsh/0a1b2c3d', from: 'main', fetch: false, phase: 'prepare', message: 'fatal: invalid reference: main', exists: false, ...overrides } } /** @@ -152,8 +152,8 @@ export function failure(overrides: Partial = {}): ForgeWor */ export function worktree(overrides: Partial = {}): ForgePanelWorktree { return { - editable: false, blocker: null, request: null, created: null, creation: null, failure: null, missing: null, restoration: null, - waiting: null, ...overrides, + editable: false, blocker: null, namePrefix: 'dsh-', request: null, created: null, creation: null, failure: null, missing: null, + restoration: null, waiting: null, ...overrides, } } @@ -171,9 +171,12 @@ export function ready(overrides: Partial = {}, checkoutOverride } } -/** Ready panel state of a Session that waits to start in a worktree requested from `from`, with further worktree facts. */ -export function requested(from: string | null = 'main', overrides: Partial = {}): ForgePanelState { - return ready({ worktree: worktree({ editable: true, request: { from }, ...overrides }) }) +/** + * Ready panel state of a Session that waits to start in a worktree requested from `from` on the branch `name`, or on a + * generated branch for null, with further worktree facts. + */ +export function requested(from: string | null = 'main', overrides: Partial = {}, name: string | null = null): ForgePanelState { + return ready({ worktree: worktree({ editable: true, request: { from, name }, ...overrides }) }) } /** diff --git a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts index cd8bf7f3b3..08d741cb0f 100644 --- a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts @@ -62,8 +62,8 @@ const ready = (state: ForgePanelState): boolean => state.checkout.state === 'rea /** Worktree facts of a Session without a worktree service, request, or creation, whose checkout can host a worktree. */ const UNAVAILABLE = { - editable: false, blocker: null, request: null, created: null, creation: null, failure: null, missing: null, restoration: null, - waiting: null, + editable: false, blocker: null, namePrefix: 'dsh-', request: null, created: null, creation: null, failure: null, missing: null, + restoration: null, waiting: null, } /** Matches a generated branch name with the default prefix. */ @@ -106,7 +106,7 @@ function worktreeState(opened: Bench, session: Session = opened.session): ForgeW * @returns the created worktree. */ async function startInWorktree(opened: Bench, from: string | null = null): Promise { - await opened.ctx.forgePanel.requestWorktree(opened.session, from, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, from, null, signal) sendPrompt(opened.agent, 'first') await opened.agent.whenIdle() const created = worktreeState(opened)?.created ?? null @@ -964,9 +964,9 @@ describe('forgePanel worktree requests', () => { const follower = reader(opened) await follower.until(ready) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) const requested = await follower.next(() => true) - await opened.ctx.forgePanel.requestWorktree(opened.session, 'main', signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'main', null, signal) const replaced = await follower.next(() => true) await opened.ctx.forgePanel.cancelWorktree(opened.session, signal) const withdrawn = await follower.next(() => true) @@ -975,8 +975,8 @@ describe('forgePanel worktree requests', () => { const editable = { ...UNAVAILABLE, editable: true } expect(follower.states[0]?.worktree).toEqual(editable) - expect(requested.worktree).toEqual({ ...editable, request: { from: null } }) - expect(replaced.worktree).toEqual({ ...editable, request: { from: 'main' } }) + expect(requested.worktree).toEqual({ ...editable, request: { from: null, name: null } }) + expect(replaced.worktree).toEqual({ ...editable, request: { from: 'main', name: null } }) expect(withdrawn.worktree).toEqual(editable) expect(started.worktree).toEqual(UNAVAILABLE) expect(opened.records).toEqual([{ action: 'request', from: null }, { action: 'request', from: 'main' }, { action: 'cancel' }]) @@ -987,7 +987,7 @@ describe('forgePanel worktree requests', () => { const opened = await open(repo, {}, { worktrees: true }) await opened.ctx.forgePanel.cancelWorktree(opened.session, signal) - await opened.ctx.forgePanel.requestWorktree(opened.session, 'main', signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'main', null, signal) await opened.ctx.forgePanel.cancelWorktree(opened.session, signal) await opened.ctx.forgePanel.cancelWorktree(opened.session, signal) @@ -997,10 +997,10 @@ describe('forgePanel worktree requests', () => { it('refuses worktree changes after the first turn starts', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) startTurn(opened.session, 1) - await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' }) + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', null, signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' }) await expect(opened.ctx.forgePanel.cancelWorktree(opened.session, signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' }) expect(opened.records).toEqual([{ action: 'request', from: null }]) }) @@ -1008,12 +1008,12 @@ describe('forgePanel worktree requests', () => { it('refuses worktree changes once the worktree exists, before any turn starts', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) await proposeStep(opened.ctx, opened.agent, { turn: 1, step: 1, messages: [prompt('go')], decision: { kind: 'reject' } }) - await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' }) + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', null, signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' }) await expect(opened.ctx.forgePanel.cancelWorktree(opened.session, signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' }) - expect(worktreeState(opened)).toMatchObject({ request: { from: null }, locked: false, stepped: false, restoring: false }) + expect(worktreeState(opened)).toMatchObject({ request: { from: null, name: null }, locked: false, stepped: false, restoring: false }) expect(opened.records).toEqual([{ action: 'request', from: null }]) expect(opened.created).toHaveLength(1) }) @@ -1032,13 +1032,13 @@ describe('forgePanel worktree requests', () => { const { repo } = await project() const opened = await open(repo) - await expect(opened.ctx.forgePanel.requestWorktree(opened.session, null, signal)).rejects.toMatchObject({ code: 'forgePanel/worktrees-unavailable' }) + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal)).rejects.toMatchObject({ code: 'forgePanel/worktrees-unavailable' }) expect(opened.records).toEqual([]) appendPluginRecord(opened.session, WORKTREE_RECORD, { action: 'request', from: null }) const follower = reader(opened) sendPrompt(opened.agent, 'first') const failed = await follower.until(state => state.worktree.failure !== null) - expect(failed.worktree.failure).toEqual({ branch: null, from: null, phase: 'prepare', message: 'No worktree service is mounted' }) + expect(failed.worktree.failure).toEqual({ branch: null, from: null, fetch: false, phase: 'prepare', message: 'No worktree service is mounted', exists: false }) // Withdrawing needs no worktree service, so the waiting message can go on. await opened.ctx.forgePanel.cancelWorktree(opened.session, signal) await opened.agent.whenIdle() @@ -1056,7 +1056,7 @@ describe('forgePanel worktree requests', () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await expect(opened.ctx.forgePanel.requestWorktree(opened.session, '', signal)).rejects.toMatchObject({ code: 'forgePanel/invalid-branch' }) + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, '', null, signal)).rejects.toMatchObject({ code: 'forgePanel/invalid-branch' }) expect(opened.records).toEqual([]) }) @@ -1065,7 +1065,7 @@ describe('forgePanel worktree requests', () => { const opened = await open(repo, {}, { worktrees: true }) const follower = reader(opened) await follower.until(ready) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) startTurn(opened.session, 1) await proposeStep(opened.ctx, opened.agent, { turn: 1, step: 1, messages: [prompt('Fix the bug')] }) @@ -1080,7 +1080,7 @@ describe('forgePanel worktree requests', () => { repository: demo, readiness: { state: 'ready', message: null, signIn: null }, changeRequests: [], - worktree: { ...UNAVAILABLE, request: { from: null }, created }, + worktree: { ...UNAVAILABLE, request: { from: null, name: null }, created }, local: { base: created?.baseCommit.slice(0, 7), files: [] }, }) expect(opened.provider.probes).toEqual(['fake.test']) @@ -1105,7 +1105,7 @@ describe('forgePanel worktree requests', () => { const worktree: ForgeSessionWorktree = { path: join(repo, 'elsewhere'), branch: 'dsh/0a1b2c3d', from: null, baseCommit: 'c'.repeat(40), repositoryRoot: repo } appendPluginRecord(opened.session, WORKTREE_RECORD, { action: 'created', worktree }) - await expect(pending).resolves.toMatchObject({ worktree: { ...UNAVAILABLE, request: { from: null }, created: worktree } }) + await expect(pending).resolves.toMatchObject({ worktree: { ...UNAVAILABLE, request: { from: null, name: null }, created: worktree } }) const later = follower.next(() => true) let republished = false @@ -1117,13 +1117,105 @@ describe('forgePanel worktree requests', () => { }) }) +describe('forgePanel named and remote-based worktrees', () => { + /** Whether the checkout was inspected; a clone of a local path names no code host, so no sign-in state follows. */ + const inspected = (state: ForgePanelState): boolean => state.checkout.state === 'ready' + + /** A clone of a fresh repository, which then gains a commit the clone has not fetched. */ + async function behind(): Promise<{ repo: string; fetched: string }> { + const { path, remove } = await scratch('dsh-forge-remote-') + cleanups.push(remove) + const upstream = await repository(path, 'upstream') + const repo = join(path, 'clone') + await git(path, 'clone', '--quiet', upstream, repo) + return { repo, fetched: await commitAt(upstream, 'remote.txt', '2026-02-01T00:00:00Z') } + } + + it('records a request that names its branch, and refuses an invalid or taken name without recording it', async () => { + const { repo } = await project() + const opened = await open(repo, {}, { worktrees: true }) + await git(repo, 'branch', 'taken') + + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'refs/heads/main', 'fix/', signal)) + .rejects.toMatchObject({ code: 'forgePanel/invalid-name' }) + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'refs/heads/main', 'taken', signal)) + .rejects.toMatchObject({ code: 'forgePanel/branch-exists' }) + expect(opened.records).toEqual([]) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'refs/heads/main', 'fix/login', signal) + + expect(opened.records).toEqual([{ action: 'request', from: 'refs/heads/main', name: 'fix/login' }]) + expect(worktreeState(opened).request).toEqual({ from: 'refs/heads/main', name: 'fix/login' }) + }) + + it('refuses a named request outside a checkout', async () => { + const opened = await open(await plain(), {}, { worktrees: true }) + + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, null, 'fix/login', signal)).rejects.toMatchObject({ code: 'forgePanel/not-a-checkout' }) + }) + + it('says a named attempt found its branch taken, and creates the worktree once the request names another branch', async () => { + const { repo } = await project() + const opened = await open(repo, {}, { worktrees: true }) + const follower = reader(opened) + await follower.until(ready) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, 'fix/login', signal) + // The branch appears after the request was checked, as when another checkout creates it meanwhile. + await git(repo, 'branch', 'fix/login') + + sendPrompt(opened.agent, 'first') + const failed = await follower.until(state => state.worktree.failure !== null && state.worktree.creation === null) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, 'fix/login-2', signal) + await opened.ctx.forgePanel.retryWorktree(opened.session, true, signal) + await opened.agent.whenIdle() + + expect(failed.worktree.failure).toMatchObject({ branch: 'fix/login', phase: 'prepare', exists: true, fetch: false }) + expect(worktreeState(opened).created).toMatchObject({ branch: 'fix/login-2', from: null }) + expect(queued(opened)).toEqual(['first']) + }) + + it('fetches a remote base branch before creating the worktree from the fetched commit', async () => { + const { repo, fetched } = await behind() + const opened = await open(repo, {}, { worktrees: true }) + const follower = reader(opened) + await follower.until(inspected) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'refs/remotes/origin/main', null, signal) + + sendPrompt(opened.agent, 'first') + const fetching = await follower.until(state => state.worktree.creation?.phase === 'fetch') + await opened.agent.whenIdle() + + expect(fetching.worktree.creation).toMatchObject({ from: 'refs/remotes/origin/main', fetch: true, held: true }) + expect(worktreeState(opened).created).toMatchObject({ from: 'refs/remotes/origin/main', baseCommit: fetched }) + }) + + it('keeps the message waiting after a failed fetch, and starts from the last fetched commit when asked to skip the fetch', async () => { + const { repo } = await behind() + const last = await git(repo, 'rev-parse', 'refs/remotes/origin/main') + await git(repo, 'remote', 'set-url', 'origin', join(repo, 'missing.git')) + const opened = await open(repo, {}, { worktrees: true }) + const follower = reader(opened) + await follower.until(inspected) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'refs/remotes/origin/main', null, signal) + + sendPrompt(opened.agent, 'first') + const failed = await follower.until(state => state.worktree.failure !== null && state.worktree.creation === null) + await opened.ctx.forgePanel.retryWorktree(opened.session, false, signal) + const retrying = await follower.next(state => state.worktree.creation !== null) + await opened.agent.whenIdle() + + expect(failed.worktree.failure).toMatchObject({ phase: 'fetch', fetch: true, exists: false, from: 'refs/remotes/origin/main' }) + expect(retrying.worktree.creation).toMatchObject({ phase: 'prepare', fetch: false }) + expect(worktreeState(opened).created).toMatchObject({ baseCommit: last }) + }) +}) + describe('forgePanel worktree creation while a message waits', () => { it('creates the requested worktree as Agent maintenance while the first message waits in the inbox, showing each step, then starts its turn', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) const follower = reader(opened) await follower.until(ready) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) const preparing = hold(opened.sandbox, 'check-ref-format') const checkingOut = hold(opened.sandbox, 'reset') @@ -1140,11 +1232,11 @@ describe('forgePanel worktree creation while a message waits', () => { const moved = await follower.until(state => state.directory === created?.path && state.checkout.state === 'ready' && state.worktree.waiting === null) const branch = created?.branch ?? '' - const running = { branch, from: null, held: true } - const waiting = { ...UNAVAILABLE, editable: true, request: { from: null }, waiting: 'creation' } + const running = { branch, from: null, fetch: false, held: true } + const waiting = { ...UNAVAILABLE, editable: true, request: { from: null, name: null }, waiting: 'creation' } expect(prepare.worktree).toEqual({ ...waiting, creation: { ...running, phase: 'prepare' } }) expect(checkout.worktree).toEqual({ ...waiting, creation: { ...running, phase: 'checkout' } }) - expect(moved.worktree).toEqual({ ...UNAVAILABLE, request: { from: null }, created }) + expect(moved.worktree).toEqual({ ...UNAVAILABLE, request: { from: null, name: null }, created }) expect(moved.checkout).toEqual({ state: 'ready', checkout: { root: created?.path, branch, linked: true, commit: COMMIT } }) expect(created).toEqual({ path: join(repo, '.agents', 'worktrees', ...branch.split('/')), @@ -1168,19 +1260,19 @@ describe('forgePanel worktree creation while a message waits', () => { const opened = await open(repo, {}, { worktrees: true }) const follower = reader(opened) await follower.until(ready) - await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', null, signal) sendPrompt(opened.agent, 'first') const failed = await follower.until(state => state.worktree.failure !== null && state.worktree.creation === null) expect(opened.agent.wakes).toBe(0) await git(repo, 'branch', 'later') - await opened.ctx.forgePanel.retryWorktree(opened.session, signal) + await opened.ctx.forgePanel.retryWorktree(opened.session, true, signal) const retrying = await follower.next(state => state.worktree.creation !== null) await opened.agent.whenIdle() expect(failed.worktree).toEqual({ - ...UNAVAILABLE, editable: true, request: { from: 'later' }, waiting: 'creation', - failure: { branch: GENERATED_BRANCH, from: 'later', phase: 'prepare', message: MISSING_BASE }, + ...UNAVAILABLE, editable: true, request: { from: 'later', name: null }, waiting: 'creation', + failure: { branch: GENERATED_BRANCH, from: 'later', fetch: false, phase: 'prepare', message: MISSING_BASE, exists: false }, }) expect(retrying.worktree.failure).toBeNull() const created = worktreeState(opened)?.created ?? null @@ -1197,20 +1289,20 @@ describe('forgePanel worktree creation while a message waits', () => { const opened = await open(repo, {}, { worktrees: true }) const follower = reader(opened) await follower.until(ready) - await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', null, signal) sendPrompt(opened.agent, 'first') await follower.until(state => state.worktree.failure !== null) - await opened.ctx.forgePanel.requestWorktree(opened.session, 'gone', signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'gone', null, signal) const changed = await follower.next(state => state.worktree.request?.from === 'gone') - await opened.ctx.forgePanel.retryWorktree(opened.session, signal) + await opened.ctx.forgePanel.retryWorktree(opened.session, true, signal) const failedAgain = await follower.next(state => state.worktree.failure !== null) const withdrawal = follower.next(state => state.worktree.request === null && state.worktree.waiting === null) await opened.ctx.forgePanel.cancelWorktree(opened.session, signal) await opened.agent.whenIdle() const withdrawn = await withdrawal - expect(changed.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: 'gone' }, waiting: 'creation' }) + expect(changed.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: 'gone', name: null }, waiting: 'creation' }) expect(failedAgain.worktree.failure).toMatchObject({ from: 'gone' }) expect(withdrawn.worktree).toEqual({ ...UNAVAILABLE, editable: true }) expect(opened.agent.wakes).toBe(1) @@ -1225,7 +1317,7 @@ describe('forgePanel worktree creation while a message waits', () => { const opened = await open(repo, {}, { worktrees: true }) const follower = reader(opened) await follower.until(ready) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) await opened.ctx.forgePanel.stopCreation(opened.session, signal) const held = hold(opened.sandbox, 'check-ref-format') @@ -1236,10 +1328,10 @@ describe('forgePanel worktree creation while a message waits', () => { held.release() const stopped = await stopping const before = { wakes: opened.agent.wakes, records: [...opened.records], cwd: opened.ctx.workingDirectory.get(opened.session) } - await opened.ctx.forgePanel.retryWorktree(opened.session, signal) + await opened.ctx.forgePanel.retryWorktree(opened.session, true, signal) await opened.agent.whenIdle() - expect(stopped.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: null }, waiting: 'creation' }) + expect(stopped.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: null, name: null }, waiting: 'creation' }) expect(before).toEqual({ wakes: 0, records: [{ action: 'request', from: null }], cwd: repo }) expect(worktreeState(opened)?.created).toMatchObject({ from: null, repositoryRoot: repo }) expect(opened.agent.wakes).toBe(1) @@ -1250,14 +1342,14 @@ describe('forgePanel worktree creation while a message waits', () => { const opened = await open(repo, {}, { worktrees: true }) const follower = reader(opened) await follower.until(ready) - await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', null, signal) sendPrompt(opened.agent, 'first') await follower.until(state => state.worktree.failure !== null) await git(repo, 'branch', 'later') // Both decisions arrive before the wait resumes, so the next attempt reads the withdrawn request. await Promise.all([ - opened.ctx.forgePanel.retryWorktree(opened.session, signal), + opened.ctx.forgePanel.retryWorktree(opened.session, true, signal), opened.ctx.forgePanel.cancelWorktree(opened.session, signal), ]) await opened.agent.whenIdle() @@ -1270,13 +1362,13 @@ describe('forgePanel worktree creation while a message waits', () => { it('refuses another attempt while no message waits or an attempt runs', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await expect(opened.ctx.forgePanel.retryWorktree(opened.session, signal)).rejects.toMatchObject({ code: 'forgePanel/not-waiting' }) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await expect(opened.ctx.forgePanel.retryWorktree(opened.session, true, signal)).rejects.toMatchObject({ code: 'forgePanel/not-waiting' }) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) const held = hold(opened.sandbox, 'check-ref-format') sendPrompt(opened.agent, 'first') await held.reached - await expect(opened.ctx.forgePanel.retryWorktree(opened.session, signal)).rejects.toMatchObject({ code: 'forgePanel/not-waiting' }) + await expect(opened.ctx.forgePanel.retryWorktree(opened.session, true, signal)).rejects.toMatchObject({ code: 'forgePanel/not-waiting' }) held.release() await opened.agent.whenIdle() @@ -1289,7 +1381,7 @@ describe('forgePanel worktree creation while a message waits', () => { const opened = await open(repo, {}, { worktrees: true }) const follower = reader(opened) await follower.until(ready) - await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', null, signal) sendPrompt(opened.agent, 'first') await follower.until(state => state.worktree.failure !== null) @@ -1298,16 +1390,16 @@ describe('forgePanel worktree creation while a message waits', () => { await opened.agent.whenIdle() const ended = await ending - expect(ended.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: 'later' } }) + expect(ended.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: 'later', name: null } }) expect(opened.agent.wakes).toBe(0) expect(queued(opened)).toEqual([]) - expect(worktreeState(opened)).toMatchObject({ request: { from: 'later' }, created: null }) + expect(worktreeState(opened)).toMatchObject({ request: { from: 'later', name: null }, created: null }) }) it('lets the waiting message go on when the panel stops', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', null, signal) sendPrompt(opened.agent, 'first') await vi.waitFor(() => { expect(() => opened.agent.runMaintenance(() => Promise.resolve())).toThrow('already has active work') }) @@ -1316,13 +1408,13 @@ describe('forgePanel worktree creation while a message waits', () => { expect(opened.agent.wakes).toBe(1) expect(queued(opened)).toEqual(['first']) - expect(worktreeState(opened)).toMatchObject({ request: { from: 'later' }, created: null }) + expect(worktreeState(opened)).toMatchObject({ request: { from: 'later', name: null }, created: null }) }) it('holds one wait for every message that arrives during it', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) const held = hold(opened.sandbox, 'check-ref-format') sendPrompt(opened.agent, 'first') @@ -1342,7 +1434,7 @@ describe('forgePanel worktree creation while a message waits', () => { const opened = await open(repo, {}, { worktrees: true }) const follower = reader(opened) await follower.until(ready) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) await follower.until(state => state.worktree.request !== null) const release = occupy(opened) @@ -1351,16 +1443,16 @@ describe('forgePanel worktree creation while a message waits', () => { const busy = follower.states.at(-1) await release() - expect(busy?.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: null } }) + expect(busy?.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: null, name: null } }) expect(opened.agent.wakes).toBe(1) - expect(worktreeState(opened)).toMatchObject({ request: { from: null }, created: null }) + expect(worktreeState(opened)).toMatchObject({ request: { from: null, name: null }, created: null }) expect(await branches(repo)).toEqual(['main']) }) it('lets a message go on without a wait once the first turn started, leaving the worktree to the first step', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) startTurn(opened.session, 1) sendPrompt(opened.agent, 'steer') @@ -1368,7 +1460,7 @@ describe('forgePanel worktree creation while a message waits', () => { expect(opened.agent.wakes).toBe(1) expect(queued(opened)).toEqual(['steer']) - expect(worktreeState(opened)).toMatchObject({ request: { from: null }, created: null, locked: true }) + expect(worktreeState(opened)).toMatchObject({ request: { from: null, name: null }, created: null, locked: true }) expect(await branches(repo)).toEqual(['main']) }) }) @@ -1377,13 +1469,13 @@ describe('forgePanel worktree requests during a creation', () => { it('refuses to change or withdraw the request while the worktree is being created, so the creation is recorded', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) const held = hold(opened.sandbox, 'check-ref-format') sendPrompt(opened.agent, 'first') await held.reached await expect(opened.ctx.forgePanel.cancelWorktree(opened.session, signal)).rejects.toMatchObject({ code: 'forgePanel/session-busy' }) - await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', signal)) + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', null, signal)) .rejects.toMatchObject({ code: 'forgePanel/session-busy' }) held.release() await opened.agent.whenIdle() @@ -1425,11 +1517,11 @@ describe('forgePanel removed worktrees', () => { await opened.agent.whenIdle() const restored = await restoration - expect(missing.worktree).toEqual({ ...UNAVAILABLE, request: { from: null }, created, missing: { branchExists: true }, waiting: 'restoration' }) + expect(missing.worktree).toEqual({ ...UNAVAILABLE, request: { from: null, name: null }, created, missing: { branchExists: true }, waiting: 'restoration' }) expect(preparing.worktree).toMatchObject({ missing: { branchExists: true }, restoration: { phase: 'prepare' }, waiting: 'restoration' }) expect(checkingOut.worktree.restoration).toEqual({ phase: 'checkout' }) expect(restored).toMatchObject({ directory: created.path, checkout: { state: 'ready', checkout: { root: created.path, branch: created.branch } } }) - expect(restored.worktree).toEqual({ ...UNAVAILABLE, request: { from: null }, created }) + expect(restored.worktree).toEqual({ ...UNAVAILABLE, request: { from: null, name: null }, created }) expect(await git(created.path, 'rev-parse', 'HEAD')).toBe(tip) expect(await readFile(join(created.path, 'later.txt'), 'utf8')).toBe('later.txt\n') expect(opened.ctx.workingDirectory.get(opened.session)).toBe(created.path) @@ -1458,7 +1550,7 @@ describe('forgePanel removed worktrees', () => { await opened.agent.whenIdle() const restored = await restoration - expect(gone.worktree).toEqual({ ...UNAVAILABLE, request: { from: null }, created, missing: { branchExists: false }, waiting: 'restoration' }) + expect(gone.worktree).toEqual({ ...UNAVAILABLE, request: { from: null, name: null }, created, missing: { branchExists: false }, waiting: 'restoration' }) expect(await git(repo, 'rev-parse', created.branch)).toBe(created.baseCommit) expect(restored.checkout).toEqual({ state: 'ready', checkout: { root: created.path, branch: created.branch, linked: true, commit: COMMIT } }) await expect(access(join(created.path, 'later.txt'))).rejects.toMatchObject({ code: 'ENOENT' }) @@ -1677,7 +1769,7 @@ describe('forgePanel leaving a worktree', () => { expect(opened.agent.inbox.nextStep).toEqual([notice(repo)]) expect(queued(opened)).toEqual(['next']) expect(moved.checkout).toEqual({ state: 'ready', checkout: { root: repo, branch: 'main', linked: false, commit: COMMIT } }) - expect(moved.worktree).toEqual({ ...UNAVAILABLE, request: { from: null }, created }) + expect(moved.worktree).toEqual({ ...UNAVAILABLE, request: { from: null, name: null }, created }) expect(await branches(repo)).toEqual([created.branch, 'main']) }) @@ -1991,23 +2083,37 @@ describe('forgePanel actions', () => { expect(opened.provider.actions).toEqual([]) }) - it('lists the base branches of the Session\'s current checkout, at most maxBranches', async () => { + it('lists the bases of a new worktree: the checked-out branch, remote defaults, local branches, and each remote, at most maxBranches each', async () => { const { repo } = await project() + await withDefaultBranch(repo) + await git(repo, 'remote', 'add', 'fork', '/srv/fork.git') await commitAt(repo, 'main.txt', '2026-03-01T00:00:00Z') await git(repo, 'checkout', '-b', 'older') await commitAt(repo, 'older.txt', '2026-01-01T00:00:00Z') + await git(repo, 'update-ref', 'refs/remotes/origin/topic', 'HEAD') + await git(repo, 'update-ref', 'refs/remotes/fork/idea', 'HEAD') await git(repo, 'checkout', '-b', 'newer', 'main') await commitAt(repo, 'newer.txt', '2026-02-01T00:00:00Z') - const opened = await open(repo, { maxBranches: 2 }) + const opened = await open(repo, { maxBranches: 1 }) - await expect(opened.ctx.forgePanel.branches(opened.session, signal)).resolves.toEqual({ current: 'newer', branches: ['newer', 'main'] }) + await expect(opened.ctx.forgePanel.worktreeBases(opened.session, '', signal)).resolves.toEqual({ + current: { ref: 'refs/heads/newer', name: 'newer' }, + defaults: [{ ref: 'refs/remotes/origin/main', name: 'origin/main', remote: 'origin' }], + local: [{ ref: 'refs/heads/main', name: 'main' }], + remotes: [ + { name: 'origin', repository: 'octo/demo', branches: [{ ref: 'refs/remotes/origin/topic', name: 'origin/topic' }] }, + { name: 'fork', repository: '/srv/fork.git', branches: [{ ref: 'refs/remotes/fork/idea', name: 'fork/idea' }] }, + ], + }) + await expect(opened.ctx.forgePanel.worktreeBases(opened.session, 'IDEA', signal)).resolves.toEqual({ + current: null, defaults: [], local: [], remotes: [{ name: 'fork', repository: '/srv/fork.git', branches: [{ ref: 'refs/remotes/fork/idea', name: 'fork/idea' }] }], + }) }) - it('refuses to list branches outside a checkout', async () => { + it('refuses to list worktree bases outside a checkout', async () => { const opened = await open(await plain()) - await expect(opened.ctx.forgePanel.branches(opened.session, signal)) - .rejects.toThrow(/^git (symbolic-ref|for-each-ref) failed \(128\): fatal: not a git repository/) + await expect(opened.ctx.forgePanel.worktreeBases(opened.session, '', signal)).rejects.toMatchObject({ code: 'forgePanel/not-a-checkout' }) }) it('checks the caller signal before every action', async () => { @@ -2025,8 +2131,8 @@ describe('forgePanel actions', () => { await expect(opened.ctx.forgePanel.changeRequestText(opened.session, pullUrl(1), 'a'.repeat(40), 'x', controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.markReady(opened.session, pullUrl(1), controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.merge(opened.session, pullUrl(1), 'merge', 'a'.repeat(40), controller.signal)).rejects.toThrow('closed') - await expect(opened.ctx.forgePanel.branches(opened.session, controller.signal)).rejects.toThrow('closed') - await expect(opened.ctx.forgePanel.requestWorktree(opened.session, null, controller.signal)).rejects.toThrow('closed') + await expect(opened.ctx.forgePanel.worktreeBases(opened.session, '', controller.signal)).rejects.toThrow('closed') + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, null, null, controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.cancelWorktree(opened.session, controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.stopCreation(opened.session, controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.restoreWorktree(opened.session, controller.signal)).rejects.toThrow('closed') @@ -2039,7 +2145,7 @@ describe('forgePanel lifecycle', () => { it('removes its Remote, worktree projection, and inbox and pre-step listeners when stopped, and folds the recorded request again after a restart', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) const proposed = prompt('go') const row = opened.ctx.sessionProjections.checkpoint(opened.session).forgeWorktree @@ -2057,7 +2163,7 @@ describe('forgePanel lifecycle', () => { await opened.ctx.plugin(ForgePanelController, {}) expect(opened.ctx.sessionProjections.checkpoint(opened.session).forgeWorktree?.val) - .toEqual({ request: { from: null }, created: null, locked: false, stepped: false, cwd: repo, restoring: false }) + .toEqual({ request: { from: null, name: null }, created: null, locked: false, stepped: false, cwd: repo, restoring: false }) }) }) @@ -2142,7 +2248,7 @@ describe('worktree recovery and unload', () => { const opened = await open(repo, {}, { worktrees: true }) const created = kind !== 'creation' ? await startInWorktree(opened) : undefined if (created !== undefined) await rm(created.path, { recursive: true, force: true }) - else await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + else await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) const entered: PromiseWithResolvers = Promise.withResolvers() const released: PromiseWithResolvers = Promise.withResolvers() let cancellation: AbortSignal | undefined diff --git a/packages/experimental/client-ui-forge/tests/git.host.spec.ts b/packages/experimental/client-ui-forge/tests/git.host.spec.ts index b956f0b858..8225d0edf3 100644 --- a/packages/experimental/client-ui-forge/tests/git.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/git.host.spec.ts @@ -5,7 +5,7 @@ import { Context } from '@deepseek-ai/cordis' import { SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox' import LocalSandbox from '@deepseek-ai/dsh-sandbox-local' import { setSandboxMode } from '@deepseek-ai/dsh-sandbox-policy' -import { hasBranch, inspectCheckout, listBranches } from '../src/git.ts' +import { hasBranch, inspectCheckout } from '../src/git.ts' import type { GitConfig } from '../src/git.ts' import { commitAt, git, gitContext, plainSession, repository, sandboxRecord, scratch, script } from './harness.ts' import type { SandboxRecord } from './harness.ts' @@ -67,10 +67,9 @@ describe('Session permissions for Git inspection', () => { const beforeStat = await stat(index) await expect(inspectCheckout(ctx, CONFIG, current, repo, live())).resolves.toMatchObject({ checkout: { branch: 'main' } }) - await expect(listBranches(ctx, CONFIG, current, repo, 50, live())).resolves.toEqual({ current: 'main', branches: ['main'] }) await expect(hasBranch(ctx, CONFIG, current, repo, 'main', live())).resolves.toBe(true) - expect(record.calls).toHaveLength(mode === 'danger-full-access' ? 0 : 10) + expect(record.calls).toHaveLength(mode === 'danger-full-access' ? 0 : 8) expect(record.calls.every(call => call.policy.mode === mode)).toBe(true) expect(await readFile(index)).toEqual(before) expect((await stat(index)).mtimeMs).toBe(beforeStat.mtimeMs) @@ -128,7 +127,7 @@ describe('inspectCheckout', () => { 'rev-parse --path-format=absolute --git-dir', 'rev-parse --short HEAD', 'rev-parse --show-toplevel', - 'symbolic-ref --quiet --short HEAD', + 'symbolic-ref --quiet HEAD', ]) for (const call of record.calls) { expect(call.policy).toMatchObject({ mode: 'workspace-write', workspaceRoot: repo }) @@ -174,6 +173,19 @@ describe('inspectCheckout', () => { }) }) + it('names the checked-out branch while a tag shares its name, and no branch while HEAD names another ref', async () => { + const root = await directory() + const repo = await repository(root) + await git(repo, 'tag', 'main') + const ctx = await context(sandboxRecord(), repo) + + // `git symbolic-ref --short HEAD` prints `heads/main` here. + expect((await inspectCheckout(ctx, CONFIG, session(repo), repo, live()))?.checkout.branch).toBe('main') + await git(repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD') + await git(repo, 'symbolic-ref', 'HEAD', 'refs/remotes/origin/main') + expect((await inspectCheckout(ctx, CONFIG, session(repo), repo, live()))?.checkout.branch).toBeNull() + }) + it('stops when the caller aborts', async () => { const root = await directory() const ctx = await context(sandboxRecord(), root) @@ -243,7 +255,7 @@ describe.skipIf(!posix)('inspectCheckout with a stand-in Git', () => { ` *--git-common-dir*) echo "${alias}/.git" ;;`, ` *--git-dir*) echo "${alias}/.git" ;;`, ' *"rev-parse --short"*) echo 0a1b2c3 ;;', - ' *symbolic-ref*) echo main ;;', + ' *symbolic-ref*) echo refs/heads/main ;;', ' *--abbrev-ref*) echo origin/main ;;', 'esac', ].join('\n')) @@ -307,79 +319,6 @@ describe.skipIf(!posix)('inspectCheckout with a stand-in Git', () => { }) }) -describe('listBranches', () => { - it('lists the checked-out branch first, then local branches by latest commit, with two read-only commands', async () => { - const root = await directory() - const repo = await branched(root) - const record = sandboxRecord() - const ctx = await context(record, repo) - - await expect(listBranches(ctx, CONFIG, session(repo), repo, 50, live())).resolves.toEqual({ - current: 'main', branches: ['main', 'newer', 'older'], - }) - expect(commands(record)).toEqual([ - 'for-each-ref --sort=-committerdate --count=50 --format=%(refname:lstrip=2) refs/heads/', - 'symbolic-ref --quiet --short HEAD', - ]) - for (const call of record.calls) { - expect(call.policy).toMatchObject({ mode: 'workspace-write', workspaceRoot: repo }) - expect(call.argv.slice(1, 1 + GIT_PREFIX.length)).toEqual(GIT_PREFIX) - } - }) - - it('keeps the checked-out branch first when the limit cuts it from the listing', async () => { - const root = await directory() - const repo = await branched(root) - await git(repo, 'checkout', 'older') - const ctx = await context(sandboxRecord(), repo) - - await expect(listBranches(ctx, CONFIG, session(repo), repo, 2, live())).resolves.toEqual({ current: 'older', branches: ['older', 'main'] }) - await expect(listBranches(ctx, CONFIG, session(repo), repo, 1, live())).resolves.toEqual({ current: 'older', branches: ['older'] }) - }) - - it('lists the branches of a detached HEAD without a current one, and an unborn branch alone', async () => { - const root = await directory() - const repo = await branched(root) - await git(repo, 'checkout', '--detach', 'main') - await git(root, 'init', '-b', 'main', 'empty') - const ctx = await context(sandboxRecord(), root) - - await expect(listBranches(ctx, CONFIG, session(root), repo, 2, live())).resolves.toEqual({ current: null, branches: ['main', 'newer'] }) - await expect(listBranches(ctx, CONFIG, session(root), join(root, 'empty'), 50, live())).resolves.toEqual({ current: 'main', branches: ['main'] }) - }) - - it('fails outside a checkout', async () => { - const root = await directory() - const ctx = await context(sandboxRecord(), root) - - await expect(listBranches(ctx, CONFIG, session(root), root, 50, live())) - .rejects.toThrow(/^git (symbolic-ref|for-each-ref) failed \(128\): fatal: not a git repository/) - }) - - it.skipIf(!posix)('names a failing branch listing', async () => { - const root = await directory() - const fake = await script(join(root, 'git'), [ - 'case "$*" in', - ' *for-each-ref*) echo "fatal: bad ref" >&2; exit 2 ;;', - ' *symbolic-ref*) echo main ;;', - 'esac', - ].join('\n')) - const ctx = await context(sandboxRecord(), root) - - await expect(listBranches(ctx, { ...CONFIG, gitCommand: fake }, session(root), root, 50, live())) - .rejects.toThrow('git for-each-ref failed (2): fatal: bad ref') - }) - - it('stops when the caller aborts', async () => { - const root = await directory() - const ctx = await context(sandboxRecord(), root) - const controller = new AbortController() - controller.abort(new Error('closed')) - - await expect(listBranches(ctx, CONFIG, session(root), root, 50, controller.signal)).rejects.toThrow('closed') - }) -}) - describe('hasBranch', () => { it('reports whether a local branch exists with one read-only command per question', async () => { const root = await directory() @@ -445,7 +384,7 @@ const sandboxUsable = await (async () => { })() describe.skipIf(!sandboxUsable)('Git inspection under the local sandbox', () => { - it('reads a checkout and lists its branches under read-only confinement without writing its index', async () => { + it('reads a checkout under read-only confinement without writing its index', async () => { const root = await directory() const repo = await repository(root) await writeFile(join(repo, 'tracked.txt'), 'changed\n') @@ -460,9 +399,8 @@ describe.skipIf(!sandboxUsable)('Git inspection under the local sandbox', () => checkout: { root: repo, branch: 'main', linked: false, commit: await git(repo, 'rev-parse', '--short', 'HEAD') }, commonDir: join(repo, '.git'), upstream: null, remotes: [], }) - await expect(listBranches(ctx, CONFIG, readOnly, repo, 50, live())).resolves.toEqual({ current: 'main', branches: ['main'] }) - expect(confine).toHaveBeenCalledTimes(9) + expect(confine).toHaveBeenCalledTimes(7) expect(confine.mock.calls.every(call => call[1].mode === 'read-only')).toBe(true) expect((await stat(index)).mtimeMs).toBe(before.mtimeMs) await expect(access(join(repo, '.git', 'index.lock'))).rejects.toThrow() @@ -471,7 +409,7 @@ describe.skipIf(!sandboxUsable)('Git inspection under the local sandbox', () => describe('parallel inspection cleanup', () => { - it.each(['checkout', 'branches'] as const)('cancels and joins sibling reads when %s inspection fails', async (kind) => { + it('cancels and joins sibling reads when checkout inspection fails', async () => { const root = await directory() const repo = await repository(root) const ctx = await context(sandboxRecord(), repo) @@ -480,8 +418,8 @@ describe('parallel inspection cleanup', () => { const original = ctx.sandbox.confine.bind(ctx.sandbox) let sibling: AbortSignal | undefined const failure = new Error('inspection failed') - const heldArg = kind === 'checkout' ? '--git-common-dir' : 'symbolic-ref' - const failedArg = kind === 'checkout' ? 'remote' : 'for-each-ref' + const heldArg = '--git-common-dir' + const failedArg = 'remote' const probe = vi.spyOn(ctx.sandbox, 'confine').mockImplementation(async (argv, policy, signal) => { if (argv.includes(heldArg)) { sibling = signal @@ -492,9 +430,7 @@ describe('parallel inspection cleanup', () => { return original(argv, policy, signal) }) let settled = false - const operation = (kind === 'checkout' - ? inspectCheckout(ctx, CONFIG, session(repo), repo, live()) - : listBranches(ctx, CONFIG, session(repo), repo, 50, live())) + const operation = inspectCheckout(ctx, CONFIG, session(repo), repo, live()) .then(() => { settled = true; return undefined }, (error: unknown) => { settled = true; return error }) try { await entered.promise diff --git a/packages/experimental/client-ui-forge/tests/mount.client.spec.ts b/packages/experimental/client-ui-forge/tests/mount.client.spec.ts index 04d66b7c75..fabc4f46de 100644 --- a/packages/experimental/client-ui-forge/tests/mount.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/mount.client.spec.ts @@ -43,9 +43,9 @@ import type { WorktreeSettingsInjected, WorktreeSettings as WorktreeSettingsFiel import { WorktreeToggle, type WorktreeToggleInjected } from '../src/client/WorktreeToggle.tsx' import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types' import type { - ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeExtensionState, ForgeLensFrame, + ForgeBaseBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeExtensionState, ForgeLensFrame, ForgeLensRequest, - ForgeCommitRange, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgePanelState, + ForgeCommitRange, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgePanelState, ForgeWorktreeBases, } from '../src/types.ts' import { entry, listState, ready, snapshot, unserved } from './client-fixtures.client.ts' import { brandString } from '@deepseek-ai/dsh-brand' @@ -53,7 +53,7 @@ import { brandString } from '@deepseek-ai/dsh-brand' const REMOTE: TypertRemoteContribution = { package: '@deepseek-ai/dsh-experimental-client-ui-forge', descriptors: [] } const S1 = brandString('s1') const S2 = brandString('s2') -const BRANCHES: ForgeBranches = { current: 'main', branches: ['main', 'release'] } +const BASES: ForgeWorktreeBases = { current: { ref: 'refs/heads/main', name: 'main' }, defaults: [], local: [], remotes: [] } const LOCAL: ForgeLocalDiff = { base: 'origin/main', files: [], omitted: 0 } const CHANGE: ForgeChangeRequestDiff = { headSha: 'a'.repeat(40), files: [], localAhead: null, fileUrls: {} } const COMMITS: ForgeCommitList = { headSha: 'a'.repeat(40), commits: [], truncated: false } @@ -98,6 +98,8 @@ const REFUSED = { busy: { ok: false, error: new RemoteError('forgePanel/session-busy', 'busy', {}) }, restore: { ok: false, error: new RemoteError('forgePanel/restore-failed', 'fatal: \'/work/repo-dsh\' already exists', {}) }, failed: { ok: false, error: new RemoteError('gateway/bad-request', 'failed', {}) }, + exists: { ok: false, error: new RemoteError('forgePanel/branch-exists', 'taken', {}) }, + invalidName: { ok: false, error: new RemoteError('forgePanel/invalid-name', 'invalid', {}) }, stale: { ok: false, error: new RemoteError('forgePanel/stale-head', 'Head branch was modified', {}) }, refused: { ok: false, error: new RemoteError('forgePanel/action-failed', 'Pull Request is not mergeable', {}) }, unknown: { ok: false, error: new RemoteError('forgePanel/action-unknown', 'Something went wrong', {}) }, @@ -128,7 +130,7 @@ function isAttentionFace(value: Record): value is Record): value is Record & WorktreeToggleInjected { - return typeof value.request === 'function' && typeof value.branches === 'function' + return typeof value.request === 'function' && typeof value.bases === 'function' } function isProgressFace(value: Record): value is Record & WorktreeProgressInjected { @@ -204,13 +206,14 @@ async function base() { ): Read => ({ ok: true, value: null })), setFileViewed: vi.fn(async (_sessionId: SessionId, _url: string, _request: ForgeViewedRequest): Promise> => OK), refresh: vi.fn(async (_sessionId: SessionId): Promise> => OK), - requestWorktree: vi.fn(async (_sessionId: SessionId, _from: string | null): Promise> => OK), + requestWorktree: vi.fn(async (_sessionId: SessionId, _from: string | null, _name: string | null): Promise> => OK), cancelWorktree: vi.fn(async (_sessionId: SessionId): Promise> => OK), stopCreation: vi.fn(async (_sessionId: SessionId): Promise> => OK), - retryWorktree: vi.fn(async (_sessionId: SessionId): Promise> => OK), + retryWorktree: vi.fn(async (_sessionId: SessionId, _fetch: boolean): Promise> => OK), restoreWorktree: vi.fn(async (_sessionId: SessionId): Promise> => OK), continueInProject: vi.fn(async (_sessionId: SessionId): Promise> => OK), - branches: vi.fn(async (_sessionId: SessionId): Promise> => ({ ok: true, value: BRANCHES })), + worktreeBases: vi.fn(async (_sessionId: SessionId, _query: string, _signal?: AbortSignal): Read => + ({ ok: true, value: BASES })), localDiff: vi.fn(async (_sessionId: SessionId, _scope: ForgeLocalScope, _signal?: AbortSignal): Read => ({ ok: true, value: LOCAL })), localText: vi.fn(async (_sessionId: SessionId, _scope: ForgeLocalScope, _path: string): Read => ({ ok: true, value: 'a\n' })), @@ -854,10 +857,10 @@ describe('mountForgePanel worktree actions', () => { it('requests and withdraws a worktree through the Remote', async () => { const f = await fixture() const option = f.worktree(S1) - expect(await option.request('release')).toBe(true) - expect(await option.request(null)).toBe(true) + expect(await option.request('refs/heads/release', 'fix/x')).toBe('accepted') + expect(await option.request(null, null)).toBe('accepted') expect(await option.cancel()).toBe(true) - expect(f.forgePanel.requestWorktree.mock.calls).toEqual([[S1, 'release'], [S1, null]]) + expect(f.forgePanel.requestWorktree.mock.calls).toEqual([[S1, 'refs/heads/release', 'fix/x'], [S1, null, null]]) expect(f.forgePanel.cancelWorktree).toHaveBeenCalledWith(S1) expect(f.notice()).toBeNull() await f.dispose() @@ -871,7 +874,7 @@ describe('mountForgePanel worktree actions', () => { const f = await fixture() const option = f.worktree(S1) f.forgePanel.requestWorktree.mockResolvedValueOnce(refusal) - expect(await option.request('main')).toBe(false) + expect(await option.request('refs/heads/main', null)).toBe('failed') expect(f.notice()).toMatchObject({ key, tone: 'failure', seq: 1 }) f.forgePanel.cancelWorktree.mockResolvedValueOnce(refusal) expect(await option.cancel()).toBe(false) @@ -879,33 +882,42 @@ describe('mountForgePanel worktree actions', () => { await f.dispose() }) - it('lists the branches of the Session checkout and reports when they cannot be read', async () => { + it.each([ + ['branch-exists', REFUSED.exists], + ['invalid-name', REFUSED.invalidName], + ] as const)('returns a branch name refused as %s to the naming dialog without a notice', async (result, refusal) => { const f = await fixture() - expect(await f.worktree(S1).branches()).toEqual(BRANCHES) - expect(f.forgePanel.branches).toHaveBeenCalledWith(S1) + f.forgePanel.requestWorktree.mockResolvedValueOnce(refusal) + expect(await f.worktree(S1).request(null, 'taken')).toBe(result) + f.forgePanel.requestWorktree.mockResolvedValueOnce(refusal) + expect(await f.progress(S1).request(null, 'taken')).toBe(result) expect(f.notice()).toBeNull() + await f.dispose() + }) - f.forgePanel.branches.mockResolvedValueOnce(REFUSED.failed) - expect(await f.worktree(S1).branches()).toBeUndefined() - expect(f.notice()).toMatchObject({ key: 'toast.branchesFailed', tone: 'failure' }) + it('lists the bases of a new worktree through the Remote', async () => { + const f = await fixture() + const signal = new AbortController().signal + expect(await f.worktree(S1).bases('rel', signal)).toEqual({ ok: true, value: BASES }) + expect(f.forgePanel.worktreeBases).toHaveBeenCalledWith(S1, 'rel', signal) await f.dispose() }) }) describe('mountForgePanel worktree card actions', () => { it.each([ - ['stops the attempt a message waits for', 'stop' as const, 'stopCreation' as const], - ['makes another attempt for the waiting message', 'retry' as const, 'retryWorktree' as const], - ['withdraws the request so the waiting message goes on', 'withdraw' as const, 'cancelWorktree' as const], - ])('%s through the Remote and reports only a failure', async (_label, action, method) => { + ['stops the attempt a message waits for', 'stop' as const, 'stopCreation' as const, []], + ['makes another attempt for the waiting message', 'retry' as const, 'retryWorktree' as const, [false]], + ['withdraws the request so the waiting message goes on', 'withdraw' as const, 'cancelWorktree' as const, []], + ])('%s through the Remote and reports only a failure', async (_label, action, method, args) => { const f = await fixture() - f.progress(S1)[action]() + f.progress(S1)[action](false) await settle() - expect(f.forgePanel[method]).toHaveBeenCalledWith(S1) + expect(f.forgePanel[method]).toHaveBeenCalledWith(S1, ...args) expect(f.notice()).toBeNull() f.forgePanel[method].mockResolvedValueOnce(REFUSED.busy) - f.progress(S1)[action]() + f.progress(S1)[action](false) await settle() expect(f.notice()).toMatchObject({ key: 'toast.worktreeFailed', tone: 'failure' }) await f.dispose() diff --git a/packages/experimental/client-ui-forge/tests/parse.host.spec.ts b/packages/experimental/client-ui-forge/tests/parse.host.spec.ts index b2c49bd448..6eb9e5bf2d 100644 --- a/packages/experimental/client-ui-forge/tests/parse.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/parse.host.spec.ts @@ -1,5 +1,7 @@ import { describe, expect, it } from 'vitest' -import { baseBranches, parseBaseBranches, parseName, parseRemotes, parseTopLevel, remoteOrder, upstreamBranch } from '../src/parse.ts' +import { + parseBaseBranches, parseName, parseRemotes, parseTopLevel, parseWorktreeBases, remoteOrder, remoteRepository, upstreamBranch, +} from '../src/parse.ts' import type { GitRemote } from '../src/parse.ts' describe('parseTopLevel', () => { @@ -27,24 +29,85 @@ describe('parseName', () => { }) }) -describe('baseBranches', () => { - it('puts the checked-out branch first without repeating it', () => { - expect(baseBranches('feat', 'main\nfeat\nfix\n', 10)).toEqual(['feat', 'main', 'fix']) +describe('parseWorktreeBases', () => { + const remotes: GitRemote[] = [ + { name: 'upstream', urls: ['https://github.com/acme/demo.git'] }, + { name: 'origin', urls: ['git@github.com:me/demo.git'] }, + { name: 'team/fork', urls: ['/srv/team.git'] }, + { name: 'empty', urls: [] }, + ] + const output = [ + 'refs/remotes/upstream/HEAD\0refs/remotes/upstream/master', + 'refs/remotes/origin/HEAD\0refs/remotes/origin/main', + 'refs/remotes/team/fork/HEAD\0refs/remotes/team/fork/gone', + 'refs/remotes/empty/HEAD\0refs/heads/main', + 'refs/remotes/origin/alias\0refs/remotes/origin/main', + 'refs/heads/alias\0refs/heads/main', + 'refs/heads/topic\0', + 'refs/remotes/upstream/master\0', + 'refs/remotes/origin/main\0', + 'refs/remotes/team/fork/feature\0', + 'refs/remotes/upstream/release/2.4\0', + 'refs/remotes/upstream/dev\0', + 'refs/heads/main\0', + 'refs/remotes/stray/main\0', + 'refs/heads/Fix/Login\0', + 'refs/tags/v1\0', + '', + ].join('\r\n') + const repositories = (remote: GitRemote): string | null => remote.urls[0] ?? null + + it('pins the checked-out branch and each remote default, then groups local branches and each remote in remote order', () => { + expect(parseWorktreeBases(output, 'main', remotes, '', 10, repositories)).toEqual({ + current: { ref: 'refs/heads/main', name: 'main' }, + defaults: [ + { ref: 'refs/remotes/upstream/master', name: 'upstream/master', remote: 'upstream' }, + { ref: 'refs/remotes/origin/main', name: 'origin/main', remote: 'origin' }, + ], + local: [{ ref: 'refs/heads/topic', name: 'topic' }, { ref: 'refs/heads/Fix/Login', name: 'Fix/Login' }], + remotes: [ + { + name: 'upstream', + repository: 'https://github.com/acme/demo.git', + branches: [{ ref: 'refs/remotes/upstream/release/2.4', name: 'upstream/release/2.4' }, { ref: 'refs/remotes/upstream/dev', name: 'upstream/dev' }], + }, + { name: 'team/fork', repository: '/srv/team.git', branches: [{ ref: 'refs/remotes/team/fork/feature', name: 'team/fork/feature' }] }, + ], + }) }) - it('keeps the checked-out branch when the listing omits it', () => { - expect(baseBranches('old', 'main\nfeat\n', 2)).toEqual(['old', 'main']) - expect(baseBranches('main', '', 50)).toEqual(['main']) + it('keeps the branches whose names contain the query, ignoring case, at most `limit` in each group', () => { + expect(parseWorktreeBases(output, 'main', remotes, ' FIX ', 10, repositories)).toEqual({ current: null, defaults: [], local: [{ ref: 'refs/heads/Fix/Login', name: 'Fix/Login' }], remotes: [] }) + const limited = parseWorktreeBases(output, null, remotes, '', 1, repositories) + expect(limited.current).toBeNull() + expect(limited.local).toEqual([{ ref: 'refs/heads/topic', name: 'topic' }]) + expect(limited.remotes.map(remote => remote.branches.length)).toEqual([1, 1]) }) - it('lists the branches of a detached HEAD in listed order', () => { - expect(baseBranches(null, 'main\r\nfeat\r\n', 10)).toEqual(['main', 'feat']) - expect(baseBranches(null, '', 10)).toEqual([]) + it('names no current branch on a detached HEAD or an unborn branch', () => { + expect(parseWorktreeBases(output, null, remotes, '', 10, repositories).current).toBeNull() + expect(parseWorktreeBases('', 'main', [], '', 10, repositories)).toEqual({ current: null, defaults: [], local: [], remotes: [] }) + }) +}) + +describe('remoteRepository', () => { + const recognize = (url: string) => url.startsWith('https://host.test/') ? { owner: 'acme', name: 'demo' } : undefined + + it('names the first recognized repository, else the first URL, else nothing', () => { + expect(remoteRepository({ name: 'origin', urls: ['/srv/demo.git', 'https://host.test/acme/demo.git'] }, recognize)).toBe('acme/demo') + expect(remoteRepository({ name: 'fork', urls: ['/srv/fork.git'] }, recognize)).toBe('/srv/fork.git') + expect(remoteRepository({ name: 'empty', urls: [] }, recognize)).toBeNull() }) - it('returns at most `limit` names and skips empty lines', () => { - expect(baseBranches('main', '\nmain\n\nfeat\nfix\n', 2)).toEqual(['main', 'feat']) - expect(baseBranches(null, 'main\nfeat\nfix\n', 1)).toEqual(['main']) + it.each([ + ['a user name and token', 'https://oauth2:glpat-secret@gitlab.internal.test/group/repo.git', 'https://gitlab.internal.test/group/repo.git'], + ['a token as the user name', 'https://ghp_secret@git.internal.test/acme/demo.git', 'https://git.internal.test/acme/demo.git'], + ['an `@` in the password', 'https://user:p@ss@git.internal.test:8443/repo', 'https://git.internal.test:8443/repo'], + ['an SSH user', 'ssh://git@git.internal.test:2222/acme/demo.git', 'ssh://git.internal.test:2222/acme/demo.git'], + ['an `@` only in the path', 'https://git.internal.test/users/@me/repo.git', 'https://git.internal.test/users/@me/repo.git'], + ['the scp-like form, which has no password', 'git@git.internal.test:acme/demo.git', 'git@git.internal.test:acme/demo.git'], + ])('shows an unrecognized URL with %s without its user information', (_label, url, shown) => { + expect(remoteRepository({ name: 'selfhost', urls: [url] }, recognize)).toBe(shown) }) }) diff --git a/packages/experimental/client-ui-forge/tests/worktree-name-dialog.client.spec.tsx b/packages/experimental/client-ui-forge/tests/worktree-name-dialog.client.spec.tsx new file mode 100644 index 0000000000..8eec26d6e4 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/worktree-name-dialog.client.spec.tsx @@ -0,0 +1,141 @@ +// @vitest-environment jsdom +/** Naming dialog of a worktree branch: the starting text, the rules checked while typing, the Host's refusals, and the retry mode. */ +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { en } from '../src/client/locales.ts' +import { WorktreeNameDialog, type WorktreeNameDialogProps } from '../src/client/WorktreeNameDialog.tsx' + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +const t = makeTranslate(en) + +function mount(props: Partial = {}) { + const submit = vi.fn(async () => 'accepted') + const close = vi.fn() + render() + const dialog = (): HTMLElement => screen.getByRole('dialog') + const field = (): HTMLInputElement => within(dialog()).getByRole('textbox', { name: en['nameDialog.field'] }) + const confirm = (): HTMLElement => within(dialog()).getByRole('button', { name: props.mode === 'retry' ? en['nameDialog.retry'] : en['nameDialog.confirm'] }) + const type = (value: string): void => { fireEvent.change(field(), { target: { value } }) } + const message = (): string | null => field().getAttribute('aria-describedby') === null + ? null : document.getElementById(field().getAttribute('aria-describedby') ?? '')?.textContent ?? null + return { submit, close, dialog, field, confirm, type, message } +} + +describe('WorktreeNameDialog rules', () => { + it.each([ + ['', en['branchName.empty']], + ['fix login', en['branchName.space']], + ['fix~1', en['branchName.character']], + ['-fix', en['branchName.leading-dash']], + ['/fix', en['branchName.leading-slash']], + ['worktree/', en['branchName.trailing-slash']], + ['fix//login', en['branchName.double-slash']], + ['fix..login', en['branchName.double-dot']], + ['fix.', en['branchName.trailing-dot']], + ['@', en['branchName.at']], + ['fix@{1}', en['branchName.at-brace']], + ['fix/.login', en['branchName.dot-segment']], + ['fix.lock/login', en['branchName.lock-segment']], + ])('refuses %j while it is typed', (value, reason) => { + const d = mount() + d.type(value) + expect(d.message()).toBe(reason) + expect(within(d.dialog()).getByRole('alert').textContent).toBe(reason) + expect(d.field().getAttribute('aria-invalid')).toBe('true') + expect(d.confirm().hasAttribute('disabled')).toBe(true) + fireEvent.keyDown(d.field(), { key: 'Enter' }) + expect(d.submit).not.toHaveBeenCalled() + }) + + it('hints at the prefix it starts with, and at the base once a name follows it', () => { + const d = mount({ prefix: 'agent/', initial: 'agent/' }) + expect(d.message()).toBe(en['nameDialog.prefixOnly']) + expect(d.field().getAttribute('aria-invalid')).toBe('false') + expect(d.confirm().hasAttribute('disabled')).toBe(true) + d.type('agent/fix') + expect(d.message()).toBe('The first message creates this branch from main; the worktree directory takes its name') + expect(d.confirm().hasAttribute('disabled')).toBe(false) + }) + + it('without a prefix, starts empty with the base hint, and names the current HEAD for a request without a base', () => { + const d = mount({ prefix: '', initial: '', from: null }) + expect(d.message()).toBe(en['nameDialog.hintHead']) + expect(d.confirm().hasAttribute('disabled')).toBe(true) + }) + + it('takes the keyboard with the caret after the starting text', () => { + const d = mount({ initial: 'dsh-fix', named: true }) + expect(document.activeElement).toBe(d.field()) + expect(d.field().selectionStart).toBe(7) + }) +}) + +describe('WorktreeNameDialog requests', () => { + it('requests the name with Enter, ignores Enter while composing, and closes once the request is accepted', async () => { + const d = mount() + d.type('dsh-fix') + fireEvent.keyDown(d.field(), { key: 'Enter', isComposing: true }) + expect(d.submit).not.toHaveBeenCalled() + fireEvent.keyDown(d.field(), { key: 'a' }) + await act(async () => { fireEvent.keyDown(d.field(), { key: 'Enter' }) }) + expect(d.submit).toHaveBeenCalledWith('dsh-fix') + expect(d.close).toHaveBeenCalledOnce() + }) + + it('stays busy until the Host answers, then shows its refusal for that name only', async () => { + let answer: (result: 'branch-exists' | 'invalid-name' | 'failed') => void = () => {} + const d = mount() + d.submit.mockImplementation(() => new Promise((resolve) => { answer = resolve })) + d.type('dsh-taken') + fireEvent.click(d.confirm()) + expect(d.confirm().hasAttribute('disabled')).toBe(true) + await act(async () => { answer('branch-exists') }) + expect(d.message()).toBe('A branch named dsh-taken already exists') + expect(d.confirm().hasAttribute('disabled')).toBe(true) + + d.type('dsh-odd') + expect(d.confirm().hasAttribute('disabled')).toBe(false) + fireEvent.click(d.confirm()) + await act(async () => { answer('invalid-name') }) + expect(d.message()).toBe(en['branchName.invalid']) + + d.type('dsh-other') + fireEvent.click(d.confirm()) + await act(async () => { answer('failed') }) + expect(d.message()).toBe('The first message creates this branch from main; the worktree directory takes its name') + expect(d.close).not.toHaveBeenCalled() + }) + + it('returns a named request to generated names, ignoring a refusal that names no branch', async () => { + const d = mount({ initial: 'dsh-fix', named: true }) + d.submit.mockResolvedValueOnce('branch-exists') + await act(async () => { fireEvent.click(within(d.dialog()).getByRole('button', { name: en['nameDialog.auto'] })) }) + expect(d.submit).toHaveBeenCalledWith(null) + expect(d.message()).toBe('The first message creates this branch from main; the worktree directory takes its name') + await act(async () => { fireEvent.click(within(d.dialog()).getByRole('button', { name: en['nameDialog.auto'] })) }) + expect(d.close).toHaveBeenCalledOnce() + }) + + it('renames for another attempt in retry mode, without the return to generated names', async () => { + const d = mount({ mode: 'retry', initial: 'dsh-fix', named: true }) + expect(screen.getByRole('dialog', { name: en['nameDialog.retryTitle'] })).toBeTruthy() + expect(within(d.dialog()).queryByRole('button', { name: en['nameDialog.auto'] })).toBeNull() + d.type('dsh-fix-2') + await act(async () => { fireEvent.click(d.confirm()) }) + expect(d.submit).toHaveBeenCalledWith('dsh-fix-2') + }) + + it('closes without a request from Cancel and the close button', () => { + const d = mount() + fireEvent.click(within(d.dialog()).getByRole('button', { name: en['nameDialog.cancel'] })) + fireEvent.click(within(d.dialog()).getByRole('button', { name: en['nameDialog.close'] })) + expect(d.close).toHaveBeenCalledTimes(2) + expect(d.submit).not.toHaveBeenCalled() + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/worktree-progress.client.spec.tsx b/packages/experimental/client-ui-forge/tests/worktree-progress.client.spec.tsx index 71fbdb43b7..fe66410c76 100644 --- a/packages/experimental/client-ui-forge/tests/worktree-progress.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/worktree-progress.client.spec.tsx @@ -3,13 +3,13 @@ * Worktree card: a running creation, which can be stopped while a message waits for it; the failed or stopped attempt a * message waits after; and a removed worktree. */ -import { act, cleanup, fireEvent, render, within } from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { en } from '../src/client/locales.ts' import type { PanelSnapshot } from '../src/client/source.ts' -import { WorktreeProgress } from '../src/client/WorktreeProgress.tsx' +import { WorktreeProgress, type WorktreeProgressInjected } from '../src/client/WorktreeProgress.tsx' import css from '../src/client/WorktreeProgress.module.css' import type { ForgePanelState } from '../src/types.ts' import { created, creation, failure, ready, removed, requested, worktree } from './client-fixtures.client.ts' @@ -21,8 +21,9 @@ const t = makeTranslate(en) function card(state: ForgePanelState | null) { const panel = createSnapshotStore({ state, disconnected: false }) const stop = vi.fn<() => void>() - const retry = vi.fn<() => void>() + const retry = vi.fn() const withdraw = vi.fn<() => void>() + const request = vi.fn(async () => 'accepted') const restore = vi.fn(async (): Promise => undefined) const leave = vi.fn<() => void>() const view = render( @@ -31,6 +32,7 @@ function card(state: ForgePanelState | null) { stop={stop} retry={retry} withdraw={withdraw} + request={request} restore={restore} leave={leave} t={t} @@ -40,7 +42,7 @@ function card(state: ForgePanelState | null) { const publish = (next: ForgePanelState | null): void => { act(() => { panel.set({ state: next, disconnected: false }) }) } - return { view, stop, retry, withdraw, restore, leave, root, publish } + return { view, stop, retry, withdraw, request, restore, leave, root, publish } } /** Glyph a step shows for its state. */ @@ -66,7 +68,7 @@ function details(view: ReturnType): string[][] | null { /** Names of the action buttons the card offers, in order. */ function actions(view: ReturnType): string[] { - const names = [en['creation.retry'], en['creation.skip'], en['creation.cancel']] + const names = [en['creation.retry'], en['creation.skip'], en['creation.cancel'], en['creation.useFetched'], en['creation.rename']] return view.getAllByRole('button').map(button => button.textContent).filter(name => names.includes(name)) } @@ -194,11 +196,58 @@ describe('WorktreeProgress waiting after a failed attempt', () => { const b = card(requested('main', { failure: failure(), waiting: 'creation' })) fireEvent.click(b.view.getByRole('button', { name: en['creation.retry'] })) fireEvent.click(b.view.getByRole('button', { name: en['creation.skip'] })) - expect(b.retry).toHaveBeenCalledOnce() + expect(b.retry).toHaveBeenCalledExactlyOnceWith(true) expect(b.withdraw).toHaveBeenCalledOnce() expect(b.stop).not.toHaveBeenCalled() }) + it('offers to start from the last fetched version after a failed fetch of a remote base branch', () => { + const fetchFailure = failure({ from: 'refs/remotes/origin/main', fetch: true, phase: 'fetch', message: 'fatal: unable to access' }) + const b = card(requested('refs/remotes/origin/main', { failure: fetchFailure, waiting: 'creation' })) + expect(steps(b.view)).toEqual([ + ['Fetch origin/main', 'failed', 'cross'], [en['creation.prepare'], 'waiting', 'ring'], [en['creation.checkout'], 'waiting', 'ring'], + ]) + expect(details(b.view)).toEqual([['Branch', 'dsh/0a1b2c3d'], ['From', 'origin/main'], ['Reason', 'fatal: unable to access']]) + expect(actions(b.view)).toEqual([en['creation.retry'], en['creation.useFetched'], en['creation.skip']]) + fireEvent.click(b.view.getByRole('button', { name: en['creation.useFetched'] })) + fireEvent.click(b.view.getByRole('button', { name: en['creation.retry'] })) + expect(b.retry.mock.calls).toEqual([[false], [true]]) + }) + + it('renames a chosen branch that already exists, then tries again on the new name', async () => { + const taken = failure({ branch: 'fix/login', exists: true, message: 'worktree branch already exists: fix/login' }) + const b = card(requested('refs/heads/main', { failure: taken, waiting: 'creation' }, 'fix/login')) + expect(actions(b.view)).toEqual([en['creation.rename'], en['creation.retry'], en['creation.skip']]) + fireEvent.click(b.view.getByRole('button', { name: en['creation.rename'] })) + const dialog = screen.getByRole('dialog', { name: en['nameDialog.retryTitle'] }) + const field = within(dialog).getByRole('textbox') + expect((field as HTMLInputElement).value).toBe('fix/login') + + b.request.mockResolvedValueOnce('branch-exists') + fireEvent.change(field, { target: { value: 'fix/login-2' } }) + await act(async () => { fireEvent.click(within(dialog).getByRole('button', { name: en['nameDialog.retry'] })) }) + expect(b.retry).not.toHaveBeenCalled() + fireEvent.change(field, { target: { value: 'fix/login-3' } }) + await act(async () => { fireEvent.click(within(dialog).getByRole('button', { name: en['nameDialog.retry'] })) }) + expect(b.request.mock.calls).toEqual([['refs/heads/main', 'fix/login-2'], ['refs/heads/main', 'fix/login-3']]) + expect(b.retry).toHaveBeenCalledExactlyOnceWith(true) + expect(screen.queryByRole('dialog')).toBeNull() + }) + + it('offers no rename for a taken generated name, whose next attempt takes another one', () => { + const b = card(requested('main', { failure: failure({ exists: true }), waiting: 'creation' })) + expect(actions(b.view)).toEqual([en['creation.retry'], en['creation.skip']]) + }) + + it('shows the fetch step of a running creation from a remote base branch', () => { + const b = card(requested('refs/remotes/origin/main', { creation: creation({ from: 'refs/remotes/origin/main', fetch: true, phase: 'fetch' }), waiting: 'creation' })) + expect(steps(b.view)).toEqual([ + ['Fetch origin/main', 'running', 'spinner'], [en['creation.prepare'], 'waiting', 'ring'], [en['creation.checkout'], 'waiting', 'ring'], + ]) + b.publish(requested('refs/remotes/origin/main', { creation: creation({ from: 'refs/remotes/origin/main', fetch: true, phase: 'checkout' }), waiting: 'creation' })) + expect(steps(b.view).map(step => step[1])).toEqual(['done', 'done', 'running']) + }) + it('shows a stopped attempt without steps, with the request\'s base and the same choices', () => { const b = card(requested(null, { waiting: 'creation' })) expect(b.root()?.getAttribute('data-forge-creation')).toBe('stopped') diff --git a/packages/experimental/client-ui-forge/tests/worktree-toggle.client.spec.tsx b/packages/experimental/client-ui-forge/tests/worktree-toggle.client.spec.tsx index baec5b9cb9..738d300a7e 100644 --- a/packages/experimental/client-ui-forge/tests/worktree-toggle.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/worktree-toggle.client.spec.tsx @@ -1,23 +1,40 @@ // @vitest-environment jsdom -/** New Session worktree option: when it shows, why it is disabled, the optimistic checkbox, the base menu, and a running creation. */ +/** + * New Session worktree option: when it shows, why it is disabled, the optimistic checkbox, the searchable base menu + * with remote groups, naming the branch, and a running creation. + */ import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import menuCss from '@deepseek-ai/dsh-client-ui-primitives/src/Menu.module.css' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { en, zh } from '../src/client/locales.ts' import type { PanelSnapshot } from '../src/client/source.ts' -import { WorktreeToggle } from '../src/client/WorktreeToggle.tsx' -import type { ForgeBranches, ForgeCheckoutState, ForgePanelState, ForgePanelWorktree, ForgeWorktreeBlocker } from '../src/types.ts' +import type { WorktreeRequestResult } from '../src/client/WorktreeNameDialog.tsx' +import { WorktreeToggle, type WorktreeToggleInjected } from '../src/client/WorktreeToggle.tsx' +import type { ForgeCheckoutState, ForgePanelState, ForgePanelWorktree, ForgeWorktreeBases, ForgeWorktreeBlocker } from '../src/types.ts' import { creation, failure, ready, worktree } from './client-fixtures.client.ts' afterEach(() => { cleanup() vi.useRealTimers() + vi.restoreAllMocks() }) const t = makeTranslate(en) -const BRANCHES: ForgeBranches = { current: 'main', branches: ['main', 'release', 'feat/x'] } +const BASES: ForgeWorktreeBases = { + current: { ref: 'refs/heads/main', name: 'main' }, + defaults: [{ ref: 'refs/remotes/upstream/master', name: 'upstream/master', remote: 'upstream' }], + local: [{ ref: 'refs/heads/release', name: 'release' }, { ref: 'refs/heads/feat/x', name: 'feat/x' }], + remotes: [ + { name: 'upstream', repository: 'acme/demo', branches: [{ ref: 'refs/remotes/upstream/feat/y', name: 'upstream/feat/y' }] }, + { name: 'team/fork', repository: null, branches: [{ ref: 'refs/remotes/team/fork/idea', name: 'team/fork/idea' }] }, + ], +} + +function ok(value: ForgeWorktreeBases): RemoteResult { + return { ok: true, value } +} /** Panel state of a Session that can still start in a worktree. */ function editable(overrides: Partial = {}, checkout?: ForgeCheckoutState): ForgePanelState { @@ -32,17 +49,22 @@ function deferred() { return { promise, resolve } } +/** Let the listing reads the menu awaits settle, past the search delay when `ms` is given. */ +async function settle(ms = 0): Promise { + await act(async () => { await new Promise(resolve => setTimeout(resolve, ms)) }) +} + function option(state: ForgePanelState | null, translate = t) { const panel = createSnapshotStore({ state, disconnected: false }) - const request = vi.fn(async (_from: string | null) => true) + const request = vi.fn(async () => 'accepted') const cancel = vi.fn(async () => true) - const branches = vi.fn(async (): Promise => BRANCHES) + const bases = vi.fn(async () => ok(BASES)) const view = render( , ) @@ -58,12 +80,15 @@ function option(state: ForgePanelState | null, translate = t) { const publish = (next: ForgePanelState): void => { act(() => { panel.set({ state: next, disconnected: false }) }) } - return { view, panel, request, cancel, branches, checkbox, base, publish } + const rows = (): string[] => screen.queryAllByRole('menuitem').map(row => row.textContent ?? '') + const search = (): HTMLElement => screen.getByRole('textbox', { name: en['diff.base.search'] }) + return { view, panel, request, cancel, bases, checkbox, base, publish, rows, search } } -/** Open the base branch menu and wait for its branches. */ +/** Open the base menu and wait for its branches. */ async function openMenu(b: ReturnType): Promise { - await act(async () => { fireEvent.click(b.base()!) }) + fireEvent.click(b.base()!) + await settle() return screen.getByRole('menu') } @@ -76,7 +101,6 @@ function hint(b: ReturnType): string | null { act(() => { vi.advanceTimersByTime(500) }) return screen.getByRole('tooltip').textContent } - describe('WorktreeToggle visibility', () => { it.each([ ['before the first state', null], @@ -92,7 +116,7 @@ describe('WorktreeToggle visibility', () => { const b = option(ready()) b.publish(editable()) expect(b.checkbox().checked).toBe(false) - b.publish(ready({ worktree: worktree({ editable: false, request: { from: 'main' } }) })) + b.publish(ready({ worktree: worktree({ editable: false, request: { from: 'main', name: null } }) })) expect(b.view.container.innerHTML).toBe('') }) }) @@ -111,8 +135,8 @@ describe('WorktreeToggle checkbox', () => { }) it.each(['read-only', 'outside-writable-root'] as const)('keeps the selected base visible after %s blocks a request until it is withdrawn', async (blocker) => { - const b = option(editable({ request: { from: 'release' } })) - b.publish(editable({ blocker, request: { from: 'release' } })) + const b = option(editable({ request: { from: 'release', name: null } })) + b.publish(editable({ blocker, request: { from: 'release', name: null } })) expect(b.checkbox().checked).toBe(true) expect(b.checkbox().disabled).toBe(false) expect(b.checkbox().closest('label')?.hasAttribute('data-disabled')).toBe(false) @@ -130,10 +154,10 @@ describe('WorktreeToggle checkbox', () => { }) it('preserves a HEAD base while blocked and restores the selected branch menu when permission returns', () => { - const b = option(editable({ blocker: 'read-only', request: { from: null } })) + const b = option(editable({ blocker: 'read-only', request: { from: null, name: null } })) expect(b.view.getByRole('button', { name: en['worktree.baseHead'] })).toBeTruthy() - b.publish(editable({ blocker: 'read-only', request: { from: 'release' } })) - b.publish(editable({ request: { from: 'release' } })) + b.publish(editable({ blocker: 'read-only', request: { from: 'release', name: null } })) + b.publish(editable({ request: { from: 'release', name: null } })) expect(b.base()?.textContent).toBe('From release') expect(b.checkbox().checked).toBe(true) }) @@ -157,7 +181,7 @@ describe('WorktreeToggle checkbox', () => { b.publish(ready({ worktree: worktree({ editable: true }) }, { branch: null, commit: null })) expect(b.view.getByRole('button', { name: copy['checkout.detached'] })).toBeTruthy() expect(b.request).not.toHaveBeenCalled() - expect(b.branches).not.toHaveBeenCalled() + expect(b.bases).not.toHaveBeenCalled() }) it('offers the option again once the blocker clears', () => { @@ -178,22 +202,22 @@ describe('WorktreeToggle checkbox', () => { const current = b.view.getByText('main') fireEvent.click(current) expect(b.request).not.toHaveBeenCalled() - expect(b.branches).not.toHaveBeenCalled() + expect(b.bases).not.toHaveBeenCalled() }) it('requests a worktree from the current branch and holds the checked state until the Host answers', async () => { const b = option(editable()) - const answer = deferred() + const answer = deferred() b.request.mockReturnValueOnce(answer.promise) fireEvent.click(b.checkbox()) - expect(b.request).toHaveBeenCalledWith('main') + expect(b.request).toHaveBeenCalledWith('refs/heads/main', null) expect(b.checkbox().checked).toBe(true) expect(b.checkbox().disabled).toBe(true) expect(b.base()?.textContent).toBe('From main') - b.publish(editable({ request: { from: 'main' } })) - await act(async () => { answer.resolve(true) }) + b.publish(editable({ request: { from: 'main', name: null } })) + await act(async () => { answer.resolve('accepted') }) expect(b.checkbox().checked).toBe(true) expect(b.checkbox().disabled).toBe(false) expect(b.base()?.textContent).toBe('From main') @@ -203,14 +227,14 @@ describe('WorktreeToggle checkbox', () => { const b = option(ready({ worktree: worktree({ editable: true }) }, { branch: null })) expect(b.view.getByText(`${en['checkout.detached']} · 0a1b2c3`)).toBeTruthy() await act(async () => { fireEvent.click(b.checkbox()) }) - expect(b.request).toHaveBeenCalledWith(null) - b.publish(ready({ worktree: worktree({ editable: true, request: { from: null } }) }, { branch: null })) + expect(b.request).toHaveBeenCalledWith(null, null) + b.publish(ready({ worktree: worktree({ editable: true, request: { from: null, name: null } }) }, { branch: null })) expect(b.base()?.textContent).toBe(en['worktree.baseHead']) }) it('returns to the Host state when the Host refuses the request', async () => { const b = option(editable()) - b.request.mockResolvedValueOnce(false) + b.request.mockResolvedValueOnce('failed') await act(async () => { fireEvent.click(b.checkbox()) }) expect(b.checkbox().checked).toBe(false) expect(b.checkbox().disabled).toBe(false) @@ -218,7 +242,7 @@ describe('WorktreeToggle checkbox', () => { }) it('withdraws an open request and shows the current branch until the Host answers', async () => { - const b = option(editable({ request: { from: 'release' } })) + const b = option(editable({ request: { from: 'release', name: null } })) expect(b.checkbox().checked).toBe(true) expect(b.base()?.textContent).toBe('From release') const answer = deferred() @@ -238,93 +262,171 @@ describe('WorktreeToggle checkbox', () => { }) }) -describe('WorktreeToggle base branch menu', () => { - it('names the current branch for a request from HEAD', () => { - const b = option(editable({ request: { from: null } })) - expect(b.base()?.textContent).toBe('From main') + +describe('WorktreeToggle base menu', () => { + it('names the current branch for a request from HEAD and the short name of a requested branch', () => { + expect(option(editable({ request: { from: null, name: null } })).base()?.textContent).toBe('From the current HEAD') + cleanup() + expect(option(editable({ request: { from: 'refs/remotes/upstream/master', name: null } })).base()?.textContent).toBe('From upstream/master') }) it('sits before the checkbox and opens below its anchor, aligned to the anchor\'s right edge', async () => { - const b = option(editable({ request: { from: 'main' } })) + const b = option(editable({ request: { from: 'refs/heads/main', name: null } })) const anchor = b.base() if (anchor === null) throw new Error('no base branch anchor') expect(anchor.compareDocumentPosition(b.checkbox()) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() - const wrapper = anchor.parentElement - if (wrapper === null) throw new Error('no menu wrapper') const menu = await openMenu(b) expect(anchor.getAttribute('aria-expanded')).toBe('true') expect(menu.dataset.anchorSide).toBe('bottom') expect(menu.dataset.anchorAlign).toBe('end') - expect(menu.style.positionAnchor).not.toBe('') - expect(menu.style.positionAnchor).toBe(wrapper.style.anchorName) }) - it('lists the local branches, marks the current and the chosen one, and requests another base', async () => { - const b = option(editable({ request: { from: 'main' } })) - const answer = deferred() - b.branches.mockReturnValueOnce(answer.promise) + it('pins the current branch and remote defaults, then lists local branches and each remote with its repository', async () => { + const b = option(editable({ request: { from: 'main', name: null } })) fireEvent.click(b.base()!) - expect(b.branches).toHaveBeenCalledOnce() - expect(b.base()?.disabled).toBe(true) - expect(screen.queryByRole('menu')).toBeNull() + expect(screen.getByRole('status').textContent).toBe(en['diff.base.loading']) + await settle() + expect(b.bases).toHaveBeenCalledWith('', expect.any(AbortSignal)) + expect(b.rows()).toEqual([ + `main${en['worktree.currentBranch']}`, `upstream/master${en['worktree.remoteDefault']}`, 'release', 'feat/x', 'upstream/feat/y', + 'team/fork/idea', `${en['worktree.name.add']}${en['worktree.name.auto']}`, + ]) + expect(screen.getAllByRole('group').map(group => group.getAttribute('aria-label'))).toEqual([ + en['worktree.pinned'], en['diff.base.local'], 'Remote · upstream', 'Remote · team/fork', + ]) + expect(screen.getByRole('group', { name: 'Remote · upstream' }).textContent).toContain('acme/demo') + // The short name that earlier panels recorded for a local branch selects that branch. + expect(screen.getByRole('menuitem', { name: /^main/ }).getAttribute('aria-current')).toBe('page') - await act(async () => { answer.resolve(BRANCHES) }) - expect(b.base()?.disabled).toBe(false) - expect(b.base()?.getAttribute('aria-expanded')).toBe('true') - const menu = screen.getByRole('menu') - expect(within(menu).getByText(en['worktree.baseMenu'])).toBeTruthy() - const items = within(menu).getAllByRole('menuitem') - expect(items.map(item => item.textContent)).toEqual([`main${en['worktree.currentBranch']}`, 'release', 'feat/x']) - expect(items.map(item => item.matches(`.${menuCss.selected}`))).toEqual([true, false, false]) - - fireEvent.click(items[1]!) - expect(b.request).toHaveBeenCalledWith('release') + fireEvent.click(screen.getByRole('menuitem', { name: 'team/fork/idea' })) + expect(b.request).toHaveBeenCalledWith('refs/remotes/team/fork/idea', null) expect(screen.queryByRole('menu')).toBeNull() }) - it('closes without a request when the chosen base is selected again', async () => { - const b = option(editable({ request: { from: 'release' } })) - const menu = await openMenu(b) - fireEvent.click(within(menu).getByRole('menuitem', { name: 'release' })) - expect(b.request).not.toHaveBeenCalled() + it('closes without a request when the chosen base is chosen again, from its anchor, and on Escape', async () => { + const b = option(editable({ request: { from: 'refs/heads/release', name: 'fix/x' } })) + await openMenu(b) + fireEvent.click(screen.getByRole('menuitem', { name: 'release' })) expect(screen.queryByRole('menu')).toBeNull() - }) - - it('closes from its anchor and on Escape', async () => { - const b = option(editable({ request: { from: 'main' } })) await openMenu(b) fireEvent.click(b.base()!) expect(screen.queryByRole('menu')).toBeNull() - expect(b.branches).toHaveBeenCalledOnce() - await openMenu(b) fireEvent.keyDown(document, { key: 'Escape' }) expect(screen.queryByRole('menu')).toBeNull() expect(b.request).not.toHaveBeenCalled() }) - it('stays closed when the branches cannot be read', async () => { - const b = option(editable({ request: { from: 'main' } })) - b.branches.mockResolvedValueOnce(undefined) - await act(async () => { fireEvent.click(b.base()!) }) - expect(screen.queryByRole('menu')).toBeNull() - expect(b.base()?.disabled).toBe(false) - expect(b.base()?.getAttribute('aria-expanded')).toBe('false') + it('keeps the chosen name when the base changes', async () => { + const b = option(editable({ request: { from: 'refs/heads/main', name: 'fix/x' } })) + await openMenu(b) + fireEvent.click(screen.getByRole('menuitem', { name: /^upstream\/master/ })) + expect(b.request).toHaveBeenCalledWith('refs/remotes/upstream/master', 'fix/x') }) -}) -describe('WorktreeToggle while the worktree is created', () => { - it('freezes the checkbox and the base branch until the creation fails, which leaves both open to change', () => { - const b = option(editable({ request: { from: 'main' }, creation: creation() })) - expect(b.checkbox().checked).toBe(true) + it('filters the listed rows at once, reads the search after a pause, and chooses the first match with Enter', async () => { + const b = option(editable({ request: { from: 'refs/heads/main', name: null } })) + b.bases.mockImplementation(async query => ok(query === '' ? BASES : { ...BASES, current: null, defaults: [], local: [] })) + await openMenu(b) + fireEvent.change(b.search(), { target: { value: 'IDEA' } }) + expect(b.rows()).toEqual(['team/fork/idea', `${en['worktree.name.add']}${en['worktree.name.auto']}`]) + await settle(200) + expect(b.bases).toHaveBeenLastCalledWith('IDEA', expect.any(AbortSignal)) + fireEvent.keyDown(b.search(), { key: 'Enter' }) + expect(b.request).toHaveBeenCalledWith('refs/remotes/team/fork/idea', null) + }) + + it('says when no branch matches, keeps Enter from choosing, and still offers to name the branch', async () => { + const b = option(editable({ request: { from: 'refs/heads/main', name: null } })) + await openMenu(b) + fireEvent.change(b.search(), { target: { value: 'hotfix' } }) + expect(screen.getByText(en['diff.base.empty'])).toBeTruthy() + fireEvent.keyDown(b.search(), { key: 'Enter' }) + expect(b.request).not.toHaveBeenCalled() + expect(b.rows()).toEqual([`${en['worktree.name.add']}${en['worktree.name.auto']}`]) + }) + + it('reports a failed listing with a retry', async () => { + const b = option(editable({ request: { from: 'refs/heads/main', name: null } })) + b.bases.mockResolvedValueOnce({ ok: false, error: new RemoteError('forgePanel/not-a-checkout', 'gone', {}) }) + await openMenu(b) + const status = screen.getByRole('status') + expect(status.textContent).toBe(`${en['toast.branchesFailed']}${en.retry}`) + fireEvent.click(within(status).getByRole('button', { name: en.retry })) + await settle() + expect(b.bases).toHaveBeenCalledTimes(2) + expect(b.rows()).toHaveLength(7) + }) + + it('stays fixed while the worktree is being created, and opens again once the attempt failed', () => { + const b = option(editable({ request: { from: 'main', name: null }, creation: creation() })) expect(b.checkbox().disabled).toBe(true) - expect(b.checkbox().closest('label')?.hasAttribute('data-disabled')).toBe(true) expect(b.base()?.disabled).toBe(true) - - b.publish(editable({ request: { from: 'main' }, failure: failure() })) - expect(b.checkbox().checked).toBe(true) + b.publish(editable({ request: { from: 'main', name: null }, failure: failure() })) expect(b.checkbox().disabled).toBe(false) - expect(b.checkbox().closest('label')?.hasAttribute('data-disabled')).toBe(false) expect(b.base()?.disabled).toBe(false) }) }) + +describe('WorktreeToggle branch name', () => { + /** Open the naming dialog from the menu's last row. */ + async function nameDialog(b: ReturnType): Promise { + await openMenu(b) + fireEvent.click(screen.getByRole('menuitem', { name: /^(Name the new branch|New branch name)/ })) + return screen.getByRole('dialog', { name: en['nameDialog.title'] }) + } + + it('starts the name from the prefix of generated names and requests the worktree on the typed name', async () => { + const b = option(editable({ request: { from: 'refs/remotes/upstream/master', name: null }, namePrefix: 'agent/' })) + const dialog = await nameDialog(b) + const field = within(dialog).getByRole('textbox', { name: en['nameDialog.field'] }) + expect((field as HTMLInputElement).value).toBe('agent/') + expect(within(dialog).getByText(en['nameDialog.prefixOnly'])).toBeTruthy() + expect(within(dialog).getByRole('button', { name: en['nameDialog.confirm'] }).hasAttribute('disabled')).toBe(true) + expect(within(dialog).queryByRole('button', { name: en['nameDialog.auto'] })).toBeNull() + + fireEvent.change(field, { target: { value: 'agent/fix-login' } }) + expect(within(dialog).getByText(en['nameDialog.hint'].replace('{branch}', 'upstream/master'))).toBeTruthy() + await act(async () => { fireEvent.click(within(dialog).getByRole('button', { name: en['nameDialog.confirm'] })) }) + expect(b.request).toHaveBeenCalledWith('refs/remotes/upstream/master', 'agent/fix-login') + expect(screen.queryByRole('dialog')).toBeNull() + }) + + it('shows a chosen name before its base and offers generated names again', async () => { + const b = option(editable({ request: { from: 'refs/heads/main', name: 'fix/login' } })) + const trigger = b.base()! + expect(trigger.textContent).toBe('fix/login · From main') + expect(trigger.getAttribute('aria-label')).toBe('New branch fix/login from main') + const dialog = await nameDialog(b) + expect(within(dialog).getByRole('textbox').value).toBe('fix/login') + await act(async () => { fireEvent.click(within(dialog).getByRole('button', { name: en['nameDialog.auto'] })) }) + expect(b.request).toHaveBeenCalledWith('refs/heads/main', null) + expect(screen.queryByRole('dialog')).toBeNull() + }) + + it('names the current HEAD for a named request without a base', () => { + const b = option(editable({ request: { from: null, name: 'fix/login' } })) + expect(b.base()?.getAttribute('aria-label')).toBe('New branch fix/login from the current HEAD') + }) + + it('keeps the dialog open with the reason when the Host refuses the name, and closes it on Cancel', async () => { + const b = option(editable({ request: { from: 'refs/heads/main', name: null } })) + const dialog = await nameDialog(b) + const field = within(dialog).getByRole('textbox') + fireEvent.change(field, { target: { value: 'taken' } }) + b.request.mockResolvedValueOnce('branch-exists') + await act(async () => { fireEvent.keyDown(field, { key: 'Enter' }) }) + expect(within(dialog).getByRole('alert').textContent).toBe('A branch named taken already exists') + fireEvent.change(field, { target: { value: 'taken-2' } }) + expect(within(dialog).queryByRole('alert')).toBeNull() + + fireEvent.click(within(dialog).getByRole('button', { name: en['nameDialog.cancel'] })) + expect(screen.queryByRole('dialog')).toBeNull() + expect(b.request).toHaveBeenCalledTimes(1) + }) + + it('shows a chosen name in Chinese copy', () => { + const b = option(editable({ request: { from: 'refs/heads/main', name: 'fix/login' } }), makeTranslate(zh)) + expect(b.base()?.textContent).toBe('fix/login · 基于 main') + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/worktree.host.spec.ts b/packages/experimental/client-ui-forge/tests/worktree.host.spec.ts index 4e18fb6a97..143c885b51 100644 --- a/packages/experimental/client-ui-forge/tests/worktree.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/worktree.host.spec.ts @@ -117,9 +117,9 @@ describe('forgeWorktree projection', () => { const { session, state } = await folded() appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: null }) - expect(state()?.request).toEqual({ from: null }) + expect(state()?.request).toEqual({ from: null, name: null }) appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: 'main' }) - expect(state()?.request).toEqual({ from: 'main' }) + expect(state()?.request).toEqual({ from: 'main', name: null }) appendPluginRecord(session, WORKTREE_RECORD, { action: 'cancel' }) const withdrawn = state() expect(withdrawn).toEqual(EMPTY) @@ -129,12 +129,24 @@ describe('forgeWorktree projection', () => { appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: 'feat' }) startTurn(session, 1) const locked = state() - expect(locked).toEqual({ ...EMPTY, request: { from: 'feat' }, locked: true }) + expect(locked).toEqual({ ...EMPTY, request: { from: 'feat', name: null }, locked: true }) appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: 'main' }) appendPluginRecord(session, WORKTREE_RECORD, { action: 'cancel' }) expect(state()).toBe(locked) }) + it('keeps the branch name a request chooses, and none for a request that names no branch or an empty one', async () => { + const { session, state } = await folded() + + appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: 'refs/remotes/origin/main', name: 'fix/login' }) + expect(state()?.request).toEqual({ from: 'refs/remotes/origin/main', name: 'fix/login' }) + const named = state() + appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: null, name: '' }) + expect(state()).toBe(named) + appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: null }) + expect(state()?.request).toEqual({ from: null, name: null }) + }) + it('applies the first created worktree of an open request, after which requests, withdrawals, and creations change nothing', async () => { const { session, state } = await folded() appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: 'main' }) @@ -145,7 +157,7 @@ describe('forgeWorktree projection', () => { appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: null }) appendPluginRecord(session, WORKTREE_RECORD, { action: 'cancel' }) - expect(created).toEqual({ ...EMPTY, request: { from: 'main' }, created: { ...WORKTREE, from: 'main' } }) + expect(created).toEqual({ ...EMPTY, request: { from: 'main', name: null }, created: { ...WORKTREE, from: 'main' } }) expect(state()).toBe(created) }) @@ -158,8 +170,8 @@ describe('forgeWorktree projection', () => { const created = state() startStep(session, 1) - expect(created).toEqual({ ...EMPTY, request: { from: null }, created: WORKTREE, locked: true }) - expect(state()).toEqual({ ...EMPTY, request: { from: null }, created: WORKTREE, locked: true, stepped: true }) + expect(created).toEqual({ ...EMPTY, request: { from: null, name: null }, created: WORKTREE, locked: true }) + expect(state()).toEqual({ ...EMPTY, request: { from: null, name: null }, created: WORKTREE, locked: true, stepped: true }) }) it('ignores a created worktree without an open request or after the first step starts', async () => { @@ -180,7 +192,7 @@ describe('forgeWorktree projection', () => { const stepped = state() appendPluginRecord(session, WORKTREE_RECORD, { action: 'created', worktree: WORKTREE }) - expect(stepped).toEqual({ ...EMPTY, request: { from: null }, locked: true, stepped: true }) + expect(stepped).toEqual({ ...EMPTY, request: { from: null, name: null }, locked: true, stepped: true }) expect(state()).toBe(stepped) }) @@ -215,7 +227,7 @@ describe('forgeWorktree projection', () => { session.append('step/end', { turn: 1, step: 1 }) expect(state()).toBe(requested) - expect(requested).toEqual({ ...EMPTY, request: { from: 'main' } }) + expect(requested).toEqual({ ...EMPTY, request: { from: 'main', name: null } }) }) }) @@ -280,7 +292,7 @@ describe('creating a requested worktree', () => { const head = await git(repo, 'rev-parse', 'HEAD') request(opened, null) - const result = await opened.creations.create(opened.agent, null, signal, false) + const result = await opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false) const branch = result.branch expect(branch).toMatch(/^dsh-[0-9a-f]{8}$/) @@ -302,9 +314,9 @@ describe('creating a requested worktree', () => { const opened = await creating(repo) request(opened, null) - const result = await opened.creations.create(opened.agent, null, signal, false) + const result = await opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false) - const running = { branch: result.branch, from: null, held: false } + const running = { branch: result.branch, from: null, fetch: false, held: false } expect(opened.changes).toEqual([{ ...running, phase: 'prepare' }, { ...running, phase: 'prepare' }, { ...running, phase: 'checkout' }, null]) expect(opened.recorded).toEqual([null, null, null, worktreeOf(opened)]) expect(worktreeOf(opened)).not.toBeNull() @@ -319,7 +331,7 @@ describe('creating a requested worktree', () => { const opened = await creating(repo) request(opened, 'base') - await opened.creations.create(opened.agent, 'base', signal, false) + await opened.creations.create(opened.agent, { from: 'base', name: null }, signal, false, false) const created = worktreeOf(opened) expect(created).toMatchObject({ from: 'base', baseCommit: base }) @@ -333,7 +345,7 @@ describe('creating a requested worktree', () => { const opened = await creating(repo, { prefix: 'agent/task-' }) request(opened, null) - const result = await opened.creations.create(opened.agent, null, signal, false) + const result = await opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false) expect(result.branch).toMatch(/^agent\/task-[0-9a-f]{8}$/) expect(opened.ctx.workingDirectory.get(opened.session)).toBe(join(repo, '.agents', 'worktrees', ...result.branch.split('/'))) @@ -344,7 +356,7 @@ describe('creating a requested worktree', () => { const opened = await creating(repo) request(opened, 'later') - const attempt = opened.creations.create(opened.agent, 'later', signal, false) + const attempt = opened.creations.create(opened.agent, { from: 'later', name: null }, signal, false, false) const branch = opened.changes[0]?.branch const cause: unknown = expect.objectContaining({ message: MISSING_BASE }) @@ -358,10 +370,10 @@ describe('creating a requested worktree', () => { cause, }) expect(branch).toEqual(GENERATED_BRANCH) - const running = { phase: 'prepare', branch, from: 'later', held: false } + const running = { phase: 'prepare', branch, from: 'later', fetch: false, held: false } expect(opened.changes).toEqual([running, running, null]) expect(opened.records).toEqual([{ action: 'request', from: 'later' }]) - expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: 'later' }, cwd: repo }) + expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: 'later', name: null }, cwd: repo }) expect(opened.ctx.workingDirectory.get(opened.session)).toBe(repo) }) @@ -371,7 +383,7 @@ describe('creating a requested worktree', () => { request(opened, null) opened.sandbox.gate = argv => argv.includes('reset') ? Promise.reject(new Error('checkout refused')) : undefined - const attempt = opened.creations.create(opened.agent, null, signal, false) + const attempt = opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false) const branch = opened.changes[0]?.branch ?? '' await expect(attempt).rejects.toMatchObject({ @@ -386,13 +398,52 @@ describe('creating a requested worktree', () => { expect(await branches(repo)).toEqual([branch, 'main']) }) + it('creates the branch a request names on every attempt', async () => { + const repo = await project() + const opened = await creating(repo) + + const result = await opened.creations.create(opened.agent, { from: null, name: 'fix/login' }, signal, false, false) + + expect(result.branch).toBe('fix/login') + expect(opened.changes[0]).toMatchObject({ branch: 'fix/login', phase: 'prepare', fetch: false }) + expect(opened.ctx.workingDirectory.get(opened.session)).toBe(join(repo, '.agents', 'worktrees', 'fix', 'login')) + }) + + it('fetches a remote base branch first, then starts from the fetched commit', async () => { + const { path: parent, remove } = await scratch('dsh-forge-worktree-fetch-') + cleanups.push(remove) + const upstream = await repository(parent, 'upstream') + const repo = join(parent, 'clone') + await git(parent, 'clone', '--quiet', upstream, repo) + const fetched = await commitAt(upstream, 'remote.txt', '2026-02-01T00:00:00Z') + const opened = await creating(repo) + + const result = await opened.creations.create(opened.agent, { from: 'refs/remotes/origin/main', name: null }, signal, false, true) + + expect(result.baseCommit).toBe(fetched) + expect(opened.changes.map(change => change?.phase ?? null)).toEqual(['fetch', 'fetch', 'prepare', 'checkout', null]) + expect(opened.changes[0]).toMatchObject({ from: 'refs/remotes/origin/main', fetch: true }) + await expect(access(join(result.path, 'remote.txt'))).resolves.toBeUndefined() + }) + + it('says when the branch an attempt names already exists', async () => { + const repo = await project() + const opened = await creating(repo) + + await expect(opened.creations.create(opened.agent, { from: null, name: 'main' }, signal, false, false)) + .rejects.toMatchObject({ name: 'CreationFailure', branch: 'main', phase: 'prepare', exists: true }) + opened.sandbox.failure = new Error('confinement denied') + await expect(opened.creations.create(opened.agent, { from: null, name: 'other' }, signal, false, false)) + .rejects.toMatchObject({ name: 'CreationFailure', exists: false }) + }) + it('reports a failure that is not an Error by its text', async () => { const repo = await project() const opened = await creating(repo) request(opened, null) opened.sandbox.failure = 'confinement denied' - await expect(opened.creations.create(opened.agent, null, signal, false)) + await expect(opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false)) .rejects.toMatchObject({ phase: 'prepare', reason: 'confinement denied', cause: 'confinement denied' }) expect(opened.changes.at(-1)).toBeNull() }) @@ -497,7 +548,7 @@ describe('worktree creation at the first step proposal', () => { const repo = await project() const opened = await creating(repo) request(opened, null) - const created = await opened.creations.create(opened.agent, null, signal, false) + const created = await opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false) const reports = opened.changes.length const proposed = prompt('go') @@ -520,7 +571,7 @@ describe('worktree creation at the first step proposal', () => { await expect(proposeStep(opened.ctx, opened.agent, { turn: 1, step: 1, messages: [prompt('go')] })) .rejects.toMatchObject({ name: 'CreationFailure', branch: GENERATED_BRANCH, phase: 'prepare', reason: MISSING_BASE }) const failed = opened.changes[0]?.branch - expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: 'later' }, locked: true, cwd: repo }) + expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: 'later', name: null }, locked: true, cwd: repo }) expect(opened.records).toEqual([{ action: 'request', from: 'later' }]) expect(opened.ctx.workingDirectory.get(opened.session)).toBe(repo) @@ -551,7 +602,7 @@ describe('worktree creation at the first step proposal', () => { expect(await settled).toBe(cause) expect(opened.changes.at(-1)).toBeNull() expect(opened.records).toEqual([{ action: 'request', from: null }]) - expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: null }, cwd: repo }) + expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: null, name: null }, cwd: repo }) expect(opened.ctx.workingDirectory.get(opened.session)).toBe(repo) expect(await branches(repo)).toEqual(['main']) }) @@ -563,13 +614,24 @@ describe('worktree creation at the first step proposal', () => { await expect(proposeStep(opened.ctx, opened.agent, { turn: 1, step: 1, messages: [prompt('go')] })) .rejects.toThrow('No worktree service is mounted') - expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: null }, cwd: repo }) + expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: null, name: null }, cwd: repo }) expect(opened.changes).toEqual([]) expect(opened.ctx.workingDirectory.get(opened.session)).toBe(repo) }) }) +it('names the fetch as the failed step of a remote-based attempt that fails before it reaches the worktree service', async () => { + const opened = await creating(await project(), { worktrees: false }) + request(opened, 'refs/remotes/origin/main') + opened.creations.holdCreation(opened.agent) + await vi.waitFor(() => { expect(opened.creations.failureOf(opened.session)).not.toBeNull() }) + expect(opened.creations.failureOf(opened.session)).toEqual({ + branch: null, from: 'refs/remotes/origin/main', fetch: true, phase: 'fetch', message: 'No worktree service is mounted', exists: false, + }) + await opened.creations.dispose() +}) + it('does not admit a new message hold after worktree operations stop', async () => { const opened = await creating(await project()) request(opened, null) diff --git a/packages/experimental/client-ui-forge/tsconfig.client.json b/packages/experimental/client-ui-forge/tsconfig.client.json index 89f15d9ba8..b0c696724c 100644 --- a/packages/experimental/client-ui-forge/tsconfig.client.json +++ b/packages/experimental/client-ui-forge/tsconfig.client.json @@ -7,6 +7,7 @@ }, "include": [ "src/client", + "src/branch-name.ts", "src/commit-range.ts", "src/css-modules.d.ts", "src/lens-version.ts", diff --git a/packages/experimental/client-ui-forge/tsconfig.host.json b/packages/experimental/client-ui-forge/tsconfig.host.json index d92dfcba55..7486a1fa45 100644 --- a/packages/experimental/client-ui-forge/tsconfig.host.json +++ b/packages/experimental/client-ui-forge/tsconfig.host.json @@ -7,6 +7,7 @@ }, "files": [ "src/index.ts", + "src/branch-name.ts", "src/commit-range.ts", "src/diff.ts", "src/git.ts", diff --git a/packages/experimental/tool-worktree/README.i18n.yaml b/packages/experimental/tool-worktree/README.i18n.yaml index 10910e375f..5d0610fed9 100644 --- a/packages/experimental/tool-worktree/README.i18n.yaml +++ b/packages/experimental/tool-worktree/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-tool-worktree/use-this-package: - en: f357051b201aa5b9 - zh: ace93e12e8d4de82 + en: 57fa5f479232a5c6 + zh: f8c1f2476a2dfef0 /deepseek-ai-dsh-experimental-tool-worktree/understand-the-implementation: en: c03f875211ab69a8 zh: 8f49b82f90a60223 diff --git a/packages/experimental/tool-worktree/README.md b/packages/experimental/tool-worktree/README.md index 2f1b293808..a405055fe8 100644 --- a/packages/experimental/tool-worktree/README.md +++ b/packages/experimental/tool-worktree/README.md @@ -34,7 +34,7 @@ For an explicit composition, mount this function plugin after the worktree runti - name: '@deepseek-ai/dsh-experimental-tool-worktree' ``` -Call `create_worktree({ name?: string, from?: string })`. Success returns the canonical checkout `path`, new `branch`, pinned `baseCommit`, and source `repositoryRoot`, and changes the calling Session's current working directory. To leave, call `working_directory({ cd: path })`; the checkout and branch remain. The [generated tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-experimental-tool-worktree) owns the exact schema and model-facing description. +Call `create_worktree({ name?: string, from?: string })`. The tool forwards only these two fields to the runtime, so it never fetches. Success returns the canonical checkout `path`, new `branch`, pinned `baseCommit`, and source `repositoryRoot`, and changes the calling Session's current working directory. To leave, call `working_directory({ cd: path })`; the checkout and branch remain. The [generated tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-experimental-tool-worktree) owns the exact schema and model-facing description. ----- diff --git a/packages/experimental/tool-worktree/README.zh.md b/packages/experimental/tool-worktree/README.zh.md index 8b37299687..d39bef7cb8 100644 --- a/packages/experimental/tool-worktree/README.zh.md +++ b/packages/experimental/tool-worktree/README.zh.md @@ -34,7 +34,7 @@ kind: "package-bundle" - name: '@deepseek-ai/dsh-experimental-tool-worktree' ``` -调用 `create_worktree({ name?: string, from?: string })`。成功会返回规范化检出路径 `path`、新分支 `branch`、固定提交 `baseCommit` 和源仓库根目录 `repositoryRoot`,并改变调用 Session 的当前工作目录。离开时调用 `working_directory({ cd: path })`;检出目录与分支会保留。[生成的工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-experimental-tool-worktree)拥有准确的 schema 与面向模型的描述。 +调用 `create_worktree({ name?: string, from?: string })`。工具只把这两个字段转给运行时,因此从不执行 fetch。成功会返回规范化检出路径 `path`、新分支 `branch`、固定提交 `baseCommit` 和源仓库根目录 `repositoryRoot`,并改变调用 Session 的当前工作目录。离开时调用 `working_directory({ cd: path })`;检出目录与分支会保留。[生成的工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-experimental-tool-worktree)拥有准确的 schema 与面向模型的描述。 ----- diff --git a/packages/experimental/tool-worktree/src/index.ts b/packages/experimental/tool-worktree/src/index.ts index ad526e61ef..6e2edd275b 100644 --- a/packages/experimental/tool-worktree/src/index.ts +++ b/packages/experimental/tool-worktree/src/index.ts @@ -34,9 +34,10 @@ export function apply(ctx: Context): void { }, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], }, - async execute(args, exec) { + async execute({ name, from }, exec) { if (exec.agent === undefined) throw new ToolContextUnavailableError('create_worktree requires a calling agent') - return ctx.worktrees.create(exec.agent, args, exec.signal) + // The parameter object is open, so only the declared fields reach the runtime; it never fetches for this tool. + return ctx.worktrees.create(exec.agent, { ...name === undefined ? {} : { name }, ...from === undefined ? {} : { from } }, exec.signal) }, presentCall: args => ({ card: 'generic', title: 'create_worktree', rawInput: args }), })) diff --git a/packages/experimental/tool-worktree/tests/loader-composition.spec.ts b/packages/experimental/tool-worktree/tests/loader-composition.spec.ts index 25af996861..3b28d175b5 100644 --- a/packages/experimental/tool-worktree/tests/loader-composition.spec.ts +++ b/packages/experimental/tool-worktree/tests/loader-composition.spec.ts @@ -106,6 +106,13 @@ describe('worktree tool through real Loader composition', () => { expect(failure.isError && failure.error.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) const existing = await invoke('new-checkout') expect(existing.isError && existing.error.info).toEqual({ name: 'WorktreeError', code: 'WORKTREE_ALREADY_EXISTS' }) + // A forwarded `fetch` would make the runtime refuse `main`, which is not a remote-tracking branch. + const undeclared = await executeToolFixture(context, { + name: 'create_worktree', callId: brandString('undeclared'), arguments: { from: 'main', fetch: true }, agent, + signal: new AbortController().signal, + }) + expect(undeclared.isError).not.toBe(true) + expect(undeclared.value).toMatchObject({ baseCommit, repositoryRoot: path }) expect(context.tools.get('create_worktree')!.presentCall!({ name: 'named' })).toEqual({ card: 'generic', title: 'create_worktree', rawInput: { name: 'named' }, }) diff --git a/packages/experimental/worktree/README.i18n.yaml b/packages/experimental/worktree/README.i18n.yaml index b97e443ecd..18b58d2fdd 100644 --- a/packages/experimental/worktree/README.i18n.yaml +++ b/packages/experimental/worktree/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-worktree/use-this-package: - en: e33f2d32037ef164 - zh: 18528ef31803c6d0 + en: 4c5c550f3abde1af + zh: a10b5f99abc209d3 /deepseek-ai-dsh-experimental-worktree/understand-the-implementation: en: 6971a7ca9073bef1 zh: b977c28a75c7f963 @@ -30,8 +30,8 @@ en: 6826dfaadb24f3da zh: 2e2ee715247fc015 /deepseek-ai-dsh-experimental-worktree/known-limitations-and-deferred-work: - en: 9115db41d1c8eed7 - zh: 87857659a8a47c1d + en: 3ce9e81c2c5ca919 + zh: c06c84179e82f4c2 /deepseek-ai-dsh-experimental-worktree/known-limitations-and-deferred-work/dev-note: en: ad12746a6cc96d8a zh: 66275f30a35c88e4 diff --git a/packages/experimental/worktree/README.md b/packages/experimental/worktree/README.md index 30cfcfca04..1d789edfc5 100644 --- a/packages/experimental/worktree/README.md +++ b/packages/experimental/worktree/README.md @@ -32,7 +32,7 @@ Mount the service alongside `workingDirectory`, `fs`, `subprocess`, `sandbox`, ` - name: '@deepseek-ai/dsh-experimental-tool-worktree' ``` -`ctx.worktrees.create(agent, { name?, from? }, signal?, onPhase?)` creates a new branch and checkout, then enters the canonical checkout directory through `ctx.workingDirectory.set`. `from` resolves to a local commit before creation and defaults to `HEAD`; staged, unstaged, untracked, and ignored source files are not copied. `baseCommit` reports the resolved commit object name; repository-local replacement refs still apply to the checked-out content. Checkout disables configured Git clean, smudge, and process filters without changing repository configuration. An existing branch or checkout path is an error. The returned record contains `path`, `branch`, `baseCommit`, and `repositoryRoot`. An optional fourth argument, `onPhase`, receives `prepare` before validation, directory allocation, and branch creation, and `checkout` before the files are written and the checkout is entered; it must not throw. +`ctx.worktrees.create(agent, { name?, from?, fetch? }, signal?, onPhase?)` creates a new branch and checkout, then enters the canonical checkout directory through `ctx.workingDirectory.set`. `from` resolves to a local commit before creation and defaults to `HEAD`. With `fetch: true`, `from` must be the full name of a remote-tracking branch, `refs/remotes//`, of a configured remote, the longest remote name winning when names nest; creation first runs `git fetch --no-tags --no-recurse-submodules --no-write-fetch-head --no-auto-maintenance +refs/heads/:`, so only that branch is fetched, then resolves the fetched commit. The fetch runs under the Session's sandbox policy and the command deadline, without prompts, and a failed fetch creates nothing; staged, unstaged, untracked, and ignored source files are not copied. `baseCommit` reports the resolved commit object name; repository-local replacement refs still apply to the checked-out content. Checkout disables configured Git clean, smudge, and process filters without changing repository configuration. An existing branch or checkout path is an error. The returned record contains `path`, `branch`, `baseCommit`, and `repositoryRoot`. An optional fourth argument, `onPhase`, receives `fetch` first when the request asks to fetch, `prepare` before validation, directory allocation, and branch creation, and `checkout` before the files are written and the checkout is entered; it must not throw. `ctx.worktrees.restore(agent, { path, branch, baseCommit, repositoryRoot }, signal?, onPhase?)` checks a removed worktree out again at its recorded directory. It validates the recorded repository root, full commit object name, branch, and canonical target inside the configured pool before mutation. It removes only the missing target's unlocked registration with `git worktree remove`; other worktrees and locked registrations remain unchanged. It then checks out the branch when it still exists, or creates the branch again at `baseCommit` when it does not, and reports which happened as `branchRecreated`. An existing directory is an error. The calling Session's working directory does not change, and changes that were never committed are not recovered. Checkout disables filters as creation does. `onPhase` receives `prepare` before validation, target-registration cleanup, and branch creation, and `checkout` before the files are written; it must not throw. @@ -89,7 +89,7 @@ This package contributes no prompt text. Its consumers own the appended tool res - **Retained artifacts** — leaving a worktree keeps its branch and files, and archive cleanup never deletes a branch. Setup failures can also retain partial artifacts, and a failed removal can leave a partial directory for the retained branch to be restored over. -- **Local revisions only** — creation does not fetch commits or missing partial-clone objects, initialize submodules, install dependencies, or copy uncommitted files. On Git that meets the execution requirements, missing local objects cause creation to fail. +- **Local revisions unless asked** — creation fetches only the one remote branch a request asks for; it does not fetch other commits or missing partial-clone objects, initialize submodules, install dependencies, or copy uncommitted files. On Git that meets the execution requirements, missing local objects cause creation to fail. - **Filtered representations** — checkout skips configured filters to avoid executing repository-configured programs or triggering implicit downloads. Git LFS pointers and encrypted blobs stay in their stored representation; hydration or decryption is a separate user-controlled operation. - **Execution requirements** — the subprocess provider must offer Git and Node in the same execution world as the filesystem provider. Git must honor `GIT_NO_LAZY_FETCH`, which Git 2.45 and the 2.39.4, 2.40.2, 2.41.1, 2.42.2, 2.43.4, and 2.44.1 maintenance releases do; older releases ignore it and proceed instead of failing, so creation can fetch missing partial-clone objects from a promisor remote. The `git --no-lazy-fetch` option would reject these releases, but it exists only in Git 2.45 and later and also rejects the patched maintenance releases. The existing sandbox must permit all checkout and shared Git metadata writes. diff --git a/packages/experimental/worktree/README.zh.md b/packages/experimental/worktree/README.zh.md index 28fc6fb0b0..edc02c6a4a 100644 --- a/packages/experimental/worktree/README.zh.md +++ b/packages/experimental/worktree/README.zh.md @@ -32,7 +32,7 @@ kind: "package-reference" - name: '@deepseek-ai/dsh-experimental-tool-worktree' ``` -`ctx.worktrees.create(agent, { name?, from? }, signal?, onPhase?)` 创建新分支与检出目录,再通过 `ctx.workingDirectory.set` 进入规范化的检出目录。`from` 在创建前解析为本地提交,默认是 `HEAD`;暂存、未暂存、未跟踪以及被忽略的源文件均不复制。`baseCommit` 报告解析出的提交对象名称;仓库本地的替换引用仍作用于检出的内容。检出操作禁用已配置的 Git clean、smudge 和 process 过滤器,不修改仓库配置。分支或检出路径已存在时会报错。返回记录包含 `path`、`branch`、`baseCommit` 和 `repositoryRoot`。可选的第四个参数 `onPhase` 在校验、分配目录与创建分支之前收到 `prepare`,在写入文件并进入检出之前收到 `checkout`;它不得抛出异常。 +`ctx.worktrees.create(agent, { name?, from?, fetch? }, signal?, onPhase?)` 创建新分支与检出目录,再通过 `ctx.workingDirectory.set` 进入规范化的检出目录。`from` 在创建前解析为本地提交,默认是 `HEAD`。`fetch: true` 时,`from` 必须是某个已配置远程的远程跟踪分支完整引用名 `refs/remotes//`,远程名相互嵌套时取最长的;创建前先运行 `git fetch --no-tags --no-recurse-submodules --no-write-fetch-head --no-auto-maintenance +refs/heads/:`,只获取这一个分支,再解析获取到的提交。获取在 Session 的沙箱策略与命令期限下运行,不会提示输入,获取失败时不创建任何东西;暂存、未暂存、未跟踪以及被忽略的源文件均不复制。`baseCommit` 报告解析出的提交对象名称;仓库本地的替换引用仍作用于检出的内容。检出操作禁用已配置的 Git clean、smudge 和 process 过滤器,不修改仓库配置。分支或检出路径已存在时会报错。返回记录包含 `path`、`branch`、`baseCommit` 和 `repositoryRoot`。可选的第四个参数 `onPhase` 在请求要求获取时先收到 `fetch`,在校验、分配目录与创建分支之前收到 `prepare`,在写入文件并进入检出之前收到 `checkout`;它不得抛出异常。 `ctx.worktrees.restore(agent, { path, branch, baseCommit, repositoryRoot }, signal?, onPhase?)` 在记录的目录重新检出被删除的 worktree。它在修改前校验记录中的仓库根目录、完整提交对象名、分支和配置池内的规范目标路径。它只通过 `git worktree remove` 移除缺失目标的未锁定登记;其他 worktree 与锁定登记保持不变。随后在分支仍存在时检出该分支,否则在 `baseCommit` 重新创建同名分支,并通过 `branchRecreated` 报告是哪种情况。目录已存在时会报错。调用方 Session 的工作目录不变,从未提交的修改无法恢复。检出与创建时一样禁用过滤器。`onPhase` 在检查目录、清理登记与创建分支之前收到 `prepare`,在写入文件之前收到 `checkout`;它不能抛出异常。 @@ -89,7 +89,7 @@ Git 与目录分配通过挂载的子进程及沙箱提供方执行,沿用调 - **保留的产物**——离开工作树时保留其分支和文件,归档清理也从不删除分支。安装失败同样可能保留部分产物;删除失败可能留下部分目录,可在保留的分支上恢复覆盖。 -- **仅限本地提交**——创建操作不会获取远端提交或部分克隆中缺失的对象、初始化子模块、安装依赖或复制未提交文件。Git 满足执行要求时,本地对象缺失会导致创建失败。 +- **默认仅限本地提交**——创建操作只获取请求指定的那一个远程分支,不会获取其他远端提交或部分克隆中缺失的对象、初始化子模块、安装依赖或复制未提交文件。Git 满足执行要求时,本地对象缺失会导致创建失败。 - **过滤器处理前的内容**——检出时跳过已配置的过滤器,以避免执行仓库配置的程序或隐式下载。Git LFS 指针与加密 blob 保持存储时的形式;拉取实体内容或解密由用户另行执行。 - **执行要求**——子进程提供方必须在与文件系统提供方相同的执行环境中提供 Git 与 Node。Git 必须识别 `GIT_NO_LAZY_FETCH`:Git 2.45 及 2.39.4、2.40.2、2.41.1、2.42.2、2.43.4、2.44.1 维护版本均支持;更早的版本会忽略该变量并继续执行而不报错,因此创建操作可能从 promisor 远程获取缺失的部分克隆对象。`git --no-lazy-fetch` 选项会拒绝这些版本,但它仅在 Git 2.45 及以后存在,也会拒绝上述已修补的维护版本。现有沙箱必须允许写入检出目录与共享 Git 元数据。 diff --git a/packages/experimental/worktree/src/index.ts b/packages/experimental/worktree/src/index.ts index 8e2c5b5ade..5ffbbeb7b8 100644 --- a/packages/experimental/worktree/src/index.ts +++ b/packages/experimental/worktree/src/index.ts @@ -64,8 +64,13 @@ type ResolvedConfig = Required & ProcessConfig interface WorktreeSpec { branch: string revision: string + /** Whether the remote-tracking branch `revision` is fetched before it is resolved. */ + fetch: boolean } +/** Prefix of the full names of remote-tracking branches. */ +const REMOTE_REFS = 'refs/remotes/' + /** Runs one confined Git command; output with an exit code outside `allowedExitCodes` throws. */ type GitRun = (directory: string, args: string[], allowedExitCodes?: number[], env?: NodeJS.ProcessEnv) => ReturnType @@ -147,19 +152,21 @@ export class WorktreeService extends Service { } /** - * Create a fresh branch and checkout at a pinned local revision, then enter it. + * Create a fresh branch and checkout at a pinned local revision, then enter it. A request that asks to fetch + * first fetches its remote-tracking branch, only that branch and without tags, then pins the fetched commit. * Existing branches or checkout paths fail. Uncommitted files stay in the source checkout. * Checkout disables configured clean, smudge, and process filters without changing Git config. * Repository-local replacement refs still apply; baseCommit reports the resolved object name. * The new checkout becomes current only after Git setup succeeds. Failures may retain newly * allocated Git/filesystem artifacts; no branch or checkout is removed automatically. * @param agent - caller whose current directory selects the source repository and file policy. - * @param request - optional new name and local revision; defaults are generated name and HEAD. + * @param request - optional new name, local revision, and fetch switch; defaults are generated name, HEAD, and no fetch. * @param signal - cancellation of lookup, creation, and working-directory publication. * @param onPhase - receives each stage before it begins; it must not throw. * @returns canonical checkout path, branch name, pinned commit, and source repository root. - * @throws {WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out - * command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. + * @throws {WorktreeError} for an invalid request, a fetch request whose `from` is not a remote-tracking branch of a + * configured remote, an existing branch or path, or a failed, oversized, or timed-out command, including the + * fetch; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ async create( agent: Agent, @@ -189,7 +196,7 @@ export class WorktreeService extends Service { * @param agent - caller whose sandbox policy confines the commands. * @param request - recorded directory, branch, base commit, and source repository root. * @param signal - cancellation of the restoration. - * @param onPhase - receives each stage before it begins; it must not throw. + * @param onPhase - receives each stage before it begins, never `fetch`; it must not throw. * @returns the directory and whether the branch was created again. * @throws {WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized, * or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. @@ -198,7 +205,7 @@ export class WorktreeService extends Service { agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, - onPhase?: (phase: CreateWorktreePhase) => void, + onPhase?: (phase: Exclude) => void, ): Promise { const operationSignal = signal === undefined ? this.lifetime.signal : AbortSignal.any([this.lifetime.signal, signal]) operationSignal.throwIfAborted() @@ -252,16 +259,20 @@ export class WorktreeService extends Service { if (!relativePath(branch) || branch.startsWith('-')) throw new WorktreeError('worktree name must be a relative Git branch name', 'WORKTREE_INVALID_ARGUMENT') const revision = request.from ?? 'HEAD' if (revision.length === 0) throw new WorktreeError('worktree from must name a local commit, branch, or tag', 'WORKTREE_INVALID_ARGUMENT') - return { branch, revision } + const fetch = request.fetch === true + if (fetch && !revision.startsWith(REMOTE_REFS)) { + throw new WorktreeError('worktree fetch needs from to name a remote-tracking branch under refs/remotes/', 'WORKTREE_INVALID_ARGUMENT') + } + return { branch, revision, fetch } } private async createCheckout( agent: Agent, - { branch, revision }: WorktreeSpec, + { branch, revision, fetch }: WorktreeSpec, signal: AbortSignal, onPhase: ((phase: CreateWorktreePhase) => void) | undefined, ): Promise { - onPhase?.('prepare') + onPhase?.(fetch ? 'fetch' : 'prepare') const cwd = await this.ctx.workingDirectory.ensure(agent, signal) const policy = this.ctx.sandboxPolicy.resolve({ session: agent.session }) const run = this.gitRunner(policy, signal) @@ -269,6 +280,10 @@ export class WorktreeService extends Service { const rootOutput = await run(cwd, ['rev-parse', '--show-toplevel']) const rootTarget = await this.ctx.fs.resolve(rootOutput.stdout.replace(/\r?\n$/, ''), { cwd, signal }) const repositoryRoot = this.ctx.fs.processPath(rootTarget) + if (fetch) { + await fetchRemoteBranch(run, repositoryRoot, revision) + onPhase?.('prepare') + } const base = await run(repositoryRoot, ['rev-parse', '--verify', '--end-of-options', `${revision}^{commit}`]) const baseCommit = base.stdout.trim() const existing = await run(repositoryRoot, ['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], [0, 1]) @@ -297,7 +312,7 @@ export class WorktreeService extends Service { agent: Agent, { path, branch, baseCommit, repositoryRoot }: RestoreWorktreeRequest, signal: AbortSignal, - onPhase: ((phase: CreateWorktreePhase) => void) | undefined, + onPhase: ((phase: Exclude) => void) | undefined, ): Promise { onPhase?.('prepare') const policy = this.ctx.sandboxPolicy.resolve({ session: agent.session }) @@ -378,6 +393,32 @@ async function assertBranchName(run: GitRun, directory: string, branch: string, if (checked.exitCode !== 0) throw new WorktreeError(`${field} must be a valid Git branch name`, 'WORKTREE_INVALID_ARGUMENT') } +/** + * Fetch one remote branch into its remote-tracking branch, without tags, submodules, `FETCH_HEAD`, or automatic + * maintenance. + * @param run - confined Git runner. + * @param repositoryRoot - root of the source checkout. + * @param ref - remote-tracking branch `refs/remotes//`. + * @throws {WorktreeError} `WORKTREE_INVALID_ARGUMENT` when no configured remote owns `ref`; the command's failure when + * listing the remotes or fetching fails. + */ +async function fetchRemoteBranch(run: GitRun, repositoryRoot: string, ref: string): Promise { + const rest = ref.slice(REMOTE_REFS.length) + const listed = await run(repositoryRoot, ['remote']) + // A remote name may contain slashes, so the longest configured name that owns the ref wins. + const [remote] = listed.stdout.split(/\r?\n/) + .filter(name => name.length > 0 && rest.startsWith(`${name}/`)) + .sort((left, right) => right.length - left.length) + const branch = remote === undefined ? '' : rest.slice(remote.length + 1) + if (remote === undefined || !relativePath(branch)) { + throw new WorktreeError(`worktree from is not a remote-tracking branch of a configured remote: ${ref}`, 'WORKTREE_INVALID_ARGUMENT') + } + await run(repositoryRoot, [ + 'fetch', '--quiet', '--no-tags', '--no-recurse-submodules', '--no-write-fetch-head', '--no-auto-maintenance', + '--end-of-options', remote, `+refs/heads/${branch}:${ref}`, + ]) +} + /** * Add retained-artifact context to a failure without changing its routable identity: * a `HarnessError` keeps its `name` and `code`, and caller cancellation stays an `AbortError`. diff --git a/packages/experimental/worktree/src/types.ts b/packages/experimental/worktree/src/types.ts index da85333e13..da503acaf5 100644 --- a/packages/experimental/worktree/src/types.ts +++ b/packages/experimental/worktree/src/types.ts @@ -1,11 +1,16 @@ /** Public requests and results for creating a Git worktree and entering it, and for restoring a removed one. */ -/** A new checkout from a locally available Git commit, branch, or tag. */ +/** A new checkout from a locally available Git commit, branch, or tag, or from a remote branch fetched first. */ export interface CreateWorktreeRequest { /** New branch name, also used as the relative checkout directory; omission generates a name. */ name?: string /** Local revision to resolve before creation; omission selects HEAD. */ from?: string + /** + * Fetch `from` from its remote before resolving it. `from` must then be the full name of a remote-tracking + * branch, `refs/remotes//`, of a configured remote; only that branch is fetched, without tags. + */ + fetch?: boolean } /** Committed Git baseline and the calling Session's resulting working directory. */ @@ -21,12 +26,13 @@ export interface CreatedWorktree { } /** - * Stage of one creation or restoration, reported before it begins: `prepare` + * Stage of one creation or restoration, reported before it begins: `fetch` + * fetches the remote base branch of a creation that asks for it; `prepare` * validates the request, allocates the checkout directory, and creates the * branch, which a restoration creates again only when it is gone; `checkout` * writes the files and, for a creation, enters the checkout. */ -export type CreateWorktreePhase = 'prepare' | 'checkout' +export type CreateWorktreePhase = 'fetch' | 'prepare' | 'checkout' /** A removed checkout to check out again at its recorded directory. */ export interface RestoreWorktreeRequest { diff --git a/packages/experimental/worktree/tests/worktree.spec.ts b/packages/experimental/worktree/tests/worktree.spec.ts index e2da8a2268..25115bf779 100644 --- a/packages/experimental/worktree/tests/worktree.spec.ts +++ b/packages/experimental/worktree/tests/worktree.spec.ts @@ -426,6 +426,93 @@ describe('creating and entering retained worktrees', () => { }) }) +describe('fetching the remote base branch first', () => { + /** A clone of a new repository, which then gains a commit, a tag, and a branch that the clone has not fetched. */ + async function behindClone(origin = 'origin'): Promise<{ upstream: string; clone: string; fetched: string }> { + const upstream = await repo() + const clone = join(upstream, 'clone') + await git(upstream, 'clone', '--origin', origin, pathToFileURL(upstream).href, clone) + // As `repository` does: a runner's global newline conversion would otherwise rewrite the files a worktree checks out. + await git(clone, 'config', 'core.autocrlf', 'false') + await writeFile(join(upstream, 'tracked.txt'), 'remote\n') + await git(upstream, 'commit', '-am', 'remote') + await git(upstream, 'tag', 'v1') + await git(upstream, 'branch', 'other') + return { upstream, clone, fetched: await git(upstream, 'rev-parse', 'HEAD') } + } + + it('fetches only the chosen branch, without tags, then pins and checks out the fetched commit without an upstream', async () => { + const { clone, fetched } = await behindClone() + ctx = await harness(clone) + const agent = testAgent(ctx, clone) + const phases: string[] = [] + + const result = await ctx.worktrees.create(agent, { name: 'fresh', from: 'refs/remotes/origin/main', fetch: true }, undefined, (phase) => { + phases.push(phase) + }) + + expect(phases).toEqual(['fetch', 'prepare', 'checkout']) + expect(result.baseCommit).toBe(fetched) + expect(await git(clone, 'rev-parse', 'refs/remotes/origin/main')).toBe(fetched) + expect(await contents(join(result.path, 'tracked.txt'))).toBe('remote\n') + expect(await git(clone, 'tag', '--list')).toBe('') + expect(await git(clone, 'for-each-ref', '--format=%(refname)', 'refs/remotes/origin/other')).toBe('') + expect(existsSync(join(clone, '.git', 'FETCH_HEAD'))).toBe(false) + await expect(git(clone, 'config', '--get', 'branch.fresh.merge')).rejects.toThrow() + }) + + it('fetches from the longest configured remote name that owns the branch', async () => { + const { upstream, clone, fetched } = await behindClone('team/fork') + // Newer `git remote add` refuses a name nested with another remote's, but configuration written earlier or by hand + // can hold both. + await git(clone, 'config', 'remote.team.url', join(upstream, 'missing.git')) + await git(clone, 'config', 'remote.team.fetch', '+refs/heads/*:refs/remotes/team/*') + ctx = await harness(clone) + const agent = testAgent(ctx, clone) + + const result = await ctx.worktrees.create(agent, { name: 'forked', from: 'refs/remotes/team/fork/main', fetch: true }) + + expect(result.baseCommit).toBe(fetched) + expect(await git(clone, 'rev-parse', 'refs/remotes/team/fork/main')).toBe(fetched) + }) + + it('refuses a base that is not a remote-tracking branch of a configured remote', async () => { + const { clone } = await behindClone() + ctx = await harness(clone) + const agent = testAgent(ctx, clone) + const phases: string[] = [] + const record = (phase: string): void => { phases.push(phase) } + + await expect(ctx.worktrees.create(agent, { name: 'local', from: 'main', fetch: true }, undefined, record)) + .rejects.toMatchObject({ code: 'WORKTREE_INVALID_ARGUMENT' }) + expect(phases).toEqual([]) + for (const from of ['refs/remotes/gone/main', 'refs/remotes/origin/']) { + await expect(ctx.worktrees.create(agent, { name: 'stray', from, fetch: true }, undefined, record)) + .rejects.toMatchObject({ code: 'WORKTREE_INVALID_ARGUMENT', message: expect.stringContaining(from) as string }) + } + expect(phases).toEqual(['fetch', 'fetch']) + expect(ctx.workingDirectory.get(agent.session)).toBe(clone) + expect(await git(clone, 'branch', '--list', 'stray')).toBe('') + }) + + it('reports a failed fetch without creating a branch, a checkout, or the pool', async () => { + const { upstream, clone } = await behindClone() + await git(clone, 'remote', 'set-url', 'origin', join(upstream, 'missing.git')) + ctx = await harness(clone) + const agent = testAgent(ctx, clone) + const phases: string[] = [] + + await expect(ctx.worktrees.create(agent, { name: 'offline', from: 'refs/remotes/origin/main', fetch: true }, undefined, (phase) => { + phases.push(phase) + })).rejects.toMatchObject({ code: 'WORKTREE_COMMAND_FAILED' }) + + expect(phases).toEqual(['fetch']) + expect(await git(clone, 'branch', '--list', 'offline')).toBe('') + expect(existsSync(join(clone, '.agents'))).toBe(false) + expect(ctx.workingDirectory.get(agent.session)).toBe(clone) + }) +}) + describe('restoring removed worktrees', () => { /** The checkout directories Git registers for `root`, in Git's notation. */ async function registered(root: string): Promise { diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 9f22b44801..380ae763a4 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1491,11 +1491,11 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the cleanup state, or null without a worktree service, an attempt, or a current revision.', }, { - signature: '@Remote async branches(session: Session, signal: AbortSignal): Promise', - description: 'List the local branches that can start a worktree of the Session\'s current checkout.', - parameters: [{ name: 'session', description: 'Session whose current directory is listed.' }, { name: 'signal', description: 'request cancellation.' }], - returns: 'the checked-out branch and at most `maxBranches` local branches, the checked-out one first.', - throws: ['when the current directory is not inside a checkout or Git fails.'], + signature: '@Remote async worktreeBases(session: Session, query: string, signal: AbortSignal): Promise', + description: 'List the branches that can start a worktree of the Session\'s current checkout: the checked-out branch, each remote\'s default branch, other local branches, and each remote\'s other remote-tracking branches, remotes in the order the panel recognizes code hosts.', + parameters: [{ name: 'session', description: 'Session whose checkout is read.' }, { name: 'query', description: 'text the branch names must contain, ignoring case; empty for every branch.' }, { name: 'signal', description: 'request cancellation.' }], + returns: 'the branches, at most `maxBranches` local branches and `maxBranches` per remote, most recently committed first.', + throws: ['`forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`.'], }, { signature: '@Remote async diffBases(session: Session, query: string, signal: AbortSignal): Promise', @@ -1661,10 +1661,10 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ throws: ['`forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; `forgePanel/stale-head` when the head moved past `headSha`; `forgePanel/action-failed` with the host\'s reason when the host refuses, cannot be reached, or updates no branches; `forgePanel/action-unknown` when the host did not confirm whether it started the update.'], }, { - signature: '@Remote async requestWorktree(session: Session, from: string | null, signal: AbortSignal): Promise', - description: 'Ask for a new worktree before the Session\'s first turn, replacing an open request and forgetting a failed attempt. While the next message waits in the inbox, or else at the first step proposal, the panel creates a branch from `from`, or from HEAD of the current checkout when it is null, and enters its checkout. A message that already waits after a failed or stopped attempt keeps waiting for ForgePanelController.retryWorktree.', - parameters: [{ name: 'session', description: 'Session without a started turn.' }, { name: 'from', description: 'local base branch, or null for HEAD.' }, { name: 'signal', description: 'request cancellation.' }], - throws: ['`forgePanel/invalid-branch` when `from` is empty; `forgePanel/worktrees-unavailable` without a worktree service; `forgePanel/session-started` after a turn started or the worktree was created; `forgePanel/session-busy` while the worktree is being created.'], + signature: '@Remote async requestWorktree(session: Session, from: string | null, name: string | null, signal: AbortSignal): Promise', + description: 'Ask for a new worktree before the Session\'s first turn, replacing an open request and forgetting a failed attempt. While the next message waits in the inbox, or else at the first step proposal, the panel creates the branch `name`, or a generated branch per attempt when it is null, from `from`, or from HEAD of the current checkout when it is null, and enters its checkout; a remote-tracking `from` is fetched first. A message that already waits after a failed or stopped attempt keeps waiting for ForgePanelController.retryWorktree.', + parameters: [{ name: 'session', description: 'Session without a started turn.' }, { name: 'from', description: 'full name of a local or remote-tracking base branch, or null for HEAD.' }, { name: 'name', description: 'new branch name, or null to generate one per attempt.' }, { name: 'signal', description: 'request cancellation.' }], + throws: ['`forgePanel/invalid-branch` when `from` is empty; `forgePanel/invalid-name` when `name` breaks a branch-name rule; `forgePanel/branch-exists` when the checkout has a local branch named `name`; `forgePanel/not-a-checkout` when a name is checked outside a checkout; `forgePanel/worktrees-unavailable` without a worktree service; `forgePanel/session-started` after a turn started or the worktree was created; `forgePanel/session-busy` while the worktree is being created.'], }, { signature: '@Remote async cancelWorktree(session: Session, signal: AbortSignal): Promise', @@ -1678,9 +1678,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'session', description: 'Session whose creation stops.' }, { name: 'signal', description: 'request cancellation.' }], }, { - signature: '@Remote async retryWorktree(session: Session, signal: AbortSignal): Promise', - description: 'Make another attempt, with a new branch name, at the worktree a message of the Session waits for after a failed or stopped attempt.', - parameters: [{ name: 'session', description: 'Session whose message waits.' }, { name: 'signal', description: 'request cancellation.' }], + signature: '@Remote async retryWorktree(session: Session, fetch: boolean, signal: AbortSignal): Promise', + description: 'Make another attempt, on the requested branch name or a new generated one, at the worktree a message of the Session waits for after a failed or stopped attempt.', + parameters: [{ name: 'session', description: 'Session whose message waits.' }, { name: 'fetch', description: 'false skips fetching a remote-tracking base branch for this attempt, which then starts from the commit last fetched.' }, { name: 'signal', description: 'request cancellation.' }], throws: ['`forgePanel/not-waiting` when no message waits or an attempt is running.'], }, { @@ -5090,15 +5090,15 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ methods: [ { signature: 'async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise', - description: 'Create a fresh branch and checkout at a pinned local revision, then enter it. Existing branches or checkout paths fail. Uncommitted files stay in the source checkout. Checkout disables configured clean, smudge, and process filters without changing Git config. Repository-local replacement refs still apply; baseCommit reports the resolved object name. The new checkout becomes current only after Git setup succeeds. Failures may retain newly allocated Git/filesystem artifacts; no branch or checkout is removed automatically.', - parameters: [{ name: 'agent', description: 'caller whose current directory selects the source repository and file policy.' }, { name: 'request', description: 'optional new name and local revision; defaults are generated name and HEAD.' }, { name: 'signal', description: 'cancellation of lookup, creation, and working-directory publication.' }, { name: 'onPhase', description: 'receives each stage before it begins; it must not throw.' }], + description: 'Create a fresh branch and checkout at a pinned local revision, then enter it. A request that asks to fetch first fetches its remote-tracking branch, only that branch and without tags, then pins the fetched commit. Existing branches or checkout paths fail. Uncommitted files stay in the source checkout. Checkout disables configured clean, smudge, and process filters without changing Git config. Repository-local replacement refs still apply; baseCommit reports the resolved object name. The new checkout becomes current only after Git setup succeeds. Failures may retain newly allocated Git/filesystem artifacts; no branch or checkout is removed automatically.', + parameters: [{ name: 'agent', description: 'caller whose current directory selects the source repository and file policy.' }, { name: 'request', description: 'optional new name, local revision, and fetch switch; defaults are generated name, HEAD, and no fetch.' }, { name: 'signal', description: 'cancellation of lookup, creation, and working-directory publication.' }, { name: 'onPhase', description: 'receives each stage before it begins; it must not throw.' }], returns: 'canonical checkout path, branch name, pinned commit, and source repository root.', - throws: ['{WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.'], + throws: ['{WorktreeError} for an invalid request, a fetch request whose `from` is not a remote-tracking branch of a configured remote, an existing branch or path, or a failed, oversized, or timed-out command, including the fetch; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.'], }, { - signature: 'async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise', + signature: 'async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: Exclude) => void, ): Promise', description: 'Check out a removed worktree again at its recorded directory: its branch when the branch still exists, otherwise a new branch of the same name at `baseCommit`. Only the missing target\'s unlocked registration is removed, and an existing directory fails. Changes that were never committed are not recovered. Checkout disables configured clean, smudge, and process filters, as creation does. The calling Session\'s working directory does not change. Failures may retain newly allocated Git/filesystem artifacts.', - parameters: [{ name: 'agent', description: 'caller whose sandbox policy confines the commands.' }, { name: 'request', description: 'recorded directory, branch, base commit, and source repository root.' }, { name: 'signal', description: 'cancellation of the restoration.' }, { name: 'onPhase', description: 'receives each stage before it begins; it must not throw.' }], + parameters: [{ name: 'agent', description: 'caller whose sandbox policy confines the commands.' }, { name: 'request', description: 'recorded directory, branch, base commit, and source repository root.' }, { name: 'signal', description: 'cancellation of the restoration.' }, { name: 'onPhase', description: 'receives each stage before it begins, never `fetch`; it must not throw.' }], returns: 'the directory and whether the branch was created again.', throws: ['{WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized, or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.'], }, @@ -6740,11 +6740,11 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'CreateWorktreePhase', - declaration: 'export type CreateWorktreePhase = \'prepare\' | \'checkout\';', + declaration: 'export type CreateWorktreePhase = \'fetch\' | \'prepare\' | \'checkout\';', }, { name: 'CreateWorktreeRequest', - declaration: 'export interface CreateWorktreeRequest {\n name?: string;\n from?: string;\n}', + declaration: 'export interface CreateWorktreeRequest {\n name?: string;\n from?: string;\n fetch?: boolean;\n}', }, { name: 'CredentialInfo', @@ -7034,10 +7034,6 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeBaseBranches', declaration: 'export interface ForgeBaseBranches {\n readonly automatic: ForgeAutomaticBase | null;\n readonly remote: readonly ForgeBaseBranch[];\n readonly local: readonly ForgeBaseBranch[];\n}', }, - { - name: 'ForgeBranches', - declaration: 'export interface ForgeBranches {\n readonly current: string | null;\n readonly branches: readonly string[];\n}', - }, { name: 'ForgeChangedFile', declaration: 'export interface ForgeChangedFile {\n readonly path: string;\n readonly additions: number;\n readonly deletions: number;\n readonly binary: boolean;\n}', @@ -7204,7 +7200,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ForgePanelWorktree', - declaration: 'export interface ForgePanelWorktree {\n readonly editable: boolean;\n readonly blocker: ForgeWorktreeBlocker | null;\n readonly request: ForgeWorktreeRequest | null;\n readonly created: ForgeSessionWorktree | null;\n readonly creation: ForgeWorktreeCreation | null;\n readonly failure: ForgeWorktreeFailure | null;\n readonly missing: ForgeMissingWorktree | null;\n readonly restoration: ForgeWorktreeRestoration | null;\n readonly waiting: ForgeWorktreeWaiting | null;\n}', + declaration: 'export interface ForgePanelWorktree {\n readonly editable: boolean;\n readonly blocker: ForgeWorktreeBlocker | null;\n readonly namePrefix: string;\n readonly request: ForgeWorktreeRequest | null;\n readonly created: ForgeSessionWorktree | null;\n readonly creation: ForgeWorktreeCreation | null;\n readonly failure: ForgeWorktreeFailure | null;\n readonly missing: ForgeMissingWorktree | null;\n readonly restoration: ForgeWorktreeRestoration | null;\n readonly waiting: ForgeWorktreeWaiting | null;\n}', }, { name: 'ForgePendingReview', @@ -7222,6 +7218,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeRegisteredLens', declaration: 'export interface ForgeRegisteredLens {\n readonly id: string;\n readonly version: string;\n}', }, + { + name: 'ForgeRemoteBranches', + declaration: 'export interface ForgeRemoteBranches {\n readonly name: string;\n readonly repository: string | null;\n readonly branches: readonly ForgeBaseBranch[];\n}', + }, + { + name: 'ForgeRemoteDefault', + declaration: 'export interface ForgeRemoteDefault extends ForgeBaseBranch {\n readonly remote: string;\n}', + }, { name: 'ForgeRepository', declaration: 'export interface ForgeRepository {\n readonly forge: string;\n readonly host: string;\n readonly owner: string;\n readonly name: string;\n}', @@ -7298,21 +7302,25 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeViewedState', declaration: 'export type ForgeViewedState = \'viewed\' | \'unviewed\' | \'dismissed\';', }, + { + name: 'ForgeWorktreeBases', + declaration: 'export interface ForgeWorktreeBases {\n readonly current: ForgeBaseBranch | null;\n readonly defaults: readonly ForgeRemoteDefault[];\n readonly local: readonly ForgeBaseBranch[];\n readonly remotes: readonly ForgeRemoteBranches[];\n}', + }, { name: 'ForgeWorktreeBlocker', declaration: 'export type ForgeWorktreeBlocker = \'not-git\' | \'outside-writable-root\' | \'read-only\';', }, { name: 'ForgeWorktreeCreation', - declaration: 'export interface ForgeWorktreeCreation {\n readonly phase: \'prepare\' | \'checkout\';\n readonly branch: string;\n readonly from: string | null;\n readonly held: boolean;\n}', + declaration: 'export interface ForgeWorktreeCreation {\n readonly phase: \'fetch\' | \'prepare\' | \'checkout\';\n readonly branch: string;\n readonly from: string | null;\n readonly fetch: boolean;\n readonly held: boolean;\n}', }, { name: 'ForgeWorktreeFailure', - declaration: 'export interface ForgeWorktreeFailure {\n readonly branch: string | null;\n readonly from: string | null;\n readonly phase: \'prepare\' | \'checkout\';\n readonly message: string;\n}', + declaration: 'export interface ForgeWorktreeFailure {\n readonly branch: string | null;\n readonly from: string | null;\n readonly fetch: boolean;\n readonly phase: \'fetch\' | \'prepare\' | \'checkout\';\n readonly message: string;\n readonly exists: boolean;\n}', }, { name: 'ForgeWorktreeRequest', - declaration: 'export interface ForgeWorktreeRequest {\n readonly from: string | null;\n}', + declaration: 'export interface ForgeWorktreeRequest {\n readonly from: string | null;\n readonly name: string | null;\n}', }, { name: 'ForgeWorktreeRestoration', diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index a5a4b2e307..a42817d7e9 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -436,7 +436,9 @@ export const LINK_MAP: Readonly> = { ForgeReviewRequest: 'forge.md', ForgeReviewResult: 'forge.md', ForgeBaseBranches: 'forge.md', - ForgeBranches: 'forge.md', + ForgeRemoteBranches: 'forge.md', + ForgeRemoteDefault: 'forge.md', + ForgeWorktreeBases: 'forge.md', ForgeChangeRequestDiff: 'forge.md', ForgeCommit: 'forge.md', ForgeCommitList: 'forge.md', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 5c59990dc2..05227e60b8 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -2771,7 +2771,17 @@ }, { "doc": "docs/subsystems/forge.md", - "symbol": "ForgeBranches", + "symbol": "ForgeWorktreeBases", + "source": "packages/experimental/client-ui-forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeRemoteDefault", + "source": "packages/experimental/client-ui-forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeRemoteBranches", "source": "packages/experimental/client-ui-forge/src/types.ts" }, { From d065d01fec1154c62f33504be79a13168220f926 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 17 Nov 2026 12:02:20 +0800 Subject: [PATCH 48/48] Windows CUA workaround for debugging VM timeouts and failures (#8464) * Increase timeout * Wait for another connectTimeout when idle * Report failure to upstream * Remove clipboard monitor * Write exception log for cua helper failure * Update comment and readme * Truncate failure log * Handle timeout * Add coverage ignore --- .../experimental/cua-windows/README.i18n.yaml | 4 +- packages/experimental/cua-windows/README.md | 2 +- .../experimental/cua-windows/README.zh.md | 2 +- .../native/entry/ClipboardPaste.cs | 161 ++---------------- .../native/entry/DesktopExecutor.cs | 9 +- .../cua-windows/native/entry/Dispatchers.cs | 23 +-- .../native/entry/NativeExceptionLog.cs | 58 +++++++ .../cua-windows/native/entry/NativeServer.cs | 138 ++++++++++----- .../cua-windows/native/entry/Program.cs | 2 + .../experimental/cua-windows/src/guidance.ts | 3 +- .../experimental/cua-windows/src/index.ts | 14 +- .../cua-windows/src/native-runtime.ts | 70 +++++++- .../tests/provider-lifecycle.spec.ts | 4 +- packages/experimental/cua/src/index.ts | 4 +- packages/experimental/cua/src/types.ts | 3 +- 15 files changed, 268 insertions(+), 229 deletions(-) create mode 100644 packages/experimental/cua-windows/native/entry/NativeExceptionLog.cs diff --git a/packages/experimental/cua-windows/README.i18n.yaml b/packages/experimental/cua-windows/README.i18n.yaml index 3840972d27..e3f75c7271 100644 --- a/packages/experimental/cua-windows/README.i18n.yaml +++ b/packages/experimental/cua-windows/README.i18n.yaml @@ -15,8 +15,8 @@ en: 8ee204b4021505b9 zh: 67040b79fcd9643b /deepseek-ai-dsh-cua-windows/setup-and-configuration: - en: 879fde2d14869543 - zh: 69d4c6c2c2823edc + en: 5f4acdea9b346066 + zh: 1793b993e7561647 /deepseek-ai-dsh-cua-windows/interface-semantics: en: 13ff5154e3ed57cf zh: b6a976028b104068 diff --git a/packages/experimental/cua-windows/README.md b/packages/experimental/cua-windows/README.md index 59e19b96b8..dcc3c9eaeb 100644 --- a/packages/experimental/cua-windows/README.md +++ b/packages/experimental/cua-windows/README.md @@ -24,7 +24,7 @@ Discover Windows applications, obtain consent, then inspect and operate their wi In a native Windows source checkout, activation uses the .NET 10 SDK on PATH to build the helper for the current architecture under `native/bin/win-`. Set `helperPath` to the absolute path of an existing executable to use it instead. For a manual build, run `pnpm run build:native:x64` or `pnpm run build:native:arm64` in this package. To use the standalone win-x64 ZIP, extract the entire archive and point `helperPath` at its exe. The framework-dependent `build:native` output in `native/bin/local` requires a matching Windows .NET runtime and an explicit `helperPath`. -`buildTimeoutMs` defaults to 300000, `connectTimeoutMs` to 30000, and `pollIntervalMs` to 25. Accessibility reads default to 2000 nodes and depth 25. Pass `maxElements` and `maxDepth` to override either limit for one read. The bundle loads this provider only on native Windows. When configured explicitly in WSL, `windowsPowerShellPath` defaults to `powershell.exe`. The WSL cache currently copies only the exe, so a multi-file publish cannot start from that cache. +`buildTimeoutMs` defaults to 300000, `connectTimeoutMs` to 600000, and `pollIntervalMs` to 25. Accessibility reads default to 2000 nodes and depth 25. Pass `maxElements` and `maxDepth` to override either limit for one read. The bundle loads this provider only on native Windows. When configured explicitly in WSL, `windowsPowerShellPath` defaults to `powershell.exe`. The WSL cache currently copies only the exe, so a multi-file publish cannot start from that cache. ## Interface semantics diff --git a/packages/experimental/cua-windows/README.zh.md b/packages/experimental/cua-windows/README.zh.md index 413061faf6..45f309ee88 100644 --- a/packages/experimental/cua-windows/README.zh.md +++ b/packages/experimental/cua-windows/README.zh.md @@ -24,7 +24,7 @@ kind: "package-reference" 在原生 Windows 的源码检出中,提供方启用时通过 PATH 中的 .NET 10 SDK 构建当前架构的 helper,输出到 `native/bin/win-`。`helperPath` 可指定现有 exe 的绝对路径。手动构建时,在本包中执行 `pnpm run build:native:x64` 或 `pnpm run build:native:arm64`。使用独立 win-x64 ZIP 时,需要完整解压,并将 `helperPath` 指向其中的 exe。使用 `build:native` 生成的 `native/bin/local` 产物时,需要匹配的 Windows .NET 运行时,并显式配置 `helperPath`。 -`buildTimeoutMs` 默认 300000,`connectTimeoutMs` 默认 30000,`pollIntervalMs` 默认 25。辅助功能树默认最多读取 2000 个节点、深度 25。一次读取可传入 `maxElements` 和 `maxDepth`。组合包仅在原生 Windows 上加载此提供方。显式在 WSL 中配置提供方时,`windowsPowerShellPath` 默认是 `powershell.exe`。目前 WSL 缓存只复制 exe,多文件发布目录不能直接从该缓存启动。 +`buildTimeoutMs` 默认 300000,`connectTimeoutMs` 默认 600000,`pollIntervalMs` 默认 25。辅助功能树默认最多读取 2000 个节点、深度 25。一次读取可传入 `maxElements` 和 `maxDepth`。组合包仅在原生 Windows 上加载此提供方。显式在 WSL 中配置提供方时,`windowsPowerShellPath` 默认是 `powershell.exe`。目前 WSL 缓存只复制 exe,多文件发布目录不能直接从该缓存启动。 ## 接口语义 diff --git a/packages/experimental/cua-windows/native/entry/ClipboardPaste.cs b/packages/experimental/cua-windows/native/entry/ClipboardPaste.cs index 3b25dc2062..6617c44232 100644 --- a/packages/experimental/cua-windows/native/entry/ClipboardPaste.cs +++ b/packages/experimental/cua-windows/native/entry/ClipboardPaste.cs @@ -1,5 +1,4 @@ -// Delayed rendering waits for clipboard data consumption before restoring the previous formats. -using System.Diagnostics; +// Paste publishes clipboard data immediately and leaves it available after dispatching Control+V. using System.Runtime.InteropServices; using System.Text; using DeepSeek.Cua.Protocol; @@ -8,96 +7,6 @@ namespace DeepSeek.Cua.Windows; internal sealed class ClipboardPaste { - private sealed class Transaction(ServiceControl control, int targetPid, uint format, byte[] payload, List<(uint Format, byte[] Data)> previous, uint originalSequence) - { - internal readonly TaskCompletionSource Consumed = new(TaskCreationOptions.RunContinuationsAsynchronously); - private uint sequence = originalSequence; - private bool replaced; - private bool restoring; - private bool changed; - private bool rendered; - - internal void Begin() - { - if (!Win32.OpenClipboard(control.Handle)) throw new NativeFailure("CLIPBOARD_BUSY", "Another application is using the clipboard"); - try - { - if (Win32.GetClipboardSequenceNumber() != sequence) throw new NativeFailure("CLIPBOARD_CHANGED", "The clipboard changed before paste; it was not replaced"); - if (!Win32.EmptyClipboard()) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused clipboard replacement"); - replaced = true; - control.ClipboardMessage = Message; - Marshal.SetLastPInvokeError(0); - Win32.SetClipboardData(format, 0); - var error = Marshal.GetLastPInvokeError(); - sequence = Win32.GetClipboardSequenceNumber(); - if (error != 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused the temporary clipboard format"); - } - finally { Win32.CloseClipboard(); } - // CloseClipboard can add synthesized formats and advance the sequence. - sequence = Win32.GetClipboardSequenceNumber(); - } - - private bool Message(int message, nint parameter) - { - if (message == 0x0307 && !restoring) - { - changed = true; - Consumed.TrySetException(new NativeFailure("CLIPBOARD_CHANGED", "Another writer replaced the clipboard; observe before deciding on further input")); - return true; - } - if (message is not (0x0305 or 0x0306)) return false; - if (message == 0x0305 && (uint)parameter != format) return false; - if (message == 0x0305) - { - Win32.GetWindowThreadProcessId(Win32.GetOpenClipboardWindow(), out var readerPid); - // Clipboard monitors can request data before the target handles Control+V. - // Leave the format delayed until the selected application requests it. - if (readerPid != targetPid) return true; - } - var opened = false; - try - { - if (Win32.GetClipboardOwner() != control.Handle) return true; - if (message == 0x0306) - { - if (!Win32.OpenClipboard(control.Handle)) return true; - opened = true; - } - if (Win32.GetClipboardSequenceNumber() != sequence) changed = true; - Publish(format, payload); - rendered = true; - sequence = Win32.GetClipboardSequenceNumber(); - if (changed) Consumed.TrySetException(new NativeFailure("CLIPBOARD_CHANGED", "Another writer changed the clipboard during paste")); - else if (message == 0x0305) Consumed.TrySetResult(null); - } - catch (Exception error) { Consumed.TrySetException(error); } - finally { if (opened) Win32.CloseClipboard(); } - return true; - } - - internal bool Restore() - { - if (!replaced) return true; - if (Win32.GetClipboardOwner() != control.Handle) { control.ClipboardMessage = null; return true; } - if (!Win32.OpenClipboard(control.Handle)) return false; - try - { - if (Win32.GetClipboardSequenceNumber() != sequence) changed = true; - if (changed) - { - // A later writer keeps its data; fulfill any remaining promise before releasing its renderer. - if (!rendered) Publish(format, payload); - return true; - } - restoring = true; - if (!Win32.EmptyClipboard()) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused clipboard restoration"); - foreach (var original in previous) Publish(original.Format, original.Data); - return true; - } - finally { control.ClipboardMessage = null; Win32.CloseClipboard(); } - } - } - private static void Publish(uint format, byte[] bytes) { var memory = Win32.GlobalAlloc(0x0002, (nuint)bytes.Length); @@ -114,71 +23,29 @@ internal sealed class ClipboardPaste finally { if (memory != 0) Win32.GlobalFree(memory); } } - private static Transaction Prepare(ServiceControl control, int targetPid, string text, string format, int maximumBytes) + private static void SetClipboard(ServiceControl control, string text, string format, int maximumBytes) { + var payload = format == "html" ? HtmlClipboard.Encode(text) : Encoding.Unicode.GetBytes(text + "\0"); + if (payload.Length > maximumBytes) throw new NativeFailure("CLIPBOARD_LIMIT", "The paste content exceeds maxClipboardBytes"); + var nativeFormat = format == "html" ? Win32.RegisterClipboardFormat("HTML Format") : 13u; + if (nativeFormat == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows could not register the requested clipboard format"); if (!Win32.OpenClipboard(control.Handle)) throw new NativeFailure("CLIPBOARD_BUSY", "Another application is using the clipboard"); try { - var previous = new List<(uint, byte[])>(); - long total = 0; - uint current = 0; - while (true) - { - Marshal.SetLastPInvokeError(0); - current = Win32.EnumClipboardFormats(current); - if (current == 0) - { - if (Marshal.GetLastPInvokeError() != 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The existing clipboard formats could not be enumerated"); - break; - } - if (current is 3 or 0x0083) - throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The clipboard contains a metafile with nested handles; paste left it unchanged"); - var memory = Win32.GetClipboardData(current); - var size = memory == 0 ? 0 : Win32.GlobalSize(memory); - if (size == 0 || size > int.MaxValue) - throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The current clipboard includes a format that cannot be preserved as bytes; paste left it unchanged"); - total += (long)size; - if (total > maximumBytes) throw new NativeFailure("CLIPBOARD_LIMIT", "The existing clipboard exceeds maxClipboardBytes; it was not replaced"); - var pointer = Win32.GlobalLock(memory); - if (pointer == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The current clipboard data could not be read; it was not replaced"); - var bytes = new byte[(int)size]; - try { Marshal.Copy(pointer, bytes, 0, bytes.Length); } - finally { Win32.GlobalUnlock(memory); } - previous.Add((current, bytes)); - } - var payload = format == "html" ? HtmlClipboard.Encode(text) : Encoding.Unicode.GetBytes(text + "\0"); - var nativeFormat = format == "html" ? Win32.RegisterClipboardFormat("HTML Format") : 13u; - if (nativeFormat == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows could not register the requested clipboard format"); - return new(control, targetPid, nativeFormat, payload, previous, Win32.GetClipboardSequenceNumber()); + if (!Win32.EmptyClipboard()) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused clipboard replacement"); + Publish(nativeFormat, payload); } finally { Win32.CloseClipboard(); } } - internal async Task Paste(AppState app, WindowState window, string text, string format, int maximumBytes, int readTimeoutMs, RequestContext context) + internal async Task Paste(AppState app, WindowState window, string text, string format, int maximumBytes, RequestContext context) { Windows.RequireForeground(app, window, context); - // Clipboard readers are matched against this window's real process, not a removal-only app identity. - var targetPid = window.ProcessId; - var transaction = await context.Sta.Invoke(control => Prepare(control, targetPid, text, format, maximumBytes), context.Cancellation); - try + await context.Sta.Invoke(control => { - await context.Sta.Invoke(() => transaction.Begin(), context.Cancellation); - Input.Press(app, window, "v", ["ctrl"], context); - try { await transaction.Consumed.Task.WaitAsync(TimeSpan.FromMilliseconds(readTimeoutMs), context.Cancellation); } - catch (TimeoutException) - { - throw new NativeFailure("PASTE_NOT_CONSUMED", "The target did not request clipboard data before pasteReadTimeoutMs; observe before deciding on further input"); - } - } - finally - { - var clock = Stopwatch.StartNew(); - while (!await context.Sta.Invoke(_ => transaction.Restore(), CancellationToken.None)) - { - if (clock.ElapsedMilliseconds >= context.Config.GraceMs) - NativeServer.Fatal("CLIPBOARD_CLEANUP", "Clipboard cleanup did not finish before the native grace deadline"); - await Task.Delay(context.Config.PollIntervalMs); - } - } + SetClipboard(control, text, format, maximumBytes); + return true; + }, context.Cancellation); + Input.Press(app, window, "v", ["ctrl"], context); } } diff --git a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs index 6af36d042f..91d63e8b62 100644 --- a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs +++ b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs @@ -48,16 +48,18 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA return (window, parameters.GetProperty("x").GetDouble(), parameters.GetProperty("y").GetDouble()); } - internal async Task Execute(NativeRequest request, ClientState state, NativeConfig config, CancellationToken cancellation) + internal async Task Execute(NativeRequest request, ClientState state, NativeConfig config, CancellationToken cancellation, + Action reportFailure) { + var context = new RequestContext(config, cancellation, mta, sta, reportFailure); if (request.Method == "screenshot") { - var context = new RequestContext(config, cancellation, mta, sta); AppState app; WindowState window; await queue.WaitAsync(cancellation); try { + context.Check(); DesktopSession.RequireInteractive(); app = state.App(String(request.Params, "appHandle")); window = Selected(app, request.Params, context); @@ -68,7 +70,6 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA await queue.WaitAsync(cancellation); try { - var context = new RequestContext(config, cancellation, mta, sta); context.Check(); var parameters = request.Params; if (request.Method == "permissionStatus") return DesktopSession.Status(WindowCapture.IsSupported); @@ -148,7 +149,7 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA { var target = Selected(app, parameters, context); await clipboard.Paste(app, target, String(parameters, "text"), OptionalString(parameters, "format") ?? "text", - parameters.GetProperty("maxClipboardBytes").GetInt32(), parameters.GetProperty("pasteReadTimeoutMs").GetInt32(), context); + parameters.GetProperty("maxClipboardBytes").GetInt32(), context); return ActionResult(foreground); } case "mouseMove": diff --git a/packages/experimental/cua-windows/native/entry/Dispatchers.cs b/packages/experimental/cua-windows/native/entry/Dispatchers.cs index 11ba63b5c1..4fec3bd8a0 100644 --- a/packages/experimental/cua-windows/native/entry/Dispatchers.cs +++ b/packages/experimental/cua-windows/native/entry/Dispatchers.cs @@ -78,16 +78,10 @@ internal sealed class MtaDispatcher : IAsyncDisposable internal sealed class ServiceControl : Forms.Control { - internal Func? ClipboardMessage; protected override Forms.CreateParams CreateParams { get { var value = base.CreateParams; value.Parent = -3; return value; } } - protected override void WndProc(ref Forms.Message message) - { - if (ClipboardMessage?.Invoke(message.Msg, message.WParam) == true) return; - base.WndProc(ref message); - } } internal sealed class StaDispatcher : IAsyncDisposable @@ -162,7 +156,8 @@ internal sealed class StaDispatcher : IAsyncDisposable } } -internal sealed class RequestContext(NativeConfig config, CancellationToken cancellation, MtaDispatcher mta, StaDispatcher sta) +internal sealed class RequestContext(NativeConfig config, CancellationToken cancellation, MtaDispatcher mta, StaDispatcher sta, + Action reportFailure) { internal NativeConfig Config { get; } = config; internal CancellationToken Cancellation { get; } = cancellation; @@ -174,12 +169,18 @@ internal sealed class RequestContext(NativeConfig config, CancellationToken canc { Check(); var completed = 0; + NativeFailure TimedOut() => new("AX_TIMEOUT", "A Windows accessibility call did not return within its configured deadline; its outcome is unknown"); using var timer = new Timer(_ => { - if (Interlocked.Exchange(ref completed, 1) == 0) - NativeServer.Fatal("AX_TIMEOUT", "A Windows accessibility call did not return within its configured deadline"); + if (Interlocked.CompareExchange(ref completed, 2, 0) == 0) reportFailure(TimedOut()); }, null, Config.AxTimeoutMs, Timeout.Infinite); - try { var result = call(); Cancellation.ThrowIfCancellationRequested(); return result; } - finally { Interlocked.Exchange(ref completed, 1); } + try + { + var result = call(); + if (Interlocked.CompareExchange(ref completed, 1, 0) == 2) throw TimedOut(); + Check(); + return result; + } + finally { Interlocked.CompareExchange(ref completed, 1, 0); } } } diff --git a/packages/experimental/cua-windows/native/entry/NativeExceptionLog.cs b/packages/experimental/cua-windows/native/entry/NativeExceptionLog.cs new file mode 100644 index 0000000000..c7c2326d91 --- /dev/null +++ b/packages/experimental/cua-windows/native/entry/NativeExceptionLog.cs @@ -0,0 +1,58 @@ +// Shared-server exception diagnostics remain readable beside the helper executable. +using System.Runtime.ExceptionServices; +using System.Text; + +namespace DeepSeek.Cua.Windows; + +internal sealed class NativeExceptionLog : IDisposable +{ + private readonly string path = Path.Combine(AppContext.BaseDirectory, "dsh-cua-windows.log"); + private readonly object gate = new(); + private bool writing; + private bool disposed; + + internal NativeExceptionLog() + { + AppDomain.CurrentDomain.FirstChanceException += FirstChance; + AppDomain.CurrentDomain.UnhandledException += Unhandled; + Write("Startup", $"Shared server PID {Environment.ProcessId}"); + } + + private void FirstChance(object? sender, FirstChanceExceptionEventArgs args) + => Write("FirstChanceException", args.Exception); + + private void Unhandled(object? sender, UnhandledExceptionEventArgs args) + => Write($"UnhandledException (terminating={args.IsTerminating})", args.ExceptionObject); + + private void Write(string kind, object value) + { + lock (gate) + { + // First-chance notifications also fire for failures while formatting or writing this log. + if (disposed || writing) return; + writing = true; + try + { + var entry = $"[{DateTimeOffset.UtcNow:O}] {kind} PID={Environment.ProcessId} Thread={Environment.CurrentManagedThreadId}{Environment.NewLine}{value.ToString()}{Environment.NewLine}"; + File.AppendAllText(path, entry, Encoding.UTF8); + } + catch (Exception error) + { + try { Console.Error.WriteLine($"NATIVE_LOG: Could not append to {path}: {error}"); } + catch (Exception diagnosticError) { _ = diagnosticError; /* Diagnostic failures must not escape an exception event handler. */ } + } + finally { writing = false; } + } + } + + public void Dispose() + { + lock (gate) + { + if (disposed) return; + disposed = true; + AppDomain.CurrentDomain.FirstChanceException -= FirstChance; + AppDomain.CurrentDomain.UnhandledException -= Unhandled; + } + } +} diff --git a/packages/experimental/cua-windows/native/entry/NativeServer.cs b/packages/experimental/cua-windows/native/entry/NativeServer.cs index 2821df97ea..9f973a8840 100644 --- a/packages/experimental/cua-windows/native/entry/NativeServer.cs +++ b/packages/experimental/cua-windows/native/entry/NativeServer.cs @@ -1,6 +1,5 @@ // The per-user service serves isolated Agent connections and Host leases on a private named pipe. using System.Collections.Concurrent; -using System.Diagnostics.CodeAnalysis; using System.IO.Pipes; using System.Security.Cryptography; using System.Text.Json; @@ -11,14 +10,6 @@ namespace DeepSeek.Cua.Windows; internal static class NativeServer { - [DoesNotReturn] - internal static void Fatal(string code, string message) - { - Console.Error.WriteLine($"{code}: {message}; native handles are no longer usable"); - Environment.Exit(70); - throw new InvalidOperationException("Process exit returned"); - } - internal static async Task Run(string instance, string expectedRuntime, int connectTimeoutMs, int graceMs) { if (!Guid.TryParseExact(instance, "N", out _)) throw new NativeFailure("INVALID_ARGUMENT", "A Host instance identifier is required"); @@ -35,14 +26,28 @@ internal static class NativeServer await mta.Invoke(() => true, lifetime.Token); await using var executor = new DesktopExecutor(mta, sta); var clients = new ConcurrentDictionary(); - NamedPipeServerStream? listener = NewPipe(pipeName); + NamedPipeServerStream? listener = null; var membership = new object(); var connections = 0; try { while (!lifetime.IsCancellationRequested) { - await listener.WaitForConnectionAsync(lifetime.Token); + try + { + listener ??= NewPipe(pipeName); + await listener.WaitForConnectionAsync(lifetime.Token); + } + catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { break; } + catch (Exception error) + { + Report("NATIVE_LISTENER", error); + try { listener?.Dispose(); } + catch (Exception cleanupError) { Report("NATIVE_CONNECTION", cleanupError); } + listener = null; + await Task.Delay(graceMs, lifetime.Token); + continue; + } var connected = listener; lock (membership) { @@ -50,14 +55,14 @@ internal static class NativeServer connections++; lifetime.CancelAfter(Timeout.Infinite); } - listener = NewPipe(pipeName); + listener = null; var task = Serve(connected, executor, instance, runtime, connectTimeoutMs, lifetime.Token); clients.TryAdd(task, 0); _ = task.ContinueWith(completed => { clients.TryRemove(completed, out _); - if (completed.IsFaulted) { _ = completed.Exception; Console.Error.WriteLine("NATIVE_CONNECTION: Connection cleanup failed"); } - lock (membership) { if (--connections == 0) lifetime.Cancel(); } + if (completed.IsFaulted) Report("NATIVE_CONNECTION", completed.Exception!); + lock (membership) { if (--connections == 0) lifetime.CancelAfter(connectTimeoutMs); } }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } @@ -71,6 +76,15 @@ internal static class NativeServer } } + private static void Report(string code, Exception error) + { + try { Console.Error.WriteLine($"{code}: {error.GetType().Name}"); } + catch (Exception reportError) when (reportError is IOException or ObjectDisposedException) + { + _ = reportError; // A disconnected diagnostic stream must not stop the shared service. + } + } + private static NamedPipeServerStream NewPipe(string name) => new(name, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); @@ -122,7 +136,12 @@ internal static class NativeServer continue; } var request = NativeRequest.Parse(value); - if (active is { IsCompleted: false }) throw new NativeFailure("NATIVE_BUSY", "Native requests must be sequential"); + if (active is { IsCompleted: false }) + { + await Write(pipe, writer, Failure(request.Id, "NATIVE_BUSY", "The previous native operation has not stopped; do not send further input until it finishes"), + config.MaxResponseBytes, config.GraceMs, lifetime.Token); + continue; + } if (active is not null) await active; cancellation?.Dispose(); cancellation = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token); @@ -133,18 +152,19 @@ internal static class NativeServer } catch (Exception error) { - if (error is not (IOException or OperationCanceledException)) Console.Error.WriteLine($"NATIVE_CONNECTION: {error.GetType().Name}"); + if (error is not (IOException or OperationCanceledException)) Report("NATIVE_CONNECTION", error); } finally { lifetime.Cancel(); cancellation?.Cancel(); - if (active is not null) + try { - try { await active; } - catch (Exception error) { Console.Error.WriteLine($"NATIVE_CONNECTION: {error.GetType().Name}"); } + if (active is not null) await active; } - cancellation?.Dispose(); + catch (NativeFailure error) when (error.Code == "NATIVE_CLEANUP") { throw; } + catch (Exception error) { Report("NATIVE_CONNECTION", error); } + finally { cancellation?.Dispose(); } state.Clear(); if (closeRequested) await Write(pipe, writer, new { type = "closed" }, 8192, cleanupTimeoutMs, CancellationToken.None); @@ -155,33 +175,67 @@ internal static class NativeServer private static async Task Dispatch(NativeRequest request, ClientState state, DesktopExecutor executor, NativeConfig config, Stream pipe, SemaphoreSlim writer, CancellationToken cancellation, CancellationToken connection) { - var operation = executor.Execute(request, state, config, cancellation); - using var monitorStop = CancellationTokenSource.CreateLinkedTokenSource(cancellation); - var monitor = WatchOperation(operation, monitorStop.Token, config.GraceMs); - object response; - try { response = new { id = request.Id, result = await operation }; } - catch (OperationCanceledException) { response = Failure(request.Id, "NATIVE_CANCELLED", "Native operation cancelled; observe before deciding on further input"); } - catch (NativeFailure error) { response = Failure(request.Id, error.Code, error.Message); } - catch (NotImplementedException error) { response = Failure(request.Id, "NOT_IMPLEMENTED", error.Message); } - catch (ElementNotAvailableException) { response = Failure(request.Id, "STALE_SNAPSHOT", "An accessibility element disappeared; read fresh state"); } - catch (ElementNotEnabledException) { response = Failure(request.Id, "ELEMENT_DISABLED", "The selected control is disabled"); } - catch (UnauthorizedAccessException) { response = Failure(request.Id, "PERMISSION_DENIED", "Windows refused access to the selected application"); } - catch (Exception error) { response = Failure(request.Id, "NATIVE_OPERATION", $"Windows operation failed (0x{error.HResult:X8}); observe before retrying"); } - finally { monitorStop.Cancel(); await monitor; } - var bytes = JsonSerializer.SerializeToUtf8Bytes(response, WireJson.Options); - if (bytes.Length + 1 > config.MaxResponseBytes) response = Failure(request.Id, "NATIVE_RESPONSE_LIMIT", "Native response exceeded its configured byte limit"); - await Write(pipe, writer, response, config.MaxResponseBytes, config.GraceMs, connection); + var operationStop = CancellationTokenSource.CreateLinkedTokenSource(cancellation); + var failure = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + // A synchronous native call must not block the pipe reader or its timeout response. + var operation = Task.Run(() => executor.Execute(request, state, config, operationStop.Token, + error => { failure.TrySetResult(error); })); + try + { + object response; + try { response = new { id = request.Id, result = await WatchOperation(operation, failure.Task, operationStop.Token, config.GraceMs) }; } + catch (OperationCanceledException) { response = Failure(request.Id, "NATIVE_CANCELLED", "Native operation cancelled; observe before deciding on further input"); } + catch (NativeFailure error) + { + if (error.Code is "AX_TIMEOUT" or "NATIVE_CLEANUP") operationStop.Cancel(); + response = Failure(request.Id, error.Code, error.Message); + } + catch (NotImplementedException error) { response = Failure(request.Id, "NOT_IMPLEMENTED", error.Message); } + catch (ElementNotAvailableException) { response = Failure(request.Id, "STALE_SNAPSHOT", "An accessibility element disappeared; read fresh state"); } + catch (ElementNotEnabledException) { response = Failure(request.Id, "ELEMENT_DISABLED", "The selected control is disabled"); } + catch (UnauthorizedAccessException) { response = Failure(request.Id, "PERMISSION_DENIED", "Windows refused access to the selected application"); } + catch (Exception error) { response = Failure(request.Id, "NATIVE_OPERATION", $"Windows operation failed (0x{error.HResult:X8}); observe before retrying"); } + var bytes = JsonSerializer.SerializeToUtf8Bytes(response, WireJson.Options); + if (bytes.Length + 1 > config.MaxResponseBytes) response = Failure(request.Id, "NATIVE_RESPONSE_LIMIT", "Native response exceeded its configured byte limit"); + await Write(pipe, writer, response, config.MaxResponseBytes, config.GraceMs, connection); + } + finally + { + try { await operation.WaitAsync(TimeSpan.FromMilliseconds(config.GraceMs)); } + catch (TimeoutException) when (!operation.IsCompleted) + { + throw new NativeFailure("NATIVE_CLEANUP", "The native operation did not stop before the cleanup deadline; its outcome is unknown"); + } + catch (Exception error) { _ = error; /* The operation failure has already been reported to the caller. */ } + finally + { + // A late native call still owns its cancellation token; observe its eventual failure. + _ = operation.ContinueWith(completed => + { + _ = completed.Exception; + operationStop.Dispose(); + }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + } } private static object Failure(string id, string code, string message) => new { id, error = new { code, message } }; - private static async Task WatchOperation(Task operation, CancellationToken cancellation, int graceMs) + private static async Task WatchOperation(Task operation, Task failure, + CancellationToken cancellation, int graceMs) { - await Task.WhenAny(operation, Task.Delay(Timeout.Infinite, cancellation)); - if (operation.IsCompleted) return; - try { await operation.WaitAsync(TimeSpan.FromMilliseconds(graceMs)); } - catch (TimeoutException) { Fatal("NATIVE_CLEANUP", "A cancelled desktop operation did not stop before the grace deadline"); } - catch (Exception error) when (operation.IsCompleted) { _ = error; /* Dispatch owns the operation result. */ } + var completed = Task.WhenAny(operation, failure); + try { await completed.WaitAsync(cancellation); } + catch (OperationCanceledException) when (cancellation.IsCancellationRequested) + { + try { await completed.WaitAsync(TimeSpan.FromMilliseconds(graceMs)); } + catch (TimeoutException) + { + throw new NativeFailure("NATIVE_CLEANUP", "A cancelled desktop operation did not stop before the grace deadline; its outcome is unknown"); + } + } + if (failure.IsCompleted) throw await failure; + return await operation; } private static async Task Write(Stream pipe, SemaphoreSlim writer, object value, int maximum, int timeoutMs, CancellationToken cancellation) diff --git a/packages/experimental/cua-windows/native/entry/Program.cs b/packages/experimental/cua-windows/native/entry/Program.cs index 9c1577cfab..7809774609 100644 --- a/packages/experimental/cua-windows/native/entry/Program.cs +++ b/packages/experimental/cua-windows/native/entry/Program.cs @@ -3,6 +3,8 @@ using System.CommandLine; using DeepSeek.Cua.Protocol; using DeepSeek.Cua.Windows; +using var exceptionLog = args.Contains("--shared-server", StringComparer.Ordinal) ? new NativeExceptionLog() : null; + try { if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 19041)) diff --git a/packages/experimental/cua-windows/src/guidance.ts b/packages/experimental/cua-windows/src/guidance.ts index 3561ecdf50..166581fae9 100644 --- a/packages/experimental/cua-windows/src/guidance.ts +++ b/packages/experimental/cua-windows/src/guidance.ts @@ -10,6 +10,7 @@ const methodDetails = new Map([ ['getAccessibilityTree', 'Set the node count or depth for one read. Windows accepts maxElements from 1 to 10000 and maxDepth from 1 to 100. Omitted limits use the provider settings; maxDepth=1 includes only the window root. If the tree is truncated, select a narrower window or increase the relevant limit. includeMenus expands menu contents. Element IDs are UI Automation RuntimeIds formatted as slash-separated integer strings, such as "12/345/6". Pass the complete string unchanged as elementId. Each element lists all its supported patterns, not action names. Disabled is an observed state, not a prohibition on attempting an operation.'], ['listActions', 'Actions use case-sensitive Pattern.Action names, such as "Invoke.Invoke", "Toggle.Toggle", and "ExpandCollapse.Expand". Each pattern has a known set of native UI Automation operations. One pattern can expose multiple actions. Use a known operation of an advertised pattern directly; call listActions when you need to confirm the exposed operations. Query methods are not exposed through performAction.'], ['invoke', 'The provider chooses default action for well-known patterns. A failed operation is not retried through another pattern or simulated input.'], + ['paste', 'Write text or HTML to the system clipboard and send Ctrl+V to the target window. The new clipboard contents remain in place. Return dispatch evidence, not confirmation that the target applied the content; observe the target before continuing. A failure is reported without substituting typeText.'], ['performAction', 'Use the exact Pattern.Action name. Omit argument or pass null for a parameter-free operation. Pass a single parameter as its direct JSON value; pass multiple parameters as an object using their native names. Enum values use their exact names as strings. Examples: await win.performAction(id, "Value.SetValue", "hello"); await win.performAction(id, "Window.SetWindowVisualState", "Normal"); await win.performAction(id, "Transform.Resize", { width: 800, height: 600 }).'], ]) @@ -19,6 +20,6 @@ export const GUIDANCE = `${PLATFORM_GUIDANCE} ${COMMON_GUIDANCE.replace(/^- ([\w.]+)\(.*$/gm, (entry, method: string) => { const detail = methodDetails.get(method) if (!detail) return entry - if (method === 'getAccessibilityTree') return `${entry.replace(/ — .*$/, '')} — ${detail}` + if (method === 'getAccessibilityTree' || method === 'paste') return `${entry.replace(/ — .*$/, '')} — ${detail}` return `${entry} ${detail}` })}` diff --git a/packages/experimental/cua-windows/src/index.ts b/packages/experimental/cua-windows/src/index.ts index 3be20956f5..875a383fca 100644 --- a/packages/experimental/cua-windows/src/index.ts +++ b/packages/experimental/cua-windows/src/index.ts @@ -39,7 +39,13 @@ export interface Config extends CuaConfig { /** Validate platform configuration before locating and launching the helper. */ export const Config = Schema.object({ ...CuaConfigFields, - connectTimeoutMs: CuaConfigFields.connectTimeoutMs.default(30_000), + timeoutMs: CuaConfigFields.timeoutMs.default(60_000), + connectTimeoutMs: CuaConfigFields.connectTimeoutMs.default(600_000), + screenshotTimeoutMs: CuaConfigFields.screenshotTimeoutMs.default(60_000), + axTimeoutMs: CuaConfigFields.axTimeoutMs.default(60_000), + // Currently unused on Windows: paste does not wait for clipboard consumption. + pasteReadTimeoutMs: CuaConfigFields.pasteReadTimeoutMs.default(60_000), + graceMs: CuaConfigFields.graceMs.default(60_000), windowsPowerShellPath: Schema.string().min(1).default('powershell.exe'), pollIntervalMs: Schema.number().step(1).min(1).max(2 ** 31 - 1).default(25), textEventIntervalMs: CuaConfigFields.textEventIntervalMs.default(0), @@ -60,7 +66,7 @@ export async function apply(ctx: Context, config: Config): Promise { const controller = new AbortController() const prepare = async () => { const wsl = host === 'wsl' ? await prepareWsl({ subprocess: ctx.subprocess, signal: controller.signal, - timeoutMs: config.connectTimeoutMs, graceMs: config.graceMs, powershellPath: config.windowsPowerShellPath }) : undefined + timeoutMs: config.timeoutMs, graceMs: config.graceMs, powershellPath: config.windowsPowerShellPath }) : undefined let helperPath = config.helperPath if (helperPath === undefined) { const architecture = wsl?.architecture ?? nativeHostArchitecture(process.platform, process.arch) @@ -79,9 +85,7 @@ export async function apply(ctx: Context, config: Config): Promise { }, 'cua-windows.native-preparation') const helperPath = await prepared controller.signal.throwIfAborted() - // Temporary native-runtime configuration. - const launchWaitMs = 1000 - const runtime = new WindowsNativeRuntime(ctx, config.pollIntervalMs, launchWaitMs, host === 'wsl' ? 'stdio' : 'pipe') + const runtime = new WindowsNativeRuntime(ctx, config.pollIntervalMs, config.timeoutMs, host === 'wsl' ? 'stdio' : 'pipe') ctx.effect(() => () => runtime.dispose(), 'cua-windows.native-runtime') installCua(ctx, config, { helperPath, createChannel: (_owner, native) => runtime.connect(native), getGuidance: () => GUIDANCE, capabilities: CAPABILITIES, diff --git a/packages/experimental/cua-windows/src/native-runtime.ts b/packages/experimental/cua-windows/src/native-runtime.ts index b5be44ac70..ca991d5fcd 100644 --- a/packages/experimental/cua-windows/src/native-runtime.ts +++ b/packages/experimental/cua-windows/src/native-runtime.ts @@ -1,8 +1,9 @@ /** Host-owned connector and independently disposable Agent connections to a shared Windows helper. */ import { createHash, randomUUID } from 'node:crypto' -import { createReadStream } from 'node:fs' +import { closeSync, createReadStream, fstatSync, openSync, readSync } from 'node:fs' import { addAbortListener } from 'node:events' import { realpath } from 'node:fs/promises' +import { dirname, join } from 'node:path' import { PassThrough, Writable, type Readable, type Duplex } from 'node:stream' import assert from 'node:assert/strict' import type { SubprocessHandle, SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' @@ -20,6 +21,43 @@ type Owner = { subprocess: Pick } function failure(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)) } +const windowsLogAttached = Symbol('windows-native-log-attached') + +/* v8 ignore start -- Temporary VM diagnostics; current transport fixtures do not exercise real log tails. */ +function readWindowsLogTail(logPath: string): string { + const file = openSync(logPath, 'r') + try { + const size = fstatSync(file).size + const start = Math.max(0, size - 64 * 1024) + const buffer = Buffer.alloc(size - start) + let length = 0 + while (length < buffer.length) { + const count = readSync(file, buffer, length, buffer.length - length, start + length) + if (count === 0) break + length += count + } + let offset = 0 + // A tail may start inside a UTF-8 character. + if (start > 0) while (offset < length && (buffer.readUInt8(offset) & 0xc0) === 0x80) offset++ + const contents = buffer.subarray(offset, length).toString('utf8') + return start > 0 ? `[Earlier log content omitted; showing the tail.]\n${contents}` : contents + } finally { closeSync(file) } +} +/* v8 ignore stop */ + +function withWindowsLog(error: unknown, logPath: string): NativeError { + const original = failure(error) + const cause = original instanceof NativeError ? original : new NativeError('NATIVE_IO', original.message, { cause: original }) + if (Object.hasOwn(cause, windowsLogAttached)) return cause + let diagnostics: string + // The shared client can reject immediately when a stream error or write callback fires. + try { diagnostics = readWindowsLogTail(logPath) } + catch (logError) { diagnostics = `Could not read the exception log: ${failure(logError).message}` } + cause.message += `\nWindows CUA exception log (${logPath}):\n${diagnostics}` + Object.defineProperty(cause, windowsLogAttached, { value: true }) + return cause +} + async function interruptible(operation: Promise, signal: AbortSignal): Promise { const cancelled = Promise.withResolvers() using _listener = addAbortListener(signal, () => { cancelled.reject(signal.reason) }) @@ -55,6 +93,7 @@ function firstFrame(stream: Readable, signal: AbortSignal): Promise<{ value: unk } class WindowsHelper { + logPath: string readonly ready: Promise> readonly done: Promise readonly sockets = new Set() @@ -66,6 +105,7 @@ class WindowsHelper { private error: Error | undefined constructor(private readonly owner: Owner, private readonly config: NativeClientConfig) { + this.logPath = join(dirname(config.helperPath), 'dsh-cua-windows.log') this.ready = this.readiness.promise void this.ready.catch(() => {}) this.done = this.run() @@ -90,6 +130,7 @@ class WindowsHelper { }, this.config.connectTimeoutMs) try { const helperPath = await realpath(this.config.helperPath) + this.logPath = join(dirname(helperPath), 'dsh-cua-windows.log') const digest = createHash('sha256') for await (const chunk of createReadStream(helperPath, { signal: this.startup.signal })) digest.update(chunk as Buffer) const runtimeKey = digest.digest('hex') @@ -134,7 +175,8 @@ class WindowsHelper { finally { clearTimeout(startupTimer) this.phase = 'closing' - const error = this.error ?? new NativeError('NATIVE_CLOSED', 'Windows helper closed; select applications again') + const error = this.error ? withWindowsLog(this.error, this.logPath) + : new NativeError('NATIVE_CLOSED', 'Windows helper closed; select applications again') for (const socket of this.sockets) socket.destroy(error) const handle = this.handle try { @@ -146,7 +188,8 @@ class WindowsHelper { if (!await handle.waitForExit()) throw new NativeError('NATIVE_CLEANUP', 'Windows helper process range did not exit') } finally { clearTimeout(timer) } } - } finally { + } catch (cleanupError) { throw withWindowsLog(cleanupError, this.logPath) } + finally { clearTimeout(this.stopTimer) this.phase = 'closed' this.readiness.reject(error) @@ -156,6 +199,7 @@ class WindowsHelper { } class WindowsChannel implements NativeChannel { + private logPath: string readonly stdout = new PassThrough() readonly stdin: Writable readonly done: Promise @@ -168,11 +212,16 @@ class WindowsChannel implements NativeChannel { constructor(helper: Promise, config: NativeClientConfig, pollIntervalMs: number, launchWaitMs: number, owner: Owner, transport: WindowsTransport) { + this.logPath = join(dirname(config.helperPath), 'dsh-cua-windows.log') this.stdin = new Writable({ write: (chunk: Buffer, _encoding, callback) => { void this.readiness.promise.then((socket) => { if (this.closing) { callback(new NativeError('NATIVE_CLOSED', 'Native connection is closing')); return } - socket.write(chunk, callback) + /* v8 ignore start -- Temporary VM diagnostics; current transport fixtures do not inject socket write failures. */ + try { + socket.write(chunk, (error) => { callback(error ? withWindowsLog(error, this.logPath) : error) }) + } catch (error) { callback(withWindowsLog(error, this.logPath)) } + /* v8 ignore stop */ }, callback) }, final: (callback) => { this.close(); callback() }, @@ -208,6 +257,7 @@ class WindowsChannel implements NativeChannel { try { helper = await interruptible(helperPromise, this.startup.signal) const ready = await interruptible(helper.ready, this.startup.signal) + this.logPath = helper.logPath this.startup.signal.throwIfAborted() connection = connectWindowsPipe(owner.subprocess, config, ready.endpoint, ready.runtimeKey, transport) const socket = connection.stream @@ -278,23 +328,25 @@ class WindowsChannel implements NativeChannel { try { await closed } finally { this.startup.signal.removeEventListener('abort', close) } } finally { this.startup.signal.removeEventListener('abort', abort) } } catch (error) { + if (helper) this.logPath = helper.logPath const cause = failure(error) - if (!this.closing || admitted) caught = cause - this.readiness.reject(cause) + if (!this.closing || admitted) caught = withWindowsLog(cause, this.logPath) + this.readiness.reject(caught ?? cause) } finally { + if (helper) this.logPath = helper.logPath clearTimeout(timer) clearTimeout(this.closeTimer) this.closing = true this.socket?.destroy() if (closed) { - try { await closed } catch (error) { if (admitted) caught ??= failure(error) } + try { await closed } catch (error) { if (admitted) caught ??= withWindowsLog(error, this.logPath) } } if (this.socket) helper?.sockets.delete(this.socket) let cleanupError: Error | undefined - try { await connection?.dispose() } catch (error) { cleanupError = failure(error); caught ??= cleanupError } + try { await connection?.dispose() } catch (error) { cleanupError = withWindowsLog(error, this.logPath); caught ??= cleanupError } if (admitted && !observation.acknowledged) { - cleanupError = new NativeError('NATIVE_CLEANUP', 'Windows pipe ended without native cleanup acknowledgement') + cleanupError = withWindowsLog(new NativeError('NATIVE_CLEANUP', 'Windows pipe ended without native cleanup acknowledgement'), this.logPath) } this.stdin.destroy() if (caught) this.stdout.destroy(caught) diff --git a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts index dcee6fa104..4109de1af6 100644 --- a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts @@ -40,7 +40,7 @@ it('uses an absolute fixture without compiling and disposes the Host runtime', a const ctx = owner(), config = Config({ helperPath: resolve('fixture.exe'), pollIntervalMs: 13 }) await apply(ctx, config) expect(native.prepare).not.toHaveBeenCalled() - expect(native.construct).toHaveBeenCalledWith(ctx, 13, 1000, 'pipe') + expect(native.construct).toHaveBeenCalledWith(ctx, 13, 60_000, 'pipe') const backend = native.install.mock.calls[0]![2] expect(backend.helperPath).toBe(config.helperPath) expect(native.architecture).not.toHaveBeenCalled() @@ -106,7 +106,7 @@ it('prepares the Windows architecture and stdio transport for WSL', async () => await apply(ctx, Config({})) expect(native.prepare.mock.calls[0]![0].architecture).toBe('arm64') expect(native.architecture).not.toHaveBeenCalled() - expect(native.construct).toHaveBeenCalledWith(ctx, 25, 1000, 'stdio') + expect(native.construct).toHaveBeenCalledWith(ctx, 25, 60_000, 'stdio') expect(native.install.mock.calls[0]![2].helperPath).toBe('/mnt/c/cache/helper.exe') }) diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 036089bcc0..c854eff7ba 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -72,9 +72,9 @@ export interface CuaConfig { maxResponseBytes: number /** Maximum installed application matches returned for one discovery query. */ maxAppMatches: number - /** Maximum bytes preserved from the system clipboard during one paste. */ + /** Provider-specific clipboard byte limit for paste. */ maxClipboardBytes: number - /** Maximum wait for clipboard data consumption after the Paste command returns. */ + /** Provider-specific paste wait budget in milliseconds. */ pasteReadTimeoutMs: number /** Maximum UTF-8 bytes admitted for one helper request frame. */ maxRequestBytes: number diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index b38229c220..29a3e21d00 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -142,9 +142,8 @@ export interface CuaSurface { /** * Paste text or HTML at the target's current input focus. * Rejects when the provider does not support keyboard input at this scope. - * PASTE_NOT_CONSUMED means no clipboard read within the configured deadline after dispatch; inspect before retrying. * @param text - Clipboard contents in the selected format; defaults to plain text. - * @param options - Clipboard format. Original contents are restored unless another writer changes them. + * @param options - Clipboard format. * @returns Dispatch evidence; unsupported Paste commands fail without typing fallback. */ paste(text: string, options?: CuaPasteOptions): Promise